ScriptPropertyDefValGenerator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 ScriptPropertyDefValGenerator : 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);
  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.FullQualifiedName() :
  62. string.Empty;
  63. bool hasNamespace = classNs.Length != 0;
  64. bool isInnerClass = symbol.ContainingType != null;
  65. string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
  66. + "_ScriptPropertyDefVal_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 exportedMembers = new List<ExportedPropertyMetadata>();
  94. var members = symbol.GetMembers();
  95. var exportedProperties = members
  96. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Property)
  97. .Cast<IPropertySymbol>()
  98. .Where(s => s.GetAttributes()
  99. .Any(a => a.AttributeClass?.IsGodotExportAttribute() ?? false))
  100. .ToArray();
  101. var exportedFields = members
  102. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Field && !s.IsImplicitlyDeclared)
  103. .Cast<IFieldSymbol>()
  104. .Where(s => s.GetAttributes()
  105. .Any(a => a.AttributeClass?.IsGodotExportAttribute() ?? false))
  106. .ToArray();
  107. foreach (var property in exportedProperties)
  108. {
  109. if (property.IsStatic)
  110. {
  111. Common.ReportExportedMemberIsStatic(context, property);
  112. continue;
  113. }
  114. // TODO: We should still restore read-only properties after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  115. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  116. if (property.IsWriteOnly)
  117. {
  118. Common.ReportExportedMemberIsWriteOnly(context, property);
  119. continue;
  120. }
  121. if (property.IsReadOnly)
  122. {
  123. Common.ReportExportedMemberIsReadOnly(context, property);
  124. continue;
  125. }
  126. var propertyType = property.Type;
  127. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(propertyType, typeCache);
  128. if (marshalType == null)
  129. {
  130. Common.ReportExportedMemberTypeNotSupported(context, property);
  131. continue;
  132. }
  133. // TODO: Detect default value from simple property getters (currently we only detect from initializers)
  134. EqualsValueClauseSyntax? initializer = property.DeclaringSyntaxReferences
  135. .Select(r => r.GetSyntax() as PropertyDeclarationSyntax)
  136. .Select(s => s?.Initializer ?? null)
  137. .FirstOrDefault();
  138. string? value = initializer?.Value.ToString();
  139. exportedMembers.Add(new ExportedPropertyMetadata(
  140. property.Name, marshalType.Value, propertyType, value));
  141. }
  142. foreach (var field in exportedFields)
  143. {
  144. if (field.IsStatic)
  145. {
  146. Common.ReportExportedMemberIsStatic(context, field);
  147. continue;
  148. }
  149. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  150. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  151. if (field.IsReadOnly)
  152. {
  153. Common.ReportExportedMemberIsReadOnly(context, field);
  154. continue;
  155. }
  156. var fieldType = field.Type;
  157. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(fieldType, typeCache);
  158. if (marshalType == null)
  159. {
  160. Common.ReportExportedMemberTypeNotSupported(context, field);
  161. continue;
  162. }
  163. EqualsValueClauseSyntax? initializer = field.DeclaringSyntaxReferences
  164. .Select(r => r.GetSyntax())
  165. .OfType<VariableDeclaratorSyntax>()
  166. .Select(s => s.Initializer)
  167. .FirstOrDefault(i => i != null);
  168. string? value = initializer?.Value.ToString();
  169. exportedMembers.Add(new ExportedPropertyMetadata(
  170. field.Name, marshalType.Value, fieldType, value));
  171. }
  172. // Generate GetGodotExportedProperties
  173. if (exportedMembers.Count > 0)
  174. {
  175. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  176. string dictionaryType = "System.Collections.Generic.Dictionary<StringName, object>";
  177. source.Append("#if TOOLS\n");
  178. source.Append(" internal new static ");
  179. source.Append(dictionaryType);
  180. source.Append(" GetGodotPropertyDefaultValues()\n {\n");
  181. source.Append(" var values = new ");
  182. source.Append(dictionaryType);
  183. source.Append("(");
  184. source.Append(exportedMembers.Count);
  185. source.Append(");\n");
  186. foreach (var exportedMember in exportedMembers)
  187. {
  188. string defaultValueLocalName = string.Concat("__", exportedMember.Name, "_default_value");
  189. source.Append(" ");
  190. source.Append(exportedMember.TypeSymbol.FullQualifiedName());
  191. source.Append(" ");
  192. source.Append(defaultValueLocalName);
  193. source.Append(" = ");
  194. source.Append(exportedMember.Value ?? "default");
  195. source.Append(";\n");
  196. source.Append(" values.Add(GodotInternal.PropName_");
  197. source.Append(exportedMember.Name);
  198. source.Append(", ");
  199. source.Append(defaultValueLocalName);
  200. source.Append(");\n");
  201. }
  202. source.Append(" return values;\n");
  203. source.Append(" }\n");
  204. source.Append("#endif\n");
  205. source.Append("#pragma warning restore CS0109\n");
  206. }
  207. source.Append("}\n"); // partial class
  208. if (isInnerClass)
  209. {
  210. var containingType = symbol.ContainingType;
  211. while (containingType != null)
  212. {
  213. source.Append("}\n"); // outer class
  214. containingType = containingType.ContainingType;
  215. }
  216. }
  217. if (hasNamespace)
  218. {
  219. source.Append("\n}\n");
  220. }
  221. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  222. }
  223. private struct ExportedPropertyMetadata
  224. {
  225. public ExportedPropertyMetadata(string name, MarshalType type, ITypeSymbol typeSymbol, string? value)
  226. {
  227. Name = name;
  228. Type = type;
  229. TypeSymbol = typeSymbol;
  230. Value = value;
  231. }
  232. public string Name { get; }
  233. public MarshalType Type { get; }
  234. public ITypeSymbol TypeSymbol { get; }
  235. public string? Value { get; }
  236. }
  237. }
  238. }