Get the SyntaxNode given the linenumber in a SyntaxTree

后端 未结 1 1409
日久生厌
日久生厌 2021-02-13 04:40

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 M         


        
相关标签:
1条回答
  • 2021-02-13 05:43

    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.

    0 讨论(0)
提交回复
热议问题