ScriptPropertiesGenerator.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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.AreGodotSourceGeneratorsDisabled())
  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 var typeMissingPartial))
  31. {
  32. Common.ReportNonPartialGodotScriptOuterClass(context, typeMissingPartial!);
  33. return false;
  34. }
  35. return true;
  36. }
  37. Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
  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. 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. while (containingType != null)
  81. {
  82. source.Append("partial ");
  83. source.Append(containingType.GetDeclarationKeyword());
  84. source.Append(" ");
  85. source.Append(containingType.NameWithTypeParameters());
  86. source.Append("\n{\n");
  87. containingType = containingType.ContainingType;
  88. }
  89. }
  90. source.Append("partial class ");
  91. source.Append(symbol.NameWithTypeParameters());
  92. source.Append("\n{\n");
  93. var members = symbol.GetMembers();
  94. var propertySymbols = members
  95. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Property)
  96. .Cast<IPropertySymbol>()
  97. .Where(s => !s.IsIndexer);
  98. var fieldSymbols = members
  99. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Field && !s.IsImplicitlyDeclared)
  100. .Cast<IFieldSymbol>();
  101. var godotClassProperties = propertySymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
  102. var godotClassFields = fieldSymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
  103. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  104. source.Append($" public new class PropertyName : {symbol.BaseType.FullQualifiedNameIncludeGlobal()}.PropertyName {{\n");
  105. // Generate cached StringNames for methods and properties, for fast lookup
  106. foreach (var property in godotClassProperties)
  107. {
  108. string propertyName = property.PropertySymbol.Name;
  109. source.Append(" public new static readonly global::Godot.StringName ");
  110. source.Append(propertyName);
  111. source.Append(" = \"");
  112. source.Append(propertyName);
  113. source.Append("\";\n");
  114. }
  115. foreach (var field in godotClassFields)
  116. {
  117. string fieldName = field.FieldSymbol.Name;
  118. source.Append(" public new static readonly global::Godot.StringName ");
  119. source.Append(fieldName);
  120. source.Append(" = \"");
  121. source.Append(fieldName);
  122. source.Append("\";\n");
  123. }
  124. source.Append(" }\n"); // class GodotInternal
  125. if (godotClassProperties.Length > 0 || godotClassFields.Length > 0)
  126. {
  127. bool isFirstEntry;
  128. // Generate SetGodotClassPropertyValue
  129. bool allPropertiesAreReadOnly = godotClassFields.All(fi => fi.FieldSymbol.IsReadOnly) &&
  130. godotClassProperties.All(pi => pi.PropertySymbol.IsReadOnly);
  131. if (!allPropertiesAreReadOnly)
  132. {
  133. source.Append(" protected override bool SetGodotClassPropertyValue(in godot_string_name name, ");
  134. source.Append("in godot_variant value)\n {\n");
  135. isFirstEntry = true;
  136. foreach (var property in godotClassProperties)
  137. {
  138. if (property.PropertySymbol.IsReadOnly)
  139. continue;
  140. GeneratePropertySetter(property.PropertySymbol.Name,
  141. property.PropertySymbol.Type, property.Type, source, isFirstEntry);
  142. isFirstEntry = false;
  143. }
  144. foreach (var field in godotClassFields)
  145. {
  146. if (field.FieldSymbol.IsReadOnly)
  147. continue;
  148. GeneratePropertySetter(field.FieldSymbol.Name,
  149. field.FieldSymbol.Type, field.Type, source, isFirstEntry);
  150. isFirstEntry = false;
  151. }
  152. source.Append(" return base.SetGodotClassPropertyValue(name, value);\n");
  153. source.Append(" }\n");
  154. }
  155. // Generate GetGodotClassPropertyValue
  156. source.Append(" protected override bool GetGodotClassPropertyValue(in godot_string_name name, ");
  157. source.Append("out godot_variant value)\n {\n");
  158. isFirstEntry = true;
  159. foreach (var property in godotClassProperties)
  160. {
  161. GeneratePropertyGetter(property.PropertySymbol.Name,
  162. property.Type, source, isFirstEntry);
  163. isFirstEntry = false;
  164. }
  165. foreach (var field in godotClassFields)
  166. {
  167. GeneratePropertyGetter(field.FieldSymbol.Name,
  168. field.Type, source, isFirstEntry);
  169. isFirstEntry = false;
  170. }
  171. source.Append(" return base.GetGodotClassPropertyValue(name, out value);\n");
  172. source.Append(" }\n");
  173. // Generate GetGodotPropertyList
  174. string dictionaryType = "global::System.Collections.Generic.List<global::Godot.Bridge.PropertyInfo>";
  175. source.Append(" internal new static ")
  176. .Append(dictionaryType)
  177. .Append(" GetGodotPropertyList()\n {\n");
  178. source.Append(" var properties = new ")
  179. .Append(dictionaryType)
  180. .Append("();\n");
  181. // To retain the definition order (and display categories correctly), we want to
  182. // iterate over fields and properties at the same time, sorted by line number.
  183. var godotClassPropertiesAndFields = Enumerable.Empty<GodotPropertyOrFieldData>()
  184. .Concat(godotClassProperties.Select(propertyData => new GodotPropertyOrFieldData(propertyData)))
  185. .Concat(godotClassFields.Select(fieldData => new GodotPropertyOrFieldData(fieldData)))
  186. .OrderBy(data => data.Symbol.Locations[0].Path())
  187. .ThenBy(data => data.Symbol.Locations[0].StartLine());
  188. foreach (var member in godotClassPropertiesAndFields)
  189. {
  190. foreach (var groupingInfo in DetermineGroupingPropertyInfo(member.Symbol))
  191. AppendGroupingPropertyInfo(source, groupingInfo);
  192. var propertyInfo = DeterminePropertyInfo(context, typeCache,
  193. member.Symbol, member.Type);
  194. if (propertyInfo == null)
  195. continue;
  196. AppendPropertyInfo(source, propertyInfo.Value);
  197. }
  198. source.Append(" return properties;\n");
  199. source.Append(" }\n");
  200. source.Append("#pragma warning restore CS0109\n");
  201. }
  202. source.Append("}\n"); // partial class
  203. if (isInnerClass)
  204. {
  205. var containingType = symbol.ContainingType;
  206. while (containingType != null)
  207. {
  208. source.Append("}\n"); // outer class
  209. containingType = containingType.ContainingType;
  210. }
  211. }
  212. if (hasNamespace)
  213. {
  214. source.Append("\n}\n");
  215. }
  216. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  217. }
  218. private static void GeneratePropertySetter(
  219. string propertyMemberName,
  220. ITypeSymbol propertyTypeSymbol,
  221. MarshalType propertyMarshalType,
  222. StringBuilder source,
  223. bool isFirstEntry
  224. )
  225. {
  226. source.Append(" ");
  227. if (!isFirstEntry)
  228. source.Append("else ");
  229. source.Append("if (name == PropertyName.")
  230. .Append(propertyMemberName)
  231. .Append(") {\n")
  232. .Append(" ")
  233. .Append(propertyMemberName)
  234. .Append(" = ")
  235. .AppendNativeVariantToManagedExpr("value", propertyTypeSymbol, propertyMarshalType)
  236. .Append(";\n")
  237. .Append(" return true;\n")
  238. .Append(" }\n");
  239. }
  240. private static void GeneratePropertyGetter(
  241. string propertyMemberName,
  242. MarshalType propertyMarshalType,
  243. StringBuilder source,
  244. bool isFirstEntry
  245. )
  246. {
  247. source.Append(" ");
  248. if (!isFirstEntry)
  249. source.Append("else ");
  250. source.Append("if (name == PropertyName.")
  251. .Append(propertyMemberName)
  252. .Append(") {\n")
  253. .Append(" value = ")
  254. .AppendManagedToNativeVariantExpr(propertyMemberName, propertyMarshalType)
  255. .Append(";\n")
  256. .Append(" return true;\n")
  257. .Append(" }\n");
  258. }
  259. private static void AppendGroupingPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
  260. {
  261. source.Append(" properties.Add(new(type: (Godot.Variant.Type)")
  262. .Append((int)VariantType.Nil)
  263. .Append(", name: \"")
  264. .Append(propertyInfo.Name)
  265. .Append("\", hint: (Godot.PropertyHint)")
  266. .Append((int)PropertyHint.None)
  267. .Append(", hintString: \"")
  268. .Append(propertyInfo.HintString)
  269. .Append("\", usage: (Godot.PropertyUsageFlags)")
  270. .Append((int)propertyInfo.Usage)
  271. .Append(", exported: true));\n");
  272. }
  273. private static void AppendPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
  274. {
  275. source.Append(" properties.Add(new(type: (global::Godot.Variant.Type)")
  276. .Append((int)propertyInfo.Type)
  277. .Append(", name: PropertyName.")
  278. .Append(propertyInfo.Name)
  279. .Append(", hint: (global::Godot.PropertyHint)")
  280. .Append((int)propertyInfo.Hint)
  281. .Append(", hintString: \"")
  282. .Append(propertyInfo.HintString)
  283. .Append("\", usage: (global::Godot.PropertyUsageFlags)")
  284. .Append((int)propertyInfo.Usage)
  285. .Append(", exported: ")
  286. .Append(propertyInfo.Exported ? "true" : "false")
  287. .Append("));\n");
  288. }
  289. private static IEnumerable<PropertyInfo> DetermineGroupingPropertyInfo(ISymbol memberSymbol)
  290. {
  291. foreach (var attr in memberSymbol.GetAttributes())
  292. {
  293. PropertyUsageFlags? propertyUsage = attr.AttributeClass?.ToString() switch
  294. {
  295. GodotClasses.ExportCategoryAttr => PropertyUsageFlags.Category,
  296. GodotClasses.ExportGroupAttr => PropertyUsageFlags.Group,
  297. GodotClasses.ExportSubgroupAttr => PropertyUsageFlags.Subgroup,
  298. _ => null
  299. };
  300. if (propertyUsage is null)
  301. continue;
  302. if (attr.ConstructorArguments.Length > 0 && attr.ConstructorArguments[0].Value is string name)
  303. {
  304. string? hintString = null;
  305. if (propertyUsage != PropertyUsageFlags.Category && attr.ConstructorArguments.Length > 1)
  306. hintString = attr.ConstructorArguments[1].Value?.ToString();
  307. yield return new PropertyInfo(VariantType.Nil, name, PropertyHint.None, hintString, propertyUsage.Value, true);
  308. }
  309. }
  310. }
  311. private static PropertyInfo? DeterminePropertyInfo(
  312. GeneratorExecutionContext context,
  313. MarshalUtils.TypeCache typeCache,
  314. ISymbol memberSymbol,
  315. MarshalType marshalType
  316. )
  317. {
  318. var exportAttr = memberSymbol.GetAttributes()
  319. .FirstOrDefault(a => a.AttributeClass?.IsGodotExportAttribute() ?? false);
  320. var propertySymbol = memberSymbol as IPropertySymbol;
  321. var fieldSymbol = memberSymbol as IFieldSymbol;
  322. if (exportAttr != null && propertySymbol != null)
  323. {
  324. if (propertySymbol.GetMethod == null)
  325. {
  326. // This should never happen, as we filtered WriteOnly properties, but just in case.
  327. Common.ReportExportedMemberIsWriteOnly(context, propertySymbol);
  328. return null;
  329. }
  330. if (propertySymbol.SetMethod == null)
  331. {
  332. // This should never happen, as we filtered ReadOnly properties, but just in case.
  333. Common.ReportExportedMemberIsReadOnly(context, propertySymbol);
  334. return null;
  335. }
  336. }
  337. var memberType = propertySymbol?.Type ?? fieldSymbol!.Type;
  338. var memberVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(marshalType)!.Value;
  339. string memberName = memberSymbol.Name;
  340. if (exportAttr == null)
  341. {
  342. return new PropertyInfo(memberVariantType, memberName, PropertyHint.None,
  343. hintString: null, PropertyUsageFlags.ScriptVariable, exported: false);
  344. }
  345. if (!TryGetMemberExportHint(typeCache, memberType, exportAttr, memberVariantType,
  346. isTypeArgument: false, out var hint, out var hintString))
  347. {
  348. var constructorArguments = exportAttr.ConstructorArguments;
  349. if (constructorArguments.Length > 0)
  350. {
  351. var hintValue = exportAttr.ConstructorArguments[0].Value;
  352. hint = hintValue switch
  353. {
  354. null => PropertyHint.None,
  355. int intValue => (PropertyHint)intValue,
  356. _ => (PropertyHint)(long)hintValue
  357. };
  358. hintString = constructorArguments.Length > 1 ?
  359. exportAttr.ConstructorArguments[1].Value?.ToString() :
  360. null;
  361. }
  362. else
  363. {
  364. hint = PropertyHint.None;
  365. }
  366. }
  367. var propUsage = PropertyUsageFlags.Default | PropertyUsageFlags.ScriptVariable;
  368. if (memberVariantType == VariantType.Nil)
  369. propUsage |= PropertyUsageFlags.NilIsVariant;
  370. return new PropertyInfo(memberVariantType, memberName,
  371. hint, hintString, propUsage, exported: true);
  372. }
  373. private static bool TryGetMemberExportHint(
  374. MarshalUtils.TypeCache typeCache,
  375. ITypeSymbol type, AttributeData exportAttr,
  376. VariantType variantType, bool isTypeArgument,
  377. out PropertyHint hint, out string? hintString
  378. )
  379. {
  380. hint = PropertyHint.None;
  381. hintString = null;
  382. if (variantType == VariantType.Nil)
  383. return true; // Variant, no export hint
  384. if (variantType == VariantType.Int &&
  385. type.IsValueType && type.TypeKind == TypeKind.Enum)
  386. {
  387. bool hasFlagsAttr = type.GetAttributes()
  388. .Any(a => a.AttributeClass?.IsSystemFlagsAttribute() ?? false);
  389. hint = hasFlagsAttr ? PropertyHint.Flags : PropertyHint.Enum;
  390. var members = type.GetMembers();
  391. var enumFields = members
  392. .Where(s => s.Kind == SymbolKind.Field && s.IsStatic &&
  393. s.DeclaredAccessibility == Accessibility.Public &&
  394. !s.IsImplicitlyDeclared)
  395. .Cast<IFieldSymbol>().ToArray();
  396. var hintStringBuilder = new StringBuilder();
  397. var nameOnlyHintStringBuilder = new StringBuilder();
  398. // True: enum Foo { Bar, Baz, Qux }
  399. // True: enum Foo { Bar = 0, Baz = 1, Qux = 2 }
  400. // False: enum Foo { Bar = 0, Baz = 7, Qux = 5 }
  401. bool usesDefaultValues = true;
  402. for (int i = 0; i < enumFields.Length; i++)
  403. {
  404. var enumField = enumFields[i];
  405. if (i > 0)
  406. {
  407. hintStringBuilder.Append(",");
  408. nameOnlyHintStringBuilder.Append(",");
  409. }
  410. string enumFieldName = enumField.Name;
  411. hintStringBuilder.Append(enumFieldName);
  412. nameOnlyHintStringBuilder.Append(enumFieldName);
  413. long val = enumField.ConstantValue switch
  414. {
  415. sbyte v => v,
  416. short v => v,
  417. int v => v,
  418. long v => v,
  419. byte v => v,
  420. ushort v => v,
  421. uint v => v,
  422. ulong v => (long)v,
  423. _ => 0
  424. };
  425. uint expectedVal = (uint)(hint == PropertyHint.Flags ? 1 << i : i);
  426. if (val != expectedVal)
  427. usesDefaultValues = false;
  428. hintStringBuilder.Append(":");
  429. hintStringBuilder.Append(val);
  430. }
  431. hintString = !usesDefaultValues ?
  432. hintStringBuilder.ToString() :
  433. // If we use the format NAME:VAL, that's what the editor displays.
  434. // That's annoying if the user is not using custom values for the enum constants.
  435. // This may not be needed in the future if the editor is changed to not display values.
  436. nameOnlyHintStringBuilder.ToString();
  437. return true;
  438. }
  439. if (variantType == VariantType.Object && type is INamedTypeSymbol memberNamedType)
  440. {
  441. if (memberNamedType.InheritsFrom("GodotSharp", "Godot.Resource"))
  442. {
  443. string nativeTypeName = memberNamedType.GetGodotScriptNativeClassName()!;
  444. hint = PropertyHint.ResourceType;
  445. hintString = nativeTypeName;
  446. return true;
  447. }
  448. if (memberNamedType.InheritsFrom("GodotSharp", "Godot.Node"))
  449. {
  450. string nativeTypeName = memberNamedType.GetGodotScriptNativeClassName()!;
  451. hint = PropertyHint.NodeType;
  452. hintString = nativeTypeName;
  453. return true;
  454. }
  455. }
  456. static bool GetStringArrayEnumHint(VariantType elementVariantType,
  457. AttributeData exportAttr, out string? hintString)
  458. {
  459. var constructorArguments = exportAttr.ConstructorArguments;
  460. if (constructorArguments.Length > 0)
  461. {
  462. var presetHintValue = exportAttr.ConstructorArguments[0].Value;
  463. PropertyHint presetHint = presetHintValue switch
  464. {
  465. null => PropertyHint.None,
  466. int intValue => (PropertyHint)intValue,
  467. _ => (PropertyHint)(long)presetHintValue
  468. };
  469. if (presetHint == PropertyHint.Enum)
  470. {
  471. string? presetHintString = constructorArguments.Length > 1 ?
  472. exportAttr.ConstructorArguments[1].Value?.ToString() :
  473. null;
  474. hintString = (int)elementVariantType + "/" + (int)PropertyHint.Enum + ":";
  475. if (presetHintString != null)
  476. hintString += presetHintString;
  477. return true;
  478. }
  479. }
  480. hintString = null;
  481. return false;
  482. }
  483. if (!isTypeArgument && variantType == VariantType.Array)
  484. {
  485. var elementType = MarshalUtils.GetArrayElementType(type);
  486. if (elementType == null)
  487. return false; // Non-generic Array, so there's no hint to add
  488. var elementMarshalType = MarshalUtils.ConvertManagedTypeToMarshalType(elementType, typeCache)!.Value;
  489. var elementVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(elementMarshalType)!.Value;
  490. bool isPresetHint = false;
  491. if (elementVariantType == VariantType.String)
  492. isPresetHint = GetStringArrayEnumHint(elementVariantType, exportAttr, out hintString);
  493. if (!isPresetHint)
  494. {
  495. bool hintRes = TryGetMemberExportHint(typeCache, elementType,
  496. exportAttr, elementVariantType, isTypeArgument: true,
  497. out var elementHint, out var elementHintString);
  498. // Format: type/hint:hint_string
  499. if (hintRes)
  500. {
  501. hintString = (int)elementVariantType + "/" + (int)elementHint + ":";
  502. if (elementHintString != null)
  503. hintString += elementHintString;
  504. }
  505. else
  506. {
  507. hintString = (int)elementVariantType + "/" + (int)PropertyHint.None + ":";
  508. }
  509. }
  510. hint = PropertyHint.TypeString;
  511. return hintString != null;
  512. }
  513. if (!isTypeArgument && variantType == VariantType.PackedStringArray)
  514. {
  515. if (GetStringArrayEnumHint(VariantType.String, exportAttr, out hintString))
  516. {
  517. hint = PropertyHint.TypeString;
  518. return true;
  519. }
  520. }
  521. if (!isTypeArgument && variantType == VariantType.Dictionary)
  522. {
  523. // TODO: Dictionaries are not supported in the inspector
  524. return false;
  525. }
  526. return false;
  527. }
  528. }
  529. }