Debian Codegraph @

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

raw symbols SCIP
1 using System;
2 using System.Collections.Generic;
3 using System.Collections.Immutable;
4 using System.Linq;
5 using System.Text;
6 using Microsoft.CodeAnalysis;
7 using Microsoft.CodeAnalysis.CSharp;
8 using Microsoft.CodeAnalysis.CSharp.Syntax;
9
10 namespace Godot.SourceGenerators
11 {
12 internal static class ExtensionMethods
13 {
14 public static bool TryGetGlobalAnalyzerProperty(
15 this GeneratorExecutionContext context, string property, out string? value
16 ) => context.AnalyzerConfigOptions.GlobalOptions
17 .TryGetValue("build_property." + property, out value);
18
19 public static bool AreGodotSourceGeneratorsDisabled(this GeneratorExecutionContext context)
20 => context.TryGetGlobalAnalyzerProperty("GodotSourceGenerators", out string? toggle) &&
21 toggle != null &&
22 toggle.Equals("disabled", StringComparison.OrdinalIgnoreCase);
23
24 public static bool IsGodotToolsProject(this GeneratorExecutionContext context)
25 => context.TryGetGlobalAnalyzerProperty("IsGodotToolsProject", out string? toggle) &&
26 toggle != null &&
27 toggle.Equals("true", StringComparison.OrdinalIgnoreCase);
28
29 public static bool IsGodotSourceGeneratorDisabled(this GeneratorExecutionContext context, string generatorName) =>
30 AreGodotSourceGeneratorsDisabled(context) ||
31 (context.TryGetGlobalAnalyzerProperty("GodotDisabledSourceGenerators", out string? disabledGenerators) &&
32 disabledGenerators != null &&
33 disabledGenerators.Split(';').Contains(generatorName));
34
35 public static bool InheritsFrom(this ITypeSymbol? symbol, string assemblyName, string typeFullName)
36 {
37 while (symbol != null)
38 {
39 if (symbol.ContainingAssembly?.Name == assemblyName &&
40 symbol.FullQualifiedNameOmitGlobal() == typeFullName)
41 {
42 return true;
43 }
44
45 symbol = symbol.BaseType;
46 }
47
48 return false;
49 }
50
51 public static INamedTypeSymbol? GetGodotScriptNativeClass(this INamedTypeSymbol classTypeSymbol)
52 {
53 var symbol = classTypeSymbol;
54
55 while (symbol != null)
56 {
57 if (symbol.ContainingAssembly?.Name == "GodotSharp")
58 return symbol;
59
60 symbol = symbol.BaseType;
61 }
62
63 return null;
64 }
65
66 public static string? GetGodotScriptNativeClassName(this INamedTypeSymbol classTypeSymbol)
67 {
68 var nativeType = classTypeSymbol.GetGodotScriptNativeClass();
69
70 if (nativeType == null)
71 return null;
72
73 var godotClassNameAttr = nativeType.GetAttributes()
74 .FirstOrDefault(a => a.AttributeClass?.IsGodotClassNameAttribute() ?? false);
75
76 string? godotClassName = null;
77
78 if (godotClassNameAttr is { ConstructorArguments: { Length: > 0 } })
79 godotClassName = godotClassNameAttr.ConstructorArguments[0].Value?.ToString();
80
81 return godotClassName ?? nativeType.Name;
82 }
83
84 private static bool TryGetGodotScriptClass(
85 this ClassDeclarationSyntax cds, Compilation compilation,
86 out INamedTypeSymbol? symbol
87 )
88 {
89 var sm = compilation.GetSemanticModel(cds.SyntaxTree);
90
91 var classTypeSymbol = sm.GetDeclaredSymbol(cds);
92
93 if (classTypeSymbol?.BaseType == null
94 || !classTypeSymbol.BaseType.InheritsFrom("GodotSharp", GodotClasses.GodotObject))
95 {
96 symbol = null;
97 return false;
98 }
99
100 symbol = classTypeSymbol;
101 return true;
102 }
103
104 public static IEnumerable<(ClassDeclarationSyntax cds, INamedTypeSymbol symbol)> SelectGodotScriptClasses(
105 this IEnumerable<ClassDeclarationSyntax> source,
106 Compilation compilation
107 )
108 {
109 foreach (var cds in source)
110 {
111 if (cds.TryGetGodotScriptClass(compilation, out var symbol))
112 yield return (cds, symbol!);
113 }
114 }
115
116 public static bool IsNested(this TypeDeclarationSyntax cds)
117 => cds.Parent is TypeDeclarationSyntax;
118
119 public static bool IsPartial(this TypeDeclarationSyntax cds)
120 => cds.Modifiers.Any(SyntaxKind.PartialKeyword);
121
122 public static bool AreAllOuterTypesPartial(
123 this TypeDeclarationSyntax cds,
124 out TypeDeclarationSyntax? typeMissingPartial
125 )
126 {
127 SyntaxNode? outerSyntaxNode = cds.Parent;
128
129 while (outerSyntaxNode is TypeDeclarationSyntax outerTypeDeclSyntax)
130 {
131 if (!outerTypeDeclSyntax.IsPartial())
132 {
133 typeMissingPartial = outerTypeDeclSyntax;
134 return false;
135 }
136
137 outerSyntaxNode = outerSyntaxNode.Parent;
138 }
139
140 typeMissingPartial = null;
141 return true;
142 }
143
144 public static string GetDeclarationKeyword(this INamedTypeSymbol namedTypeSymbol)
145 {
146 string? keyword = namedTypeSymbol.DeclaringSyntaxReferences
147 .OfType<TypeDeclarationSyntax>().FirstOrDefault()?
148 .Keyword.Text;
149
150 return keyword ?? namedTypeSymbol.TypeKind switch
151 {
152 TypeKind.Interface => "interface",
153 TypeKind.Struct => "struct",
154 _ => "class"
155 };
156 }
157
158 public static string GetAccessibilityKeyword(this INamedTypeSymbol namedTypeSymbol)
159 {
160 if (namedTypeSymbol.DeclaredAccessibility == Accessibility.NotApplicable)
161 {
162 // Accessibility not specified. Get the default accessibility.
163 return namedTypeSymbol.ContainingSymbol switch
164 {
165 null or INamespaceSymbol => "internal",
166 ITypeSymbol { TypeKind: TypeKind.Class or TypeKind.Struct } => "private",
167 ITypeSymbol { TypeKind: TypeKind.Interface } => "public",
168 _ => "",
169 };
170 }
171
172 return namedTypeSymbol.DeclaredAccessibility switch
173 {
174 Accessibility.Private => "private",
175 Accessibility.Protected => "protected",
176 Accessibility.Internal => "internal",
177 Accessibility.ProtectedAndInternal => "private",
178 Accessibility.ProtectedOrInternal => "private",
179 Accessibility.Public => "public",
180 _ => "",
181 };
182 }
183
184 private static SymbolDisplayFormat FullyQualifiedFormatOmitGlobal { get; } =
185 SymbolDisplayFormat.FullyQualifiedFormat
186 .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted)
187 .WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType);
188
189 private static SymbolDisplayFormat FullyQualifiedFormatIncludeGlobal { get; } =
190 SymbolDisplayFormat.FullyQualifiedFormat
191 .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Included)
192 .WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType);
193
194 public static string FullQualifiedNameOmitGlobal(this ITypeSymbol symbol)
195 => symbol.ToDisplayString(NullableFlowState.NotNull, FullyQualifiedFormatOmitGlobal);
196
197 public static string FullQualifiedNameOmitGlobal(this INamespaceSymbol namespaceSymbol)
198 => namespaceSymbol.ToDisplayString(FullyQualifiedFormatOmitGlobal);
199
200 public static string FullQualifiedNameIncludeGlobal(this ITypeSymbol symbol)
201 => symbol.ToDisplayString(NullableFlowState.NotNull, FullyQualifiedFormatIncludeGlobal);
202
203 public static string FullQualifiedNameIncludeGlobal(this INamespaceSymbol namespaceSymbol)
204 => namespaceSymbol.ToDisplayString(FullyQualifiedFormatIncludeGlobal);
205
206 public static string FullQualifiedSyntax(this SyntaxNode node, SemanticModel sm)
207 {
208 StringBuilder sb = new();
209 FullQualifiedSyntax(node, sm, sb, true);
210 return sb.ToString();
211 }
212
213 private static void FullQualifiedSyntax(SyntaxNode node, SemanticModel sm, StringBuilder sb, bool isFirstNode)
214 {
215 if (node is NameSyntax ns)
216 {
217 bool isMemberAccess = !isFirstNode && node.Parent is MemberAccessExpressionSyntax;
218 bool isInitializer = isFirstNode && node.Parent is AssignmentExpressionSyntax { Parent: InitializerExpressionSyntax };
219
220 if (!isMemberAccess && !isInitializer)
221 {
222 SymbolInfo nameInfo = sm.GetSymbolInfo(ns);
223 sb.Append(nameInfo.Symbol?.ToDisplayString(FullyQualifiedFormatIncludeGlobal) ?? ns.ToString());
224 return;
225 }
226 }
227
228 bool innerIsFirstNode = true;
229 foreach (var child in node.ChildNodesAndTokens())
230 {
231 if (child.HasLeadingTrivia)
232 {
233 sb.Append(child.GetLeadingTrivia());
234 }
235
236 if (child.IsNode)
237 {
238 var childNode = child.AsNode()!;
239
240 if (node is InterpolationSyntax && childNode is ExpressionSyntax)
241 {
242 ParenEnclosedFullQualifiedSyntax(childNode, sm, sb, isFirstNode: innerIsFirstNode);
243 }
244 else
245 {
246 FullQualifiedSyntax(childNode, sm, sb, isFirstNode: innerIsFirstNode);
247 }
248
249 innerIsFirstNode = false;
250 }
251 else
252 {
253 sb.Append(child);
254 }
255
256 if (child.HasTrailingTrivia)
257 {
258 sb.Append(child.GetTrailingTrivia());
259 }
260 }
261
262 static void ParenEnclosedFullQualifiedSyntax(SyntaxNode node, SemanticModel sm, StringBuilder sb, bool isFirstNode)
263 {
264 sb.Append(SyntaxFactory.Token(SyntaxKind.OpenParenToken));
265 FullQualifiedSyntax(node, sm, sb, isFirstNode);
266 sb.Append(SyntaxFactory.Token(SyntaxKind.CloseParenToken));
267 }
268 }
269
270 public static string SanitizeQualifiedNameForUniqueHint(this string qualifiedName)
271 => qualifiedName
272 // AddSource() doesn't support @ prefix
273 .Replace("@", "")
274 // AddSource() doesn't support angle brackets
275 .Replace("<", "(Of ")
276 .Replace(">", ")");
277
278 public static bool IsGodotExportAttribute(this INamedTypeSymbol symbol)
279 => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.ExportAttr;
280
281 public static bool IsGodotSignalAttribute(this INamedTypeSymbol symbol)
282 => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.SignalAttr;
283
284 public static bool IsGodotMustBeVariantAttribute(this INamedTypeSymbol symbol)
285 => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.MustBeVariantAttr;
286
287 public static bool IsGodotClassNameAttribute(this INamedTypeSymbol symbol)
288 => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.GodotClassNameAttr;
289
290 public static bool IsGodotGlobalClassAttribute(this INamedTypeSymbol symbol)
291 => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.GlobalClassAttr;
292
293 public static bool IsGodotExportToolButtonAttribute(this INamedTypeSymbol symbol)
294 => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.ExportToolButtonAttr;
295
296 public static bool IsGodotToolAttribute(this INamedTypeSymbol symbol)
297 => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.ToolAttr;
298
299 public static bool IsSystemFlagsAttribute(this INamedTypeSymbol symbol)
300 => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.SystemFlagsAttr;
301
302 public static GodotMethodData? HasGodotCompatibleSignature(
303 this IMethodSymbol method,
304 MarshalUtils.TypeCache typeCache
305 )
306 {
307 if (method.IsGenericMethod)
308 return null;
309
310 var retSymbol = method.ReturnType;
311 var retType = method.ReturnsVoid ?
312 null :
313 MarshalUtils.ConvertManagedTypeToMarshalType(method.ReturnType, typeCache);
314
315 if (retType == null && !method.ReturnsVoid)
316 return null;
317
318 var parameters = method.Parameters;
319
320 var paramTypes = parameters
321 // Currently we don't support `ref`, `out`, `in`, `ref readonly` parameters (and we never may)
322 .Where(p => p.RefKind == RefKind.None)
323 // Attempt to determine the variant type
324 .Select(p => MarshalUtils.ConvertManagedTypeToMarshalType(p.Type, typeCache))
325 // Discard parameter types that couldn't be determined (null entries)
326 .Where(t => t != null).Cast<MarshalType>().ToImmutableArray();
327
328 // If any parameter type was incompatible, it was discarded so the length won't match
329 if (parameters.Length > paramTypes.Length)
330 return null; // Ignore incompatible method
331
332 return new GodotMethodData(method, paramTypes,
333 parameters.Select(p => p.Type).ToImmutableArray(),
334 retType != null ? (retType.Value, retSymbol) : null);
335 }
336
337 public static IEnumerable<GodotMethodData> WhereHasGodotCompatibleSignature(
338 this IEnumerable<IMethodSymbol> methods,
339 MarshalUtils.TypeCache typeCache
340 )
341 {
342 foreach (var method in methods)
343 {
344 var methodData = HasGodotCompatibleSignature(method, typeCache);
345
346 if (methodData != null)
347 yield return methodData.Value;
348 }
349 }
350
351 public static IEnumerable<GodotPropertyData> WhereIsGodotCompatibleType(
352 this IEnumerable<IPropertySymbol> properties,
353 MarshalUtils.TypeCache typeCache
354 )
355 {
356 foreach (var property in properties)
357 {
358 var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(property.Type, typeCache);
359
360 if (marshalType == null)
361 continue;
362
363 yield return new GodotPropertyData(property, marshalType.Value);
364 }
365 }
366
367 public static IEnumerable<GodotFieldData> WhereIsGodotCompatibleType(
368 this IEnumerable<IFieldSymbol> fields,
369 MarshalUtils.TypeCache typeCache
370 )
371 {
372 foreach (var field in fields)
373 {
374 // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
375 var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(field.Type, typeCache);
376
377 if (marshalType == null)
378 continue;
379
380 yield return new GodotFieldData(field, marshalType.Value);
381 }
382 }
383
384 public static Location? FirstLocationWithSourceTreeOrDefault(this IEnumerable<Location> locations)
385 {
386 return locations.FirstOrDefault(location => location.SourceTree != null) ?? locations.FirstOrDefault();
387 }
388
389 public static string Path(this Location location)
390 => location.SourceTree?.GetLineSpan(location.SourceSpan).Path
391 ?? location.GetLineSpan().Path;
392
393 public static int StartLine(this Location location)
394 => location.SourceTree?.GetLineSpan(location.SourceSpan).StartLinePosition.Line
395 ?? location.GetLineSpan().StartLinePosition.Line;
396 }
397 }