Skip to content

Commit

Permalink
Allow char constants in C# interpolated strings
Browse files Browse the repository at this point in the history
  • Loading branch information
tats-u committed Mar 20, 2024
1 parent c0d7b49 commit d7d542f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,17 @@ private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSynta
if (!isResultConstant ||
value.ConstantValueOpt == null ||
!(interpolation is { FormatClause: null, AlignmentClause: null }) ||
!(value.ConstantValueOpt is { IsString: true, IsBad: false }))
!(value.ConstantValueOpt is { IsBad: false } and ({ IsString: true } or { IsChar: true })))
{
isResultConstant = false;
continue;
}
ConstantValue valueConstantValueOpt = value.ConstantValueOpt.IsChar
? ConstantValue.Create(value.ConstantValueOpt.CharValue.ToString())
: value.ConstantValueOpt;
resultConstant = (resultConstant is null)
? value.ConstantValueOpt
: FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValueOpt);
? valueConstantValueOpt
: FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, valueConstantValueOpt);
continue;
}
case SyntaxKind.InterpolatedStringText:
Expand Down
23 changes: 23 additions & 0 deletions src/Compilers/CSharp/Test/Semantic/Semantics/InterpolationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18478,6 +18478,29 @@ .maxstack 1
IL_0005: call ""void System.Console.Write(string)""
IL_000a: ret
}}
");
}
[Theory]
[InlineData(@"$""{'c'}""", "c")]
[InlineData(@"$""{$""{'c'}h""}ar""", "char")]
public void CharConstantToConstString(string expression, string output)
{
var code = @"
const string expression = " + expression + @";
System.Console.Write(expression);";

var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });

var verifier = CompileAndVerify(comp, expectedOutput: output);

verifier.VerifyIL("<top-level-statements-entry-point>", @$"
{{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""{output}""
IL_0005: call ""void System.Console.Write(string)""
IL_000a: ret
}}
");
}
}
Expand Down

0 comments on commit d7d542f

Please sign in to comment.