繁体   English   中英

使用Roslyn替换跨度内的所有节点

[英]Using Roslyn to replace all nodes within span

我有大量生成的C#代码,希望使用Roslyn进行预处理,以帮助进行后续的手动重构。

该代码包含结构已知的开始和结束注释块,我需要将这些块之间的代码重构为方法。

幸运的是,生成的代码中的所有状态都是全局的,因此我们可以保证目标方法不需要任何参数。

例如,以下代码:

public void Foo()
{
    Console.WriteLine("Before block");

    // Start block
    var foo = 1;
    var bar = 2;
    // End block

    Console.WriteLine("After block");
}

应该转换为类似于以下内容的内容:

public void Foo()
{
    Console.WriteLine("Before block");

    TestMethod();

    Console.WriteLine("After block");
}

private void TestMethod()
{
    var foo = 1;
    var bar = 2;
}

显然,这是一个人为的例子。 单个方法可以具有任意数量的这些注释和代码块。

我研究了CSharpSyntaxRewriter并为这些注释提取了SyntaxTrivia对象的集合。 我的幼稚方法是重写VisitMethodDeclaration() ,确定代码在开始和结束注释块之间的范围,并以某种方式提取节点。

我已经能够使用node.GetText().Replace(codeSpan) ,但是我不知道如何使用结果。

我已经看到了许多使用CSharpSyntaxRewriter示例,但是所有这些示例似乎都很琐碎,并且不涉及涉及多个相关节点的重构。

使用DocumentEditor会更好吗? 这种重构是否有通用的方法?

我可能很懒,根本不使用Roslyn,但是结构化的代码解析似乎比正则表达式和将源视为纯文本更优雅。

我已经设法通过DocumentEditor获得了可喜的结果。

我的代码看起来像是有人通过SDK弄乱了他们的方式,反复试验,并且删除尾随注释的方法看起来非常笨拙,但是一切似乎都有效(至少对于简单的示例而言)。

这是概念的粗略证明。

public class Program
{
    static async Task Main()
    {
        var document = CreateDocument(@"..\..\..\TestClass.cs");

        var refactoredClass = await Refactor(document);
        Console.Write(await refactoredClass.GetTextAsync());
    }

    private static async Task<Document> Refactor(Document document)
    {
        var documentEditor = await DocumentEditor.CreateAsync(document);

        var syntaxRoot = await document.GetSyntaxRootAsync();
        var comments = syntaxRoot
            .DescendantTrivia()
            .Where(t => t.IsKind(SyntaxKind.SingleLineCommentTrivia))
            .ToList();

        // Identify comments which are used to target candidate code to be refactored
        var startComments = new Queue<SyntaxTrivia>(comments.Where(c => c.ToString().TrimEnd() == "// Start block"));
        var endBlock = new Queue<SyntaxTrivia>(comments.Where(c => c.ToString().TrimEnd() == "// End block"));

        // Identify class in target file
        var parentClass = syntaxRoot.DescendantNodes().OfType<ClassDeclarationSyntax>().First();

        var blockIndex = 0;

        foreach (var startComment in startComments)
        {
            var targetMethodName = $"TestMethod_{blockIndex}";

            var endComment = endBlock.Dequeue();

            // Create invocation for method containing refactored code
            var testMethodInvocation =
                ExpressionStatement(
                        InvocationExpression(
                            IdentifierName(targetMethodName)))
                    .WithLeadingTrivia(Whitespace("\n"))
                    .WithTrailingTrivia(Whitespace("\n\n"));

            // Identify nodes between start and end comments, recursing only for nodes outside comments
            var nodes = syntaxRoot.DescendantNodes(c => c.SpanStart <= startComment.Span.Start)
                .Where(n =>
                    n.Span.Start > startComment.Span.End &&
                    n.Span.End < endComment.SpanStart)
                .Cast<StatementSyntax>()
                .ToList();

            // Construct list of nodes to add to target method, removing starting comment
            var targetNodes = nodes.Select((node, nodeIndex) => nodeIndex == 0 ? node.WithoutLeadingTrivia() : node).ToList();

            // Remove end comment trivia which is attached to the node after the nodes we have refactored
            // FIXME this is nasty and doesn't work if there are no nodes after the end comment
            var endCommentNode = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.SpanStart > nodes.Last().Span.End && n is StatementSyntax);
            if (endCommentNode != null) documentEditor.ReplaceNode(endCommentNode, endCommentNode.WithoutLeadingTrivia());

            // Create target method, containing selected nodes
            var testMethod =
                MethodDeclaration(
                        PredefinedType(
                            Token(SyntaxKind.VoidKeyword)),
                        Identifier(targetMethodName))
                    .WithModifiers(
                        TokenList(
                            Token(SyntaxKind.PublicKeyword)))
                    .WithBody(Block(targetNodes))
                    .NormalizeWhitespace()
                    .WithTrailingTrivia(Whitespace("\n\n"));

            // Add method invocation
            documentEditor.InsertBefore(nodes.Last(), testMethodInvocation);

            // Remove nodes from main method
            foreach (var node in nodes) documentEditor.RemoveNode(node);

            // Add new method to class
            documentEditor.InsertMembers(parentClass, 0, new List<SyntaxNode> { testMethod });

            blockIndex++;
        }

        // Return formatted document
        var updatedDocument = documentEditor.GetChangedDocument();
        return await Formatter.FormatAsync(updatedDocument);
    }

    private static Document CreateDocument(string sourcePath)
    {
        var workspace = new AdhocWorkspace();
        var projectId = ProjectId.CreateNewId();
        var versionStamp = VersionStamp.Create();
        var projectInfo = ProjectInfo.Create(projectId, versionStamp, "NewProject", "Test", LanguageNames.CSharp);
        var newProject = workspace.AddProject(projectInfo);

        var source = File.ReadAllText(sourcePath);
        var sourceText = SourceText.From(source);

        return workspace.AddDocument(newProject.Id, Path.GetFileName(sourcePath), sourceText);
    }
}

我很想看看我是否为此感到难过-我敢肯定还有更多优雅的方法可以做我想做的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM