ScriptPropertyDefValGenerator.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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.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. + "_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. if (property.IsIndexer)
  115. {
  116. Common.ReportExportedMemberIsIndexer(context, property);
  117. continue;
  118. }
  119. // TODO: We should still restore read-only properties after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  120. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  121. if (property.IsWriteOnly)
  122. {
  123. Common.ReportExportedMemberIsWriteOnly(context, property);
  124. continue;
  125. }
  126. if (property.IsReadOnly)
  127. {
  128. Common.ReportExportedMemberIsReadOnly(context, property);
  129. continue;
  130. }
  131. var propertyType = property.Type;
  132. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(propertyType, typeCache);
  133. if (marshalType == null)
  134. {
  135. Common.ReportExportedMemberTypeNotSupported(context, property);
  136. continue;
  137. }
  138. // TODO: Detect default value from simple property getters (currently we only detect from initializers)
  139. EqualsValueClauseSyntax? initializer = property.DeclaringSyntaxReferences
  140. .Select(r => r.GetSyntax() as PropertyDeclarationSyntax)
  141. .Select(s => s?.Initializer ?? null)
  142. .FirstOrDefault();
  143. // Fully qualify the value to avoid issues with namespaces.
  144. string? value = null;
  145. if (initializer != null)
  146. {
  147. var sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  148. value = initializer.Value.FullQualifiedSyntax(sm);
  149. }
  150. exportedMembers.Add(new ExportedPropertyMetadata(
  151. property.Name, marshalType.Value, propertyType, value));
  152. }
  153. foreach (var field in exportedFields)
  154. {
  155. if (field.IsStatic)
  156. {
  157. Common.ReportExportedMemberIsStatic(context, field);
  158. continue;
  159. }
  160. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  161. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  162. if (field.IsReadOnly)
  163. {
  164. Common.ReportExportedMemberIsReadOnly(context, field);
  165. continue;
  166. }
  167. var fieldType = field.Type;
  168. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(fieldType, typeCache);
  169. if (marshalType == null)
  170. {
  171. Common.ReportExportedMemberTypeNotSupported(context, field);
  172. continue;
  173. }
  174. EqualsValueClauseSyntax? initializer = field.DeclaringSyntaxReferences
  175. .Select(r => r.GetSyntax())
  176. .OfType<VariableDeclaratorSyntax>()
  177. .Select(s => s.Initializer)
  178. .FirstOrDefault(i => i != null);
  179. // This needs to be fully qualified to avoid issues with namespaces.
  180. string? value = null;
  181. if (initializer != null)
  182. {
  183. var sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  184. value = initializer.Value.FullQualifiedSyntax(sm);
  185. }
  186. exportedMembers.Add(new ExportedPropertyMetadata(
  187. field.Name, marshalType.Value, fieldType, value));
  188. }
  189. // Generate GetGodotExportedProperties
  190. if (exportedMembers.Count > 0)
  191. {
  192. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  193. string dictionaryType = "System.Collections.Generic.Dictionary<StringName, object>";
  194. source.Append("#if TOOLS\n");
  195. source.Append(" internal new static ");
  196. source.Append(dictionaryType);
  197. source.Append(" GetGodotPropertyDefaultValues()\n {\n");
  198. source.Append(" var values = new ");
  199. source.Append(dictionaryType);
  200. source.Append("(");
  201. source.Append(exportedMembers.Count);
  202. source.Append(");\n");
  203. foreach (var exportedMember in exportedMembers)
  204. {
  205. string defaultValueLocalName = string.Concat("__", exportedMember.Name, "_default_value");
  206. source.Append(" ");
  207. source.Append(exportedMember.TypeSymbol.FullQualifiedNameIncludeGlobal());
  208. source.Append(" ");
  209. source.Append(defaultValueLocalName);
  210. source.Append(" = ");
  211. source.Append(exportedMember.Value ?? "default");
  212. source.Append(";\n");
  213. source.Append(" values.Add(PropertyName.");
  214. source.Append(exportedMember.Name);
  215. source.Append(", ");
  216. source.Append(defaultValueLocalName);
  217. source.Append(");\n");
  218. }
  219. source.Append(" return values;\n");
  220. source.Append(" }\n");
  221. source.Append("#endif\n");
  222. source.Append("#pragma warning restore CS0109\n");
  223. }
  224. source.Append("}\n"); // partial class
  225. if (isInnerClass)
  226. {
  227. var containingType = symbol.ContainingType;
  228. while (containingType != null)
  229. {
  230. source.Append("}\n"); // outer class
  231. containingType = containingType.ContainingType;
  232. }
  233. }
  234. if (hasNamespace)
  235. {
  236. source.Append("\n}\n");
  237. }
  238. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  239. }
  240. private struct ExportedPropertyMetadata
  241. {
  242. public ExportedPropertyMetadata(string name, MarshalType type, ITypeSymbol typeSymbol, string? value)
  243. {
  244. Name = name;
  245. Type = type;
  246. TypeSymbol = typeSymbol;
  247. Value = value;
  248. }
  249. public string Name { get; }
  250. public MarshalType Type { get; }
  251. public ITypeSymbol TypeSymbol { get; }
  252. public string? Value { get; }
  253. }
  254. }
  255. }