ScriptPropertyDefValGenerator.cs 19 KB

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