ScriptPropertiesGenerator.cs 30 KB

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