Get the SyntaxNode given the linenumber in a SyntaxTree

独自空忆成欢 提交于 2019-12-12 08:22:54

问题


I want to get the SyntaxNode of a line given the location(lineNumber). The code below should be self-explanatory, but let me know of any questions.

static void Main()
        {
            string codeSnippet = @"using System;
                                        class Program
                                        {
                                            static void Main(string[] args)
                                            {
                                                Console.WriteLine(""Hello, World!"");
                                            }
                                        }";

            SyntaxTree tree = SyntaxTree.ParseCompilationUnit(codeSnippet);
            string[] lines = codeSnippet.Split('\n');
            SyntaxNode node = GetNode(tree, 6); //How??
        }

        static SyntaxNode GetNode(SyntaxTree tree,int lineNumber)
        {
            throw new NotImplementedException();
            // *** What I did ***
            //Calculted length from using System... to Main(string[] args) and named it (totalSpan)
            //Calculated length of the line(lineNumber) Console.Writeline("Helllo...."); and named it (lineSpan)
            //Created a textspan : TextSpan span = new TextSpan(totalSpan, lineSpan);
            //Was able to get back the text of the line : tree.GetLocation(span);
            //But how to get the SyntaxNode corresponding to that line??
        }

回答1:


First, to get TextSpan based on a line number, you can use the indexer of Lines of the SourceText returned by GetText() (but careful, it counts lines from 0).

Then, to get all nodes that intersect that span, you can use an overload of DescendantNodes().

Finally, you filter that list to get the first node that is contained fully in that line.

In code:

static SyntaxNode GetNode(SyntaxTree tree, int lineNumber)
{
    var lineSpan = tree.GetText().Lines[lineNumber - 1].Span;
    return tree.GetRoot().DescendantNodes(lineSpan)
        .First(n => lineSpan.Contains(n.Span));
}

If there is no node on that line, this will throw an exception. If there is more than one, it will return the first one.



来源:https://stackoverflow.com/questions/13887396/get-the-syntaxnode-given-the-linenumber-in-a-syntaxtree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!