This project is read-only.
1

Resolved

Spaces are trimmed after rewriting

description

Space between left expression and operator ('+', '/', '*', 'as' ) could be trimmed if you replace SyntaxNode complitelly

Rewriter code:
internal class ExperimentalRewriter : CSharpSyntaxRewriter
{
    public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
    {
        var rootIdentifier = node.DescendantNodes().OfType<IdentifierNameSyntax>().FirstOrDefault();
        if (null != rootIdentifier && rootIdentifier.Identifier.Text == "node")
        {
            SyntaxNode res = this.Visit(node.Expression);
            // doesn't matter if it is one or more char between expr and name 
            var replaced = string.Format("{0}?.{1}", res, node.Name);
            var expr = SyntaxFactory.ParseExpression(replaced);
            node.CopyAnnotationsTo(expr);
            return expr;
        }

        return base.VisitMemberAccessExpression(node);
    }
}
Full code with tests:
https://gist.github.com/alexeysuvorov/276e7e93a8ec8025cfb4

Workaround is manually adding spacebar after expression (will be trimmed in case of A.B.C.D)
 SyntaxNode res = this.Visit(node.Expression);
 // doesn't matter if it is one or more char between expression and name 
 var replaced = string.Format("{0}?.{1} ", res, node.Name);
 var expr = SyntaxFactory.ParseExpression(replaced);

comments

Zarat wrote Nov 5, 2014 at 3:24 PM

Isn't that the intended behavior? If whitespace is attached to the node you are replacing, and you replace it with a node without whitespace (and don't reformat), then of course the whitespace is gone.

Note that it is by design that whitespace is attached to syntax nodes instead of being placed "between" syntax nodes.

You can retrieve the whitespace attached to the node you want to replace by calling GetLeadingTrivia and GetTrailingTrivia and attach it to the replacement node via WithLeadingTrivia and WithTrailingTrivia.

(Of course there are alternatives to manually preserving the whitespace, like auto-formatting or automatic insertion of whitespace etc.)

VSadov wrote Nov 6, 2014 at 11:25 PM

Yes that is ByDesign. The whitespace is always attached to a token and a token is attached to a node. So when node is removed it takes all constituent tokens and whitespace with it.