ScriptPathAttributeGenerator.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
  48. return false;
  49. })
  50. )
  51. .Where(x =>
  52. // Ignore classes whose name is not the same as the file name
  53. Path.GetFileNameWithoutExtension(x.cds.SyntaxTree.FilePath) == x.symbol.Name)
  54. .GroupBy(x => x.symbol)
  55. .ToDictionary(g => g.Key, g => g.Select(x => x.cds));
  56. foreach (var godotClass in godotClasses)
  57. {
  58. VisitGodotScriptClass(context, godotProjectDir,
  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. INamedTypeSymbol symbol,
  70. IEnumerable<ClassDeclarationSyntax> classDeclarations
  71. )
  72. {
  73. var attributes = new StringBuilder();
  74. // Remember syntax trees for which we already added an attribute, to prevent unnecessary duplicates.
  75. var attributedTrees = new List<SyntaxTree>();
  76. foreach (var cds in classDeclarations)
  77. {
  78. if (attributedTrees.Contains(cds.SyntaxTree))
  79. continue;
  80. attributedTrees.Add(cds.SyntaxTree);
  81. if (attributes.Length != 0)
  82. attributes.Append("\n");
  83. attributes.Append(@"[ScriptPathAttribute(""res://");
  84. attributes.Append(RelativeToDir(cds.SyntaxTree.FilePath, godotProjectDir));
  85. attributes.Append(@""")]");
  86. }
  87. INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
  88. string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
  89. namespaceSymbol.FullQualifiedNameOmitGlobal() :
  90. string.Empty;
  91. bool hasNamespace = classNs.Length != 0;
  92. string uniqueHint = symbol.FullQualifiedNameOmitGlobal().SanitizeQualifiedNameForUniqueHint()
  93. + "_ScriptPath.generated";
  94. var source = new StringBuilder();
  95. // using Godot;
  96. // namespace {classNs} {
  97. // {attributesBuilder}
  98. // partial class {className} { }
  99. // }
  100. source.Append("using Godot;\n");
  101. if (hasNamespace)
  102. {
  103. source.Append("namespace ");
  104. source.Append(classNs);
  105. source.Append(" {\n\n");
  106. }
  107. source.Append(attributes);
  108. source.Append("\npartial class ");
  109. source.Append(symbol.NameWithTypeParameters());
  110. source.Append("\n{\n}\n");
  111. if (hasNamespace)
  112. {
  113. source.Append("\n}\n");
  114. }
  115. context.AddSource(uniqueHint, 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. }