ScriptPropertyDefValGenerator.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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 _))
  32. {
  33. return false;
  34. }
  35. return true;
  36. }
  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.Compilation);
  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 is { IsGlobalNamespace: false }
  60. ? namespaceSymbol.FullQualifiedNameOmitGlobal()
  61. : string.Empty;
  62. bool hasNamespace = classNs.Length != 0;
  63. bool isNode = symbol.InheritsFrom("GodotSharp", GodotClasses.Node);
  64. bool isInnerClass = symbol.ContainingType != null;
  65. string uniqueHint = symbol.FullQualifiedNameOmitGlobal().SanitizeQualifiedNameForUniqueHint()
  66. + "_ScriptPropertyDefVal.generated";
  67. var source = new StringBuilder();
  68. if (hasNamespace)
  69. {
  70. source.Append("namespace ");
  71. source.Append(classNs);
  72. source.Append(" {\n\n");
  73. }
  74. if (isInnerClass)
  75. {
  76. var containingType = symbol.ContainingType;
  77. AppendPartialContainingTypeDeclarations(containingType);
  78. void AppendPartialContainingTypeDeclarations(INamedTypeSymbol? containingType)
  79. {
  80. if (containingType == null)
  81. return;
  82. AppendPartialContainingTypeDeclarations(containingType.ContainingType);
  83. source.Append("partial ");
  84. source.Append(containingType.GetDeclarationKeyword());
  85. source.Append(" ");
  86. source.Append(containingType.NameWithTypeParameters());
  87. source.Append("\n{\n");
  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.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.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. context.ReportDiagnostic(Diagnostic.Create(
  112. Common.ExportedMemberIsStaticRule,
  113. property.Locations.FirstLocationWithSourceTreeOrDefault(),
  114. property.ToDisplayString()
  115. ));
  116. continue;
  117. }
  118. if (property.IsIndexer)
  119. {
  120. context.ReportDiagnostic(Diagnostic.Create(
  121. Common.ExportedMemberIsIndexerRule,
  122. property.Locations.FirstLocationWithSourceTreeOrDefault(),
  123. property.ToDisplayString()
  124. ));
  125. continue;
  126. }
  127. // TODO: We should still restore read-only properties after reloading assembly.
  128. // Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  129. // Ignore properties without a getter, without a setter or with an init-only setter.
  130. // Godot properties must be both readable and writable.
  131. if (property.IsWriteOnly)
  132. {
  133. context.ReportDiagnostic(Diagnostic.Create(
  134. Common.ExportedPropertyIsWriteOnlyRule,
  135. property.Locations.FirstLocationWithSourceTreeOrDefault(),
  136. property.ToDisplayString()
  137. ));
  138. continue;
  139. }
  140. if (property.IsReadOnly || property.SetMethod!.IsInitOnly)
  141. {
  142. context.ReportDiagnostic(Diagnostic.Create(
  143. Common.ExportedMemberIsReadOnlyRule,
  144. property.Locations.FirstLocationWithSourceTreeOrDefault(),
  145. property.ToDisplayString()
  146. ));
  147. continue;
  148. }
  149. if (property.ExplicitInterfaceImplementations.Length > 0)
  150. {
  151. context.ReportDiagnostic(Diagnostic.Create(
  152. Common.ExportedMemberIsExplicitInterfaceImplementationRule,
  153. property.Locations.FirstLocationWithSourceTreeOrDefault(),
  154. property.ToDisplayString()
  155. ));
  156. continue;
  157. }
  158. var propertyType = property.Type;
  159. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(propertyType, typeCache);
  160. if (marshalType == null)
  161. {
  162. context.ReportDiagnostic(Diagnostic.Create(
  163. Common.ExportedMemberTypeIsNotSupportedRule,
  164. property.Locations.FirstLocationWithSourceTreeOrDefault(),
  165. property.ToDisplayString()
  166. ));
  167. continue;
  168. }
  169. if (marshalType == MarshalType.GodotObjectOrDerived)
  170. {
  171. if (!isNode && propertyType.InheritsFrom("GodotSharp", GodotClasses.Node))
  172. {
  173. context.ReportDiagnostic(Diagnostic.Create(
  174. Common.OnlyNodesShouldExportNodesRule,
  175. property.Locations.FirstLocationWithSourceTreeOrDefault()
  176. ));
  177. continue;
  178. }
  179. }
  180. var propertyDeclarationSyntax = property.DeclaringSyntaxReferences
  181. .Select(r => r.GetSyntax() as PropertyDeclarationSyntax).FirstOrDefault();
  182. // Fully qualify the value to avoid issues with namespaces.
  183. string? value = null;
  184. if (propertyDeclarationSyntax != null)
  185. {
  186. if (propertyDeclarationSyntax.Initializer != null)
  187. {
  188. var sm = context.Compilation.GetSemanticModel(propertyDeclarationSyntax.Initializer.SyntaxTree);
  189. value = propertyDeclarationSyntax.Initializer.Value.FullQualifiedSyntax(sm);
  190. }
  191. else
  192. {
  193. var propertyGet = propertyDeclarationSyntax.AccessorList?.Accessors
  194. .FirstOrDefault(a => a.Keyword.IsKind(SyntaxKind.GetKeyword));
  195. if (propertyGet != null)
  196. {
  197. if (propertyGet.ExpressionBody != null)
  198. {
  199. if (propertyGet.ExpressionBody.Expression is IdentifierNameSyntax identifierNameSyntax)
  200. {
  201. var sm = context.Compilation.GetSemanticModel(identifierNameSyntax.SyntaxTree);
  202. var fieldSymbol = sm.GetSymbolInfo(identifierNameSyntax).Symbol as IFieldSymbol;
  203. EqualsValueClauseSyntax? initializer = fieldSymbol?.DeclaringSyntaxReferences
  204. .Select(r => r.GetSyntax())
  205. .OfType<VariableDeclaratorSyntax>()
  206. .Select(s => s.Initializer)
  207. .FirstOrDefault(i => i != null);
  208. if (initializer != null)
  209. {
  210. sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  211. value = initializer.Value.FullQualifiedSyntax(sm);
  212. }
  213. }
  214. }
  215. else
  216. {
  217. var returns = propertyGet.DescendantNodes().OfType<ReturnStatementSyntax>();
  218. if (returns.Count() == 1)
  219. {
  220. // Generate only single return
  221. var returnStatementSyntax = returns.Single();
  222. if (returnStatementSyntax.Expression is IdentifierNameSyntax identifierNameSyntax)
  223. {
  224. var sm = context.Compilation.GetSemanticModel(identifierNameSyntax.SyntaxTree);
  225. var fieldSymbol = sm.GetSymbolInfo(identifierNameSyntax).Symbol as IFieldSymbol;
  226. EqualsValueClauseSyntax? initializer = fieldSymbol?.DeclaringSyntaxReferences
  227. .Select(r => r.GetSyntax())
  228. .OfType<VariableDeclaratorSyntax>()
  229. .Select(s => s.Initializer)
  230. .FirstOrDefault(i => i != null);
  231. if (initializer != null)
  232. {
  233. sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  234. value = initializer.Value.FullQualifiedSyntax(sm);
  235. }
  236. }
  237. }
  238. }
  239. }
  240. }
  241. }
  242. exportedMembers.Add(new ExportedPropertyMetadata(
  243. property.Name, marshalType.Value, propertyType, value));
  244. }
  245. foreach (var field in exportedFields)
  246. {
  247. if (field.IsStatic)
  248. {
  249. context.ReportDiagnostic(Diagnostic.Create(
  250. Common.ExportedMemberIsStaticRule,
  251. field.Locations.FirstLocationWithSourceTreeOrDefault(),
  252. field.ToDisplayString()
  253. ));
  254. continue;
  255. }
  256. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  257. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  258. if (field.IsReadOnly)
  259. {
  260. context.ReportDiagnostic(Diagnostic.Create(
  261. Common.ExportedMemberIsReadOnlyRule,
  262. field.Locations.FirstLocationWithSourceTreeOrDefault(),
  263. field.ToDisplayString()
  264. ));
  265. continue;
  266. }
  267. var fieldType = field.Type;
  268. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(fieldType, typeCache);
  269. if (marshalType == null)
  270. {
  271. context.ReportDiagnostic(Diagnostic.Create(
  272. Common.ExportedMemberTypeIsNotSupportedRule,
  273. field.Locations.FirstLocationWithSourceTreeOrDefault(),
  274. field.ToDisplayString()
  275. ));
  276. continue;
  277. }
  278. if (marshalType == MarshalType.GodotObjectOrDerived)
  279. {
  280. if (!isNode && fieldType.InheritsFrom("GodotSharp", GodotClasses.Node))
  281. {
  282. context.ReportDiagnostic(Diagnostic.Create(
  283. Common.OnlyNodesShouldExportNodesRule,
  284. field.Locations.FirstLocationWithSourceTreeOrDefault()
  285. ));
  286. continue;
  287. }
  288. }
  289. EqualsValueClauseSyntax? initializer = field.DeclaringSyntaxReferences
  290. .Select(r => r.GetSyntax())
  291. .OfType<VariableDeclaratorSyntax>()
  292. .Select(s => s.Initializer)
  293. .FirstOrDefault(i => i != null);
  294. // This needs to be fully qualified to avoid issues with namespaces.
  295. string? value = null;
  296. if (initializer != null)
  297. {
  298. var sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  299. value = initializer.Value.FullQualifiedSyntax(sm);
  300. }
  301. exportedMembers.Add(new ExportedPropertyMetadata(
  302. field.Name, marshalType.Value, fieldType, value));
  303. }
  304. // Generate GetGodotExportedProperties
  305. if (exportedMembers.Count > 0)
  306. {
  307. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  308. const string DictionaryType =
  309. "global::System.Collections.Generic.Dictionary<global::Godot.StringName, global::Godot.Variant>";
  310. source.Append("#if TOOLS\n");
  311. source.Append(" /// <summary>\n")
  312. .Append(" /// Get the default values for all properties declared in this class.\n")
  313. .Append(" /// This method is used by Godot to determine the value that will be\n")
  314. .Append(" /// used by the inspector when resetting properties.\n")
  315. .Append(" /// Do not call this method.\n")
  316. .Append(" /// </summary>\n");
  317. source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
  318. source.Append(" internal new static ");
  319. source.Append(DictionaryType);
  320. source.Append(" GetGodotPropertyDefaultValues()\n {\n");
  321. source.Append(" var values = new ");
  322. source.Append(DictionaryType);
  323. source.Append("(");
  324. source.Append(exportedMembers.Count);
  325. source.Append(");\n");
  326. foreach (var exportedMember in exportedMembers)
  327. {
  328. string defaultValueLocalName = string.Concat("__", exportedMember.Name, "_default_value");
  329. source.Append(" ");
  330. source.Append(exportedMember.TypeSymbol.FullQualifiedNameIncludeGlobal());
  331. source.Append(" ");
  332. source.Append(defaultValueLocalName);
  333. source.Append(" = ");
  334. source.Append(exportedMember.Value ?? "default");
  335. source.Append(";\n");
  336. source.Append(" values.Add(PropertyName.");
  337. source.Append(exportedMember.Name);
  338. source.Append(", ");
  339. source.AppendManagedToVariantExpr(defaultValueLocalName,
  340. exportedMember.TypeSymbol, exportedMember.Type);
  341. source.Append(");\n");
  342. }
  343. source.Append(" return values;\n");
  344. source.Append(" }\n");
  345. source.Append("#endif // TOOLS\n");
  346. source.Append("#pragma warning restore CS0109\n");
  347. }
  348. source.Append("}\n"); // partial class
  349. if (isInnerClass)
  350. {
  351. var containingType = symbol.ContainingType;
  352. while (containingType != null)
  353. {
  354. source.Append("}\n"); // outer class
  355. containingType = containingType.ContainingType;
  356. }
  357. }
  358. if (hasNamespace)
  359. {
  360. source.Append("\n}\n");
  361. }
  362. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  363. }
  364. private struct ExportedPropertyMetadata
  365. {
  366. public ExportedPropertyMetadata(string name, MarshalType type, ITypeSymbol typeSymbol, string? value)
  367. {
  368. Name = name;
  369. Type = type;
  370. TypeSymbol = typeSymbol;
  371. Value = value;
  372. }
  373. public string Name { get; }
  374. public MarshalType Type { get; }
  375. public ITypeSymbol TypeSymbol { get; }
  376. public string? Value { get; }
  377. }
  378. }
  379. }