ScriptPropertiesGenerator.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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.Syntax;
  7. using Microsoft.CodeAnalysis.Text;
  8. namespace Godot.SourceGenerators
  9. {
  10. [Generator]
  11. public class ScriptPropertiesGenerator : ISourceGenerator
  12. {
  13. public void Initialize(GeneratorInitializationContext context)
  14. {
  15. }
  16. public void Execute(GeneratorExecutionContext context)
  17. {
  18. if (context.IsGodotSourceGeneratorDisabled("ScriptProperties"))
  19. return;
  20. INamedTypeSymbol[] godotClasses = context
  21. .Compilation.SyntaxTrees
  22. .SelectMany(tree =>
  23. tree.GetRoot().DescendantNodes()
  24. .OfType<ClassDeclarationSyntax>()
  25. .SelectGodotScriptClasses(context.Compilation)
  26. // Report and skip non-partial classes
  27. .Where(x =>
  28. {
  29. if (x.cds.IsPartial())
  30. {
  31. if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out _))
  32. {
  33. return false;
  34. }
  35. return true;
  36. }
  37. return false;
  38. })
  39. .Select(x => x.symbol)
  40. )
  41. .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
  42. .ToArray();
  43. if (godotClasses.Length > 0)
  44. {
  45. var typeCache = new MarshalUtils.TypeCache(context.Compilation);
  46. foreach (var godotClass in godotClasses)
  47. {
  48. VisitGodotScriptClass(context, typeCache, godotClass);
  49. }
  50. }
  51. }
  52. private static void VisitGodotScriptClass(
  53. GeneratorExecutionContext context,
  54. MarshalUtils.TypeCache typeCache,
  55. INamedTypeSymbol symbol
  56. )
  57. {
  58. INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
  59. string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
  60. namespaceSymbol.FullQualifiedNameOmitGlobal() :
  61. string.Empty;
  62. bool hasNamespace = classNs.Length != 0;
  63. bool isInnerClass = symbol.ContainingType != null;
  64. bool isToolClass = symbol.GetAttributes().Any(a => a.AttributeClass?.IsGodotToolAttribute() ?? false);
  65. string uniqueHint = symbol.FullQualifiedNameOmitGlobal().SanitizeQualifiedNameForUniqueHint()
  66. + "_ScriptProperties.generated";
  67. var source = new StringBuilder();
  68. source.Append("using Godot;\n");
  69. source.Append("using Godot.NativeInterop;\n");
  70. source.Append("\n");
  71. if (hasNamespace)
  72. {
  73. source.Append("namespace ");
  74. source.Append(classNs);
  75. source.Append(" {\n\n");
  76. }
  77. if (isInnerClass)
  78. {
  79. var containingType = symbol.ContainingType;
  80. AppendPartialContainingTypeDeclarations(containingType);
  81. void AppendPartialContainingTypeDeclarations(INamedTypeSymbol? containingType)
  82. {
  83. if (containingType == null)
  84. return;
  85. AppendPartialContainingTypeDeclarations(containingType.ContainingType);
  86. source.Append("partial ");
  87. source.Append(containingType.GetDeclarationKeyword());
  88. source.Append(" ");
  89. source.Append(containingType.NameWithTypeParameters());
  90. source.Append("\n{\n");
  91. }
  92. }
  93. source.Append("partial class ");
  94. source.Append(symbol.NameWithTypeParameters());
  95. source.Append("\n{\n");
  96. var members = symbol.GetMembers();
  97. var propertySymbols = members
  98. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Property)
  99. .Cast<IPropertySymbol>()
  100. .Where(s => !s.IsIndexer && s.ExplicitInterfaceImplementations.Length == 0);
  101. var fieldSymbols = members
  102. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Field && !s.IsImplicitlyDeclared)
  103. .Cast<IFieldSymbol>();
  104. var godotClassProperties = propertySymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
  105. var godotClassFields = fieldSymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
  106. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  107. source.Append(" /// <summary>\n")
  108. .Append(" /// Cached StringNames for the properties and fields contained in this class, for fast lookup.\n")
  109. .Append(" /// </summary>\n");
  110. source.Append(
  111. $" public new class PropertyName : {symbol.BaseType!.FullQualifiedNameIncludeGlobal()}.PropertyName {{\n");
  112. // Generate cached StringNames for methods and properties, for fast lookup
  113. foreach (var property in godotClassProperties)
  114. {
  115. string propertyName = property.PropertySymbol.Name;
  116. source.Append(" /// <summary>\n")
  117. .Append(" /// Cached name for the '")
  118. .Append(propertyName)
  119. .Append("' property.\n")
  120. .Append(" /// </summary>\n");
  121. source.Append(" public new static readonly global::Godot.StringName @");
  122. source.Append(propertyName);
  123. source.Append(" = \"");
  124. source.Append(propertyName);
  125. source.Append("\";\n");
  126. }
  127. foreach (var field in godotClassFields)
  128. {
  129. string fieldName = field.FieldSymbol.Name;
  130. source.Append(" /// <summary>\n")
  131. .Append(" /// Cached name for the '")
  132. .Append(fieldName)
  133. .Append("' field.\n")
  134. .Append(" /// </summary>\n");
  135. source.Append(" public new static readonly global::Godot.StringName @");
  136. source.Append(fieldName);
  137. source.Append(" = \"");
  138. source.Append(fieldName);
  139. source.Append("\";\n");
  140. }
  141. source.Append(" }\n"); // class GodotInternal
  142. if (godotClassProperties.Length > 0 || godotClassFields.Length > 0)
  143. {
  144. // Generate SetGodotClassPropertyValue
  145. bool allPropertiesAreReadOnly = godotClassFields.All(fi => fi.FieldSymbol.IsReadOnly) &&
  146. godotClassProperties.All(pi => pi.PropertySymbol.IsReadOnly || pi.PropertySymbol.SetMethod!.IsInitOnly);
  147. if (!allPropertiesAreReadOnly)
  148. {
  149. source.Append(" /// <inheritdoc/>\n");
  150. source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
  151. source.Append(" protected override bool SetGodotClassPropertyValue(in godot_string_name name, ");
  152. source.Append("in godot_variant value)\n {\n");
  153. foreach (var property in godotClassProperties)
  154. {
  155. if (property.PropertySymbol.IsReadOnly || property.PropertySymbol.SetMethod!.IsInitOnly)
  156. continue;
  157. GeneratePropertySetter(property.PropertySymbol.Name,
  158. property.PropertySymbol.Type, property.Type, source);
  159. }
  160. foreach (var field in godotClassFields)
  161. {
  162. if (field.FieldSymbol.IsReadOnly)
  163. continue;
  164. GeneratePropertySetter(field.FieldSymbol.Name,
  165. field.FieldSymbol.Type, field.Type, source);
  166. }
  167. source.Append(" return base.SetGodotClassPropertyValue(name, value);\n");
  168. source.Append(" }\n");
  169. }
  170. // Generate GetGodotClassPropertyValue
  171. bool allPropertiesAreWriteOnly = godotClassFields.Length == 0 && godotClassProperties.All(pi => pi.PropertySymbol.IsWriteOnly);
  172. if (!allPropertiesAreWriteOnly)
  173. {
  174. source.Append(" /// <inheritdoc/>\n");
  175. source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
  176. source.Append(" protected override bool GetGodotClassPropertyValue(in godot_string_name name, ");
  177. source.Append("out godot_variant value)\n {\n");
  178. foreach (var property in godotClassProperties)
  179. {
  180. if (property.PropertySymbol.IsWriteOnly)
  181. continue;
  182. GeneratePropertyGetter(property.PropertySymbol.Name,
  183. property.PropertySymbol.Type, property.Type, source);
  184. }
  185. foreach (var field in godotClassFields)
  186. {
  187. GeneratePropertyGetter(field.FieldSymbol.Name,
  188. field.FieldSymbol.Type, field.Type, source);
  189. }
  190. source.Append(" return base.GetGodotClassPropertyValue(name, out value);\n");
  191. source.Append(" }\n");
  192. }
  193. // Generate GetGodotPropertyList
  194. const string DictionaryType = "global::System.Collections.Generic.List<global::Godot.Bridge.PropertyInfo>";
  195. source.Append(" /// <summary>\n")
  196. .Append(" /// Get the property information for all the properties declared in this class.\n")
  197. .Append(" /// This method is used by Godot to register the available properties in the editor.\n")
  198. .Append(" /// Do not call this method.\n")
  199. .Append(" /// </summary>\n");
  200. source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
  201. source.Append(" internal new static ")
  202. .Append(DictionaryType)
  203. .Append(" GetGodotPropertyList()\n {\n");
  204. source.Append(" var properties = new ")
  205. .Append(DictionaryType)
  206. .Append("();\n");
  207. // To retain the definition order (and display categories correctly), we want to
  208. // iterate over fields and properties at the same time, sorted by line number.
  209. var godotClassPropertiesAndFields = Enumerable.Empty<GodotPropertyOrFieldData>()
  210. .Concat(godotClassProperties.Select(propertyData => new GodotPropertyOrFieldData(propertyData)))
  211. .Concat(godotClassFields.Select(fieldData => new GodotPropertyOrFieldData(fieldData)))
  212. .OrderBy(data => data.Symbol.Locations[0].Path())
  213. .ThenBy(data => data.Symbol.Locations[0].StartLine());
  214. foreach (var member in godotClassPropertiesAndFields)
  215. {
  216. foreach (var groupingInfo in DetermineGroupingPropertyInfo(member.Symbol))
  217. AppendGroupingPropertyInfo(source, groupingInfo);
  218. var propertyInfo = DeterminePropertyInfo(context, typeCache,
  219. member.Symbol, member.Type);
  220. if (propertyInfo == null)
  221. continue;
  222. if (propertyInfo.Value.Hint == PropertyHint.ToolButton && !isToolClass)
  223. {
  224. context.ReportDiagnostic(Diagnostic.Create(
  225. Common.OnlyToolClassesShouldUseExportToolButtonRule,
  226. member.Symbol.Locations.FirstLocationWithSourceTreeOrDefault(),
  227. member.Symbol.ToDisplayString()
  228. ));
  229. continue;
  230. }
  231. AppendPropertyInfo(source, propertyInfo.Value);
  232. }
  233. source.Append(" return properties;\n");
  234. source.Append(" }\n");
  235. source.Append("#pragma warning restore CS0109\n");
  236. }
  237. source.Append("}\n"); // partial class
  238. if (isInnerClass)
  239. {
  240. var containingType = symbol.ContainingType;
  241. while (containingType != null)
  242. {
  243. source.Append("}\n"); // outer class
  244. containingType = containingType.ContainingType;
  245. }
  246. }
  247. if (hasNamespace)
  248. {
  249. source.Append("\n}\n");
  250. }
  251. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  252. }
  253. private static void GeneratePropertySetter(
  254. string propertyMemberName,
  255. ITypeSymbol propertyTypeSymbol,
  256. MarshalType propertyMarshalType,
  257. StringBuilder source
  258. )
  259. {
  260. source.Append(" ");
  261. source.Append("if (name == PropertyName.@")
  262. .Append(propertyMemberName)
  263. .Append(") {\n")
  264. .Append(" this.@")
  265. .Append(propertyMemberName)
  266. .Append(" = ")
  267. .AppendNativeVariantToManagedExpr("value", propertyTypeSymbol, propertyMarshalType)
  268. .Append(";\n")
  269. .Append(" return true;\n")
  270. .Append(" }\n");
  271. }
  272. private static void GeneratePropertyGetter(
  273. string propertyMemberName,
  274. ITypeSymbol propertyTypeSymbol,
  275. MarshalType propertyMarshalType,
  276. StringBuilder source
  277. )
  278. {
  279. source.Append(" ");
  280. source.Append("if (name == PropertyName.@")
  281. .Append(propertyMemberName)
  282. .Append(") {\n")
  283. .Append(" value = ")
  284. .AppendManagedToNativeVariantExpr("this.@" + propertyMemberName,
  285. propertyTypeSymbol, propertyMarshalType)
  286. .Append(";\n")
  287. .Append(" return true;\n")
  288. .Append(" }\n");
  289. }
  290. private static void AppendGroupingPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
  291. {
  292. source.Append(" properties.Add(new(type: (global::Godot.Variant.Type)")
  293. .Append((int)VariantType.Nil)
  294. .Append(", name: \"")
  295. .Append(propertyInfo.Name)
  296. .Append("\", hint: (global::Godot.PropertyHint)")
  297. .Append((int)PropertyHint.None)
  298. .Append(", hintString: \"")
  299. .Append(propertyInfo.HintString)
  300. .Append("\", usage: (global::Godot.PropertyUsageFlags)")
  301. .Append((int)propertyInfo.Usage)
  302. .Append(", exported: true));\n");
  303. }
  304. private static void AppendPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
  305. {
  306. source.Append(" properties.Add(new(type: (global::Godot.Variant.Type)")
  307. .Append((int)propertyInfo.Type)
  308. .Append(", name: PropertyName.@")
  309. .Append(propertyInfo.Name)
  310. .Append(", hint: (global::Godot.PropertyHint)")
  311. .Append((int)propertyInfo.Hint)
  312. .Append(", hintString: \"")
  313. .Append(propertyInfo.HintString)
  314. .Append("\", usage: (global::Godot.PropertyUsageFlags)")
  315. .Append((int)propertyInfo.Usage)
  316. .Append(", exported: ")
  317. .Append(propertyInfo.Exported ? "true" : "false")
  318. .Append("));\n");
  319. }
  320. private static IEnumerable<PropertyInfo> DetermineGroupingPropertyInfo(ISymbol memberSymbol)
  321. {
  322. foreach (var attr in memberSymbol.GetAttributes())
  323. {
  324. PropertyUsageFlags? propertyUsage = attr.AttributeClass?.FullQualifiedNameOmitGlobal() switch
  325. {
  326. GodotClasses.ExportCategoryAttr => PropertyUsageFlags.Category,
  327. GodotClasses.ExportGroupAttr => PropertyUsageFlags.Group,
  328. GodotClasses.ExportSubgroupAttr => PropertyUsageFlags.Subgroup,
  329. _ => null
  330. };
  331. if (propertyUsage is null)
  332. continue;
  333. if (attr.ConstructorArguments.Length > 0 && attr.ConstructorArguments[0].Value is string name)
  334. {
  335. string? hintString = null;
  336. if (propertyUsage != PropertyUsageFlags.Category && attr.ConstructorArguments.Length > 1)
  337. hintString = attr.ConstructorArguments[1].Value?.ToString();
  338. yield return new PropertyInfo(VariantType.Nil, name, PropertyHint.None, hintString,
  339. propertyUsage.Value, true);
  340. }
  341. }
  342. }
  343. private static PropertyInfo? DeterminePropertyInfo(
  344. GeneratorExecutionContext context,
  345. MarshalUtils.TypeCache typeCache,
  346. ISymbol memberSymbol,
  347. MarshalType marshalType
  348. )
  349. {
  350. var exportAttr = memberSymbol.GetAttributes()
  351. .FirstOrDefault(a => a.AttributeClass?.IsGodotExportAttribute() ?? false);
  352. var exportToolButtonAttr = memberSymbol.GetAttributes()
  353. .FirstOrDefault(a => a.AttributeClass?.IsGodotExportToolButtonAttribute() ?? false);
  354. if (exportAttr != null && exportToolButtonAttr != null)
  355. {
  356. context.ReportDiagnostic(Diagnostic.Create(
  357. Common.ExportToolButtonShouldNotBeUsedWithExportRule,
  358. memberSymbol.Locations.FirstLocationWithSourceTreeOrDefault(),
  359. memberSymbol.ToDisplayString()
  360. ));
  361. return null;
  362. }
  363. var propertySymbol = memberSymbol as IPropertySymbol;
  364. var fieldSymbol = memberSymbol as IFieldSymbol;
  365. if (exportAttr != null && propertySymbol != null)
  366. {
  367. if (propertySymbol.GetMethod == null)
  368. {
  369. // This should never happen, as we filtered WriteOnly properties, but just in case.
  370. context.ReportDiagnostic(Diagnostic.Create(
  371. Common.ExportedPropertyIsWriteOnlyRule,
  372. propertySymbol.Locations.FirstLocationWithSourceTreeOrDefault(),
  373. propertySymbol.ToDisplayString()
  374. ));
  375. return null;
  376. }
  377. if (propertySymbol.SetMethod == null || propertySymbol.SetMethod.IsInitOnly)
  378. {
  379. // This should never happen, as we filtered ReadOnly properties, but just in case.
  380. context.ReportDiagnostic(Diagnostic.Create(
  381. Common.ExportedMemberIsReadOnlyRule,
  382. propertySymbol.Locations.FirstLocationWithSourceTreeOrDefault(),
  383. propertySymbol.ToDisplayString()
  384. ));
  385. return null;
  386. }
  387. }
  388. if (exportToolButtonAttr != null && propertySymbol != null && propertySymbol.GetMethod == null)
  389. {
  390. context.ReportDiagnostic(Diagnostic.Create(
  391. Common.ExportedPropertyIsWriteOnlyRule,
  392. propertySymbol.Locations.FirstLocationWithSourceTreeOrDefault(),
  393. propertySymbol.ToDisplayString()
  394. ));
  395. return null;
  396. }
  397. var memberType = propertySymbol?.Type ?? fieldSymbol!.Type;
  398. var memberVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(marshalType)!.Value;
  399. string memberName = memberSymbol.Name;
  400. string? hintString = null;
  401. if (exportToolButtonAttr != null)
  402. {
  403. if (memberVariantType != VariantType.Callable)
  404. {
  405. context.ReportDiagnostic(Diagnostic.Create(
  406. Common.ExportToolButtonIsNotCallableRule,
  407. memberSymbol.Locations.FirstLocationWithSourceTreeOrDefault(),
  408. memberSymbol.ToDisplayString()
  409. ));
  410. return null;
  411. }
  412. hintString = exportToolButtonAttr.ConstructorArguments[0].Value?.ToString() ?? "";
  413. foreach (var namedArgument in exportToolButtonAttr.NamedArguments)
  414. {
  415. if (namedArgument is { Key: "Icon", Value.Value: string { Length: > 0 } })
  416. {
  417. hintString += $",{namedArgument.Value.Value}";
  418. }
  419. }
  420. return new PropertyInfo(memberVariantType, memberName, PropertyHint.ToolButton,
  421. hintString: hintString, PropertyUsageFlags.Editor, exported: true);
  422. }
  423. if (exportAttr == null)
  424. {
  425. return new PropertyInfo(memberVariantType, memberName, PropertyHint.None,
  426. hintString: hintString, PropertyUsageFlags.ScriptVariable, exported: false);
  427. }
  428. if (!TryGetMemberExportHint(typeCache, memberType, exportAttr, memberVariantType,
  429. isTypeArgument: false, out var hint, out hintString))
  430. {
  431. var constructorArguments = exportAttr.ConstructorArguments;
  432. if (constructorArguments.Length > 0)
  433. {
  434. var hintValue = exportAttr.ConstructorArguments[0].Value;
  435. hint = hintValue switch
  436. {
  437. null => PropertyHint.None,
  438. int intValue => (PropertyHint)intValue,
  439. _ => (PropertyHint)(long)hintValue
  440. };
  441. hintString = constructorArguments.Length > 1 ?
  442. exportAttr.ConstructorArguments[1].Value?.ToString() :
  443. null;
  444. }
  445. else
  446. {
  447. hint = PropertyHint.None;
  448. }
  449. }
  450. var propUsage = PropertyUsageFlags.Default | PropertyUsageFlags.ScriptVariable;
  451. if (memberVariantType == VariantType.Nil)
  452. propUsage |= PropertyUsageFlags.NilIsVariant;
  453. return new PropertyInfo(memberVariantType, memberName,
  454. hint, hintString, propUsage, exported: true);
  455. }
  456. private static bool TryGetMemberExportHint(
  457. MarshalUtils.TypeCache typeCache,
  458. ITypeSymbol type, AttributeData exportAttr,
  459. VariantType variantType, bool isTypeArgument,
  460. out PropertyHint hint, out string? hintString
  461. )
  462. {
  463. hint = PropertyHint.None;
  464. hintString = null;
  465. if (variantType == VariantType.Nil)
  466. return true; // Variant, no export hint
  467. if (variantType == VariantType.Int &&
  468. type.IsValueType && type.TypeKind == TypeKind.Enum)
  469. {
  470. bool hasFlagsAttr = type.GetAttributes()
  471. .Any(a => a.AttributeClass?.IsSystemFlagsAttribute() ?? false);
  472. hint = hasFlagsAttr ? PropertyHint.Flags : PropertyHint.Enum;
  473. var members = type.GetMembers();
  474. var enumFields = members
  475. .Where(s => s.Kind == SymbolKind.Field && s.IsStatic &&
  476. s.DeclaredAccessibility == Accessibility.Public &&
  477. !s.IsImplicitlyDeclared)
  478. .Cast<IFieldSymbol>().ToArray();
  479. var hintStringBuilder = new StringBuilder();
  480. var nameOnlyHintStringBuilder = new StringBuilder();
  481. // True: enum Foo { Bar, Baz, Qux }
  482. // True: enum Foo { Bar = 0, Baz = 1, Qux = 2 }
  483. // False: enum Foo { Bar = 0, Baz = 7, Qux = 5 }
  484. bool usesDefaultValues = true;
  485. for (int i = 0; i < enumFields.Length; i++)
  486. {
  487. var enumField = enumFields[i];
  488. if (i > 0)
  489. {
  490. hintStringBuilder.Append(",");
  491. nameOnlyHintStringBuilder.Append(",");
  492. }
  493. string enumFieldName = enumField.Name;
  494. hintStringBuilder.Append(enumFieldName);
  495. nameOnlyHintStringBuilder.Append(enumFieldName);
  496. long val = enumField.ConstantValue switch
  497. {
  498. sbyte v => v,
  499. short v => v,
  500. int v => v,
  501. long v => v,
  502. byte v => v,
  503. ushort v => v,
  504. uint v => v,
  505. ulong v => (long)v,
  506. _ => 0
  507. };
  508. uint expectedVal = (uint)(hint == PropertyHint.Flags ? 1 << i : i);
  509. if (val != expectedVal)
  510. usesDefaultValues = false;
  511. hintStringBuilder.Append(":");
  512. hintStringBuilder.Append(val);
  513. }
  514. hintString = !usesDefaultValues ?
  515. hintStringBuilder.ToString() :
  516. // If we use the format NAME:VAL, that's what the editor displays.
  517. // That's annoying if the user is not using custom values for the enum constants.
  518. // This may not be needed in the future if the editor is changed to not display values.
  519. nameOnlyHintStringBuilder.ToString();
  520. return true;
  521. }
  522. if (variantType == VariantType.Object && type is INamedTypeSymbol memberNamedType)
  523. {
  524. if (TryGetNodeOrResourceType(exportAttr, out hint, out hintString))
  525. {
  526. return true;
  527. }
  528. if (memberNamedType.InheritsFrom("GodotSharp", "Godot.Resource"))
  529. {
  530. hint = PropertyHint.ResourceType;
  531. hintString = GetTypeName(memberNamedType);
  532. return true;
  533. }
  534. if (memberNamedType.InheritsFrom("GodotSharp", "Godot.Node"))
  535. {
  536. hint = PropertyHint.NodeType;
  537. hintString = GetTypeName(memberNamedType);
  538. return true;
  539. }
  540. }
  541. static bool TryGetNodeOrResourceType(AttributeData exportAttr, out PropertyHint hint, out string? hintString)
  542. {
  543. hint = PropertyHint.None;
  544. hintString = null;
  545. if (exportAttr.ConstructorArguments.Length <= 1) return false;
  546. var hintValue = exportAttr.ConstructorArguments[0].Value;
  547. var hintEnum = hintValue switch
  548. {
  549. null => PropertyHint.None,
  550. int intValue => (PropertyHint)intValue,
  551. _ => (PropertyHint)(long)hintValue
  552. };
  553. if (!hintEnum.HasFlag(PropertyHint.NodeType) && !hintEnum.HasFlag(PropertyHint.ResourceType))
  554. return false;
  555. var hintStringValue = exportAttr.ConstructorArguments[1].Value?.ToString();
  556. if (string.IsNullOrWhiteSpace(hintStringValue))
  557. {
  558. return false;
  559. }
  560. hint = hintEnum;
  561. hintString = hintStringValue;
  562. return true;
  563. }
  564. static string GetTypeName(INamedTypeSymbol memberSymbol)
  565. {
  566. if (memberSymbol.GetAttributes()
  567. .Any(a => a.AttributeClass?.IsGodotGlobalClassAttribute() ?? false))
  568. {
  569. return memberSymbol.Name;
  570. }
  571. return memberSymbol.GetGodotScriptNativeClassName()!;
  572. }
  573. static bool GetStringArrayEnumHint(VariantType elementVariantType,
  574. AttributeData exportAttr, out string? hintString)
  575. {
  576. var constructorArguments = exportAttr.ConstructorArguments;
  577. if (constructorArguments.Length > 0)
  578. {
  579. var presetHintValue = exportAttr.ConstructorArguments[0].Value;
  580. PropertyHint presetHint = presetHintValue switch
  581. {
  582. null => PropertyHint.None,
  583. int intValue => (PropertyHint)intValue,
  584. _ => (PropertyHint)(long)presetHintValue
  585. };
  586. if (presetHint == PropertyHint.Enum)
  587. {
  588. string? presetHintString = constructorArguments.Length > 1 ?
  589. exportAttr.ConstructorArguments[1].Value?.ToString() :
  590. null;
  591. hintString = (int)elementVariantType + "/" + (int)PropertyHint.Enum + ":";
  592. if (presetHintString != null)
  593. hintString += presetHintString;
  594. return true;
  595. }
  596. }
  597. hintString = null;
  598. return false;
  599. }
  600. if (!isTypeArgument && variantType == VariantType.Array)
  601. {
  602. var elementType = MarshalUtils.GetArrayElementType(type);
  603. if (elementType == null)
  604. return false; // Non-generic Array, so there's no hint to add.
  605. if (elementType.TypeKind == TypeKind.TypeParameter)
  606. return false; // The generic is not constructed, we can't really hint anything.
  607. var elementMarshalType = MarshalUtils.ConvertManagedTypeToMarshalType(elementType, typeCache)!.Value;
  608. var elementVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(elementMarshalType)!.Value;
  609. bool isPresetHint = false;
  610. if (elementVariantType == VariantType.String || elementVariantType == VariantType.StringName)
  611. isPresetHint = GetStringArrayEnumHint(elementVariantType, exportAttr, out hintString);
  612. if (!isPresetHint)
  613. {
  614. bool hintRes = TryGetMemberExportHint(typeCache, elementType,
  615. exportAttr, elementVariantType, isTypeArgument: true,
  616. out var elementHint, out var elementHintString);
  617. // Format: type/hint:hint_string
  618. if (hintRes)
  619. {
  620. hintString = (int)elementVariantType + "/" + (int)elementHint + ":";
  621. if (elementHintString != null)
  622. hintString += elementHintString;
  623. }
  624. else
  625. {
  626. hintString = (int)elementVariantType + "/" + (int)PropertyHint.None + ":";
  627. }
  628. }
  629. hint = PropertyHint.TypeString;
  630. return hintString != null;
  631. }
  632. if (!isTypeArgument && variantType == VariantType.PackedStringArray)
  633. {
  634. if (GetStringArrayEnumHint(VariantType.String, exportAttr, out hintString))
  635. {
  636. hint = PropertyHint.TypeString;
  637. return true;
  638. }
  639. }
  640. if (!isTypeArgument && variantType == VariantType.Dictionary)
  641. {
  642. var elementTypes = MarshalUtils.GetGenericElementTypes(type);
  643. if (elementTypes == null)
  644. return false; // Non-generic Dictionary, so there's no hint to add
  645. Debug.Assert(elementTypes.Length == 2);
  646. var keyElementMarshalType = MarshalUtils.ConvertManagedTypeToMarshalType(elementTypes[0], typeCache)!.Value;
  647. var keyElementVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(keyElementMarshalType)!.Value;
  648. var keyIsPresetHint = false;
  649. var keyHintString = (string?)null;
  650. if (keyElementVariantType == VariantType.String || keyElementVariantType == VariantType.StringName)
  651. keyIsPresetHint = GetStringArrayEnumHint(keyElementVariantType, exportAttr, out keyHintString);
  652. if (!keyIsPresetHint)
  653. {
  654. bool hintRes = TryGetMemberExportHint(typeCache, elementTypes[0],
  655. exportAttr, keyElementVariantType, isTypeArgument: true,
  656. out var keyElementHint, out var keyElementHintString);
  657. // Format: type/hint:hint_string
  658. if (hintRes)
  659. {
  660. keyHintString = (int)keyElementVariantType + "/" + (int)keyElementHint + ":";
  661. if (keyElementHintString != null)
  662. keyHintString += keyElementHintString;
  663. }
  664. else
  665. {
  666. keyHintString = (int)keyElementVariantType + "/" + (int)PropertyHint.None + ":";
  667. }
  668. }
  669. var valueElementMarshalType = MarshalUtils.ConvertManagedTypeToMarshalType(elementTypes[1], typeCache)!.Value;
  670. var valueElementVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(valueElementMarshalType)!.Value;
  671. var valueIsPresetHint = false;
  672. var valueHintString = (string?)null;
  673. if (valueElementVariantType == VariantType.String || valueElementVariantType == VariantType.StringName)
  674. valueIsPresetHint = GetStringArrayEnumHint(valueElementVariantType, exportAttr, out valueHintString);
  675. if (!valueIsPresetHint)
  676. {
  677. bool hintRes = TryGetMemberExportHint(typeCache, elementTypes[1],
  678. exportAttr, valueElementVariantType, isTypeArgument: true,
  679. out var valueElementHint, out var valueElementHintString);
  680. // Format: type/hint:hint_string
  681. if (hintRes)
  682. {
  683. valueHintString = (int)valueElementVariantType + "/" + (int)valueElementHint + ":";
  684. if (valueElementHintString != null)
  685. valueHintString += valueElementHintString;
  686. }
  687. else
  688. {
  689. valueHintString = (int)valueElementVariantType + "/" + (int)PropertyHint.None + ":";
  690. }
  691. }
  692. hint = PropertyHint.DictionaryType;
  693. hintString = keyHintString != null && valueHintString != null ? $"{keyHintString};{valueHintString}" : null;
  694. return hintString != null;
  695. }
  696. return false;
  697. }
  698. }
  699. }