用Roslyn中的节点替换琐事

时间:2016-07-17 20:02:48

标签: c# parsing roslyn

例如,我在C#代码文件中有以下文档注释:

/// add k+5

我想用节点

REPLACE
_tst.AddElement(k+5);

我怎样才能使用C#/ Roslyn?我已经找到了如何添加这一行,但没有找到如何替换。我添加节点的代码:

public static MethodDeclarationSyntax getChangedNode(MethodDeclarationSyntax method)
{
    var newmethod = method;
    var TestEntryArgName = "_tst";

    /* Adding _tst.AddElement(i); */
    foreach (var s in newmethod.Body.DescendantNodes())
    {
        SyntaxTrivia st = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ");
        bool fl = false;
        bool before = true;
        var lt = s.GetLeadingTrivia();

        foreach (var triviaEntry in lt)
        {
            if (triviaEntry.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia)
            {
                fl = true;
                st = triviaEntry;
                break;
            }
        }

        if (!fl)
        {
            lt = s.GetTrailingTrivia();
            before = false;
            foreach (var triviaEntry in lt)
            {
                if (triviaEntry.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia)
                {
                    fl = true;
                    st = triviaEntry;
                    break;
                }
            }
            if (!fl) continue;
        }

        var commentContents = st.ToString();
        char[] delim = { ' ', '\n', '\t', '\r' };
        var ar = commentContents.Split(delim, StringSplitOptions.RemoveEmptyEntries);
        if (ar.Length != 2 || ar[0] != "add") continue;

        var lineToAdd = TestEntryArgName + ".AddElement(" + ar[1] + ")";
        var linelist = new List<ExpressionStatementSyntax>();
        linelist.Add(SyntaxFactory.ExpressionStatement(SyntaxFactory.ParseExpression(lineToAdd)));

        var childlist = s.Parent.ChildNodes();

        foreach (var si in childlist)
        {
            if (s != si) continue;
            if (before) newmethod = newmethod.InsertNodesBefore(si, linelist);
            else newmethod = newmethod.InsertNodesAfter(si, linelist);
            break;
        }

        break;
    }

    return newmethod;
}

我需要在我的方法中替换所有这些注释。此函数仅插入节点,并且只执行一次。

编辑。在这一刻,我有以下解决方案,但它看起来太复杂而且不明显......

   public static MethodDeclarationSyntax getChangedNode(MethodDeclarationSyntax method)
    {
        var TestEntryArgName = "__tst";
        /* Adding last param */
        var parlist = method.ChildNodes().OfType<ParameterListSyntax>().First();
        var newparlist = parlist.AddParameters(SyntaxFactory.Parameter(
                                                                SyntaxFactory.Identifier(TestEntryArgName))
                                                                                .WithType(SyntaxFactory.ParseTypeName("Heap ")));
        var newmethod = method.ReplaceNode(parlist, newparlist);

        /* Adding __tst.AddElement(i); */
        while (true) {
            IEnumerable<SyntaxNode> desc;
            bool triviaFound;
            desc = newmethod.Body.DescendantNodes();
            triviaFound = false;
            foreach (var s in desc)
            {
                SyntaxTrivia st = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ");
                bool fl = false;
                bool before = true;
                var lt = s.GetLeadingTrivia();

                foreach (var triviaEntry in lt)
                {
                    if (triviaEntry.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia)
                    {
                        fl = true;
                        st = triviaEntry;
                        break;
                    }
                }

                if (!fl)
                {
                    lt = s.GetTrailingTrivia();
                    before = false;
                    foreach (var triviaEntry in lt)
                    {
                        if (triviaEntry.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia)
                        {
                            fl = true;
                            st = triviaEntry;
                            break;
                        }
                    }
                    if (!fl) continue;
                }

                var commentContents = st.ToString();
                char[] delim = { ' ', '\n', '\t', '\r' };
                var ar = commentContents.Split(delim, StringSplitOptions.RemoveEmptyEntries);
                if (ar.Length != 2 || ar[0] != "add") continue;

                var lineToAdd = TestEntryArgName + ".AddElement(" + ar[1] + ")";
                var linelist = new List<ExpressionStatementSyntax>();
                linelist.Add(SyntaxFactory.ExpressionStatement(SyntaxFactory.ParseExpression(lineToAdd)));

                var childlist = s.Parent.ChildNodes();

                foreach (var si in childlist)
                {
                    if (s != si) continue;
                    if (before) newmethod = newmethod.InsertNodesBefore(si, linelist);
                    else newmethod = newmethod.InsertNodesAfter(si, linelist);
                    break;
                }

                var newTrvias = newmethod.DescendantTrivia().Where((t) =>
                                {
                                    if (t.Kind() != SyntaxKind.SingleLineDocumentationCommentTrivia)
                                        return false;
                                    var arr = t.ToString().Split(delim, StringSplitOptions.RemoveEmptyEntries);
                                    return arr.Length == 2 && arr[0] == "add";
                                });

                newmethod = newmethod.ReplaceTrivia(newTrvias.First(), SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "));
                triviaFound = true;
                break;
            }
            if (!triviaFound) break;
        }
        return newmethod;
    }

2 个答案:

答案 0 :(得分:3)

您正在寻找的可能是CSharpSyntaxRewriter。这是一个roslyn中的类,它在您的代码的语法模型中访问每个节点,标记和琐事。您可以创建自己的重写器,覆盖VisitTrivia并返回您想要获取的表达式。例如:

    public class MyRewriter : CSharpSyntaxRewriter
{
public MyRewriter(): base(true)
{
}
public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia)
{
    if(trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia)
    {
        string xml = trivia.ToFullString();

        var TestEntryArgName = "__tst";

        char[] delim = { ' ', '\n', '\t', '\r' };
        var ar = xml.Split(delim, StringSplitOptions.RemoveEmptyEntries);
        if (ar.Length != 3 || ar[1] != "add")
        {
            return base.VisitTrivia(trivia);
        }
        var lineToAdd = TestEntryArgName + ".AddElement(" + ar[2] + ")";

        var expression = SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, lineToAdd);

        return expression;
    }
    return base.VisitTrivia(trivia);
    }
}

样本使用:

    var myRewriter = new MyRewriter();

    string code = "";

    using (StreamReader sr = new StreamReader("Program.cs"))
    {
        code = sr.ReadToEnd();
    }
    var tree = CSharpSyntaxTree.ParseText(code);
    var node = tree.GetRoot();


    using(StreamWriter sw = new StreamWriter("Program.cs"))
    {
        sw.Write(myRewriter.Visit(node));
    }

答案 1 :(得分:1)

我找到了一个简单的解决方案,我认为它适合我,但是,我知道,它不能称为“正确”解决方案,因为它处理源代码。无论如何:

public static MethodDeclarationSyntax getChangedNode(MethodDeclarationSyntax newmethod)
{
    /* Adding __tst.AddElement(i); */
    while (true)
    {
        var desc = newmethod.Body.DescendantTrivia().Where((t) => t.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia));
        var triviaFound = false;

        foreach (var s in desc)
        {
            var commentContents = s.ToString();
            char[] delim = { ' ', '\n', '\t', '\r' };
            var ar = commentContents.Split(delim, StringSplitOptions.RemoveEmptyEntries);
            if (ar.Length != 2 || ar[0] != "add") continue;

            var lineToAdd = "\r\n__tst.AddElement(" + ar[1] + ");\r\n";
            newmethod = CSharpSyntaxTree.ParseText(newmethod.GetText().Replace(s.FullSpan, lineToAdd))
                .GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
            triviaFound = true;
            break;
        }
        if (!triviaFound) break;
    }
    return newmethod;
}