|
| 1 | +module FSharpLint.Rules.InterpolatedStringWithNoSubstitution |
| 2 | + |
| 3 | +open System |
| 4 | +open FSharpLint.Framework |
| 5 | +open FSharpLint.Framework.Suggestion |
| 6 | +open FSharp.Compiler.Syntax |
| 7 | +open FSharpLint.Framework.Ast |
| 8 | +open FSharpLint.Framework.Rules |
| 9 | + |
| 10 | +let private makeWarning range = |
| 11 | + { |
| 12 | + Range = range |
| 13 | + Message = Resources.GetString "InterpolatedStringWithNoSubstitution" |
| 14 | + SuggestedFix = None |
| 15 | + TypeChecks = List.Empty |
| 16 | + } |
| 17 | + |
| 18 | +let checkInterpolatedString (contents: List<SynInterpolatedStringPart>) range = |
| 19 | + if contents |> List.exists (fun part -> part.IsFillExpr) then |
| 20 | + Array.empty |
| 21 | + else |
| 22 | + Array.singleton (makeWarning range) |
| 23 | + |
| 24 | +let stringFormattingFunctionNames = [ "sprintf"; "failwithf" ] |
| 25 | + |
| 26 | +// https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/plaintext-formatting#format-specifiers-for-printf |
| 27 | +let formatSpecifierRegex = Text.RegularExpressions.Regex(@"($|[^\%])\%[^\s\%]") |
| 28 | + |
| 29 | +let checkFormattingFunctionApplication (formatString: string) range = |
| 30 | + if formatSpecifierRegex.IsMatch formatString then |
| 31 | + Array.empty |
| 32 | + else |
| 33 | + Array.singleton (makeWarning range) |
| 34 | + |
| 35 | +let runner (args: AstNodeRuleParams) = |
| 36 | + match args.AstNode with |
| 37 | + | AstNode.Expression(SynExpr.InterpolatedString(contents, _synStringKind, range)) -> |
| 38 | + checkInterpolatedString contents range |
| 39 | + | AstNode.Expression(SynExpr.App(_, false, SynExpr.Ident(ident), SynExpr.Const(SynConst.String(text, _, _stringRange),_), range)) |
| 40 | + when stringFormattingFunctionNames |> List.contains ident.idText -> |
| 41 | + checkFormattingFunctionApplication text range |
| 42 | + | _ -> Array.empty |
| 43 | + |
| 44 | +let rule = |
| 45 | + AstNodeRule |
| 46 | + { |
| 47 | + Name = "InterpolatedStringWithNoSubstitution" |
| 48 | + Identifier = Identifiers.InterpolatedStringWithNoSubstitution |
| 49 | + RuleConfig = |
| 50 | + { |
| 51 | + AstNodeRuleConfig.Runner = runner |
| 52 | + Cleanup = ignore |
| 53 | + } |
| 54 | + } |
0 commit comments