Karwos
Karwos

Reputation: 13

Formatting code after rewriting C# Roslyn

I'm trying to make rewriter using CSharpSyntaxRewriter that change, whenever it appear,

YIELD(variable); 

into

foreach (var item in variable)
{
  yield return item;
}

but it change

        public static string Upper(string s)
        {
            YIELD(variable);
        }

into this

    public static string Upper(string s)
        {
            foreach (var item in variable)
{
    yield return item;
}
        }

Here is some of my

if (@"YIELD".Equals(expression_name.Identifier.ValueText, StringComparison.Ordinal))
{
    var argumentName = (ArgumentSyntax)expression.Parent.ChildNodes().OfType<ArgumentListSyntax>().FirstOrDefault()?.ChildNodes().FirstOrDefault();

    var myExpression = SyntaxFactory.ForEachStatement(
        SyntaxFactory.IdentifierName("var"),
        "item",
        argumentName.Expression,
        SyntaxFactory.Block(
                SyntaxFactory.YieldStatement(
                    SyntaxKind.YieldReturnStatement,
                    SyntaxFactory.IdentifierName("item")))
        ).NormalizeWhitespace().WithLeadingTrivia(leadingTrivia);

    node = node.ReplaceNode(
        expressionStatment,
        Enumerable.Repeat(myExpression.WithTrailingTrivia(SyntaxFactory.EndOfLine(Environment.NewLine)), 1));
}

I've tried to add Leading Trivia to Block in myExpression, but it didn't work.

Upvotes: 1

Views: 1162

Answers (1)

SJP
SJP

Reputation: 1010

The reason why your foreach statement is not indented is because you call NormalizeWhitespace in the wrong place. When you call it on a single note you will format said note without the context of the remaining syntax tree, so basically you're only formatting the following which you then paste into the existing code:

foreach (var item in variable)
{
    yield return item;
}

If you however execute .NormalizeWhitespace() on the root of the syntax tree (after you modified it of course) you format the entire tree which should result in the correct formatting.

Upvotes: 1

Related Questions