ScriptPropertiesGenerator.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. using System.Linq;
  2. using System.Text;
  3. using Microsoft.CodeAnalysis;
  4. using Microsoft.CodeAnalysis.CSharp.Syntax;
  5. using Microsoft.CodeAnalysis.Text;
  6. namespace Godot.SourceGenerators
  7. {
  8. [Generator]
  9. public class ScriptPropertiesGenerator : ISourceGenerator
  10. {
  11. public void Initialize(GeneratorInitializationContext context)
  12. {
  13. }
  14. public void Execute(GeneratorExecutionContext context)
  15. {
  16. if (context.AreGodotSourceGeneratorsDisabled())
  17. return;
  18. INamedTypeSymbol[] godotClasses = context
  19. .Compilation.SyntaxTrees
  20. .SelectMany(tree =>
  21. tree.GetRoot().DescendantNodes()
  22. .OfType<ClassDeclarationSyntax>()
  23. .SelectGodotScriptClasses(context.Compilation)
  24. // Report and skip non-partial classes
  25. .Where(x =>
  26. {
  27. if (x.cds.IsPartial())
  28. {
  29. if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out var typeMissingPartial))
  30. {
  31. Common.ReportNonPartialGodotScriptOuterClass(context, typeMissingPartial!);
  32. return false;
  33. }
  34. return true;
  35. }
  36. Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
  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);
  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.FullQualifiedName() :
  61. string.Empty;
  62. bool hasNamespace = classNs.Length != 0;
  63. bool isInnerClass = symbol.ContainingType != null;
  64. string uniqueHint = symbol.FullQualifiedName().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. while (containingType != null)
  80. {
  81. source.Append("partial ");
  82. source.Append(containingType.GetDeclarationKeyword());
  83. source.Append(" ");
  84. source.Append(containingType.NameWithTypeParameters());
  85. source.Append("\n{\n");
  86. containingType = containingType.ContainingType;
  87. }
  88. }
  89. source.Append("partial class ");
  90. source.Append(symbol.NameWithTypeParameters());
  91. source.Append("\n{\n");
  92. var members = symbol.GetMembers();
  93. var propertySymbols = members
  94. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Property)
  95. .Cast<IPropertySymbol>();
  96. var fieldSymbols = members
  97. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Field && !s.IsImplicitlyDeclared)
  98. .Cast<IFieldSymbol>();
  99. var godotClassProperties = propertySymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
  100. var godotClassFields = fieldSymbols.WhereIsGodotCompatibleType(typeCache).ToArray();
  101. source.Append(" private partial class GodotInternal {\n");
  102. // Generate cached StringNames for methods and properties, for fast lookup
  103. foreach (var property in godotClassProperties)
  104. {
  105. string propertyName = property.PropertySymbol.Name;
  106. source.Append(" public static readonly StringName PropName_");
  107. source.Append(propertyName);
  108. source.Append(" = \"");
  109. source.Append(propertyName);
  110. source.Append("\";\n");
  111. }
  112. foreach (var field in godotClassFields)
  113. {
  114. string fieldName = field.FieldSymbol.Name;
  115. source.Append(" public static readonly StringName PropName_");
  116. source.Append(fieldName);
  117. source.Append(" = \"");
  118. source.Append(fieldName);
  119. source.Append("\";\n");
  120. }
  121. source.Append(" }\n"); // class GodotInternal
  122. // Generate GetGodotPropertiesMetadata
  123. if (godotClassProperties.Length > 0 || godotClassFields.Length > 0)
  124. {
  125. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  126. string dictionaryType = "System.Collections.Generic.List<global::Godot.Bridge.PropertyInfo>";
  127. source.Append(" internal new static ")
  128. .Append(dictionaryType)
  129. .Append(" GetGodotPropertiesMetadata()\n {\n");
  130. source.Append(" var properties = new ")
  131. .Append(dictionaryType)
  132. .Append("();\n");
  133. foreach (var property in godotClassProperties)
  134. {
  135. var propertyInfo = GetPropertyMetadata(context, typeCache,
  136. property.PropertySymbol, property.Type);
  137. if (propertyInfo == null)
  138. continue;
  139. AppendPropertyInfo(source, propertyInfo.Value);
  140. }
  141. foreach (var field in godotClassFields)
  142. {
  143. var propertyInfo = GetPropertyMetadata(context, typeCache,
  144. field.FieldSymbol, field.Type);
  145. if (propertyInfo == null)
  146. continue;
  147. AppendPropertyInfo(source, propertyInfo.Value);
  148. }
  149. source.Append(" return properties;\n");
  150. source.Append(" }\n");
  151. source.Append("#pragma warning restore CS0109\n");
  152. }
  153. source.Append("}\n"); // partial class
  154. if (isInnerClass)
  155. {
  156. var containingType = symbol.ContainingType;
  157. while (containingType != null)
  158. {
  159. source.Append("}\n"); // outer class
  160. containingType = containingType.ContainingType;
  161. }
  162. }
  163. if (hasNamespace)
  164. {
  165. source.Append("\n}\n");
  166. }
  167. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  168. }
  169. private static void AppendPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
  170. {
  171. source.Append(" properties.Add(new(type: (Godot.Variant.Type)")
  172. .Append((int)propertyInfo.Type)
  173. .Append(", name: GodotInternal.PropName_")
  174. .Append(propertyInfo.Name)
  175. .Append(", hint: (Godot.PropertyHint)")
  176. .Append((int)propertyInfo.Hint)
  177. .Append(", hintString: \"")
  178. .Append(propertyInfo.HintString)
  179. .Append("\", usage: (Godot.PropertyUsageFlags)")
  180. .Append((int)propertyInfo.Usage)
  181. .Append(", exported: ")
  182. .Append(propertyInfo.Exported ? "true" : "false")
  183. .Append("));\n");
  184. }
  185. private struct PropertyInfo
  186. {
  187. public PropertyInfo(VariantType type, string name, PropertyHint hint,
  188. string? hintString, PropertyUsageFlags usage, bool exported)
  189. {
  190. Type = type;
  191. Name = name;
  192. Hint = hint;
  193. HintString = hintString;
  194. Usage = usage;
  195. Exported = exported;
  196. }
  197. public VariantType Type { get; }
  198. public string Name { get; }
  199. public PropertyHint Hint { get; }
  200. public string? HintString { get; }
  201. public PropertyUsageFlags Usage { get; }
  202. public bool Exported { get; }
  203. }
  204. private static PropertyInfo? GetPropertyMetadata(
  205. GeneratorExecutionContext context,
  206. MarshalUtils.TypeCache typeCache,
  207. ISymbol memberSymbol,
  208. MarshalType marshalType
  209. )
  210. {
  211. var exportAttr = memberSymbol.GetAttributes()
  212. .FirstOrDefault(a => a.AttributeClass?.IsGodotExportAttribute() ?? false);
  213. var propertySymbol = memberSymbol as IPropertySymbol;
  214. var fieldSymbol = memberSymbol as IFieldSymbol;
  215. if (exportAttr != null && propertySymbol != null)
  216. {
  217. if (propertySymbol.GetMethod == null)
  218. {
  219. // This should never happen, as we filtered WriteOnly properties, but just in case.
  220. Common.ReportExportedMemberIsWriteOnly(context, propertySymbol);
  221. return null;
  222. }
  223. if (propertySymbol.SetMethod == null)
  224. {
  225. // This should never happen, as we filtered ReadOnly properties, but just in case.
  226. Common.ReportExportedMemberIsReadOnly(context, propertySymbol);
  227. return null;
  228. }
  229. }
  230. var memberType = propertySymbol?.Type ?? fieldSymbol!.Type;
  231. var memberVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(marshalType)!.Value;
  232. string memberName = memberSymbol.Name;
  233. if (exportAttr == null)
  234. {
  235. return new PropertyInfo(memberVariantType, memberName, PropertyHint.None,
  236. hintString: null, PropertyUsageFlags.ScriptVariable, exported: false);
  237. }
  238. if (!TryGetMemberExportHint(typeCache, memberType, exportAttr, memberVariantType,
  239. isTypeArgument: false, out var hint, out var hintString))
  240. {
  241. var constructorArguments = exportAttr.ConstructorArguments;
  242. if (constructorArguments.Length > 0)
  243. {
  244. var hintValue = exportAttr.ConstructorArguments[0].Value;
  245. hint = hintValue switch
  246. {
  247. null => PropertyHint.None,
  248. int intValue => (PropertyHint)intValue,
  249. _ => (PropertyHint)(long)hintValue
  250. };
  251. hintString = constructorArguments.Length > 1 ?
  252. exportAttr.ConstructorArguments[1].Value?.ToString() :
  253. null;
  254. }
  255. else
  256. {
  257. hint = PropertyHint.None;
  258. }
  259. }
  260. var propUsage = PropertyUsageFlags.Default | PropertyUsageFlags.ScriptVariable;
  261. if (memberVariantType == VariantType.Nil)
  262. propUsage |= PropertyUsageFlags.NilIsVariant;
  263. return new PropertyInfo(memberVariantType, memberName,
  264. hint, hintString, propUsage, exported: true);
  265. }
  266. private static bool TryGetMemberExportHint(
  267. MarshalUtils.TypeCache typeCache,
  268. ITypeSymbol type, AttributeData exportAttr,
  269. VariantType variantType, bool isTypeArgument,
  270. out PropertyHint hint, out string? hintString
  271. )
  272. {
  273. hint = PropertyHint.None;
  274. hintString = null;
  275. if (variantType == VariantType.Nil)
  276. return true; // Variant, no export hint
  277. if (variantType == VariantType.Int &&
  278. type.IsValueType && type.TypeKind == TypeKind.Enum)
  279. {
  280. bool hasFlagsAttr = type.GetAttributes()
  281. .Any(a => a.AttributeClass?.IsSystemFlagsAttribute() ?? false);
  282. hint = hasFlagsAttr ? PropertyHint.Flags : PropertyHint.Enum;
  283. var members = type.GetMembers();
  284. var enumFields = members
  285. .Where(s => s.Kind == SymbolKind.Field && s.IsStatic &&
  286. s.DeclaredAccessibility == Accessibility.Public &&
  287. !s.IsImplicitlyDeclared)
  288. .Cast<IFieldSymbol>().ToArray();
  289. var hintStringBuilder = new StringBuilder();
  290. var nameOnlyHintStringBuilder = new StringBuilder();
  291. // True: enum Foo { Bar, Baz, Qux }
  292. // True: enum Foo { Bar = 0, Baz = 1, Qux = 2 }
  293. // False: enum Foo { Bar = 0, Baz = 7, Qux = 5 }
  294. bool usesDefaultValues = true;
  295. for (int i = 0; i < enumFields.Length; i++)
  296. {
  297. var enumField = enumFields[i];
  298. if (i > 0)
  299. {
  300. hintStringBuilder.Append(",");
  301. nameOnlyHintStringBuilder.Append(",");
  302. }
  303. string enumFieldName = enumField.Name;
  304. hintStringBuilder.Append(enumFieldName);
  305. nameOnlyHintStringBuilder.Append(enumFieldName);
  306. long val = enumField.ConstantValue switch
  307. {
  308. sbyte v => v,
  309. short v => v,
  310. int v => v,
  311. long v => v,
  312. byte v => v,
  313. ushort v => v,
  314. uint v => v,
  315. ulong v => (long)v,
  316. _ => 0
  317. };
  318. uint expectedVal = (uint)(hint == PropertyHint.Flags ? 1 << i : i);
  319. if (val != expectedVal)
  320. usesDefaultValues = false;
  321. hintStringBuilder.Append(":");
  322. hintStringBuilder.Append(val);
  323. }
  324. hintString = !usesDefaultValues ?
  325. hintStringBuilder.ToString() :
  326. // If we use the format NAME:VAL, that's what the editor displays.
  327. // That's annoying if the user is not using custom values for the enum constants.
  328. // This may not be needed in the future if the editor is changed to not display values.
  329. nameOnlyHintStringBuilder.ToString();
  330. return true;
  331. }
  332. if (variantType == VariantType.Object && type is INamedTypeSymbol memberNamedType)
  333. {
  334. if (memberNamedType.InheritsFrom("GodotSharp", "Godot.Resource"))
  335. {
  336. string nativeTypeName = memberNamedType.GetGodotScriptNativeClassName()!;
  337. hint = PropertyHint.ResourceType;
  338. hintString = nativeTypeName;
  339. return true;
  340. }
  341. if (memberNamedType.InheritsFrom("GodotSharp", "Godot.Node"))
  342. {
  343. string nativeTypeName = memberNamedType.GetGodotScriptNativeClassName()!;
  344. hint = PropertyHint.NodeType;
  345. hintString = nativeTypeName;
  346. return true;
  347. }
  348. }
  349. static bool GetStringArrayEnumHint(VariantType elementVariantType,
  350. AttributeData exportAttr, out string? hintString)
  351. {
  352. var constructorArguments = exportAttr.ConstructorArguments;
  353. if (constructorArguments.Length > 0)
  354. {
  355. var presetHintValue = exportAttr.ConstructorArguments[0].Value;
  356. PropertyHint presetHint = presetHintValue switch
  357. {
  358. null => PropertyHint.None,
  359. int intValue => (PropertyHint)intValue,
  360. _ => (PropertyHint)(long)presetHintValue
  361. };
  362. if (presetHint == PropertyHint.Enum)
  363. {
  364. string? presetHintString = constructorArguments.Length > 1 ?
  365. exportAttr.ConstructorArguments[1].Value?.ToString() :
  366. null;
  367. hintString = (int)elementVariantType + "/" + (int)PropertyHint.Enum + ":";
  368. if (presetHintString != null)
  369. hintString += presetHintString;
  370. return true;
  371. }
  372. }
  373. hintString = null;
  374. return false;
  375. }
  376. if (!isTypeArgument && variantType == VariantType.Array)
  377. {
  378. var elementType = MarshalUtils.GetArrayElementType(type);
  379. if (elementType == null)
  380. return false; // Non-generic Array, so there's no hint to add
  381. var elementMarshalType = MarshalUtils.ConvertManagedTypeToMarshalType(elementType, typeCache)!.Value;
  382. var elementVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(elementMarshalType)!.Value;
  383. bool isPresetHint = false;
  384. if (elementVariantType == VariantType.String)
  385. isPresetHint = GetStringArrayEnumHint(elementVariantType, exportAttr, out hintString);
  386. if (!isPresetHint)
  387. {
  388. bool hintRes = TryGetMemberExportHint(typeCache, elementType,
  389. exportAttr, elementVariantType, isTypeArgument: true,
  390. out var elementHint, out var elementHintString);
  391. // Format: type/hint:hint_string
  392. if (hintRes)
  393. {
  394. hintString = (int)elementVariantType + "/" + (int)elementHint + ":";
  395. if (elementHintString != null)
  396. hintString += elementHintString;
  397. }
  398. else
  399. {
  400. hintString = (int)elementVariantType + "/" + (int)PropertyHint.None + ":";
  401. }
  402. }
  403. hint = PropertyHint.TypeString;
  404. return hintString != null;
  405. }
  406. if (!isTypeArgument && variantType == VariantType.PackedStringArray)
  407. {
  408. if (GetStringArrayEnumHint(VariantType.String, exportAttr, out hintString))
  409. {
  410. hint = PropertyHint.TypeString;
  411. return true;
  412. }
  413. }
  414. if (!isTypeArgument && variantType == VariantType.Dictionary)
  415. {
  416. // TODO: Dictionaries are not supported in the inspector
  417. return false;
  418. }
  419. return false;
  420. }
  421. }
  422. }