将 SyntaxNode 重写为两个 SyntaxNode [英] Rewrite SyntaxNode to two SyntaxNodes

查看:50
本文介绍了将 SyntaxNode 重写为两个 SyntaxNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Roslyn 的 CSharpSyntaxRewriter重写以下内容:

I'm using Roslyn's CSharpSyntaxRewriter to rewrite the following:

string myString = "Hello ";
myString += "World!";

到:

string myString = "Hello ";
myString += "World!"; Log("myString", myString);

我的语法重写器重写了 VisitAssignmentExpression 如下.

My syntax rewriter overrides VisitAssignmentExpression as follows.

public override SyntaxNode VisitAssignmentExpression(AssignmentExpressionSyntax node)
{
    //Construct a new node without trailing trivia
    var newNode = node.WithoutTrailingTrivia();
    InvocationExpressionSyntax invocation = //Build proper invocation

    //Now what? I need to bundle up newNode and invocation and return them
    //as an expression syntax
}

在处理 StatementSyntax 时,我已经能够通过构造一个缺少大括号的 BlockSyntax 来欺骗"这个限制:

I have been able to "cheat" this limitation when dealing with StatementSyntax by constructing a BlockSyntax with missing braces:

var statements = new SyntaxList<StatementSyntax>();
//Tried bundling newNode and invocation together
statements.Add(SyntaxFactory.ExpressionStatement(newNode));
statements.Add(SyntaxFactory.ExpressionStatement(invocation));
var wrapper = SyntaxFactory.Block(statements);

//Now we can remove the { and } braces
wrapper = wrapper.WithOpenBraceToken(SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken))
    .WithCloseBraceToken(SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken)

然而,这种方法不适用于 AssignmentExpressionSyntax,因为 BlockSyntax 不能转换为 ExpressionSyntax.(CSharpSyntaxRewriter 试图让这个演员.)

However this approach won't work with AssignmentExpressionSyntax as BlockSyntax cannot be cast to ExpressionSyntax. (The CSharpSyntaxRewriter tries to make this cast.)

如何将一个 SyntaxNode 重写为两个 SyntaxNode?

How can I rewrite one SyntaxNode into two SyntaxNodes?

我是否遇到过 API 的限制,或者是否有任何与上述类似的技巧可以分享?

Have I run up against a limitation of the API, or are there any tricks similar to the above that someone could share?

推荐答案

您需要访问父 ExpressionStatementSyntax 并将其替换为 BlockSyntax.

You need to visit the parent ExpressionStatementSyntax and replace that with a BlockSyntax.

您不能在表达式语句中插入 BlockSyntax 作为表达式.

You cannot insert a BlockSyntax as an expression in an expression statement.

这篇关于将 SyntaxNode 重写为两个 SyntaxNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆