.net 如何在源代码生成器中查找类声明的文件路径

3mpgtkmj  于 2023-01-10  发布在  .NET
关注(0)|答案(2)|浏览(146)

我正在写一个源代码生成器,想知道如何找到一个给定的ClassDeclarationSyntax节点的文件路径。下面是一个我希望能够使用它的例子。

IEnumerable<SyntaxNode> allNodes = compilation.SyntaxTrees.SelectMany(s => s.GetRoot().DescendantNodes());
IEnumerable<ClassDeclarationSyntax> allClasses = allNodes.Where(d => d.IsKind(SyntaxKind.ClassDeclaration))
                                                         .OfType<ClassDeclarationSyntax>();
IEnumerable<string> filePaths = allClasses.Select(x=> x.GetFilePath());
hkmswyz6

hkmswyz61#

可以使用以下代码获取包含文件的路径:

SyntaxNode node = ...;
_ = node.SyntaxTree.FilePath;
_ = node.GetLocation().SourceTree?.FilePath // SourceTree can be null
kq4fsx7k

kq4fsx7k2#

对于那些希望在单元测试中实现这一点的人。当手动创建一个语法树时,你还需要填充路径参数。

[Fact]
public Task ExecGenerator()
{
    var generator = new MyGenerator();
    // Create the driver that will control the generation, passing in our generator
    GeneratorDriver driver = CSharpGeneratorDriver.Create(generator);

    // Run the generation pass
    // (Note: the generator driver itself is immutable, and all calls return an updated version of the driver that you should use for subsequent calls)
    var compilation = CreateCompilation("MyFile.cs");
    return driver.RunGenerators(compilation);
}

private static Compilation CreateCompilation(string filePath)
{
    var source = File.ReadAllText(filePath);

    return CSharpCompilation.Create(
        assemblyName: "tests",
        syntaxTrees: new[] { CSharpSyntaxTree.ParseText(source, path: filePath) },
        references: new[]
        {
            MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
        });
}

然后,在生成器中,您可以用途:

syntaxNode.SyntaxTree.FilePath

相关问题