Skip to content

Commit

Permalink
Keep parens when removal would result in shadowing
Browse files Browse the repository at this point in the history
  • Loading branch information
brianrourkeboll committed Feb 7, 2024
1 parent 6071d00 commit bba8e2a
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 26 deletions.
27 changes: 27 additions & 0 deletions src/Compiler/Service/SynExpr.fs
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,33 @@ module SynExpr =
->
true

// Keep parens if a name in the outer scope is rebound
// in the inner scope and would shadow the outer binding
// if the parens were removed, e.g.:
//
// let x = 3
// (
// let x = 4
// printfn $"{x}"
// )
// x
| SynExpr.Sequential(expr1 = SynExpr.Paren(expr = Is inner); expr2 = expr2), _ ->
let identsBoundInInner =
(Set.empty, [ SyntaxNode.SynExpr inner ])
||> SyntaxNodes.fold (fun idents _path node ->
match node with
| SyntaxNode.SynPat(SynPat.Named(ident = SynIdent(ident = ident))) -> idents.Add ident.idText
| _ -> idents)

if identsBoundInInner.IsEmpty then
false
else
(outer.Range.End, [ SyntaxNode.SynExpr expr2 ])
||> SyntaxNodes.exists (fun _path node ->
match node with
| SyntaxNode.SynExpr(SynExpr.Ident ident) -> identsBoundInInner.Contains ident.idText
| _ -> false)

| SynExpr.InterpolatedString _, SynExpr.Sequential _ -> true

| SynExpr.InterpolatedString(contents = contents), (SynExpr.Tuple(isStruct = false) | Dangling.Problematic _) ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -618,32 +618,6 @@ in x
y - x
"

(*
Bug: removing parens shadows `y` in `x + y`.
To address this, we'd need to ensure that any name bound in the inner scope
is never used again in the outer scope.
*)
//"
//let _ =
// let y = 100
// let x = 3
// (
// let y = 99
// ignore (y - x)
// )
// x + y
//",
//"
//let _ =
// let y = 100
// let x = 3
// (
// let y = 99
// ignore (y - x)
// )
// x + y
//"

// TryWith
"try (raise null) with _ -> reraise ()", "try raise null with _ -> reraise ()"
"try raise null with (_) -> reraise ()", "try raise null with _ -> reraise ()"
Expand All @@ -670,6 +644,82 @@ in x
""" printfn "1"; (printfn "2") """, """ printfn "1"; printfn "2" """
"let x = 3; (5) in x", "let x = 3; 5 in x"

"
let _ =
let y = 100
let x = 3
(
let y = 99
ignore (y - x)
)
x + y
",
"
let _ =
let y = 100
let x = 3
(
let y = 99
ignore (y - x)
)
x + y
"

"
let _ =
let y = 100
let x = 3
(
let y = 99
ignore (y - x)
)
x
",
"
let _ =
let y = 100
let x = 3
let y = 99
ignore (y - x)
x
"

"
let f y =
let x = 3
(
let y = 99
ignore (y - x)
)
x + y
",
"
let f y =
let x = 3
(
let y = 99
ignore (y - x)
)
x + y
"

"
let f y =
let x = 3
(
let y = 99
ignore (y - x)
)
x
",
"
let f y =
let x = 3
let y = 99
ignore (y - x)
x
"

// IfThenElse
"if (3 = 3) then 3 else 3", "if 3 = 3 then 3 else 3"
"if 3 = 3 then (3) else 3", "if 3 = 3 then 3 else 3"
Expand Down

0 comments on commit bba8e2a

Please sign in to comment.