|
| 1 | +namespace BizHawk.SrcGen.VIM; |
| 2 | + |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Linq; |
| 5 | +using System.Text; |
| 6 | + |
| 7 | +using BizHawk.Common; |
| 8 | + |
| 9 | +using Microsoft.CodeAnalysis; |
| 10 | +using Microsoft.CodeAnalysis.CSharp; |
| 11 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 12 | +using Microsoft.CodeAnalysis.Text; |
| 13 | + |
| 14 | +[Generator] |
| 15 | +public sealed class VIMGenerator : ISourceGenerator |
| 16 | +{ |
| 17 | + private sealed class VIMGenSyntaxReceiver : ISyntaxReceiver |
| 18 | + { |
| 19 | + public readonly List<TypeDeclarationSyntax> Candidates = new(); |
| 20 | + |
| 21 | + public void OnVisitSyntaxNode(SyntaxNode syntaxNode) |
| 22 | + { |
| 23 | + if (syntaxNode is TypeDeclarationSyntax syn) Candidates.Add(syn); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + private class ImplNotes |
| 28 | + { |
| 29 | + public readonly string BaseImplNamePrefix; |
| 30 | + |
| 31 | + public readonly string InvokeCall; |
| 32 | + |
| 33 | + public readonly string MethodFullName; |
| 34 | + |
| 35 | + public readonly ISymbol MethodSym; |
| 36 | + |
| 37 | + public readonly string ReturnType; |
| 38 | + |
| 39 | + public ImplNotes(ISymbol intfSym, IMethodSymbol methodSym, AttributeData vimAttr) |
| 40 | + { |
| 41 | + string? baseImplMethodName = null; |
| 42 | + string? implsClassFullName = null; |
| 43 | + foreach (var kvp in vimAttr.NamedArguments) switch (kvp.Key) |
| 44 | + { |
| 45 | + case nameof(VirtualMethodAttribute.BaseImplMethodName): |
| 46 | + baseImplMethodName = kvp.Value.Value?.ToString(); |
| 47 | + break; |
| 48 | + case nameof(VirtualMethodAttribute.ImplsClassFullName): |
| 49 | + implsClassFullName = kvp.Value.Value?.ToString(); |
| 50 | + break; |
| 51 | + } |
| 52 | + if (string.IsNullOrEmpty(baseImplMethodName)) baseImplMethodName = methodSym.Name; |
| 53 | + if (string.IsNullOrEmpty(implsClassFullName)) implsClassFullName = $"{intfSym.FullNamespace()}.MethodDefaultImpls"; |
| 54 | + BaseImplNamePrefix = $"{implsClassFullName}.{baseImplMethodName}"; |
| 55 | + InvokeCall = $"(this{string.Concat(methodSym.Parameters.Select(static pSym => $", {pSym.Name}"))})"; |
| 56 | + MethodFullName = $"{intfSym.FullNamespace()}.{methodSym.Name}({string.Join(", ", methodSym.Parameters.Select(static pSym => $"{pSym.Type.ToDisplayString()} {pSym.Name}"))})"; |
| 57 | + MethodSym = methodSym; |
| 58 | + ReturnType = methodSym.ReturnType.ToDisplayString(); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | +// private static readonly DiagnosticDescriptor DiagNoEnum = new( |
| 63 | +// id: "BHI2000", |
| 64 | +//// title: "Apply [VirtualMethod] to enums used with generator", |
| 65 | +//// messageFormat: "Matching enum should have [VirtualMethod] to enable better analysis and codegen", |
| 66 | +// title: "debug", |
| 67 | +// messageFormat: "{0}", |
| 68 | +// category: "Usage", |
| 69 | +// defaultSeverity: DiagnosticSeverity.Warning, |
| 70 | +// isEnabledByDefault: true); |
| 71 | + |
| 72 | + public void Initialize(GeneratorInitializationContext context) |
| 73 | + => context.RegisterForSyntaxNotifications(static () => new VIMGenSyntaxReceiver()); |
| 74 | + |
| 75 | + public void Execute(GeneratorExecutionContext context) |
| 76 | + { |
| 77 | +// void DebugMsg(Location location, string msg) |
| 78 | +// => context.ReportDiagnostic(Diagnostic.Create(DiagNoEnum, location, msg)); |
| 79 | + |
| 80 | + if (context.SyntaxReceiver is not VIMGenSyntaxReceiver receiver) return; |
| 81 | + |
| 82 | + // boilerplate to get attr working |
| 83 | + var compilation = context.Compilation; |
| 84 | + var vimAttrSymbol = compilation.GetTypeByMetadataName("BizHawk.Common." + nameof(VirtualMethodAttribute)); |
| 85 | + if (vimAttrSymbol is null) |
| 86 | + { |
| 87 | + var attributesSource = SourceText.From(typeof(VIMGenerator).Assembly.GetManifestResourceStream("BizHawk.SrcGen.VIM.VirtualMethodAttribute.cs")!, Encoding.UTF8, canBeEmbedded: true); |
| 88 | + context.AddSource("VirtualMethodAttribute.cs", attributesSource); |
| 89 | + compilation = context.Compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(attributesSource, (CSharpParseOptions) ((CSharpCompilation) context.Compilation).SyntaxTrees[0].Options)); |
| 90 | + vimAttrSymbol = compilation.GetTypeByMetadataName("BizHawk.Common." + nameof(VirtualMethodAttribute))!; |
| 91 | + } |
| 92 | + |
| 93 | + Dictionary<string, List<ImplNotes>> vimDict = new(); |
| 94 | + List<ImplNotes> Lookup(INamedTypeSymbol intfSym) |
| 95 | + { |
| 96 | + var fqn = intfSym.FullNamespace(); |
| 97 | + if (vimDict.TryGetValue(fqn, out var implNotes)) return implNotes; |
| 98 | + // else cache miss |
| 99 | + List<ImplNotes> implNotes1 = new(); |
| 100 | + foreach (var methodSym in intfSym.GetMembers()) |
| 101 | + { |
| 102 | + var vimAttr = methodSym.GetAttributes().FirstOrDefault(ad => vimAttrSymbol.Matches(ad.AttributeClass)); |
| 103 | + if (vimAttr is not null) implNotes1.Add(new(intfSym: intfSym, methodSym: (IMethodSymbol) methodSym, vimAttr)); |
| 104 | + } |
| 105 | + return vimDict[fqn] = implNotes1; |
| 106 | + } |
| 107 | + |
| 108 | + List<INamedTypeSymbol> seen = new(); |
| 109 | + foreach (var tds in receiver.Candidates) |
| 110 | + { |
| 111 | + var cSym = compilation.GetSemanticModel(tds.SyntaxTree).GetDeclaredSymbol(tds)!; |
| 112 | + if (seen.Contains(cSym)) continue; // dedup partial classes |
| 113 | + seen.Add(cSym); |
| 114 | + var typeKeywords = tds.GetTypeKeywords(cSym); |
| 115 | + if (typeKeywords.Contains("enum") || typeKeywords.Contains("interface") || typeKeywords.Contains("static")) continue; |
| 116 | + |
| 117 | + List<string> innerText = new(); |
| 118 | + foreach (var intfSym in cSym.BaseType is not null |
| 119 | + ? cSym.AllInterfaces.Except(cSym.BaseType.AllInterfaces) // superclass (or its superclass, etc.) already has the delegated base implementations of these interfaces' virtual methods |
| 120 | + : cSym.AllInterfaces) |
| 121 | + { |
| 122 | + //TODO let an interface override a superinterface's virtual method -- may need to order above enumerable somehow |
| 123 | + foreach (var method in Lookup(intfSym)) |
| 124 | + { |
| 125 | + if (cSym.FindImplementationForInterfaceMember(method.MethodSym) is not null) continue; // overridden |
| 126 | + innerText.Add($@"{method.ReturnType} {method.MethodFullName} |
| 127 | + => {method.BaseImplNamePrefix}{method.InvokeCall};"); // set up this way so I can whack a "_get"/"_set" before the '(' for virtual props |
| 128 | + } |
| 129 | + } |
| 130 | + if (innerText.Count is not 0) context.AddSource( |
| 131 | + source: $@"#nullable enable |
| 132 | +
|
| 133 | +namespace {cSym.ContainingNamespace.ToDisplayString()} |
| 134 | +{{ |
| 135 | + public {string.Join(" ", typeKeywords)} {cSym.Name} |
| 136 | + {{ |
| 137 | + {string.Join("\n\n", innerText)} |
| 138 | + }} |
| 139 | +}} |
| 140 | +", |
| 141 | + hintName: $"{cSym.Name}.VIMDelegation.cs"); |
| 142 | + } |
| 143 | + } |
| 144 | +} |
0 commit comments