ScriptPathAttributeGenerator.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using Microsoft.CodeAnalysis;
  7. using Microsoft.CodeAnalysis.CSharp.Syntax;
  8. using Microsoft.CodeAnalysis.Text;
  9. namespace Godot.SourceGenerators
  10. {
  11. [Generator]
  12. public class ScriptPathAttributeGenerator : ISourceGenerator
  13. {
  14. public void Execute(GeneratorExecutionContext context)
  15. {
  16. if (context.TryGetGlobalAnalyzerProperty("GodotScriptPathAttributeGenerator", out string? toggle)
  17. && toggle == "disabled")
  18. {
  19. return;
  20. }
  21. // NOTE: IsNullOrEmpty doesn't work well with nullable checks
  22. // ReSharper disable once ReplaceWithStringIsNullOrEmpty
  23. if (!context.TryGetGlobalAnalyzerProperty("GodotProjectDir", out string? godotProjectDir)
  24. || godotProjectDir!.Length == 0)
  25. {
  26. throw new InvalidOperationException("Property 'GodotProjectDir' is null or empty.");
  27. }
  28. var godotClasses = context.Compilation.SyntaxTrees
  29. .SelectMany(tree =>
  30. tree.GetRoot().DescendantNodes()
  31. .OfType<ClassDeclarationSyntax>()
  32. // Ignore inner classes
  33. .Where(cds => !(cds.Parent is ClassDeclarationSyntax))
  34. .SelectGodotScriptClasses(context.Compilation)
  35. // Report and skip non-partial classes
  36. .Where(x =>
  37. {
  38. if (x.cds.IsPartial() || x.symbol.HasDisableGeneratorsAttribute())
  39. return true;
  40. Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
  41. return false;
  42. })
  43. )
  44. // Ignore classes whose name is not the same as the file name
  45. .Where(x => Path.GetFileNameWithoutExtension(x.cds.SyntaxTree.FilePath) == x.symbol.Name)
  46. .GroupBy(x => x.symbol)
  47. .ToDictionary(g => g.Key, g => g.Select(x => x.cds));
  48. foreach (var godotClass in godotClasses)
  49. {
  50. VisitGodotScriptClass(context, godotProjectDir,
  51. symbol: godotClass.Key,
  52. classDeclarations: godotClass.Value);
  53. }
  54. if (godotClasses.Count <= 0)
  55. return;
  56. AddScriptTypesAssemblyAttr(context, godotClasses);
  57. }
  58. private static void VisitGodotScriptClass(
  59. GeneratorExecutionContext context,
  60. string godotProjectDir,
  61. INamedTypeSymbol symbol,
  62. IEnumerable<ClassDeclarationSyntax> classDeclarations
  63. )
  64. {
  65. var attributes = new StringBuilder();
  66. // Remember syntax trees for which we already added an attribute, to prevent unnecessary duplicates.
  67. var attributedTrees = new List<SyntaxTree>();
  68. foreach (var cds in classDeclarations)
  69. {
  70. if (attributedTrees.Contains(cds.SyntaxTree))
  71. continue;
  72. attributedTrees.Add(cds.SyntaxTree);
  73. if (attributes.Length != 0)
  74. attributes.Append("\n");
  75. attributes.Append(@"[ScriptPathAttribute(""res://");
  76. attributes.Append(RelativeToDir(cds.SyntaxTree.FilePath, godotProjectDir));
  77. attributes.Append(@""")]");
  78. }
  79. string className = symbol.Name;
  80. INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
  81. string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
  82. namespaceSymbol.FullQualifiedName() :
  83. string.Empty;
  84. bool hasNamespace = classNs.Length != 0;
  85. string uniqueName = hasNamespace ?
  86. classNs + "." + className + "_ScriptPath_Generated" :
  87. className + "_ScriptPath_Generated";
  88. var source = new StringBuilder();
  89. // using Godot;
  90. // namespace {classNs} {
  91. // {attributesBuilder}
  92. // partial class {className} { }
  93. // }
  94. source.Append("using Godot;\n");
  95. if (hasNamespace)
  96. {
  97. source.Append("namespace ");
  98. source.Append(classNs);
  99. source.Append(" {\n\n");
  100. }
  101. source.Append(attributes);
  102. source.Append("\n partial class ");
  103. source.Append(className);
  104. source.Append("\n{\n}\n");
  105. if (hasNamespace)
  106. {
  107. source.Append("\n}\n");
  108. }
  109. context.AddSource(uniqueName, SourceText.From(source.ToString(), Encoding.UTF8));
  110. }
  111. private static void AddScriptTypesAssemblyAttr(GeneratorExecutionContext context,
  112. Dictionary<INamedTypeSymbol, IEnumerable<ClassDeclarationSyntax>> godotClasses)
  113. {
  114. var sourceBuilder = new StringBuilder();
  115. sourceBuilder.Append("[assembly:");
  116. sourceBuilder.Append(GodotClasses.AssemblyHasScriptsAttr);
  117. sourceBuilder.Append("(new System.Type[] {");
  118. bool first = true;
  119. foreach (var godotClass in godotClasses)
  120. {
  121. var qualifiedName = godotClass.Key.ToDisplayString(
  122. NullableFlowState.NotNull, SymbolDisplayFormat.FullyQualifiedFormat);
  123. if (!first)
  124. sourceBuilder.Append(", ");
  125. first = false;
  126. sourceBuilder.Append("typeof(");
  127. sourceBuilder.Append(qualifiedName);
  128. sourceBuilder.Append(")");
  129. }
  130. sourceBuilder.Append("})]\n");
  131. context.AddSource("AssemblyScriptTypes_Generated",
  132. SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
  133. }
  134. public void Initialize(GeneratorInitializationContext context)
  135. {
  136. }
  137. private static string RelativeToDir(string path, string dir)
  138. {
  139. // Make sure the directory ends with a path separator
  140. dir = Path.Combine(dir, " ").TrimEnd();
  141. if (Path.DirectorySeparatorChar == '\\')
  142. dir = dir.Replace("/", "\\") + "\\";
  143. var fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
  144. var relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
  145. // MakeRelativeUri converts spaces to %20, hence why we need UnescapeDataString
  146. return Uri.UnescapeDataString(relRoot.MakeRelativeUri(fullPath).ToString());
  147. }
  148. }
  149. }