Debian Codegraph @

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

raw symbols SCIP
1 using System.Collections.Generic;
2 using System.Diagnostics;
3 using System.Linq;
4 using System.Text;
5 using Microsoft.CodeAnalysis;
6 using Microsoft.CodeAnalysis.CSharp;
7 using Microsoft.CodeAnalysis.CSharp.Syntax;
8 using Microsoft.CodeAnalysis.Text;
9
10 namespace Godot.SourceGenerators
11 {
12 [Generator]
13 public class ScriptPropertiesGenerator : ISourceGenerator
14 {
15 public void Initialize(GeneratorInitializationContext context)
16 {
17 }
18
19 public void Execute(GeneratorExecutionContext context)
20 {
21 if (context.IsGodotSourceGeneratorDisabled("ScriptProperties"))
22 return;
23
24 INamedTypeSymbol[] godotClasses = context
25 .Compilation.SyntaxTrees
26 .SelectMany(tree =>
27 tree.GetRoot().DescendantNodes()
28 .OfType<ClassDeclarationSyntax>()
29 .SelectGodotScriptClasses(context.Compilation)
30 // Report and skip non-partial classes
31 .Where(x =>
32 {
33 if (x.cds.IsPartial())
34 {
35 if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out _))
36 {
37 return false;
38 }
39
40 return true;
41 }
42 return false;
43 })
44 .Select(x => x.symbol)
45 )
46 .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
47 .ToArray();
48
49 if (godotClasses.Length > 0)
50 {
51 var typeCache = new MarshalUtils.TypeCache(context.Compilation);
52
53 foreach (var godotClass in godotClasses)
54 {
55 VisitGodotScriptClass(context, typeCache, godotClass);
56 }
57 }
58 }
59
60 private static void VisitGodotScriptClass(
61 GeneratorExecutionContext context,
62 MarshalUtils.TypeCache typeCache,
63 INamedTypeSymbol symbol
64 )
65 {
66 INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
67 string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
68 namespaceSymbol.FullQualifiedNameOmitGlobal() :
69 string.Empty;
70 bool hasNamespace = classNs.Length != 0;
71
72 bool isInnerClass = symbol.ContainingType != null;
73 bool isToolClass = symbol.GetAttributes().Any(a => a.AttributeClass?.IsGodotToolAttribute() ?? false);
74
75 string uniqueHint = symbol.FullQualifiedNameOmitGlobal().SanitizeQualifiedNameForUniqueHint()
76 + "_ScriptProperties.generated";
77
78 var source = new StringBuilder();
79
80 source.Append("using Godot;\n");
81 source.Append("using Godot.NativeInterop;\n");
82 source.Append("\n");
83
84 if (hasNamespace)
85 {
86 source.Append("namespace ");
87 source.Append(classNs);
88 source.Append(" {\n\n");
89 }
90
91 if (isInnerClass)
92 {
93 var containingType = symbol.ContainingType;
94 AppendPartialContainingTypeDeclarations(containingType);
95
96 void AppendPartialContainingTypeDeclarations(INamedTypeSymbol? containingType)
97 {
98 if (containingType == null)
99 return;
100
101 AppendPartialContainingTypeDeclarations(containingType.ContainingType);
102
103 source.Append("partial ");
104 source.Append(containingType.GetDeclarationKeyword());
105 source.Append(" ");
106 source.Append(containingType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
107 source.Append("\n{\n");
108 }
109 }
110
111 source.Append("partial class ");
112 source.Append(symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
113 source.Append("\n{\n");
114
115 var members = symbol.GetMembers();
116
117 var propertySymbols = members
118 .Where(s => !s.IsStatic && s.Kind == SymbolKind.Property)
119 .Cast<IPropertySymbol>()
120 .Where(s => !s.IsIndexer && s.ExplicitInterfaceImplementations.Length == 0);
121
122 var fieldSymbols = members
123 .Where(s => !s.IsStatic && s.Kind == SymbolKind.Field && !s.IsImplicitlyDeclared)
124 .Cast<IFieldSymbol>();
125
126 var godotClassProperties = propertySymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
127 var godotClassFields = fieldSymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
128
129 source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
130
131 source.Append(" /// <summary>\n")
132 .Append(" /// Cached StringNames for the properties and fields contained in this class, for fast lookup.\n")
133 .Append(" /// </summary>\n");
134
135 source.Append(
136 $" public new class PropertyName : {symbol.BaseType!.FullQualifiedNameIncludeGlobal()}.PropertyName {{\n");
137
138 // Generate cached StringNames for methods and properties, for fast lookup
139
140 foreach (var property in godotClassProperties)
141 {
142 string propertyName = property.PropertySymbol.Name;
143
144 source.Append(" /// <summary>\n")
145 .Append(" /// Cached name for the '")
146 .Append(propertyName)
147 .Append("' property.\n")
148 .Append(" /// </summary>\n");
149
150 source.Append(" public new static readonly global::Godot.StringName @");
151 source.Append(propertyName);
152 source.Append(" = \"");
153 source.Append(propertyName);
154 source.Append("\";\n");
155 }
156
157 foreach (var field in godotClassFields)
158 {
159 string fieldName = field.FieldSymbol.Name;
160
161 source.Append(" /// <summary>\n")
162 .Append(" /// Cached name for the '")
163 .Append(fieldName)
164 .Append("' field.\n")
165 .Append(" /// </summary>\n");
166
167 source.Append(" public new static readonly global::Godot.StringName @");
168 source.Append(fieldName);
169 source.Append(" = \"");
170 source.Append(fieldName);
171 source.Append("\";\n");
172 }
173
174 source.Append(" }\n"); // class GodotInternal
175
176 if (godotClassProperties.Length > 0 || godotClassFields.Length > 0)
177 {
178
179 // Generate SetGodotClassPropertyValue
180
181 bool allPropertiesAreReadOnly = godotClassFields.All(fi => fi.FieldSymbol.IsReadOnly) &&
182 godotClassProperties.All(pi => pi.PropertySymbol.IsReadOnly || pi.PropertySymbol.SetMethod!.IsInitOnly);
183
184 if (!allPropertiesAreReadOnly)
185 {
186 source.Append(" /// <inheritdoc/>\n");
187 source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
188 source.Append(" protected override bool SetGodotClassPropertyValue(in godot_string_name name, ");
189 source.Append("in godot_variant value)\n {\n");
190
191 foreach (var property in godotClassProperties)
192 {
193 if (property.PropertySymbol.IsReadOnly || property.PropertySymbol.SetMethod!.IsInitOnly)
194 continue;
195
196 GeneratePropertySetter(property.PropertySymbol.Name,
197 property.PropertySymbol.Type, property.Type, source);
198 }
199
200 foreach (var field in godotClassFields)
201 {
202 if (field.FieldSymbol.IsReadOnly)
203 continue;
204
205 GeneratePropertySetter(field.FieldSymbol.Name,
206 field.FieldSymbol.Type, field.Type, source);
207 }
208
209 source.Append(" return base.SetGodotClassPropertyValue(name, value);\n");
210
211 source.Append(" }\n");
212 }
213
214 // Generate GetGodotClassPropertyValue
215 bool allPropertiesAreWriteOnly = godotClassFields.Length == 0 && godotClassProperties.All(pi => pi.PropertySymbol.IsWriteOnly);
216
217 if (!allPropertiesAreWriteOnly)
218 {
219 source.Append(" /// <inheritdoc/>\n");
220 source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
221 source.Append(" protected override bool GetGodotClassPropertyValue(in godot_string_name name, ");
222 source.Append("out godot_variant value)\n {\n");
223
224 foreach (var property in godotClassProperties)
225 {
226 if (property.PropertySymbol.IsWriteOnly)
227 continue;
228
229 GeneratePropertyGetter(property.PropertySymbol.Name,
230 property.PropertySymbol.Type, property.Type, source);
231 }
232
233 foreach (var field in godotClassFields)
234 {
235 GeneratePropertyGetter(field.FieldSymbol.Name,
236 field.FieldSymbol.Type, field.Type, source);
237 }
238
239 source.Append(" return base.GetGodotClassPropertyValue(name, out value);\n");
240
241 source.Append(" }\n");
242 }
243 // Generate GetGodotPropertyList
244
245 const string DictionaryType = "global::System.Collections.Generic.List<global::Godot.Bridge.PropertyInfo>";
246
247 source.Append(" /// <summary>\n")
248 .Append(" /// Get the property information for all the properties declared in this class.\n")
249 .Append(" /// This method is used by Godot to register the available properties in the editor.\n")
250 .Append(" /// Do not call this method.\n")
251 .Append(" /// </summary>\n");
252
253 source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
254
255 source.Append(" internal new static ")
256 .Append(DictionaryType)
257 .Append(" GetGodotPropertyList()\n {\n");
258
259 source.Append(" var properties = new ")
260 .Append(DictionaryType)
261 .Append("();\n");
262
263 // To retain the definition order (and display categories correctly), we want to
264 // iterate over fields and properties at the same time, sorted by line number.
265 var godotClassPropertiesAndFields = Enumerable.Empty<GodotPropertyOrFieldData>()
266 .Concat(godotClassProperties.Select(propertyData => new GodotPropertyOrFieldData(propertyData)))
267 .Concat(godotClassFields.Select(fieldData => new GodotPropertyOrFieldData(fieldData)))
268 .OrderBy(data => data.Symbol.Locations[0].Path())
269 .ThenBy(data => data.Symbol.Locations[0].StartLine());
270
271 foreach (var member in godotClassPropertiesAndFields)
272 {
273 foreach (var groupingInfo in DetermineGroupingPropertyInfo(member.Symbol))
274 AppendGroupingPropertyInfo(source, groupingInfo);
275
276 var propertyInfo = DeterminePropertyInfo(context, typeCache,
277 member.Symbol, member.Type);
278
279 if (propertyInfo == null)
280 continue;
281
282 if (propertyInfo.Value.Hint == PropertyHint.ToolButton && !isToolClass)
283 {
284 context.ReportDiagnostic(Diagnostic.Create(
285 Common.OnlyToolClassesShouldUseExportToolButtonRule,
286 member.Symbol.Locations.FirstLocationWithSourceTreeOrDefault(),
287 member.Symbol.ToDisplayString()
288 ));
289 continue;
290 }
291
292 AppendPropertyInfo(source, propertyInfo.Value);
293 }
294
295 source.Append(" return properties;\n");
296 source.Append(" }\n");
297
298 source.Append("#pragma warning restore CS0109\n");
299 }
300
301 source.Append("}\n"); // partial class
302
303 if (isInnerClass)
304 {
305 var containingType = symbol.ContainingType;
306
307 while (containingType != null)
308 {
309 source.Append("}\n"); // outer class
310
311 containingType = containingType.ContainingType;
312 }
313 }
314
315 if (hasNamespace)
316 {
317 source.Append("\n}\n");
318 }
319
320 context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
321 }
322
323 private static void GeneratePropertySetter(
324 string propertyMemberName,
325 ITypeSymbol propertyTypeSymbol,
326 MarshalType propertyMarshalType,
327 StringBuilder source
328 )
329 {
330 source.Append(" ");
331
332 source.Append("if (name == PropertyName.@")
333 .Append(propertyMemberName)
334 .Append(") {\n")
335 .Append(" this.@")
336 .Append(propertyMemberName)
337 .Append(" = ")
338 .AppendNativeVariantToManagedExpr("value", propertyTypeSymbol, propertyMarshalType)
339 .Append(";\n")
340 .Append(" return true;\n")
341 .Append(" }\n");
342 }
343
344 private static void GeneratePropertyGetter(
345 string propertyMemberName,
346 ITypeSymbol propertyTypeSymbol,
347 MarshalType propertyMarshalType,
348 StringBuilder source
349 )
350 {
351 source.Append(" ");
352
353 source.Append("if (name == PropertyName.@")
354 .Append(propertyMemberName)
355 .Append(") {\n")
356 .Append(" value = ")
357 .AppendManagedToNativeVariantExpr("this.@" + propertyMemberName,
358 propertyTypeSymbol, propertyMarshalType)
359 .Append(";\n")
360 .Append(" return true;\n")
361 .Append(" }\n");
362 }
363
364 private static void AppendGroupingPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
365 {
366 source.Append(" properties.Add(new(type: (global::Godot.Variant.Type)")
367 .Append((int)VariantType.Nil)
368 .Append(", name: \"")
369 .Append(propertyInfo.Name)
370 .Append("\", hint: (global::Godot.PropertyHint)")
371 .Append((int)PropertyHint.None)
372 .Append(", hintString: \"")
373 .Append(propertyInfo.HintString)
374 .Append("\", usage: (global::Godot.PropertyUsageFlags)")
375 .Append((int)propertyInfo.Usage)
376 .Append(", exported: true));\n");
377 }
378
379 private static void AppendPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
380 {
381 source.Append(" properties.Add(new(type: (global::Godot.Variant.Type)")
382 .Append((int)propertyInfo.Type)
383 .Append(", name: PropertyName.@")
384 .Append(propertyInfo.Name)
385 .Append(", hint: (global::Godot.PropertyHint)")
386 .Append((int)propertyInfo.Hint)
387 .Append(", hintString: \"")
388 .Append(propertyInfo.HintString)
389 .Append("\", usage: (global::Godot.PropertyUsageFlags)")
390 .Append((int)propertyInfo.Usage)
391 .Append(", exported: ")
392 .Append(propertyInfo.Exported ? "true" : "false")
393 .Append("));\n");
394 }
395
396 private static IEnumerable<PropertyInfo> DetermineGroupingPropertyInfo(ISymbol memberSymbol)
397 {
398 foreach (var attr in memberSymbol.GetAttributes())
399 {
400 PropertyUsageFlags? propertyUsage = attr.AttributeClass?.FullQualifiedNameOmitGlobal() switch
401 {
402 GodotClasses.ExportCategoryAttr => PropertyUsageFlags.Category,
403 GodotClasses.ExportGroupAttr => PropertyUsageFlags.Group,
404 GodotClasses.ExportSubgroupAttr => PropertyUsageFlags.Subgroup,
405 _ => null
406 };
407
408 if (propertyUsage is null)
409 continue;
410
411 if (attr.ConstructorArguments.Length > 0 && attr.ConstructorArguments[0].Value is string name)
412 {
413 string? hintString = null;
414 if (propertyUsage != PropertyUsageFlags.Category && attr.ConstructorArguments.Length > 1)
415 hintString = attr.ConstructorArguments[1].Value?.ToString();
416
417 yield return new PropertyInfo(VariantType.Nil, name, PropertyHint.None, hintString,
418 propertyUsage.Value, true);
419 }
420 }
421 }
422
423 private static PropertyInfo? DeterminePropertyInfo(
424 GeneratorExecutionContext context,
425 MarshalUtils.TypeCache typeCache,
426 ISymbol memberSymbol,
427 MarshalType marshalType
428 )
429 {
430 var exportAttr = memberSymbol.GetAttributes()
431 .FirstOrDefault(a => a.AttributeClass?.IsGodotExportAttribute() ?? false);
432
433 var exportToolButtonAttr = memberSymbol.GetAttributes()
434 .FirstOrDefault(a => a.AttributeClass?.IsGodotExportToolButtonAttribute() ?? false);
435
436 if (exportAttr != null && exportToolButtonAttr != null)
437 {
438 context.ReportDiagnostic(Diagnostic.Create(
439 Common.ExportToolButtonShouldNotBeUsedWithExportRule,
440 memberSymbol.Locations.FirstLocationWithSourceTreeOrDefault(),
441 memberSymbol.ToDisplayString()
442 ));
443 return null;
444 }
445
446 var propertySymbol = memberSymbol as IPropertySymbol;
447 var fieldSymbol = memberSymbol as IFieldSymbol;
448
449 if (exportAttr != null && propertySymbol != null)
450 {
451 if (propertySymbol.GetMethod == null || propertySymbol.SetMethod == null || propertySymbol.SetMethod.IsInitOnly)
452 {
453 // Exports can be neither read-only nor write-only but the diagnostic errors for properties are already
454 // reported by ScriptPropertyDefValGenerator.cs so just quit early here.
455 return null;
456 }
457 }
458
459 if (exportToolButtonAttr != null && propertySymbol != null && propertySymbol.GetMethod == null)
460 {
461 context.ReportDiagnostic(Diagnostic.Create(
462 Common.ExportedPropertyIsWriteOnlyRule,
463 propertySymbol.Locations.FirstLocationWithSourceTreeOrDefault(),
464 propertySymbol.ToDisplayString()
465 ));
466 return null;
467 }
468
469 if (exportToolButtonAttr != null && propertySymbol != null)
470 {
471 if (!PropertyIsExpressionBodiedAndReturnsNewCallable(context.Compilation, propertySymbol))
472 {
473 context.ReportDiagnostic(Diagnostic.Create(
474 Common.ExportToolButtonMustBeExpressionBodiedProperty,
475 propertySymbol.Locations.FirstLocationWithSourceTreeOrDefault(),
476 propertySymbol.ToDisplayString()
477 ));
478 return null;
479 }
480
481 static bool PropertyIsExpressionBodiedAndReturnsNewCallable(Compilation compilation, IPropertySymbol? propertySymbol)
482 {
483 if (propertySymbol == null)
484 {
485 return false;
486 }
487
488 var propertyDeclarationSyntax = propertySymbol.DeclaringSyntaxReferences
489 .Select(r => r.GetSyntax() as PropertyDeclarationSyntax).FirstOrDefault();
490 if (propertyDeclarationSyntax == null || propertyDeclarationSyntax.Initializer != null)
491 {
492 return false;
493 }
494
495 if (propertyDeclarationSyntax.AccessorList != null)
496 {
497 var accessors = propertyDeclarationSyntax.AccessorList.Accessors;
498 foreach (var accessor in accessors)
499 {
500 if (!accessor.IsKind(SyntaxKind.GetAccessorDeclaration))
501 {
502 // Only getters are allowed.
503 return false;
504 }
505
506 if (!ExpressionBodyReturnsNewCallable(compilation, accessor.ExpressionBody))
507 {
508 return false;
509 }
510 }
511 }
512 else if (!ExpressionBodyReturnsNewCallable(compilation, propertyDeclarationSyntax.ExpressionBody))
513 {
514 return false;
515 }
516
517 return true;
518 }
519
520 static bool ExpressionBodyReturnsNewCallable(Compilation compilation, ArrowExpressionClauseSyntax? expressionSyntax)
521 {
522 if (expressionSyntax == null)
523 {
524 return false;
525 }
526
527 var semanticModel = compilation.GetSemanticModel(expressionSyntax.SyntaxTree);
528
529 switch (expressionSyntax.Expression)
530 {
531 case ImplicitObjectCreationExpressionSyntax creationExpression:
532 // We already validate that the property type must be 'Callable'
533 // so we can assume this constructor is valid.
534 return true;
535
536 case ObjectCreationExpressionSyntax creationExpression:
537 var typeSymbol = semanticModel.GetSymbolInfo(creationExpression.Type).Symbol as ITypeSymbol;
538 if (typeSymbol != null)
539 {
540 return typeSymbol.FullQualifiedNameOmitGlobal() == GodotClasses.Callable;
541 }
542 break;
543
544 case InvocationExpressionSyntax invocationExpression:
545 var methodSymbol = semanticModel.GetSymbolInfo(invocationExpression).Symbol as IMethodSymbol;
546 if (methodSymbol != null && methodSymbol.Name == "From")
547 {
548 return methodSymbol.ContainingType.FullQualifiedNameOmitGlobal() == GodotClasses.Callable;
549 }
550 break;
551 }
552
553 return false;
554 }
555 }
556
557 var memberType = propertySymbol?.Type ?? fieldSymbol!.Type;
558
559 var memberVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(marshalType)!.Value;
560 string memberName = memberSymbol.Name;
561
562 string? hintString = null;
563
564 if (exportToolButtonAttr != null)
565 {
566 if (memberVariantType != VariantType.Callable)
567 {
568 context.ReportDiagnostic(Diagnostic.Create(
569 Common.ExportToolButtonIsNotCallableRule,
570 memberSymbol.Locations.FirstLocationWithSourceTreeOrDefault(),
571 memberSymbol.ToDisplayString()
572 ));
573 return null;
574 }
575
576 hintString = exportToolButtonAttr.ConstructorArguments[0].Value?.ToString() ?? "";
577 foreach (var namedArgument in exportToolButtonAttr.NamedArguments)
578 {
579 if (namedArgument is { Key: "Icon", Value.Value: string { Length: > 0 } })
580 {
581 hintString += $",{namedArgument.Value.Value}";
582 }
583 }
584
585 return new PropertyInfo(memberVariantType, memberName, PropertyHint.ToolButton,
586 hintString: hintString, PropertyUsageFlags.Editor, exported: true);
587 }
588
589 if (exportAttr == null)
590 {
591 return new PropertyInfo(memberVariantType, memberName, PropertyHint.None,
592 hintString: hintString, PropertyUsageFlags.ScriptVariable, exported: false);
593 }
594
595 if (!TryGetMemberExportHint(typeCache, memberType, exportAttr, memberVariantType,
596 isTypeArgument: false, out var hint, out hintString))
597 {
598 var constructorArguments = exportAttr.ConstructorArguments;
599
600 if (constructorArguments.Length > 0)
601 {
602 var hintValue = exportAttr.ConstructorArguments[0].Value;
603
604 hint = hintValue switch
605 {
606 null => PropertyHint.None,
607 int intValue => (PropertyHint)intValue,
608 _ => (PropertyHint)(long)hintValue
609 };
610
611 hintString = constructorArguments.Length > 1 ?
612 exportAttr.ConstructorArguments[1].Value?.ToString() :
613 null;
614 }
615 else
616 {
617 hint = PropertyHint.None;
618 }
619 }
620
621 var propUsage = PropertyUsageFlags.Default | PropertyUsageFlags.ScriptVariable;
622
623 if (memberVariantType == VariantType.Nil)
624 propUsage |= PropertyUsageFlags.NilIsVariant;
625
626 return new PropertyInfo(memberVariantType, memberName,
627 hint, hintString, propUsage, exported: true);
628 }
629
630 private static bool TryGetMemberExportHint(
631 MarshalUtils.TypeCache typeCache,
632 ITypeSymbol type, AttributeData exportAttr,
633 VariantType variantType, bool isTypeArgument,
634 out PropertyHint hint, out string? hintString
635 )
636 {
637 hint = PropertyHint.None;
638 hintString = null;
639
640 if (variantType == VariantType.Nil)
641 return true; // Variant, no export hint
642
643 if (variantType == VariantType.Int &&
644 type.IsValueType && type.TypeKind == TypeKind.Enum)
645 {
646 bool hasFlagsAttr = type.GetAttributes()
647 .Any(a => a.AttributeClass?.IsSystemFlagsAttribute() ?? false);
648
649 hint = hasFlagsAttr ? PropertyHint.Flags : PropertyHint.Enum;
650
651 var members = type.GetMembers();
652
653 var enumFields = members
654 .Where(s => s.Kind == SymbolKind.Field && s.IsStatic &&
655 s.DeclaredAccessibility == Accessibility.Public &&
656 !s.IsImplicitlyDeclared)
657 .Cast<IFieldSymbol>().ToArray();
658
659 var hintStringBuilder = new StringBuilder();
660 var nameOnlyHintStringBuilder = new StringBuilder();
661
662 // True: enum Foo { Bar, Baz, Qux }
663 // True: enum Foo { Bar = 0, Baz = 1, Qux = 2 }
664 // False: enum Foo { Bar = 0, Baz = 7, Qux = 5 }
665 bool usesDefaultValues = true;
666
667 for (int i = 0; i < enumFields.Length; i++)
668 {
669 var enumField = enumFields[i];
670
671 if (i > 0)
672 {
673 hintStringBuilder.Append(",");
674 nameOnlyHintStringBuilder.Append(",");
675 }
676
677 string enumFieldName = enumField.Name;
678 hintStringBuilder.Append(enumFieldName);
679 nameOnlyHintStringBuilder.Append(enumFieldName);
680
681 long val = enumField.ConstantValue switch
682 {
683 sbyte v => v,
684 short v => v,
685 int v => v,
686 long v => v,
687 byte v => v,
688 ushort v => v,
689 uint v => v,
690 ulong v => (long)v,
691 _ => 0
692 };
693
694 uint expectedVal = (uint)(hint == PropertyHint.Flags ? 1 << i : i);
695 if (val != expectedVal)
696 usesDefaultValues = false;
697
698 hintStringBuilder.Append(":");
699 hintStringBuilder.Append(val);
700 }
701
702 hintString = !usesDefaultValues ?
703 hintStringBuilder.ToString() :
704 // If we use the format NAME:VAL, that's what the editor displays.
705 // That's annoying if the user is not using custom values for the enum constants.
706 // This may not be needed in the future if the editor is changed to not display values.
707 nameOnlyHintStringBuilder.ToString();
708
709 return true;
710 }
711
712 if (variantType == VariantType.Object && type is INamedTypeSymbol memberNamedType)
713 {
714 if (TryGetNodeOrResourceType(exportAttr, out hint, out hintString))
715 {
716 return true;
717 }
718
719 if (memberNamedType.InheritsFrom("GodotSharp", "Godot.Resource"))
720 {
721 hint = PropertyHint.ResourceType;
722 hintString = GetTypeName(memberNamedType);
723
724 return true;
725 }
726
727 if (memberNamedType.InheritsFrom("GodotSharp", "Godot.Node"))
728 {
729 hint = PropertyHint.NodeType;
730 hintString = GetTypeName(memberNamedType);
731
732 return true;
733 }
734 }
735
736 static bool TryGetNodeOrResourceType(AttributeData exportAttr, out PropertyHint hint, out string? hintString)
737 {
738 hint = PropertyHint.None;
739 hintString = null;
740
741 if (exportAttr.ConstructorArguments.Length <= 1) return false;
742
743 var hintValue = exportAttr.ConstructorArguments[0].Value;
744
745 var hintEnum = hintValue switch
746 {
747 null => PropertyHint.None,
748 int intValue => (PropertyHint)intValue,
749 _ => (PropertyHint)(long)hintValue
750 };
751
752 if (!hintEnum.HasFlag(PropertyHint.NodeType) && !hintEnum.HasFlag(PropertyHint.ResourceType))
753 return false;
754
755 var hintStringValue = exportAttr.ConstructorArguments[1].Value?.ToString();
756 if (string.IsNullOrWhiteSpace(hintStringValue))
757 {
758 return false;
759 }
760
761 hint = hintEnum;
762 hintString = hintStringValue;
763
764 return true;
765 }
766
767 static string GetTypeName(INamedTypeSymbol memberSymbol)
768 {
769 if (memberSymbol.GetAttributes()
770 .Any(a => a.AttributeClass?.IsGodotGlobalClassAttribute() ?? false))
771 {
772 return memberSymbol.Name;
773 }
774
775 return memberSymbol.GetGodotScriptNativeClassName()!;
776 }
777
778 static bool GetStringArrayEnumHint(VariantType elementVariantType,
779 AttributeData exportAttr, out string? hintString)
780 {
781 var constructorArguments = exportAttr.ConstructorArguments;
782
783 if (constructorArguments.Length > 0)
784 {
785 var presetHintValue = exportAttr.ConstructorArguments[0].Value;
786
787 PropertyHint presetHint = presetHintValue switch
788 {
789 null => PropertyHint.None,
790 int intValue => (PropertyHint)intValue,
791 _ => (PropertyHint)(long)presetHintValue
792 };
793
794 if (presetHint == PropertyHint.Enum)
795 {
796 string? presetHintString = constructorArguments.Length > 1 ?
797 exportAttr.ConstructorArguments[1].Value?.ToString() :
798 null;
799
800 hintString = (int)elementVariantType + "/" + (int)PropertyHint.Enum + ":";
801
802 if (presetHintString != null)
803 hintString += presetHintString;
804
805 return true;
806 }
807 }
808
809 hintString = null;
810 return false;
811 }
812
813 if (!isTypeArgument && variantType == VariantType.Array)
814 {
815 var elementType = MarshalUtils.GetArrayElementType(type);
816
817 if (elementType == null)
818 return false; // Non-generic Array, so there's no hint to add.
819
820 if (elementType.TypeKind == TypeKind.TypeParameter)
821 return false; // The generic is not constructed, we can't really hint anything.
822
823 var elementMarshalType = MarshalUtils.ConvertManagedTypeToMarshalType(elementType, typeCache)!.Value;
824 var elementVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(elementMarshalType)!.Value;
825
826 bool isPresetHint = false;
827
828 if (elementVariantType == VariantType.String || elementVariantType == VariantType.StringName)
829 isPresetHint = GetStringArrayEnumHint(elementVariantType, exportAttr, out hintString);
830
831 if (!isPresetHint)
832 {
833 bool hintRes = TryGetMemberExportHint(typeCache, elementType,
834 exportAttr, elementVariantType, isTypeArgument: true,
835 out var elementHint, out var elementHintString);
836
837 // Format: type/hint:hint_string
838 if (hintRes)
839 {
840 hintString = (int)elementVariantType + "/" + (int)elementHint + ":";
841
842 if (elementHintString != null)
843 hintString += elementHintString;
844 }
845 else
846 {
847 hintString = (int)elementVariantType + "/" + (int)PropertyHint.None + ":";
848 }
849 }
850
851 hint = PropertyHint.TypeString;
852
853 return hintString != null;
854 }
855
856 if (!isTypeArgument && variantType == VariantType.PackedStringArray)
857 {
858 if (GetStringArrayEnumHint(VariantType.String, exportAttr, out hintString))
859 {
860 hint = PropertyHint.TypeString;
861 return true;
862 }
863 }
864
865 if (!isTypeArgument && variantType == VariantType.Dictionary)
866 {
867 var elementTypes = MarshalUtils.GetGenericElementTypes(type);
868
869 if (elementTypes == null)
870 return false; // Non-generic Dictionary, so there's no hint to add
871 Debug.Assert(elementTypes.Length == 2);
872
873 var keyElementMarshalType = MarshalUtils.ConvertManagedTypeToMarshalType(elementTypes[0], typeCache);
874 var valueElementMarshalType = MarshalUtils.ConvertManagedTypeToMarshalType(elementTypes[1], typeCache);
875
876 if (keyElementMarshalType == null || valueElementMarshalType == null)
877 {
878 // To maintain compatibility with previous versions of Godot before 4.4,
879 // we must preserve the old behavior for generic dictionaries with non-marshallable
880 // generic type arguments.
881 return false;
882 }
883
884 var keyElementVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(keyElementMarshalType.Value)!.Value;
885 var keyIsPresetHint = false;
886 var keyHintString = (string?)null;
887
888 if (keyElementVariantType == VariantType.String || keyElementVariantType == VariantType.StringName)
889 keyIsPresetHint = GetStringArrayEnumHint(keyElementVariantType, exportAttr, out keyHintString);
890
891 if (!keyIsPresetHint)
892 {
893 bool hintRes = TryGetMemberExportHint(typeCache, elementTypes[0],
894 exportAttr, keyElementVariantType, isTypeArgument: true,
895 out var keyElementHint, out var keyElementHintString);
896
897 // Format: type/hint:hint_string
898 if (hintRes)
899 {
900 keyHintString = (int)keyElementVariantType + "/" + (int)keyElementHint + ":";
901
902 if (keyElementHintString != null)
903 keyHintString += keyElementHintString;
904 }
905 else
906 {
907 keyHintString = (int)keyElementVariantType + "/" + (int)PropertyHint.None + ":";
908 }
909 }
910
911 var valueElementVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(valueElementMarshalType.Value)!.Value;
912 var valueIsPresetHint = false;
913 var valueHintString = (string?)null;
914
915 if (valueElementVariantType == VariantType.String || valueElementVariantType == VariantType.StringName)
916 valueIsPresetHint = GetStringArrayEnumHint(valueElementVariantType, exportAttr, out valueHintString);
917
918 if (!valueIsPresetHint)
919 {
920 bool hintRes = TryGetMemberExportHint(typeCache, elementTypes[1],
921 exportAttr, valueElementVariantType, isTypeArgument: true,
922 out var valueElementHint, out var valueElementHintString);
923
924 // Format: type/hint:hint_string
925 if (hintRes)
926 {
927 valueHintString = (int)valueElementVariantType + "/" + (int)valueElementHint + ":";
928
929 if (valueElementHintString != null)
930 valueHintString += valueElementHintString;
931 }
932 else
933 {
934 valueHintString = (int)valueElementVariantType + "/" + (int)PropertyHint.None + ":";
935 }
936 }
937
938 hint = PropertyHint.TypeString;
939
940 hintString = keyHintString != null && valueHintString != null ? $"{keyHintString};{valueHintString}" : null;
941 return hintString != null;
942 }
943
944 return false;
945 }
946 }
947 }