ScriptPathAttributeGenerator.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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.AreGodotSourceGeneratorsDisabled())
  17. return;
  18. if (context.IsGodotToolsProject())
  19. return;
  20. // NOTE: NotNullWhen diagnostics don't work on projects targeting .NET Standard 2.0
  21. // ReSharper disable once ReplaceWithStringIsNullOrEmpty
  22. if (!context.TryGetGlobalAnalyzerProperty("GodotProjectDir", out string? godotProjectDir)
  23. || godotProjectDir!.Length == 0)
  24. {
  25. throw new InvalidOperationException("Property 'GodotProjectDir' is null or empty.");
  26. }
  27. Dictionary<INamedTypeSymbol, IEnumerable<ClassDeclarationSyntax>> godotClasses = context
  28. .Compilation.SyntaxTrees
  29. .SelectMany(tree =>
  30. tree.GetRoot().DescendantNodes()
  31. .OfType<ClassDeclarationSyntax>()
  32. // Ignore inner classes
  33. .Where(cds => !cds.IsNested())
  34. .SelectGodotScriptClasses(context.Compilation)
  35. // Report and skip non-partial classes
  36. .Where(x =>
  37. {
  38. if (x.cds.IsPartial())
  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. var uniqueName = new StringBuilder();
  86. if (hasNamespace)
  87. uniqueName.Append($"{classNs}.");
  88. uniqueName.Append(className);
  89. if (symbol.IsGenericType)
  90. uniqueName.Append($"Of{string.Join(string.Empty, symbol.TypeParameters)}");
  91. uniqueName.Append("_ScriptPath_Generated");
  92. var source = new StringBuilder();
  93. // using Godot;
  94. // namespace {classNs} {
  95. // {attributesBuilder}
  96. // partial class {className} { }
  97. // }
  98. source.Append("using Godot;\n");
  99. if (hasNamespace)
  100. {
  101. source.Append("namespace ");
  102. source.Append(classNs);
  103. source.Append(" {\n\n");
  104. }
  105. source.Append(attributes);
  106. source.Append("\n partial class ");
  107. source.Append(className);
  108. if (symbol.IsGenericType)
  109. source.Append($"<{string.Join(", ", symbol.TypeParameters)}>");
  110. source.Append("\n{\n}\n");
  111. if (hasNamespace)
  112. {
  113. source.Append("\n}\n");
  114. }
  115. context.AddSource(uniqueName.ToString(), SourceText.From(source.ToString(), Encoding.UTF8));
  116. }
  117. private static void AddScriptTypesAssemblyAttr(GeneratorExecutionContext context,
  118. Dictionary<INamedTypeSymbol, IEnumerable<ClassDeclarationSyntax>> godotClasses)
  119. {
  120. var sourceBuilder = new StringBuilder();
  121. sourceBuilder.Append("[assembly:");
  122. sourceBuilder.Append(GodotClasses.AssemblyHasScriptsAttr);
  123. sourceBuilder.Append("(new System.Type[] {");
  124. bool first = true;
  125. foreach (var godotClass in godotClasses)
  126. {
  127. var qualifiedName = godotClass.Key.ToDisplayString(
  128. NullableFlowState.NotNull, SymbolDisplayFormat.FullyQualifiedFormat
  129. .WithGenericsOptions(SymbolDisplayGenericsOptions.None));
  130. if (!first)
  131. sourceBuilder.Append(", ");
  132. first = false;
  133. sourceBuilder.Append("typeof(");
  134. sourceBuilder.Append(qualifiedName);
  135. if (godotClass.Key.IsGenericType)
  136. sourceBuilder.Append($"<{new string(',', godotClass.Key.TypeParameters.Count() - 1)}>");
  137. sourceBuilder.Append(")");
  138. }
  139. sourceBuilder.Append("})]\n");
  140. context.AddSource("AssemblyScriptTypes_Generated",
  141. SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
  142. }
  143. public void Initialize(GeneratorInitializationContext context)
  144. {
  145. }
  146. private static string RelativeToDir(string path, string dir)
  147. {
  148. // Make sure the directory ends with a path separator
  149. dir = Path.Combine(dir, " ").TrimEnd();
  150. if (Path.DirectorySeparatorChar == '\\')
  151. dir = dir.Replace("/", "\\") + "\\";
  152. var fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
  153. var relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
  154. // MakeRelativeUri converts spaces to %20, hence why we need UnescapeDataString
  155. return Uri.UnescapeDataString(relRoot.MakeRelativeUri(fullPath).ToString());
  156. }
  157. }
  158. }