【发布时间】:2020-11-26 14:06:07
【问题描述】:
在使用 VisualStudio 2019 和我自己的源代码生成器时。我在 Visual Studio 中遇到异常,它提示我打开调试器。
这只会在编码时发生,而不是在构建时发生(这让我认为我的源生成器很好)。
在尝试调试时,我看到一个空白页面并且调用堆栈没有任何信息。
我知道它必须链接到我的生成器,但我不知道如何。任何有关如何调试的提示将不胜感激。
完整的源代码在这里:https://github.com/kYann/StrongTypeId/tree/master/src/StrongType.Generators
[Generator]
public class StrongTypeIdGenerator : ISourceGenerator
{
Template template;
public void Initialize(GeneratorInitializationContext context)
{
var file = "StrongTypeId.sbntxt";
template = Template.Parse(EmbeddedResource.GetContent(file), file);
context.RegisterForSyntaxNotifications(() => new StrongTypeIdReceiver());
}
private string GenerateStrongTypeId(string @namespace, string className)
{
var model = new
{
Namespace = @namespace,
ClassName = className,
};
// apply the template
var output = template.Render(model, member => member.Name);
return output;
}
public bool IsStrongTypeId(INamedTypeSymbol recordSymbol)
{
var strongTypeIdType = typeof(StrongTypeId<>);
var originalBaseTypeDef = recordSymbol.BaseType.OriginalDefinition;
var baseTypeAssembly = originalBaseTypeDef.ContainingAssembly;
var isSameAssembly = baseTypeAssembly.ToDisplayString() == strongTypeIdType.Assembly.FullName;
var isSameTypeName = strongTypeIdType.Name == originalBaseTypeDef.MetadataName;
return isSameAssembly && isSameTypeName;
}
public void Execute(GeneratorExecutionContext context)
{
if (context.SyntaxReceiver is not StrongTypeIdReceiver receiver)
return;
foreach (var rds in receiver.RecordDeclarations)
{
var model = context.Compilation.GetSemanticModel(rds.SyntaxTree);
if (model.GetDeclaredSymbol(rds) is not INamedTypeSymbol recordSymbol)
continue;
if (!IsStrongTypeId(recordSymbol))
continue;
var ns = recordSymbol.ContainingNamespace.ToDisplayString();
var output = GenerateStrongTypeId(ns, recordSymbol.Name);
// add the file
context.AddSource($"{recordSymbol.Name}.generated.cs", SourceText.From(output, Encoding.UTF8));
}
}
private class StrongTypeIdReceiver : ISyntaxReceiver
{
public StrongTypeIdReceiver()
{
RecordDeclarations = new();
}
public List<RecordDeclarationSyntax> RecordDeclarations { get; private set; }
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is RecordDeclarationSyntax rds &&
rds.BaseList is not null)
{
this.RecordDeclarations.Add(rds);
}
}
}
}
【问题讨论】:
标签: c# .net roslyn roslyn-code-analysis