Skip to content

Commit

Permalink
Remove Context.HasSource (#2890)
Browse files Browse the repository at this point in the history
* Create context with HasSource true.

* Correct interpolated string parts in ASTTransformer fallback.
  • Loading branch information
nojaf authored Jun 2, 2023
1 parent bfb4afc commit 187cb01
Show file tree
Hide file tree
Showing 9 changed files with 64 additions and 29 deletions.
20 changes: 20 additions & 0 deletions src/Fantomas.Core.Tests/CodeFormatterTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,23 @@ let ``trivia is parsed for Oak`` () =
|> fst

Assert.True(oak.ModulesOrNamespaces.[0].HasContentAfter)

[<Test>]
let ``parsed oak can be formatted back to source`` () =
let source = "$\"gc{i}\""

let oak =
CodeFormatter.ParseOakAsync(false, source)
|> Async.RunSynchronously
|> Array.head
|> fst

let formatted =
CodeFormatter.FormatOakAsync(
oak,
{ FormatConfig.Default with
InsertFinalNewline = false }
)
|> Async.RunSynchronously

Assert.AreEqual(source, formatted)
15 changes: 15 additions & 0 deletions src/Fantomas.Core.Tests/InterpolatedStringTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,21 @@ let text = "foo"
let s = $"%s{text} bar"
"""

[<Test>]
let ``interpolation from AST with multiple fillExprs`` () =
formatAST
false
"""
$"%s{text} %i{bar} %f{meh}"
"""
config
|> prepend newline
|> should
equal
"""
$"%s{text} %i{bar} %f{meh}"
"""

[<Test>]
let ``multiline expression in multiline string`` () =
formatSourceString
Expand Down
18 changes: 16 additions & 2 deletions src/Fantomas.Core/ASTTransformer.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1466,11 +1466,25 @@ let mkExpr (creationAide: CreationAide) (e: SynExpr) : Expr =
)
|> Expr.LibraryOnlyStaticOptimization
| SynExpr.InterpolatedString(parts, _, _) ->
let lastIndex = parts.Length - 1

let parts =
parts
|> List.map (function
|> List.mapi (fun idx part ->
match part with
| SynInterpolatedStringPart.String(v, r) ->
stn (creationAide.TextFromSource (fun () -> v) r) r |> Choice1Of2
stn
(creationAide.TextFromSource
(fun () ->
if idx = 0 && not (v.StartsWith("$")) then
$"$\"%s{v}{{"
elif idx = lastIndex && not (v.EndsWith("\"")) then
$"}}%s{v}\""
else
$"}}{v}{{")
r)
r
|> Choice1Of2
| SynInterpolatedStringPart.FillExpr(fillExpr, qualifiers) ->
let m =
match qualifiers with
Expand Down
4 changes: 2 additions & 2 deletions src/Fantomas.Core/CodeFormatter.fs
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,14 @@ type CodeFormatter =

static member FormatOakAsync(oak: Oak) : Async<string> =
async {
let context = Context.Context.Create false FormatConfig.Default
let context = Context.Context.Create FormatConfig.Default
let result = context |> CodePrinter.genFile oak |> Context.dump false
return result.Code
}

static member FormatOakAsync(oak: Oak, config: FormatConfig) : Async<string> =
async {
let context = Context.Context.Create false config
let context = Context.Context.Create config
let result = context |> CodePrinter.genFile oak |> Context.dump false
return result.Code
}
2 changes: 1 addition & 1 deletion src/Fantomas.Core/CodeFormatterImpl.fs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ let formatAST
(config: FormatConfig)
(cursor: pos option)
: FormatResult =
let context = Context.Context.Create sourceText.IsSome config
let context = Context.Context.Create config

let oak =
match sourceText with
Expand Down
9 changes: 2 additions & 7 deletions src/Fantomas.Core/CodePrinter.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1524,8 +1524,7 @@ let genExpr (e: Expr) =
|> fun ctx -> { ctx with Config = currentConfig }
|> atCurrentColumnIndent

onlyIfCtx (fun ctx -> not ctx.HasSource) (!- "$\"")
+> col sepNone node.Parts (fun part ->
col sepNone node.Parts (fun part ->
match part with
| Choice1Of2 stringNode -> genSingleTextNode stringNode
| Choice2Of2 fillNode ->
Expand All @@ -1534,11 +1533,7 @@ let genExpr (e: Expr) =
genInterpolatedFillExpr fillNode.Expr
+> optSingle (fun format -> sepColonFixed +> genSingleTextNode format) fillNode.Ident

if not ctx.HasSource then
(!- "{" +> genFill +> !- "}") ctx
else
genFill ctx)
+> onlyIfCtx (fun ctx -> not ctx.HasSource) (!- "\"")
genFill ctx)
|> genNode node
| Expr.IndexRangeWildcard node -> genSingleTextNode node
| Expr.TripleNumberIndexRange node ->
Expand Down
8 changes: 2 additions & 6 deletions src/Fantomas.Core/Context.fs
Original file line number Diff line number Diff line change
Expand Up @@ -181,23 +181,19 @@ module WriterEvents =
[<System.Diagnostics.DebuggerDisplay("\"{Dump()}\"")>]
type Context =
{ Config: FormatConfig
HasSource: bool
WriterModel: WriterModel
WriterEvents: Queue<WriterEvent>
FormattedCursor: pos option }

/// Initialize with a string writer and use space as delimiter
static member Default =
{ Config = FormatConfig.Default
HasSource = false
WriterModel = WriterModel.init
WriterEvents = Queue.empty
FormattedCursor = None }

static member Create hasSource config : Context =
{ Context.Default with
Config = config
HasSource = hasSource }
static member Create config : Context =
{ Context.Default with Config = config }

member x.WithDummy(writerCommands, ?keepPageWidth) =
let keepPageWidth = keepPageWidth |> Option.defaultValue false
Expand Down
15 changes: 5 additions & 10 deletions src/Fantomas.Core/Context.fsi
Original file line number Diff line number Diff line change
Expand Up @@ -53,19 +53,14 @@ type WriterModel =

[<System.Diagnostics.DebuggerDisplay("\"{Dump()}\"")>]
type Context =
{
Config: FormatConfig
/// Indicates the presence of source code.
/// This could be absent in the case we are formatting from AST.
HasSource: bool
WriterModel: WriterModel
WriterEvents: Queue<WriterEvent>
FormattedCursor: pos option
}
{ Config: FormatConfig
WriterModel: WriterModel
WriterEvents: Queue<WriterEvent>
FormattedCursor: pos option }

/// Initialize with a string writer and use space as delimiter
static member Default: Context
static member Create: hasSource: bool -> config: FormatConfig -> Context
static member Create: config: FormatConfig -> Context
member WithDummy: writerCommands: Queue<WriterEvent> * ?keepPageWidth: bool -> Context
member WithShortExpression: maxWidth: int * ?startColumn: int -> Context
member Column: int
Expand Down
2 changes: 1 addition & 1 deletion src/Fantomas.Core/Selection.fs
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ let formatSelection
MaxLineLength = maxLineLength }

let formattedSelection =
let context = Context.Context.Create true selectionConfig
let context = Context.Context.Create selectionConfig

match tree with
| TreeForSelection.Unsupported ->
Expand Down

0 comments on commit 187cb01

Please sign in to comment.