-
Notifications
You must be signed in to change notification settings - Fork 867
Compiled ToStrings under -reflectionfree for DUs and Records #19976
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
Open
charlesroddie
wants to merge
26
commits into
dotnet:main
Choose a base branch
from
charlesroddie:DUsRecordsCompiledToStrings
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
4e8c86c
Add a compiler intrinsic for the 'string' operator
charlesroddie 1d5769c
Generate a match-based ToString for unions under --reflectionfree
charlesroddie bfb3939
Extract mkStringConcat helper for arity-dispatched String.Concat
charlesroddie e5710fa
Fix generated union ToString for generic unions
charlesroddie d5712c8
Render union ToString fields like option (null -> "null")
charlesroddie 26f0e53
Tidy reflection-free union ToString tests
charlesroddie 87e6870
Add reflection-free ToString to Result and Choice
charlesroddie 956a4b0
Generate a single-line ToString for records under --reflectionfree
charlesroddie a021166
Update FSharp.Core surface-area baselines for Result/Choice ToString
charlesroddie 8eef294
Add release notes
charlesroddie 3754def
Generate a single-line ToString for anonymous records under --reflect…
charlesroddie a5f33ca
Test that a hand-written ToString override is kept under --reflection…
charlesroddie 7ed0d8d
Rename ToString generators for clarity
charlesroddie dd3d75c
Restore tabular layout for string_operator_info in TcGlobals
charlesroddie 1a5065e
Add reflection-free ToString tests for field shapes, structs, anon re…
charlesroddie 2c108ed
Add EmittedIL tests for reflection-free record and union ToString
charlesroddie 6a2199c
Generate reflection-free ToString in the augmentation phase
charlesroddie 474b9f9
Guard generated reflection-free ToString against deep-recursion overflow
charlesroddie e130e50
Test the reflection-free ToString deep-recursion guard
charlesroddie 6e276b1
revert ToString additions to fsharp.core types
charlesroddie e3c1a34
Remove stale FSharp.Core release note for the reverted Result/Choice …
charlesroddie 93ee8ce
Merge remote-tracking branch 'upstream/main' into DUsRecordsCompiledT…
charlesroddie dcb4fc3
Merge branch 'main' into DUsRecordsCompiledToStrings
charlesroddie c4debaf
Merge branch 'main' into DUsRecordsCompiledToStrings
charlesroddie 817e9de
Fix code formatting in IlxGen.fs (dotnet fantomas)
charlesroddie 770601f
Merge branch 'main' into DUsRecordsCompiledToStrings
charlesroddie File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -81,6 +81,9 @@ let mkGetHashCodeSlotSig (g: TcGlobals) = | |
| let mkEqualsSlotSig (g: TcGlobals) = | ||
| TSlotSig("Equals", g.obj_ty_noNulls, [], [], [ [ TSlotParam(Some("obj"), g.obj_ty_withNulls, false, false, false, []) ] ], Some g.bool_ty) | ||
|
|
||
| let mkToStringSlotSig (g: TcGlobals) = | ||
| TSlotSig("ToString", g.obj_ty_noNulls, [], [], [ [] ], Some g.string_ty) | ||
|
|
||
| //------------------------------------------------------------------------- | ||
| // Helpers associated with code-generation of comparison/hash augmentations | ||
| //------------------------------------------------------------------------- | ||
|
|
@@ -112,6 +115,9 @@ let mkEqualsWithComparerTyExact g ty = | |
| let mkHashTy g ty = | ||
| mkFunTy g (mkThisTy g ty) (mkFunTy g g.unit_ty g.int_ty) | ||
|
|
||
| let mkToStringTy (g: TcGlobals, ty: TType) = | ||
| mkFunTy g (mkThisTy g ty) (mkFunTy g g.unit_ty g.string_ty) | ||
|
|
||
| let mkHashWithComparerTy g ty = | ||
| mkFunTy g (mkThisTy g ty) (mkFunTy g g.IEqualityComparer_ty g.int_ty) | ||
|
|
||
|
|
@@ -1697,3 +1703,141 @@ let MakeBindingsForUnionAugmentation g (tycon: Tycon) (vals: ValRef list) = | |
| let isdata = mkUnionCaseTest g (thise, ucr, tinst, m) | ||
| let expr = mkLambdas g m tps [ thisv; unitv ] (isdata, g.bool_ty) | ||
| mkCompGenBind v.Deref expr) | ||
|
|
||
| //------------------------------------------------------------------------- | ||
| // Build reflection-free ToString functions for union and record types. | ||
| // | ||
| // Under --reflectionfree the reflective 'sprintf "%+A"' ToString is unavailable, so we build a structural | ||
| // one here (during type augmentation, so the 'string' operator calls flow through the optimizer and get | ||
| // specialised - e.g. an int field renders via a direct, allocation-free ToString rather than a boxed call). | ||
| //------------------------------------------------------------------------- | ||
|
|
||
| // Render one field value as a string the way option/list do (LanguagePrimitives.anyToStringShowingNull): | ||
| // a null reference renders as "null", everything else via the 'string' operator. A value-type field can | ||
| // never be null, so it skips the box+null-guard and renders directly. | ||
| let mkFieldToString (g: TcGlobals, m: Text.range, fe: Expr) = | ||
| let fieldTy = tyOfExpr g fe | ||
|
|
||
| if isStructTy g fieldTy then | ||
| mkCallStringOperator g m fieldTy fe | ||
| else | ||
| let v, ve = mkCompGenLocal m "field" fieldTy | ||
| mkCompGenLet m v fe (mkNonNullCond g m g.string_ty (mkCallBox g m fieldTy ve) (mkCallStringOperator g m fieldTy ve) (mkString g m "null")) | ||
|
|
||
| // A record's ToString as a single line "{ F1 = v1; F2 = v2 }" (no line breaks, unlike "%+A"). | ||
| // openBrace/closeBrace are "{ "/" }" for records and "{| "/" |}" for anonymous records. | ||
| let mkRecdToString (g: TcGlobals, tcref: TyconRef, tycon: Tycon, openBrace: string, closeBrace: string) = | ||
| let m = tycon.Range | ||
| let tinst, ty = mkMinimalTy g tcref | ||
| let thisv, thise = mkThisVar g m ty | ||
|
|
||
| let fieldParts = | ||
| tcref.AllInstanceFieldsAsList | ||
| |> List.mapi (fun i fspec -> | ||
| let fref = tcref.MakeNestedRecdFieldRef fspec | ||
| let value = mkFieldToString (g, m, mkRecdFieldGetViaExprAddr (thise, fref, tinst, m)) | ||
| let nameEq = mkString g m (fspec.DisplayName + " = ") | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
type U = ``My Case`` of int
// %A : My Case 5
// --reflectionfree : ``My Case``(5)Suggestion: use |
||
| if i = 0 then [ nameEq; value ] else [ mkString g m "; "; nameEq; value ]) | ||
| |> List.concat | ||
|
|
||
| let parts = mkString g m openBrace :: fieldParts @ [ mkString g m closeBrace ] | ||
| thisv, mkStringConcat (g, m, parts) | ||
|
|
||
| // A union's ToString as a match over the cases building "CaseName(f0, f1, ...)" (or just "CaseName" for a | ||
| // nullary case). | ||
| let mkUnionToString (g: TcGlobals, tcref: TyconRef, tycon: Tycon) = | ||
| let m = tycon.Range | ||
| let tinst, ty = mkMinimalTy g tcref | ||
| let thisv, thise = mkThisVar g m ty | ||
| let mbuilder = MatchBuilder(DebugPointAtBinding.NoneAtInvisible, m) | ||
|
|
||
| let mkResult (ucase: UnionCase) = | ||
| let cref = tcref.MakeNestedUnionCaseRef ucase | ||
| let rfields = ucase.RecdFields | ||
|
|
||
| if isNil rfields then | ||
| mkString g m ucase.DisplayName | ||
| else | ||
| // provene is an expression proven to be of this case (the value itself for struct unions, | ||
| // otherwise a 'UnionCaseProof'), from which fields can be read. | ||
| let mkBody (provene: Expr) = | ||
| let fieldStrs = | ||
| rfields | ||
| |> List.mapi (fun j _ -> mkFieldToString (g, m, mkUnionCaseFieldGetProvenViaExprAddr (provene, cref, tinst, j, m))) | ||
|
|
||
| let sep = mkString g m ", " | ||
|
|
||
| let fieldsWithSeps = | ||
| fieldStrs |> List.mapi (fun i fe -> if i = 0 then [ fe ] else [ sep; fe ]) |> List.concat | ||
|
|
||
| let parts = mkString g m (ucase.DisplayName + "(") :: fieldsWithSeps @ [ mkString g m ")" ] | ||
| mkStringConcat (g, m, parts) | ||
|
|
||
| if cref.Tycon.IsStructOrEnumTycon then | ||
| mkBody thise | ||
| else | ||
| let ucv, ucve = mkCompGenLocal m "thisCast" (mkProvenUnionCaseTy cref tinst) | ||
| mkCompGenLet m ucv (mkUnionCaseProof (thise, cref, tinst, m)) (mkBody ucve) | ||
|
|
||
| let cases = | ||
| tcref.UnionCasesAsList | ||
| |> List.map (fun ucase -> | ||
| let cref = tcref.MakeNestedUnionCaseRef ucase | ||
| mkCase (DecisionTreeTest.UnionCase(cref, tinst), mbuilder.AddResultTarget(mkResult ucase))) | ||
|
|
||
| let dtree = TDSwitch(thise, cases, None, m) | ||
| thisv, mbuilder.Close(dtree, m, g.string_ty) | ||
|
|
||
| let TyconIsCandidateForAugmentationWithToString (g: TcGlobals, tycon: Tycon) = | ||
| g.useReflectionFreeCodeGen && (tycon.IsUnionTycon || tycon.IsRecordTycon) | ||
|
|
||
| let MakeValsForToStringAugmentation (g: TcGlobals, tcref: TyconRef) = | ||
| let _, ty = mkMinimalTy g tcref | ||
| let vis = tcref.Accessibility | ||
| let tps = tcref.Typars | ||
| mkValSpec g tcref ty vis (Some(mkToStringSlotSig g)) "ToString" (tps +-> (mkToStringTy (g, ty))) unitArg false | ||
|
|
||
| let MakeBindingsForToStringAugmentation (g: TcGlobals, tycon: Tycon, toStringVal: Val) = | ||
| let tcref = mkLocalTyconRef tycon | ||
| let m = tycon.Range | ||
| let tps = tycon.Typars | ||
|
|
||
| let thisv, body = | ||
| if tycon.IsUnionTycon then | ||
| mkUnionToString (g, tcref, tycon) | ||
| else | ||
| mkRecdToString (g, tcref, tycon, "{ ", " }") | ||
|
|
||
| let mightRecurse = | ||
| let isPrimitive (ty: TType) = | ||
| isIntegerTy g ty | ||
| || isFpTy g ty | ||
| || isDecimalTy g ty | ||
| || isStringTy g ty | ||
| || typeEquiv g g.char_ty ty | ||
| || isBoolTy g ty | ||
| || isUnitTy g ty | ||
| || isEnumTy g ty | ||
|
|
||
| let fieldTys = | ||
| if tycon.IsUnionTycon then | ||
| tycon.UnionCasesAsList |> List.collect (fun uc -> uc.RecdFields) |> List.map (fun rf -> rf.FormalType) | ||
| else | ||
| tycon.AllInstanceFieldsAsList |> List.map (fun rf -> rf.FormalType) | ||
|
|
||
| fieldTys |> List.exists (isPrimitive >> not) | ||
|
|
||
| // Guard deep recursion with a catchable exception, as C# records' PrintMembers do, when the runtime provides it. | ||
| let body = | ||
| if mightRecurse then | ||
| match g.TryFindSysILTypeRef "System.Runtime.CompilerServices.RuntimeHelpers" with | ||
| | Some tref -> | ||
| let mspec = mkILNonGenericStaticMethSpecInTy (mkILNonGenericBoxedTy tref, "EnsureSufficientExecutionStack", [], ILType.Void) | ||
| mkSequential m (mkAsmExpr ([ mkNormalCall mspec ], [], [], [], m)) body | ||
| | None -> body | ||
| else | ||
| body | ||
|
|
||
| let unitv, _ = mkCompGenLocal m "unitArg" g.unit_ty | ||
| let expr = mkLambdas g m tps [ thisv; unitv ] (body, g.string_ty) | ||
| [ mkCompGenBind toStringVal expr ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
--reflectionfreerendering diverges from%+Ain enough ways to be worth documenting/announcing as acceptance wording. Not release-note material — suggest a durabledocs/reflectionfree-printing.mdthis note can link to. Also currently omits anonymous records.%+A(default)--reflectionfree{ X = 1; Y = 2 }{ X = 1⏎Y = 2 }{ X = 1; Y = 2 }B 5B 5B(5)C (3, "hi")C (3, "hi")C(3, hi)Wrap "hi"Wrap "hi"Wrap(hi)'a'a{ P = None }Nonenull{ A = [|1;2;3|] }[|1; 2; 3|]System.Int32[]{ V = ValueSome 2 }ValueSome 22U ()U ()U(null)5.05.05250uy/42n/1.5M250uy/42n/1.5M250/42/1.5[<StructuredFormatDisplay("Custom<{X}>")>]Custom<5>{ X = 5 }(ignored)``My Case`` 5My Case 5``My Case``(5)(see AugmentWithHashCompare comment)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It could go to https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/plaintext-formatting#a-formatting to communicate the differences.
I also want the table in this PR so that people can come in and express how acceptable the differences are (vs building on top of this PR and replicating reflection-based
%Ain codegen by switching over field type).(pinging people who interacted with this PR: @kerams , @ShalokShalom , @smoothdeveloper , @jwosty )
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think quotes should be preserved around strings so that there is no ambiguity without consulting the type's shape.
If we had something like tostring levels, then we could choose how complex the emission should be (should
ToStringgenerate code to iterate over a portion of any collection?). Then again, with--reflectionfreepeople supposedly care more about AOT than these strings, and one can always write a customToString, so maybe adding levels to this is needless complexity.