ScriptPropertyDefValGenerator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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.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. 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. string? value = initializer?.Value.ToString();
  144. exportedMembers.Add(new ExportedPropertyMetadata(
  145. property.Name, marshalType.Value, propertyType, value));
  146. }
  147. foreach (var field in exportedFields)
  148. {
  149. if (field.IsStatic)
  150. {
  151. Common.ReportExportedMemberIsStatic(context, field);
  152. continue;
  153. }
  154. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  155. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  156. if (field.IsReadOnly)
  157. {
  158. Common.ReportExportedMemberIsReadOnly(context, field);
  159. continue;
  160. }
  161. var fieldType = field.Type;
  162. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(fieldType, typeCache);
  163. if (marshalType == null)
  164. {
  165. Common.ReportExportedMemberTypeNotSupported(context, field);
  166. continue;
  167. }
  168. EqualsValueClauseSyntax? initializer = field.DeclaringSyntaxReferences
  169. .Select(r => r.GetSyntax())
  170. .OfType<VariableDeclaratorSyntax>()
  171. .Select(s => s.Initializer)
  172. .FirstOrDefault(i => i != null);
  173. string? value = initializer?.Value.ToString();
  174. exportedMembers.Add(new ExportedPropertyMetadata(
  175. field.Name, marshalType.Value, fieldType, value));
  176. }
  177. // Generate GetGodotExportedProperties
  178. if (exportedMembers.Count > 0)
  179. {
  180. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  181. string dictionaryType = "System.Collections.Generic.Dictionary<StringName, object>";
  182. source.Append("#if TOOLS\n");
  183. source.Append(" internal new static ");
  184. source.Append(dictionaryType);
  185. source.Append(" GetGodotPropertyDefaultValues()\n {\n");
  186. source.Append(" var values = new ");
  187. source.Append(dictionaryType);
  188. source.Append("(");
  189. source.Append(exportedMembers.Count);
  190. source.Append(");\n");
  191. foreach (var exportedMember in exportedMembers)
  192. {
  193. string defaultValueLocalName = string.Concat("__", exportedMember.Name, "_default_value");
  194. source.Append(" ");
  195. source.Append(exportedMember.TypeSymbol.FullQualifiedName());
  196. source.Append(" ");
  197. source.Append(defaultValueLocalName);
  198. source.Append(" = ");
  199. source.Append(exportedMember.Value ?? "default");
  200. source.Append(";\n");
  201. source.Append(" values.Add(PropertyName.");
  202. source.Append(exportedMember.Name);
  203. source.Append(", ");
  204. source.Append(defaultValueLocalName);
  205. source.Append(");\n");
  206. }
  207. source.Append(" return values;\n");
  208. source.Append(" }\n");
  209. source.Append("#endif\n");
  210. source.Append("#pragma warning restore CS0109\n");
  211. }
  212. source.Append("}\n"); // partial class
  213. if (isInnerClass)
  214. {
  215. var containingType = symbol.ContainingType;
  216. while (containingType != null)
  217. {
  218. source.Append("}\n"); // outer class
  219. containingType = containingType.ContainingType;
  220. }
  221. }
  222. if (hasNamespace)
  223. {
  224. source.Append("\n}\n");
  225. }
  226. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  227. }
  228. private struct ExportedPropertyMetadata
  229. {
  230. public ExportedPropertyMetadata(string name, MarshalType type, ITypeSymbol typeSymbol, string? value)
  231. {
  232. Name = name;
  233. Type = type;
  234. TypeSymbol = typeSymbol;
  235. Value = value;
  236. }
  237. public string Name { get; }
  238. public MarshalType Type { get; }
  239. public ITypeSymbol TypeSymbol { get; }
  240. public string? Value { get; }
  241. }
  242. }
  243. }