ScriptPathAttributeGenerator.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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.IsGodotSourceGeneratorDisabled("ScriptPathAttribute"))
  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("GodotProjectDirBase64", out string? godotProjectDir) || godotProjectDir!.Length == 0)
  23. {
  24. if (!context.TryGetGlobalAnalyzerProperty("GodotProjectDir", out godotProjectDir) || godotProjectDir!.Length == 0)
  25. {
  26. throw new InvalidOperationException("Property 'GodotProjectDir' is null or empty.");
  27. }
  28. }
  29. else
  30. {
  31. // Workaround for https://github.com/dotnet/roslyn/issues/51692
  32. godotProjectDir = Encoding.UTF8.GetString(Convert.FromBase64String(godotProjectDir));
  33. }
  34. Dictionary<INamedTypeSymbol, IEnumerable<ClassDeclarationSyntax>> godotClasses = context
  35. .Compilation.SyntaxTrees
  36. .SelectMany(tree =>
  37. tree.GetRoot().DescendantNodes()
  38. .OfType<ClassDeclarationSyntax>()
  39. // Ignore inner classes
  40. .Where(cds => !cds.IsNested())
  41. .SelectGodotScriptClasses(context.Compilation)
  42. // Report and skip non-partial classes
  43. .Where(x =>
  44. {
  45. if (x.cds.IsPartial())
  46. return true;
  47. return false;
  48. })
  49. )
  50. .Where(x =>
  51. // Ignore classes whose name is not the same as the file name
  52. Path.GetFileNameWithoutExtension(x.cds.SyntaxTree.FilePath) == x.symbol.Name)
  53. .GroupBy<(ClassDeclarationSyntax cds, INamedTypeSymbol symbol), INamedTypeSymbol>(x => x.symbol, SymbolEqualityComparer.Default)
  54. .ToDictionary<IGrouping<INamedTypeSymbol, (ClassDeclarationSyntax cds, INamedTypeSymbol symbol)>, INamedTypeSymbol, IEnumerable<ClassDeclarationSyntax>>(g => g.Key, g => g.Select(x => x.cds), SymbolEqualityComparer.Default);
  55. var usedPaths = new HashSet<string>();
  56. foreach (var godotClass in godotClasses)
  57. {
  58. VisitGodotScriptClass(context, godotProjectDir, usedPaths,
  59. symbol: godotClass.Key,
  60. classDeclarations: godotClass.Value);
  61. }
  62. if (godotClasses.Count <= 0)
  63. return;
  64. AddScriptTypesAssemblyAttr(context, godotClasses);
  65. }
  66. private static void VisitGodotScriptClass(
  67. GeneratorExecutionContext context,
  68. string godotProjectDir,
  69. HashSet<string> usedPaths,
  70. INamedTypeSymbol symbol,
  71. IEnumerable<ClassDeclarationSyntax> classDeclarations
  72. )
  73. {
  74. var attributes = new StringBuilder();
  75. // Remember syntax trees for which we already added an attribute, to prevent unnecessary duplicates.
  76. var attributedTrees = new List<SyntaxTree>();
  77. foreach (var cds in classDeclarations)
  78. {
  79. if (attributedTrees.Contains(cds.SyntaxTree))
  80. continue;
  81. attributedTrees.Add(cds.SyntaxTree);
  82. if (attributes.Length != 0)
  83. attributes.Append("\n");
  84. string scriptPath = RelativeToDir(cds.SyntaxTree.FilePath, godotProjectDir);
  85. if (!usedPaths.Add(scriptPath))
  86. {
  87. context.ReportDiagnostic(Diagnostic.Create(
  88. Common.MultipleClassesInGodotScriptRule,
  89. cds.Identifier.GetLocation(),
  90. symbol.Name
  91. ));
  92. return;
  93. }
  94. attributes.Append(@"[ScriptPathAttribute(""res://");
  95. attributes.Append(scriptPath);
  96. attributes.Append(@""")]");
  97. }
  98. INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
  99. string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
  100. namespaceSymbol.FullQualifiedNameOmitGlobal() :
  101. string.Empty;
  102. bool hasNamespace = classNs.Length != 0;
  103. string uniqueHint = symbol.FullQualifiedNameOmitGlobal().SanitizeQualifiedNameForUniqueHint()
  104. + "_ScriptPath.generated";
  105. var source = new StringBuilder();
  106. // using Godot;
  107. // namespace {classNs} {
  108. // {attributesBuilder}
  109. // partial class {className} { }
  110. // }
  111. source.Append("using Godot;\n");
  112. if (hasNamespace)
  113. {
  114. source.Append("namespace ");
  115. source.Append(classNs);
  116. source.Append(" {\n\n");
  117. }
  118. source.Append(attributes);
  119. source.Append("\npartial class ");
  120. source.Append(symbol.NameWithTypeParameters());
  121. source.Append("\n{\n}\n");
  122. if (hasNamespace)
  123. {
  124. source.Append("\n}\n");
  125. }
  126. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  127. }
  128. private static void AddScriptTypesAssemblyAttr(GeneratorExecutionContext context,
  129. Dictionary<INamedTypeSymbol, IEnumerable<ClassDeclarationSyntax>> godotClasses)
  130. {
  131. var sourceBuilder = new StringBuilder();
  132. sourceBuilder.Append("[assembly:");
  133. sourceBuilder.Append(GodotClasses.AssemblyHasScriptsAttr);
  134. sourceBuilder.Append("(new System.Type[] {");
  135. bool first = true;
  136. foreach (var godotClass in godotClasses)
  137. {
  138. var qualifiedName = godotClass.Key.ToDisplayString(
  139. NullableFlowState.NotNull, SymbolDisplayFormat.FullyQualifiedFormat
  140. .WithGenericsOptions(SymbolDisplayGenericsOptions.None));
  141. if (!first)
  142. sourceBuilder.Append(", ");
  143. first = false;
  144. sourceBuilder.Append("typeof(");
  145. sourceBuilder.Append(qualifiedName);
  146. if (godotClass.Key.IsGenericType)
  147. sourceBuilder.Append($"<{new string(',', godotClass.Key.TypeParameters.Count() - 1)}>");
  148. sourceBuilder.Append(")");
  149. }
  150. sourceBuilder.Append("})]\n");
  151. context.AddSource("AssemblyScriptTypes.generated",
  152. SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
  153. }
  154. public void Initialize(GeneratorInitializationContext context)
  155. {
  156. }
  157. private static string RelativeToDir(string path, string dir)
  158. {
  159. // Make sure the directory ends with a path separator
  160. dir = Path.Combine(dir, " ").TrimEnd();
  161. if (Path.DirectorySeparatorChar == '\\')
  162. dir = dir.Replace("/", "\\") + "\\";
  163. var fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
  164. var relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
  165. // MakeRelativeUri converts spaces to %20, hence why we need UnescapeDataString
  166. return Uri.UnescapeDataString(relRoot.MakeRelativeUri(fullPath).ToString());
  167. }
  168. }
  169. }