Skip to content
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

Remove strict mode #2798

Merged
merged 3 commits into from
Mar 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions build.fsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,14 @@ pipeline "Build" {
run (
cleanFolders
[| "bin"
"src/Fantomas.FCS/bin"
"src/Fantomas.FCS/obj"
"src/Fantomas.Core/bin"
"src/Fantomas.Core/obj"
"src/Fantomas/bin"
"src/Fantomas/obj"
"src/Fantomas.Client/bin"
"src/Fantomas.Client/obj" |]
"src/Fantomas.FCS/bin/Release"
"src/Fantomas.FCS/obj/Release"
"src/Fantomas.Core/bin/Release"
"src/Fantomas.Core/obj/Release"
"src/Fantomas/bin/Release"
"src/Fantomas/obj/Release"
"src/Fantomas.Client/bin/Release"
"src/Fantomas.Client/obj/Release" |]
)
}
stage "CheckFormat" { run "dotnet fantomas src docs build.fsx --recurse --check" }
Expand Down
26 changes: 0 additions & 26 deletions docs/docs/end-users/Configuration.fsx
Original file line number Diff line number Diff line change
Expand Up @@ -908,32 +908,6 @@ let singleList =
ExperimentalElmish = true }
(*** include-output ***)

(**
<fantomas-setting name="fsharp_strict_mode" red></fantomas-setting>

If being set, pretty printing is only done via ASTs. Compiler directives, inline comments and block comments will be ignored.
There are numerous situations when the information in the AST alone cannot restore the original code.

**Please do not use this setting for formatting hand written code!**

Valid use-case of this settings is code generation in projects like [FsAst](https://github.com/ionide/FsAst) and [Myriad](https://github.com/MoiraeSoftware/myriad).

Default = false.
*)

formatCode
"""
// some great comment
let add a b =
#if INTERACTIVE
42
#else
a + b
#endif
"""
{ FormatConfig.Default with
StrictMode = true }
(*** include-output ***)
(**
<fantomas-nav previous="./StyleGuide.html" next="./IgnoreFiles.html"></fantomas-nav>

Expand Down
2 changes: 2 additions & 0 deletions docs/docs/end-users/UpgradeGuide.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ fsharp_experimental_stroustrup_style = true
- `fsharp_multiline_block_brackets_on_same_column` and `fsharp_experimental_stroustrup_style` are replaced with `fsharp_multiline_bracket_style`
- `experimental_stroustrup` for `fsharp_multiline_bracket_style` is now `stroustrup`
- `fsharp_newline_before_multiline_computation_expression` was extracted from `fsharp_multiline_bracket_style = stroustrup` and now controls how computation expression behave.
- `fsharp_strict_mode` was removed and can no longer be used.

### console application
- `-v` is now short for `--verbosity` instead of `--version`
Expand All @@ -74,5 +75,6 @@ fsharp_experimental_stroustrup_style = true

### Miscellaneous
- The public API of CodeFormatter no longer uses `FSharpOption<'T>`, instead overloads are now used.
- `StrictMode` was removed from `FormatConfig`, not passing the source text in the public API will have the same effect.

<fantomas-nav previous="./VSCode.html" next="./FAQ.html"></fantomas-nav>
4 changes: 2 additions & 2 deletions src/Fantomas.Core.Tests/ExternTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ open Fantomas.Core.Tests.TestHelper

[<Test>]
let ``attribute above extern keyword, 562`` () =
formatSourceString
formatAST
false
"""
module C =
[<DllImport("")>]
extern IntPtr f()
"""
{ config with StrictMode = true }
config
|> prepend newline
|> should
equal
Expand Down
4 changes: 2 additions & 2 deletions src/Fantomas.Core.Tests/InterpolatedStringTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,13 @@ let s = $\"\"\"%s{text} bar\"\"\"

[<Test>]
let ``interpolation in strict mode`` () =
formatSourceString
formatAST
false
"""
let text = "foo"
let s = $"%s{text} bar"
"""
{ config with StrictMode = true }
config
|> prepend newline
|> should
equal
Expand Down
8 changes: 4 additions & 4 deletions src/Fantomas.Core.Tests/StringTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ let g = '\n'

[<Test>]
let ``uncommon literals strict mode`` () =
formatSourceString
formatAST
false
"""
let a = 0xFFy
Expand All @@ -123,7 +123,7 @@ let e = 1.40e10f
let f = 23.4M
let g = '\n'
"""
{ config with StrictMode = true }
config
|> prepend newline
|> should
equal
Expand Down Expand Up @@ -219,14 +219,14 @@ let ``chars should be properly escaped`` () =

[<Test>]
let ``quotes should be escaped in strict mode`` () =
formatSourceString
formatAST
false
"""
let formatter =
// escape commas left in invalid entries
sprintf "%i,\"%s\""
"""
{ config with StrictMode = true }
config
|> should
equal
"""let formatter = sprintf "%i,\"%s\""
Expand Down
4 changes: 2 additions & 2 deletions src/Fantomas.Core.Tests/SynConstTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -705,12 +705,12 @@ a:hover {color: #ecc;}

[<Test>]
let ``verbatim string in AST is preserved, 560`` () =
formatSourceString
formatAST
false
"""
let s = @"\"
"""
{ config with StrictMode = true }
config
|> prepend newline
|> should
equal
Expand Down
1 change: 0 additions & 1 deletion src/Fantomas.Core.Tests/SynLongIdentTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,6 @@ let ``backticks can be added from AST only scenarios`` () =
tree,
config =
{ config with
StrictMode = true
InsertFinalNewline = false }
)
|> Async.RunSynchronously
Expand Down
29 changes: 16 additions & 13 deletions src/Fantomas.Core.Tests/TestHelpers.fs
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,31 @@ let private safeToIgnoreWarnings =

let formatSourceString isFsiFile (s: string) config =
async {
let! formatted =
if not config.StrictMode then
CodeFormatter.FormatDocumentAsync(isFsiFile, s, config)
else
let ast, _ =
Fantomas.FCS.Parse.parseFile isFsiFile (FSharp.Compiler.Text.SourceText.ofString s) []
let! formatted = CodeFormatter.FormatDocumentAsync(isFsiFile, s, config)
let! isValid = CodeFormatter.IsValidFSharpCodeAsync(isFsiFile, formatted.Code)

CodeFormatter.FormatASTAsync(ast, config = config)
if not isValid then
failwithf $"The formatted result is not valid F# code or contains warnings\n%s{formatted.Code}"

return formatted.Code.Replace("\r\n", "\n")
}

|> Async.RunSynchronously

/// The `source` will first be parsed to AST.
let formatAST isFsiFile (source: string) config =
async {
let ast, _ =
Fantomas.FCS.Parse.parseFile isFsiFile (FSharp.Compiler.Text.SourceText.ofString source) []

let! formatted = CodeFormatter.FormatASTAsync(ast, config = config)
let! isValid = CodeFormatter.IsValidFSharpCodeAsync(isFsiFile, formatted.Code)

if not isValid then
failwithf $"The formatted result is not valid F# code or contains warnings\n%s{formatted.Code}"

return formatted.Code.Replace("\r\n", "\n")
}

|> Async.RunSynchronously

let formatSourceStringWithDefines defines (s: string) config =
Expand Down Expand Up @@ -83,11 +91,6 @@ let equal x =
equal x

let inline prepend s content = s + content

let formatConfig =
{ FormatConfig.Default with
StrictMode = true }

let (==) actual expected = Assert.AreEqual(expected, actual)
let fail () = Assert.Fail()
let pass () = Assert.Pass()
4 changes: 2 additions & 2 deletions src/Fantomas.Core.Tests/UnionTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -203,15 +203,15 @@ let main argv =

[<Test>]
let ``enums conversion with strict mode`` () =
formatSourceString
formatAST
false
"""
type uColor =
| Red = 0u
| Green = 1u
| Blue = 2u
let col3 = Microsoft.FSharp.Core.LanguagePrimitives.EnumOfValue<uint32, uColor>(2u)"""
{ config with StrictMode = true }
config
|> prepend newline
|> should
equal
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 @@ -66,14 +66,14 @@ type CodeFormatter =

static member FormatOakAsync(oak: Oak) : Async<string> =
async {
let context = Context.Context.Create FormatConfig.Default
let context = Context.Context.Create false 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 config
let context = Context.Context.Create false 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 config
let context = Context.Context.Create sourceText.IsSome config

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

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

if ctx.Config.StrictMode then
if not ctx.HasSource then
(!- "{" +> genFill +> !- "}") ctx
else
genFill ctx)
+> onlyIfCtx (fun ctx -> ctx.Config.StrictMode) (!- "\"")
+> onlyIfCtx (fun ctx -> not ctx.HasSource) (!- "\"")
|> genNode node
| Expr.IndexRangeWildcard node -> genSingleTextNode node
| Expr.TripleNumberIndexRange node ->
Expand Down
8 changes: 6 additions & 2 deletions src/Fantomas.Core/Context.fs
Original file line number Diff line number Diff line change
Expand Up @@ -181,19 +181,23 @@ 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 config : Context =
{ Context.Default with Config = config }
static member Create hasSource config : Context =
{ Context.Default with
Config = config
HasSource = hasSource }

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

[<System.Diagnostics.DebuggerDisplay("\"{Dump()}\"")>]
type Context =
{ Config: FormatConfig
WriterModel: WriterModel
WriterEvents: Queue<WriterEvent>
FormattedCursor: pos option }
{
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
}

/// Initialize with a string writer and use space as delimiter
static member Default: Context
static member Create: config: FormatConfig -> Context
static member Create: hasSource: bool -> config: FormatConfig -> Context
member WithDummy: writerCommands: Queue<WriterEvent> * ?keepPageWidth: bool -> Context
member WithShortExpression: maxWidth: int * ?startColumn: int -> Context
member Column: int
Expand Down
10 changes: 2 additions & 8 deletions src/Fantomas.Core/FormatConfig.fs
Original file line number Diff line number Diff line change
Expand Up @@ -227,12 +227,7 @@ type FormatConfig =

[<Category("Convention")>]
[<DisplayName("Applies the Stroustrup style to the final (two) array or list argument(s) in a function application")>]
ExperimentalElmish: bool

[<Category("Convention")>]
[<DisplayName("Strict mode")>]
[<Description("Pretty printing based on ASTs only.\nPlease do not use this setting for formatting hand written code!")>]
StrictMode: bool }
ExperimentalElmish: bool }

member x.IsStroustrupStyle = x.MultilineBracketStyle = Stroustrup

Expand Down Expand Up @@ -273,5 +268,4 @@ type FormatConfig =
MultilineBracketStyle = Cramped
KeepMaxNumberOfBlankLines = 100
NewlineBeforeMultilineComputationExpression = true
ExperimentalElmish = false
StrictMode = false }
ExperimentalElmish = false }
2 changes: 1 addition & 1 deletion src/Fantomas.Core/Selection.fs
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ let formatSelection
MaxLineLength = maxLineLength }

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

match tree with
| TreeForSelection.Unsupported ->
Expand Down