ScriptPropertiesGenerator.cs 39 KB

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