Skip to content

Commit

Permalink
Fix #2013: Consider true, false as compiler define identifiers. (#2019)
Browse files Browse the repository at this point in the history
* Consider true, false as compiler define identifiers.

Fix #2013
  • Loading branch information
jindraivanek authored Jan 13, 2022
1 parent 24705b9 commit aeda840
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 3 deletions.
23 changes: 23 additions & 0 deletions src/Fantomas.Tests/CompilerDirectivesTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -2692,3 +2692,26 @@ try
with
| _ -> ()
"""

[<Test>]
let ``should handle #if with boolean constant`` () =
formatSourceString
false
"""
#if false
let x = 1
#endif
#if true
let x = 1
#endif
"""
config
|> should
equal
"""#if false
let x = 1
#endif
#if true
let x = 1
#endif
"""
32 changes: 30 additions & 2 deletions src/Fantomas.Tests/TokenParserBoolExprTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,28 @@ let x = 1
)
))

let ``Get define exprs from boolean constant`` booleanConstString =
let source =
(sprintf
"""
#if %s
let x = 1
#endif
"""
booleanConstString)

getDefineExprs source
|> List.head
|> should equal (BoolExpr.Ident booleanConstString)

[<Test>]
let ``Get define exprs from boolean constant (true)`` () =
``Get define exprs from boolean constant`` "true"

[<Test>]
let ``Get define exprs from boolean constant (false)`` () =
``Get define exprs from boolean constant`` "false"

[<Test>]
let ``simple compiler directive - else expr`` () =
let source =
Expand Down Expand Up @@ -212,8 +234,14 @@ type BoolExprGenerator =
static member SimpleIdent() =
{ new Arbitrary<string>() with
member x.Generator =
Gen.choose (int 'A', int 'Z')
|> Gen.map (char >> string)
let idents =
Gen.choose (int 'A', int 'Z')
|> Gen.map (char >> string)

let constants = Gen.elements [ "true"; "false" ]

Gen.frequency [ 10, idents
1, constants ]

member x.Shrinker t = Seq.empty }

Expand Down
4 changes: 3 additions & 1 deletion src/Fantomas/TokenParser.fs
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ and tokenize defines (hashTokens: Token list) (content: string) : Token list =

let getDefinesWords (tokens: Token list) =
tokens
|> List.filter (fun { TokenInfo = { TokenName = tn } } -> tn = "IDENT")
|> List.filter (fun { TokenInfo = { TokenName = tn } } -> tn = "IDENT" || tn = "FALSE" || tn = "TRUE")
|> List.map (fun t -> t.Content)
|> List.distinct

Expand All @@ -385,6 +385,8 @@ let getDefineExprs (hashTokens: Token list) =
|> Seq.filter
(fun t ->
t.TokenInfo.TokenName = "IDENT"
|| t.TokenInfo.TokenName = "TRUE"
|| t.TokenInfo.TokenName = "FALSE"
|| Set.contains t.Content allowedContent)
|> Seq.map (fun t -> t.Content)
|> Seq.toList
Expand Down

0 comments on commit aeda840

Please sign in to comment.