根据 SyntaxTree 中的行号获取 SyntaxNode [英] Get the SyntaxNode given the linenumber in a SyntaxTree
问题描述
我想获取给定位置(lineNumber)的行的 SyntaxNode.下面的代码应该是不言自明的,但如果有任何问题,请告诉我.
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??
}
推荐答案
首先,要根据行号得到TextSpan
,可以使用Lines
的索引器GetText()
返回的 SourceText
(但要小心,它从 0 开始计数).
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).
然后,要获得与该跨度相交的所有节点,您可以使用 DescendantNodes()
的重载.
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.
在代码中:
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.
这篇关于根据 SyntaxTree 中的行号获取 SyntaxNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!