LILAC
Language to language Interop LAyer Compiler
Loading...
Searching...
No Matches
ExportAttributeGenerator.cs
Go to the documentation of this file.
1using System.CodeDom.Compiler;
2using System.Text;
4using Microsoft.CodeAnalysis;
5using Microsoft.CodeAnalysis.CSharp;
6using Microsoft.CodeAnalysis.CSharp.Syntax;
7using Microsoft.CodeAnalysis.Text;
8
9namespace Lilac.Generator;
10
11[Generator]
12public class ExportAttributeGenerator : ISourceGenerator
13{
14 public void Initialize(GeneratorInitializationContext context)
15 {
16 }
17
18 public void Execute(GeneratorExecutionContext context)
19 {
20 const string attrSource =
21 """
22 // <auto-generated />
23
24 using System;
25
26 namespace Lilac.Annotations
27 {
28 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Enum | AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
29 internal class ExportAttribute : Attribute
30 {
31 }
32 }
33 """;
34
35 context.AddSource("ExportAttribute.g.cs", SourceText.From(attrSource, Encoding.UTF8));
36
37 var syntax = CSharpSyntaxTree.ParseText(
38 attrSource,
39 (CSharpParseOptions)context.Compilation.SyntaxTrees.First().Options);
40 var compilation = context.Compilation.AddSyntaxTrees(syntax);
41
42 using var swSource = new StringWriter();
43 using var swHeader = new StringWriter();
44 using var swManaged = new StringWriter();
45
46 var source = new IndentedTextWriter(swSource, " ");
47 var header = new IndentedTextWriter(swHeader, " ");
48 var managed = new IndentedTextWriter(swManaged, " ");
49
50 foreach (var symbol in compilation.GetSymbolsWithName(_ => true).Where(TypeHelper.IsExported))
51 {
52 if (symbol is not INamedTypeSymbol namedT)
53 {
54 var method = (IMethodSymbol)symbol;
55
56 if (!method.ContainingType.IsExported())
57 {
58 context.ReportDiagnostic(
59 Diagnostic.Create(
60 Diagnostics.Type_should_be_exported_to_export_its_member,
61 method.Locations.First(),
62 method.ContainingType.ToDisplayString(),
63 method.ToDisplayString()
64 )
65 );
66 }
67
68 continue;
69 }
70
71 var exporter = IExporter.Create(namedT);
72 exporter.GenerateUnmanagedCode(source, header);
73 exporter.GenerateManagedCode(managed);
74
75 header.WriteLine();
76 }
77
78 Console.WriteLine(swHeader.ToString());
79 Console.WriteLine("-------------------------------");
80 Console.WriteLine(swSource.ToString());
81 Console.WriteLine("-------------------------------");
82 Console.WriteLine(swManaged.ToString());
83 }
84}
void Initialize(GeneratorInitializationContext context)
void Execute(GeneratorExecutionContext context)
static IExporter Create(ISymbol symbol)
Definition IExporter.cs:13
void GenerateUnmanagedCode(IndentedTextWriter source, IndentedTextWriter header)