ScriptPathAttributeGenerator.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
  80. string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
  81. namespaceSymbol.FullQualifiedName() :
  82. string.Empty;
  83. bool hasNamespace = classNs.Length != 0;
  84. string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
  85. + "_ScriptPath.generated";
  86. var source = new StringBuilder();
  87. // using Godot;
  88. // namespace {classNs} {
  89. // {attributesBuilder}
  90. // partial class {className} { }
  91. // }
  92. source.Append("using Godot;\n");
  93. if (hasNamespace)
  94. {
  95. source.Append("namespace ");
  96. source.Append(classNs);
  97. source.Append(" {\n\n");
  98. }
  99. source.Append(attributes);
  100. source.Append("\npartial class ");
  101. source.Append(symbol.NameWithTypeParameters());
  102. source.Append("\n{\n}\n");
  103. if (hasNamespace)
  104. {
  105. source.Append("\n}\n");
  106. }
  107. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  108. }
  109. private static void AddScriptTypesAssemblyAttr(GeneratorExecutionContext context,
  110. Dictionary<INamedTypeSymbol, IEnumerable<ClassDeclarationSyntax>> godotClasses)
  111. {
  112. var sourceBuilder = new StringBuilder();
  113. sourceBuilder.Append("[assembly:");
  114. sourceBuilder.Append(GodotClasses.AssemblyHasScriptsAttr);
  115. sourceBuilder.Append("(new System.Type[] {");
  116. bool first = true;
  117. foreach (var godotClass in godotClasses)
  118. {
  119. var qualifiedName = godotClass.Key.ToDisplayString(
  120. NullableFlowState.NotNull, SymbolDisplayFormat.FullyQualifiedFormat
  121. .WithGenericsOptions(SymbolDisplayGenericsOptions.None));
  122. if (!first)
  123. sourceBuilder.Append(", ");
  124. first = false;
  125. sourceBuilder.Append("typeof(");
  126. sourceBuilder.Append(qualifiedName);
  127. if (godotClass.Key.IsGenericType)
  128. sourceBuilder.Append($"<{new string(',', godotClass.Key.TypeParameters.Count() - 1)}>");
  129. sourceBuilder.Append(")");
  130. }
  131. sourceBuilder.Append("})]\n");
  132. context.AddSource("AssemblyScriptTypes.generated",
  133. SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
  134. }
  135. public void Initialize(GeneratorInitializationContext context)
  136. {
  137. }
  138. private static string RelativeToDir(string path, string dir)
  139. {
  140. // Make sure the directory ends with a path separator
  141. dir = Path.Combine(dir, " ").TrimEnd();
  142. if (Path.DirectorySeparatorChar == '\\')
  143. dir = dir.Replace("/", "\\") + "\\";
  144. var fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
  145. var relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
  146. // MakeRelativeUri converts spaces to %20, hence why we need UnescapeDataString
  147. return Uri.UnescapeDataString(relRoot.MakeRelativeUri(fullPath).ToString());
  148. }
  149. }
  150. }