-
Notifications
You must be signed in to change notification settings - Fork 866
Implement interpolated strings via String.Concat #19971
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
11
commits into
dotnet:main
Choose a base branch
from
charlesroddie:InterpolatedStringCollector
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
11 commits
Select commit
Hold shift + click to select a range
f571df9
Lower string-typed interpolation to String.Concat (reflection-free)
charlesroddie 423d007
Add release notes for interpolated string String.Concat lowering
charlesroddie c7beb02
tidy
charlesroddie 1951198
Lower string interpolation by type-checking each part in place
charlesroddie 3d5bb3d
cleanup
charlesroddie 5eae16c
Pass a bare %s through as a string instead of via sprintf
charlesroddie b278961
%s is AOT compatible now
charlesroddie e83ddfb
Type-check formatted interpolation holes only once
charlesroddie 6112fd2
Lower bare %c/%d/%i/%M interpolation holes to String.Concat
charlesroddie 7d2a246
Check NativeAOT interpolated-string output against expected values
charlesroddie e87b12f
Add EmittedIL tests for interpolation cases not optimized before
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
234 changes: 122 additions & 112 deletions
234
src/Compiler/Checking/Expressions/CheckExpressions.fs
Large diffs are not rendered by default.
Oops, something went wrong.
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 |
|---|---|---|
|
|
@@ -69,6 +69,50 @@ let rhs2 (parseState: IParseState) i j = | |
| /// Get the range corresponding to one of the r.h.s. symbols of a grammar rule while it is being reduced | ||
| let rhs parseState i = rhs2 parseState i i | ||
|
|
||
| /// Split a trailing printf specifier (e.g. "%d") off an interpolated-string literal that precedes a | ||
| /// hole. '%%' is a literal escape, not a specifier. | ||
| let peelTrailingPrintfSpecifier (litText: string) : string * string option = | ||
| let n = litText.Length | ||
| let mutable i = 0 | ||
| let mutable specStart = -1 | ||
|
|
||
| while i < n && specStart < 0 do | ||
| if litText[i] = '%' then | ||
| if i + 1 < n && litText[i + 1] = '%' then | ||
| i <- i + 2 // '%%' escape, keep scanning | ||
| else | ||
| specStart <- i // start of a real specifier | ||
| else | ||
| i <- i + 1 | ||
|
|
||
| // A real printf specifier ends, immediately before the hole, with a type character. Anything else | ||
| // (for example the explicit '%P(' placeholder syntax) is left in the literal untouched. | ||
| if specStart < 0 || "bscdiuxXoBeEfFgGMOAat".IndexOf litText[n - 1] < 0 then | ||
| litText, None | ||
| else | ||
| litText[.. specStart - 1], Some litText[specStart..] | ||
|
Comment on lines
+72
to
+93
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. I would love if we could have this logic inside the |
||
|
|
||
| /// Build the [String literal; FillExpr hole] pair for one interpolation hole, splitting the '{x,n}' | ||
| /// alignment out of its tuple encoding and peeling a trailing printf specifier onto the hole. | ||
| let mkInterpolatedStringFillParts (litText: string, litRange: range, fill: SynExpr * Ident option) = | ||
| let fillExpr, qualifier = fill | ||
|
|
||
| let holeExpr, alignment = | ||
| match fillExpr with | ||
| | SynExpr.Tuple(false, [ e; (SynExpr.Const(SynConst.Int32 _, _) as n) ], _, _) -> e, Some n | ||
| | _ -> fillExpr, None | ||
|
|
||
| let litValue, formatting = | ||
| match qualifier, alignment with | ||
| | None, None -> | ||
| match peelTrailingPrintfSpecifier litText with | ||
| | lit, Some spec -> lit, SynInterpolationFormatting.Printf(spec, litRange) | ||
| | _, None -> litText, SynInterpolationFormatting.DotNet(None, None) | ||
| | _ -> litText, SynInterpolationFormatting.DotNet(alignment, qualifier) | ||
|
|
||
| [ SynInterpolatedStringPart.String(litValue, litRange) | ||
| SynInterpolatedStringPart.FillExpr(holeExpr, formatting) ] | ||
|
|
||
| //------------------------------------------------------------------------ | ||
| // Parsing/lexing: status of #if/#endif processing in lexing, used for continuations | ||
| // for whitespace tokens in parser specification. | ||
|
|
||
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
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
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
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
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 |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFrameworks>net9.0</TargetFrameworks> | ||
| <LangVersion>preview</LangVersion> | ||
| <TreatWarningsAsErrors>true</TreatWarningsAsErrors> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup> | ||
| <DisableImplicitFSharpCoreReference>true</DisableImplicitFSharpCoreReference> | ||
| <DisableImplicitNuGetFallbackFolder>true</DisableImplicitNuGetFallbackFolder> | ||
| <DisableImplicitLibraryPacksFolder>true</DisableImplicitLibraryPacksFolder> | ||
| <PublishAot>true</PublishAot> | ||
| <RuntimeIdentifier>win-x64</RuntimeIdentifier> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup> | ||
| <FSharpBuildAssemblyFile>$(LocalFSharpBuildBinPath)/FSharp.Build.dll</FSharpBuildAssemblyFile> | ||
| <DotnetFscCompilerPath>$(LocalFSharpBuildBinPath)/fsc.dll</DotnetFscCompilerPath> | ||
| <Fsc_DotNET_DotnetFscCompilerPath>$(LocalFSharpBuildBinPath)/fsc.dll</Fsc_DotNET_DotnetFscCompilerPath> | ||
| <FSharpPreferNetFrameworkTools>False</FSharpPreferNetFrameworkTools> | ||
| <FSharpPrefer64BitTools>True</FSharpPrefer64BitTools> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <Compile Include="Program.fs" /> | ||
| </ItemGroup> | ||
|
|
||
| <Import Project="$(MSBuildThisFileDirectory)../../../eng/Versions.props" /> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="FSharp.Core" Version="$(FSharpCorePreviewPackageVersionValue)" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
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 |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| module Program | ||
|
|
||
| open System | ||
|
|
||
| // Check a rendering against an expected string literal; a mismatch prints a "FAILED" line. | ||
| let check (actual: string, expected: string) = | ||
| if actual <> expected then | ||
| Console.WriteLine $"FAILED: expected '{expected}' but got '{actual}'" | ||
|
|
||
| let runChecks () = | ||
| let x = 42 | ||
| let name = "world" | ||
| let pi = 3.14159 | ||
| let initial = 'F' | ||
| check ($"answer = {x}", "answer = 42") | ||
| check ($"hello {name}", "hello world") | ||
| check ($"pi ~ {pi:F2}", "pi ~ 3.14") | ||
| check ($"padded:{x,6}", "padded: 42") | ||
| check ($"greeting %s{name}", "greeting world") | ||
| // Bare '%d'/'%i'/'%c'/'%M' specifiers lower to the same reflection-free path as a plain hole. | ||
| check ($"answer = %d{x}", "answer = 42") | ||
| check ($"initial = %c{initial}", "initial = F") | ||
|
|
||
| // The following use printf specifiers that still route through 'sprintf', so they would make the | ||
| // NativeAOT publish fail with IL2026/IL2070/IL3050. | ||
| // check ($"pi ~ %.2f{pi}", "pi ~ 3.14") | ||
| // check ($"value = %A{x}", "value = 42") | ||
|
|
||
| [<EntryPoint>] | ||
| let main _ = | ||
| runChecks () | ||
| // Success sentinel; a failed check above printed a "FAILED" line first, so the output won't be just this. | ||
| Console.WriteLine "Finished" | ||
| 0 |
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 |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| @echo off | ||
| powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0check.ps1"""" |
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 |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| # Publish the test project with NativeAOT and check that it runs. | ||
| # | ||
| # The point of this check is that the publish succeeds: a string-typed interpolated string | ||
| # must lower to a reflection-free form (System.String.Concat), not the reflection-based | ||
| # printf engine. If it regresses to printf, FSharp.Reflection becomes statically reachable, | ||
| # NativeAOT analysis emits IL2026/IL2070/IL3050, TreatWarningsAsErrors turns them into errors, | ||
| # and this publish fails. | ||
|
|
||
| $ErrorActionPreference = "Stop" | ||
|
|
||
| $root = "NativeAOT_Test" | ||
| $tfm = "net9.0" | ||
|
|
||
| $cwd = Get-Location | ||
| Set-Location $PSScriptRoot | ||
|
|
||
| dotnet publish -restore -c release -f:$tfm "$root.fsproj" -bl:"$PSScriptRoot/../../../artifacts/log/Release/AheadOfTime/NativeAOT/$root.binlog" | ||
| if (-not ($LASTEXITCODE -eq 0)) { | ||
| Set-Location $cwd | ||
| Write-Error "NativeAOT publish failed with exit code $LASTEXITCODE" -ErrorAction Stop | ||
| } | ||
|
|
||
| $exe = Join-Path $PSScriptRoot "bin/release/$tfm/win-x64/publish/$root.exe" | ||
| $output = (& $exe) -join "`n" | ||
| $exitCode = $LASTEXITCODE | ||
| Set-Location $cwd | ||
|
|
||
| # The app prints a "FAILED" line per mismatch and "Finished" last, so its output is exactly "Finished" only if all checks passed. | ||
| if (-not ($exitCode -eq 0)) { | ||
|
T-Gro marked this conversation as resolved.
|
||
| Write-Error "NativeAOT app crashed with exit code $exitCode.`nOutput:`n$output" -ErrorAction Stop | ||
| } | ||
|
|
||
| if ($output.Trim() -ne "Finished") { | ||
| Write-Error "NativeAOT interpolation checks failed.`nOutput:`n$output" -ErrorAction Stop | ||
| } | ||
|
|
||
| Write-Host "NativeAOT interpolated-string test passed." | ||
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 |
|---|---|---|
|
|
@@ -2,3 +2,4 @@ Write-Host "AheadOfTime: check1.ps1" | |
|
|
||
| Equality\check.ps1 | ||
| Trimming\check.ps1 | ||
| NativeAOT\check.ps1 | ||
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.