gpt4 book ai didi

c# - 在给定 SyntaxTree 中的行号的情况下获取 SyntaxNode

转载 作者:可可西里 更新时间:2023-11-01 07:46:56 25 4
gpt4 key购买 nike

我想在给定位置(lineNumber)的情况下获取一行的 SyntaxNode。下面的代码应该是不言自明的,但如有任何问题,请告诉我。

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,可以使用 返回的 SourceTextLines 的索引器GetText()(但要小心,它从 0 开始计算行数)。

然后,要获取与该跨度相交的所有节点,您可以使用 DescendantNodes() 的重载。

最后,您过滤该列表以获取完全包含在该行中的第一个节点。

在代码中:

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));
}

如果该行上没有节点,则会抛出异常。如果有多个,它将​​返回第一个。

关于c# - 在给定 SyntaxTree 中的行号的情况下获取 SyntaxNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13887396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com