ScriptPropertyDefValGenerator.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Text;
  4. using Microsoft.CodeAnalysis;
  5. using Microsoft.CodeAnalysis.CSharp;
  6. using Microsoft.CodeAnalysis.CSharp.Syntax;
  7. using Microsoft.CodeAnalysis.Text;
  8. namespace Godot.SourceGenerators
  9. {
  10. [Generator]
  11. public class ScriptPropertyDefValGenerator : ISourceGenerator
  12. {
  13. public void Initialize(GeneratorInitializationContext context)
  14. {
  15. }
  16. public void Execute(GeneratorExecutionContext context)
  17. {
  18. if (context.IsGodotSourceGeneratorDisabled("ScriptPropertyDefVal"))
  19. return;
  20. INamedTypeSymbol[] godotClasses = context
  21. .Compilation.SyntaxTrees
  22. .SelectMany(tree =>
  23. tree.GetRoot().DescendantNodes()
  24. .OfType<ClassDeclarationSyntax>()
  25. .SelectGodotScriptClasses(context.Compilation)
  26. // Report and skip non-partial classes
  27. .Where(x =>
  28. {
  29. if (x.cds.IsPartial())
  30. {
  31. if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out var typeMissingPartial))
  32. {
  33. Common.ReportNonPartialGodotScriptOuterClass(context, typeMissingPartial!);
  34. return false;
  35. }
  36. return true;
  37. }
  38. Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
  39. return false;
  40. })
  41. .Select(x => x.symbol)
  42. )
  43. .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
  44. .ToArray();
  45. if (godotClasses.Length > 0)
  46. {
  47. var typeCache = new MarshalUtils.TypeCache(context.Compilation);
  48. foreach (var godotClass in godotClasses)
  49. {
  50. VisitGodotScriptClass(context, typeCache, godotClass);
  51. }
  52. }
  53. }
  54. private static void VisitGodotScriptClass(
  55. GeneratorExecutionContext context,
  56. MarshalUtils.TypeCache typeCache,
  57. INamedTypeSymbol symbol
  58. )
  59. {
  60. INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
  61. string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
  62. namespaceSymbol.FullQualifiedNameOmitGlobal() :
  63. string.Empty;
  64. bool hasNamespace = classNs.Length != 0;
  65. bool isInnerClass = symbol.ContainingType != null;
  66. string uniqueHint = symbol.FullQualifiedNameOmitGlobal().SanitizeQualifiedNameForUniqueHint()
  67. + "_ScriptPropertyDefVal.generated";
  68. var source = new StringBuilder();
  69. if (hasNamespace)
  70. {
  71. source.Append("namespace ");
  72. source.Append(classNs);
  73. source.Append(" {\n\n");
  74. }
  75. if (isInnerClass)
  76. {
  77. var containingType = symbol.ContainingType;
  78. AppendPartialContainingTypeDeclarations(containingType);
  79. void AppendPartialContainingTypeDeclarations(INamedTypeSymbol? containingType)
  80. {
  81. if (containingType == null)
  82. return;
  83. AppendPartialContainingTypeDeclarations(containingType.ContainingType);
  84. source.Append("partial ");
  85. source.Append(containingType.GetDeclarationKeyword());
  86. source.Append(" ");
  87. source.Append(containingType.NameWithTypeParameters());
  88. source.Append("\n{\n");
  89. }
  90. }
  91. source.Append("partial class ");
  92. source.Append(symbol.NameWithTypeParameters());
  93. source.Append("\n{\n");
  94. var exportedMembers = new List<ExportedPropertyMetadata>();
  95. var members = symbol.GetMembers();
  96. var exportedProperties = members
  97. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Property)
  98. .Cast<IPropertySymbol>()
  99. .Where(s => s.GetAttributes()
  100. .Any(a => a.AttributeClass?.IsGodotExportAttribute() ?? false))
  101. .ToArray();
  102. var exportedFields = members
  103. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Field && !s.IsImplicitlyDeclared)
  104. .Cast<IFieldSymbol>()
  105. .Where(s => s.GetAttributes()
  106. .Any(a => a.AttributeClass?.IsGodotExportAttribute() ?? false))
  107. .ToArray();
  108. foreach (var property in exportedProperties)
  109. {
  110. if (property.IsStatic)
  111. {
  112. Common.ReportExportedMemberIsStatic(context, property);
  113. continue;
  114. }
  115. if (property.IsIndexer)
  116. {
  117. Common.ReportExportedMemberIsIndexer(context, property);
  118. continue;
  119. }
  120. // TODO: We should still restore read-only properties after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  121. // Ignore properties without a getter, without a setter or with an init-only setter. Godot properties must be both readable and writable.
  122. if (property.IsWriteOnly)
  123. {
  124. Common.ReportExportedMemberIsWriteOnly(context, property);
  125. continue;
  126. }
  127. if (property.IsReadOnly || property.SetMethod!.IsInitOnly)
  128. {
  129. Common.ReportExportedMemberIsReadOnly(context, property);
  130. continue;
  131. }
  132. if (property.ExplicitInterfaceImplementations.Length > 0)
  133. {
  134. Common.ReportExportedMemberIsExplicitInterfaceImplementation(context, property);
  135. continue;
  136. }
  137. var propertyType = property.Type;
  138. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(propertyType, typeCache);
  139. if (marshalType == null)
  140. {
  141. Common.ReportExportedMemberTypeNotSupported(context, property);
  142. continue;
  143. }
  144. if (marshalType == MarshalType.GodotObjectOrDerived)
  145. {
  146. if (!symbol.InheritsFrom("GodotSharp", "Godot.Node") &&
  147. propertyType.InheritsFrom("GodotSharp", "Godot.Node"))
  148. {
  149. Common.ReportOnlyNodesShouldExportNodes(context, property);
  150. }
  151. }
  152. var propertyDeclarationSyntax = property.DeclaringSyntaxReferences
  153. .Select(r => r.GetSyntax() as PropertyDeclarationSyntax).FirstOrDefault();
  154. // Fully qualify the value to avoid issues with namespaces.
  155. string? value = null;
  156. if (propertyDeclarationSyntax != null)
  157. {
  158. if (propertyDeclarationSyntax.Initializer != null)
  159. {
  160. var sm = context.Compilation.GetSemanticModel(propertyDeclarationSyntax.Initializer.SyntaxTree);
  161. value = propertyDeclarationSyntax.Initializer.Value.FullQualifiedSyntax(sm);
  162. }
  163. else
  164. {
  165. var propertyGet = propertyDeclarationSyntax.AccessorList?.Accessors
  166. .Where(a => a.Keyword.IsKind(SyntaxKind.GetKeyword)).FirstOrDefault();
  167. if (propertyGet != null)
  168. {
  169. if (propertyGet.ExpressionBody != null)
  170. {
  171. if (propertyGet.ExpressionBody.Expression is IdentifierNameSyntax identifierNameSyntax)
  172. {
  173. var sm = context.Compilation.GetSemanticModel(identifierNameSyntax.SyntaxTree);
  174. var fieldSymbol = sm.GetSymbolInfo(identifierNameSyntax).Symbol as IFieldSymbol;
  175. EqualsValueClauseSyntax? initializer = fieldSymbol?.DeclaringSyntaxReferences
  176. .Select(r => r.GetSyntax())
  177. .OfType<VariableDeclaratorSyntax>()
  178. .Select(s => s.Initializer)
  179. .FirstOrDefault(i => i != null);
  180. if (initializer != null)
  181. {
  182. sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  183. value = initializer.Value.FullQualifiedSyntax(sm);
  184. }
  185. }
  186. }
  187. else
  188. {
  189. var returns = propertyGet.DescendantNodes().OfType<ReturnStatementSyntax>();
  190. if (returns.Count() == 1)
  191. {
  192. // Generate only single return
  193. var returnStatementSyntax = returns.Single();
  194. if (returnStatementSyntax.Expression is IdentifierNameSyntax identifierNameSyntax)
  195. {
  196. var sm = context.Compilation.GetSemanticModel(identifierNameSyntax.SyntaxTree);
  197. var fieldSymbol = sm.GetSymbolInfo(identifierNameSyntax).Symbol as IFieldSymbol;
  198. EqualsValueClauseSyntax? initializer = fieldSymbol?.DeclaringSyntaxReferences
  199. .Select(r => r.GetSyntax())
  200. .OfType<VariableDeclaratorSyntax>()
  201. .Select(s => s.Initializer)
  202. .FirstOrDefault(i => i != null);
  203. if (initializer != null)
  204. {
  205. sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  206. value = initializer.Value.FullQualifiedSyntax(sm);
  207. }
  208. }
  209. }
  210. }
  211. }
  212. }
  213. }
  214. exportedMembers.Add(new ExportedPropertyMetadata(
  215. property.Name, marshalType.Value, propertyType, value));
  216. }
  217. foreach (var field in exportedFields)
  218. {
  219. if (field.IsStatic)
  220. {
  221. Common.ReportExportedMemberIsStatic(context, field);
  222. continue;
  223. }
  224. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  225. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  226. if (field.IsReadOnly)
  227. {
  228. Common.ReportExportedMemberIsReadOnly(context, field);
  229. continue;
  230. }
  231. var fieldType = field.Type;
  232. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(fieldType, typeCache);
  233. if (marshalType == null)
  234. {
  235. Common.ReportExportedMemberTypeNotSupported(context, field);
  236. continue;
  237. }
  238. if (marshalType == MarshalType.GodotObjectOrDerived)
  239. {
  240. if (!symbol.InheritsFrom("GodotSharp", "Godot.Node") &&
  241. fieldType.InheritsFrom("GodotSharp", "Godot.Node"))
  242. {
  243. Common.ReportOnlyNodesShouldExportNodes(context, field);
  244. }
  245. }
  246. EqualsValueClauseSyntax? initializer = field.DeclaringSyntaxReferences
  247. .Select(r => r.GetSyntax())
  248. .OfType<VariableDeclaratorSyntax>()
  249. .Select(s => s.Initializer)
  250. .FirstOrDefault(i => i != null);
  251. // This needs to be fully qualified to avoid issues with namespaces.
  252. string? value = null;
  253. if (initializer != null)
  254. {
  255. var sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  256. value = initializer.Value.FullQualifiedSyntax(sm);
  257. }
  258. exportedMembers.Add(new ExportedPropertyMetadata(
  259. field.Name, marshalType.Value, fieldType, value));
  260. }
  261. // Generate GetGodotExportedProperties
  262. if (exportedMembers.Count > 0)
  263. {
  264. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  265. const string dictionaryType =
  266. "global::System.Collections.Generic.Dictionary<global::Godot.StringName, global::Godot.Variant>";
  267. source.Append("#if TOOLS\n");
  268. source.Append(" /// <summary>\n")
  269. .Append(" /// Get the default values for all properties declared in this class.\n")
  270. .Append(" /// This method is used by Godot to determine the value that will be\n")
  271. .Append(" /// used by the inspector when resetting properties.\n")
  272. .Append(" /// Do not call this method.\n")
  273. .Append(" /// </summary>\n");
  274. source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
  275. source.Append(" internal new static ");
  276. source.Append(dictionaryType);
  277. source.Append(" GetGodotPropertyDefaultValues()\n {\n");
  278. source.Append(" var values = new ");
  279. source.Append(dictionaryType);
  280. source.Append("(");
  281. source.Append(exportedMembers.Count);
  282. source.Append(");\n");
  283. foreach (var exportedMember in exportedMembers)
  284. {
  285. string defaultValueLocalName = string.Concat("__", exportedMember.Name, "_default_value");
  286. source.Append(" ");
  287. source.Append(exportedMember.TypeSymbol.FullQualifiedNameIncludeGlobal());
  288. source.Append(" ");
  289. source.Append(defaultValueLocalName);
  290. source.Append(" = ");
  291. source.Append(exportedMember.Value ?? "default");
  292. source.Append(";\n");
  293. source.Append(" values.Add(PropertyName.");
  294. source.Append(exportedMember.Name);
  295. source.Append(", ");
  296. source.AppendManagedToVariantExpr(defaultValueLocalName,
  297. exportedMember.TypeSymbol, exportedMember.Type);
  298. source.Append(");\n");
  299. }
  300. source.Append(" return values;\n");
  301. source.Append(" }\n");
  302. source.Append("#endif // TOOLS\n");
  303. source.Append("#pragma warning restore CS0109\n");
  304. }
  305. source.Append("}\n"); // partial class
  306. if (isInnerClass)
  307. {
  308. var containingType = symbol.ContainingType;
  309. while (containingType != null)
  310. {
  311. source.Append("}\n"); // outer class
  312. containingType = containingType.ContainingType;
  313. }
  314. }
  315. if (hasNamespace)
  316. {
  317. source.Append("\n}\n");
  318. }
  319. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  320. }
  321. private struct ExportedPropertyMetadata
  322. {
  323. public ExportedPropertyMetadata(string name, MarshalType type, ITypeSymbol typeSymbol, string? value)
  324. {
  325. Name = name;
  326. Type = type;
  327. TypeSymbol = typeSymbol;
  328. Value = value;
  329. }
  330. public string Name { get; }
  331. public MarshalType Type { get; }
  332. public ITypeSymbol TypeSymbol { get; }
  333. public string? Value { get; }
  334. }
  335. }
  336. }