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

Fix NormalizeWhitespace - String Interpolation with e.g. Initializer-expressions #51213

Merged
merged 9 commits into from
Feb 19, 2021
25 changes: 25 additions & 0 deletions src/Compilers/CSharp/Portable/Syntax/SyntaxNormalizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ internal class SyntaxNormalizer : CSharpSyntaxRewriter

private bool _afterLineBreak;
private bool _afterIndentation;
private bool _inSingleLineInterpolation;

// CONSIDER: if we become concerned about space, we shouldn't actually need any
// of the values between indentations[0] and indentations[initialDepth] (exclusive).
Expand Down Expand Up @@ -177,6 +178,11 @@ private static bool NeedsIndentAfterLineBreak(SyntaxToken token)

private int LineBreaksAfter(SyntaxToken currentToken, SyntaxToken nextToken)
{
if (_inSingleLineInterpolation)
{
return 0;
}

if (currentToken.IsKind(SyntaxKind.EndOfDirectiveToken))
{
return 1;
Expand Down Expand Up @@ -915,5 +921,24 @@ node is QueryExpressionSyntax ||

return 0;
}

public override SyntaxNode? VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node)
{
if (node.StringStartToken.Kind() == SyntaxKind.InterpolatedStringStartToken)
bernd5 marked this conversation as resolved.
Show resolved Hide resolved
{
var old = _inSingleLineInterpolation;
_inSingleLineInterpolation = true;
try
{
return base.VisitInterpolatedStringExpression(node);
}
finally
{
_inSingleLineInterpolation = old;
}
}

return base.VisitInterpolatedStringExpression(node);
}
}
}
12 changes: 12 additions & 0 deletions src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxFactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,18 @@ public void TestSpacingOnTernary()
Assert.Equal("x is DateTime ? y : z", syntaxNode2.ToFullString());
}

[Fact]
[WorkItem(50742, "https://github.com/dotnet/roslyn/issues/50742")]
public void TestLineBreakInterpolations()
{
var code = @"$""Printed: { new Printer() { TextToPrint = ""Hello world!"" }.PrintedText }""";

var syntaxNode = SyntaxFactory.ParseExpression(code).NormalizeWhitespace();
var aText = syntaxNode.ToFullString();
bernd5 marked this conversation as resolved.
Show resolved Hide resolved

Assert.True(!aText.Contains('\n'));
bernd5 marked this conversation as resolved.
Show resolved Hide resolved
}

[Fact]
[WorkItem(21231, "https://github.com/dotnet/roslyn/issues/21231")]
public void TestSpacingOnCoalescing()
Expand Down