-
Notifications
You must be signed in to change notification settings - Fork 74
Added NoImpureFunctions rule #885
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
webwarrior-ws
wants to merge
5
commits into
fsprojects:master
Choose a base branch
from
webwarrior-ws:no-impure-functions
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
1c770f2
NoImpureFunctions: added rule
webwarrior-ws 354f5e6
NoImpureFunctions: implemented rule
webwarrior-ws 9c2d5f7
NoImpureFunctions: option to disallow types
webwarrior-ws c3ce173
NoImpureFunctions: allow whitelisting of types
webwarrior-ws 3cc9094
NoImpureFunctions: implemented whitelisting of types
webwarrior-ws File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| --- | ||
| title: FL0098 | ||
| category: how-to | ||
| hide_menu: true | ||
| --- | ||
|
|
||
| # NoImpureFunctions (FL0098) | ||
|
|
||
| ## Cause | ||
|
|
||
| An impure function (that mutates one or more of its parameters) was used. | ||
|
|
||
| ## Rationale | ||
|
|
||
| Using pure functions without side-effects is preferrable in functional programming. | ||
|
|
||
| ## How To Fix | ||
|
|
||
| Use pure function. | ||
|
|
||
| ## Rule Settings | ||
|
|
||
| { | ||
| "noImpureFunctions": { | ||
| "enabled": false, | ||
| "config": { | ||
| "allowedImpureFunctions": [], | ||
| "additionalImpureFunctions": [] | ||
| } | ||
| } | ||
| } | ||
|
|
||
| * *allowedImpureFunctions* - list of strings representing impure functions to allow (e.g. `"Array.set"`). | ||
| * *additionalImpureFunctions* - list of strings representing additional impure functions to disallow. | ||
|
|
||
| If a string in either of those settings ends in `.*` (e.g. `Foo.Bar.Baz.*`), then it is treated as type `Foo.Bar.Baz` (without type parameters). In this case, usage of type's constructors is checked. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
144 changes: 144 additions & 0 deletions
144
src/FSharpLint.Core/Rules/Conventions/NoImpureFunctions.fs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| module FSharpLint.Rules.NoImpureFunctions | ||
|
|
||
| open System | ||
| open FSharpLint.Framework | ||
| open FSharpLint.Framework.Suggestion | ||
| open FSharpLint.Framework.Ast | ||
| open FSharpLint.Framework.Rules | ||
| open FSharp.Compiler.Text | ||
| open FSharp.Compiler.CodeAnalysis | ||
| open FSharp.Compiler.Symbols | ||
| open FSharp.Compiler.Syntax | ||
|
|
||
| [<RequireQualifiedAccess>] | ||
| type Config = { | ||
| AllowedImpureFunctions:string list | ||
| AdditionalImpureFunctions:string list | ||
| } | ||
|
|
||
| let private impureFunctionIdentifiers = | ||
| Map.ofList | ||
| [ | ||
| ("Array.sortInPlace", Some "Array.sort") | ||
| ("Array.sortInPlaceBy", Some "Array.Array.sortBy") | ||
| ("Array.sortInPlaceWith", Some "Array.sortWith") | ||
|
|
||
| ("Array.set", Some "Array.updateAt") | ||
|
|
||
| ("Array.fill", None) | ||
| ("Array.blit", None) | ||
|
|
||
| ("Array2D.fill", None) | ||
| ("Array2D.blit", None) | ||
|
|
||
| // Disallowed types | ||
| ("System.Collections.Generic.List.*", None) | ||
| ("System.Collections.Generic.Dictionary.*", None) | ||
| ("System.Collections.Generic.HashSet.*", None) | ||
| ("System.Collections.Generic.LinkedList.*", None) | ||
| ("System.Collections.Generic.SortedDictionary.*", None) | ||
| ("System.Collections.Generic.SortedSet.*", None) | ||
| ("System.Collections.Generic.Stack.*", None) | ||
| ] | ||
|
|
||
| let runner (config:Config) (args:AstNodeRuleParams) = | ||
| let checkIfImpureIdentifier (identifier:string) (range:Range) = | ||
| let issueWarning maybeReplacementFunction = | ||
| match maybeReplacementFunction with | ||
| | Some replacementFunction -> | ||
| { | ||
| Range = range | ||
| Message = String.Format(Resources.GetString "RulesConventionsNoImpureFunctionsReplacementError", replacementFunction, identifier) | ||
| SuggestedFix = Some (lazy ( Some { FromText = identifier; FromRange = range; ToText = replacementFunction })) | ||
| TypeChecks = List.Empty | ||
| } | ||
| | None -> | ||
| { | ||
| Range = range | ||
| Message = String.Format(Resources.GetString "RulesConventionsNoImpureFunctionsError", identifier) | ||
| SuggestedFix = None | ||
| TypeChecks = List.Empty | ||
| } | ||
|
|
||
| if List.contains identifier config.AllowedImpureFunctions then | ||
| None | ||
| elif List.contains identifier config.AdditionalImpureFunctions then | ||
| issueWarning None |> Some | ||
| else | ||
| Map.tryFind identifier impureFunctionIdentifiers | ||
| |> Option.filter (fun _ -> not (List.contains identifier config.AllowedImpureFunctions)) | ||
| |> Option.map issueWarning | ||
|
|
||
| let disallowedTypes = | ||
| let builtinIdentifiers = Map.keys impureFunctionIdentifiers |> Set.ofSeq | ||
| (Set.ofList config.AdditionalImpureFunctions) + builtinIdentifiers - (Set.ofList config.AllowedImpureFunctions) | ||
| |> Seq.choose (fun definition -> | ||
| let wildcardSuffix = ".*" | ||
| if definition.EndsWith wildcardSuffix then | ||
| Some <| definition.Substring(0, definition.Length - wildcardSuffix.Length) | ||
| else | ||
| None) | ||
| |> Set.ofSeq | ||
|
|
||
| let checkForDisallowedType (checkResults: FSharpCheckFileResults) (range: Range) = | ||
| let allSymbolUses = checkResults.GetAllUsesOfAllSymbolsInFile() | ||
| let maybeSymbolUse = | ||
| allSymbolUses | ||
| |> Seq.tryFind (fun symbolUse -> range = symbolUse.Range) | ||
| match maybeSymbolUse with | ||
| | Some symbolUse -> | ||
| match symbolUse.Symbol with | ||
| | :? FSharpMemberOrFunctionOrValue as value when value.IsConstructor || value.IsImplicitConstructor -> | ||
| let declaringEntity = value.DeclaringEntity | ||
| match declaringEntity with | ||
| | Some entity -> | ||
| let fullNameWithoutTypeParams = | ||
| let lestBackTickIndex = entity.FullName.LastIndexOf '`' | ||
| if lestBackTickIndex > 0 then | ||
| entity.FullName.Substring(0, lestBackTickIndex) | ||
| else | ||
| entity.FullName | ||
|
|
||
| if disallowedTypes |> Set.contains fullNameWithoutTypeParams then | ||
| Array.singleton | ||
| { | ||
| Range = range | ||
| Message = String.Format(Resources.GetString "RulesConventionsNoImpureFunctionsDisallowedTypeError", entity.FullName) | ||
| SuggestedFix = None | ||
| TypeChecks = List.Empty | ||
| } | ||
| else | ||
| Array.empty | ||
| | _ -> Array.empty | ||
| | _ -> Array.empty | ||
| | None -> Array.empty | ||
|
|
||
| match (args.AstNode, args.CheckInfo) with | ||
| | AstNode.Identifier (identifier, range), _ -> | ||
| match checkIfImpureIdentifier (String.concat "." identifier) range with | ||
| | Some impureIdentifierWarning -> | ||
| Array.singleton impureIdentifierWarning | ||
| | _ -> | ||
| Array.Empty() | ||
| | AstNode.Expression(SynExpr.App(_, false, funcExpr, _, _range)), Some(checkResults) when not disallowedTypes.IsEmpty -> | ||
| match funcExpr with | ||
| | SynExpr.LongIdent(_, SynLongIdent(_), _, identRange) -> | ||
| checkForDisallowedType checkResults identRange | ||
| | SynExpr.TypeApp(SynExpr.LongIdent(_, SynLongIdent(_), _, identRange),_,_,_,_,_,_) -> | ||
| checkForDisallowedType checkResults identRange | ||
| | _ -> Array.empty | ||
| | AstNode.Expression(SynExpr.New(_, targetType, _, _)), Some(checkResults) when not disallowedTypes.IsEmpty -> | ||
| checkForDisallowedType checkResults targetType.Range | ||
| | _ -> Array.empty | ||
|
|
||
| let rule config = | ||
| AstNodeRule | ||
| { | ||
| Name = "NoImpureFunctions" | ||
| Identifier = Identifiers.NoImpureFunctions | ||
| RuleConfig = | ||
| { | ||
| AstNodeRuleConfig.Runner = runner config | ||
| Cleanup = ignore | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
73 changes: 73 additions & 0 deletions
73
tests/FSharpLint.Core.Tests/Rules/Conventions/NoImpureFunctions.fs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| module FSharpLint.Core.Tests.Rules.Conventions.NoImpureFunctions | ||
|
|
||
|
|
||
| open NUnit.Framework | ||
| open FSharpLint.Rules | ||
| open FSharpLint.Core.Tests | ||
|
|
||
| [<TestFixture>] | ||
| type TestConventionsNoImpureFunctions() = | ||
| inherit TestAstNodeRuleBase.TestAstNodeRuleBase( | ||
| NoImpureFunctions.rule { | ||
| AdditionalImpureFunctions = ["Custom.impure"] | ||
| AllowedImpureFunctions = ["Array.set"; "System.Collections.Generic.Dictionary.*"] | ||
| }) | ||
|
|
||
| [<Test>] | ||
| member this.``Error for impure function which should be replaced with another function``() = | ||
| this.Parse("let x = Array.sortInPlace [2; 1; 4]") | ||
|
|
||
| Assert.IsTrue this.ErrorsExist | ||
|
|
||
| [<Test>] | ||
| member this.``Error for user-specified impure function``() = | ||
| this.Parse("let x = Custom.impure (ref 4)") | ||
|
|
||
| Assert.IsTrue this.ErrorsExist | ||
|
|
||
| [<Test>] | ||
| member this.``No error for user-specified allowed partial function``() = | ||
| this.Parse("let x = [| Some 4; None |] | ||
| Array.set x 0 None") | ||
|
|
||
| this.AssertNoWarnings() | ||
|
|
||
| [<Test>] | ||
| member this.``Error for creating a mutable list``() = | ||
| this.Parse("let x = System.Collections.Generic.List<int>()") | ||
|
|
||
| Assert.IsTrue this.ErrorsExist | ||
|
|
||
| [<Test>] | ||
| member this.``Error for creating a mutable list without explicit type param``() = | ||
| this.Parse("let x = System.Collections.Generic.List [ 1; 2 ]") | ||
|
|
||
| Assert.IsTrue this.ErrorsExist | ||
|
|
||
| [<Test>] | ||
| member this.``Error for creating a mutable list with new keyword``() = | ||
| this.Parse("open System.Collections.Generic | ||
|
|
||
| let x = new List<int>()") | ||
|
|
||
| Assert.IsTrue this.ErrorsExist | ||
|
|
||
| [<Test>] | ||
| member this.``No error for using an existing mutable list``() = | ||
| this.Parse("open System.Collections.Generic | ||
|
|
||
| type IHasList = | ||
| abstract List: List<int> | ||
|
|
||
| let x (hasList: IHasList) = hasList.List") | ||
|
|
||
| this.AssertNoWarnings() | ||
|
|
||
| [<Test>] | ||
| member this.``No error for creating a type from allowed list``() = | ||
| this.Parse("open System.Collections.Generic | ||
|
|
||
| let x = new Dictionary<int,int>()") | ||
|
|
||
| this.AssertNoWarnings() | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@webwarrior-ws actually separate this commit in two, I want to see the CI fail before you add the commit that makes it pass
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Split into 2 commits.