Debian Codegraph @

modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs

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