PublicApiGenerator.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System.Collections.Generic;
  2. using System.Runtime.Serialization;
  3. using System.Text;
  4. using Microsoft.CodeAnalysis;
  5. using Microsoft.CodeAnalysis.CSharp;
  6. using Microsoft.CodeAnalysis.Text;
  7. namespace QuestPDF.InteropGenerators;
  8. /// <summary>
  9. /// Source generator that creates interop bindings for QuestPDF public API.
  10. /// Combines analysis, C# generation, and Python generation into a complete pipeline.
  11. /// </summary>
  12. [Generator]
  13. public sealed class PublicApiGenerator : IIncrementalGenerator
  14. {
  15. public void Initialize(IncrementalGeneratorInitializationContext context)
  16. {
  17. context.RegisterSourceOutput(context.CompilationProvider, static (spc, compilation) =>
  18. {
  19. var content = NewGenerator.AnalyzeAndGenerate(compilation.Assembly.GlobalNamespace);
  20. var csharpBuilder = new StringBuilder();
  21. var pythonBuilder = new StringBuilder();
  22. var generators = new List<ISourceGenerator>
  23. {
  24. new EnumSourceGenerator("QuestPDF.Infrastructure.AspectRatioOption"),
  25. new EnumSourceGenerator("QuestPDF.Infrastructure.ImageCompressionQuality"),
  26. new EnumSourceGenerator("QuestPDF.Infrastructure.ImageFormat"),
  27. new ContainerSourceGenerator() // Generate interop for IContainer extension methods
  28. };
  29. foreach (var generator in generators)
  30. {
  31. var csharpCodeFragment = generator.GenerateCSharpCode(compilation.Assembly.GlobalNamespace);
  32. csharpBuilder.AppendLine(csharpCodeFragment);
  33. var pythonCodeFragment = generator.GeneratePythonCode(compilation.Assembly.GlobalNamespace);
  34. pythonBuilder.AppendLine(pythonCodeFragment);
  35. }
  36. var csharpCode = csharpBuilder.ToString();
  37. var pythonCode = pythonBuilder.ToString();
  38. // Output C# interop code1
  39. if (!string.IsNullOrWhiteSpace(csharpCode))
  40. {
  41. spc.AddSource("QuestPDF.Interop.g.cs", SourceText.From(csharpCode, System.Text.Encoding.UTF8));
  42. }
  43. // Output Python bindings code
  44. if (!string.IsNullOrWhiteSpace(pythonCode))
  45. {
  46. //spc.AddSource("QuestPDF.Python.py", SourceText.From(pythonCode, System.Text.Encoding.UTF8));
  47. }
  48. });
  49. }
  50. }