ScriptPropertiesGenerator.cs 33 KB

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