ScriptPropertyDefValGenerator.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
  87. source.Append("\n{\n");
  88. }
  89. }
  90. source.Append("partial class ");
  91. source.Append(symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
  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 (!isNode && MemberHasNodeType(propertyType, marshalType.Value))
  170. {
  171. context.ReportDiagnostic(Diagnostic.Create(
  172. Common.OnlyNodesShouldExportNodesRule,
  173. property.Locations.FirstLocationWithSourceTreeOrDefault()
  174. ));
  175. continue;
  176. }
  177. var propertyDeclarationSyntax = property.DeclaringSyntaxReferences
  178. .Select(r => r.GetSyntax() as PropertyDeclarationSyntax).FirstOrDefault();
  179. // Fully qualify the value to avoid issues with namespaces.
  180. string? value = null;
  181. if (propertyDeclarationSyntax != null)
  182. {
  183. if (propertyDeclarationSyntax.Initializer != null)
  184. {
  185. var sm = context.Compilation.GetSemanticModel(propertyDeclarationSyntax.Initializer.SyntaxTree);
  186. var initializerValue = propertyDeclarationSyntax.Initializer.Value;
  187. if (!IsStaticallyResolvable(initializerValue, sm))
  188. value = "default";
  189. else
  190. value = propertyDeclarationSyntax.Initializer.Value.FullQualifiedSyntax(sm);
  191. }
  192. else
  193. {
  194. var propertyGet = propertyDeclarationSyntax.AccessorList?.Accessors
  195. .FirstOrDefault(a => a.Keyword.IsKind(SyntaxKind.GetKeyword));
  196. if (propertyGet != null)
  197. {
  198. if (propertyGet.ExpressionBody != null)
  199. {
  200. if (propertyGet.ExpressionBody.Expression is IdentifierNameSyntax identifierNameSyntax)
  201. {
  202. var sm = context.Compilation.GetSemanticModel(identifierNameSyntax.SyntaxTree);
  203. var fieldSymbol = sm.GetSymbolInfo(identifierNameSyntax).Symbol as IFieldSymbol;
  204. EqualsValueClauseSyntax? initializer = fieldSymbol?.DeclaringSyntaxReferences
  205. .Select(r => r.GetSyntax())
  206. .OfType<VariableDeclaratorSyntax>()
  207. .Select(s => s.Initializer)
  208. .FirstOrDefault(i => i != null);
  209. if (initializer != null)
  210. {
  211. sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  212. value = initializer.Value.FullQualifiedSyntax(sm);
  213. }
  214. }
  215. }
  216. else
  217. {
  218. var returns = propertyGet.DescendantNodes().OfType<ReturnStatementSyntax>();
  219. if (returns.Count() == 1)
  220. {
  221. // Generate only single return
  222. var returnStatementSyntax = returns.Single();
  223. if (returnStatementSyntax.Expression is IdentifierNameSyntax identifierNameSyntax)
  224. {
  225. var sm = context.Compilation.GetSemanticModel(identifierNameSyntax.SyntaxTree);
  226. var fieldSymbol = sm.GetSymbolInfo(identifierNameSyntax).Symbol as IFieldSymbol;
  227. EqualsValueClauseSyntax? initializer = fieldSymbol?.DeclaringSyntaxReferences
  228. .Select(r => r.GetSyntax())
  229. .OfType<VariableDeclaratorSyntax>()
  230. .Select(s => s.Initializer)
  231. .FirstOrDefault(i => i != null);
  232. if (initializer != null)
  233. {
  234. sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  235. value = initializer.Value.FullQualifiedSyntax(sm);
  236. }
  237. }
  238. }
  239. }
  240. }
  241. }
  242. }
  243. exportedMembers.Add(new ExportedPropertyMetadata(
  244. property.Name, marshalType.Value, propertyType, value));
  245. }
  246. foreach (var field in exportedFields)
  247. {
  248. if (field.IsStatic)
  249. {
  250. context.ReportDiagnostic(Diagnostic.Create(
  251. Common.ExportedMemberIsStaticRule,
  252. field.Locations.FirstLocationWithSourceTreeOrDefault(),
  253. field.ToDisplayString()
  254. ));
  255. continue;
  256. }
  257. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  258. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  259. if (field.IsReadOnly)
  260. {
  261. context.ReportDiagnostic(Diagnostic.Create(
  262. Common.ExportedMemberIsReadOnlyRule,
  263. field.Locations.FirstLocationWithSourceTreeOrDefault(),
  264. field.ToDisplayString()
  265. ));
  266. continue;
  267. }
  268. var fieldType = field.Type;
  269. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(fieldType, typeCache);
  270. if (marshalType == null)
  271. {
  272. context.ReportDiagnostic(Diagnostic.Create(
  273. Common.ExportedMemberTypeIsNotSupportedRule,
  274. field.Locations.FirstLocationWithSourceTreeOrDefault(),
  275. field.ToDisplayString()
  276. ));
  277. continue;
  278. }
  279. if (!isNode && MemberHasNodeType(fieldType, marshalType.Value))
  280. {
  281. context.ReportDiagnostic(Diagnostic.Create(
  282. Common.OnlyNodesShouldExportNodesRule,
  283. field.Locations.FirstLocationWithSourceTreeOrDefault()
  284. ));
  285. continue;
  286. }
  287. EqualsValueClauseSyntax? initializer = field.DeclaringSyntaxReferences
  288. .Select(r => r.GetSyntax())
  289. .OfType<VariableDeclaratorSyntax>()
  290. .Select(s => s.Initializer)
  291. .FirstOrDefault(i => i != null);
  292. // This needs to be fully qualified to avoid issues with namespaces.
  293. string? value = null;
  294. if (initializer != null)
  295. {
  296. var sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  297. var initializerValue = initializer.Value;
  298. if (!IsStaticallyResolvable(initializerValue, sm))
  299. value = "default";
  300. else
  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 static bool IsStaticallyResolvable(ExpressionSyntax expression, SemanticModel semanticModel)
  367. {
  368. // Find non-static node in expression
  369. foreach (SyntaxNode descendant in expression.DescendantNodesAndSelf())
  370. {
  371. // Constant nodes are static
  372. if (semanticModel.GetConstantValue(descendant).HasValue)
  373. {
  374. continue;
  375. }
  376. // Check non-static symbol
  377. SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(descendant);
  378. if (symbolInfo.Symbol is ISymbol symbol)
  379. {
  380. if (symbol.Kind is SymbolKind.Local or SymbolKind.Parameter)
  381. {
  382. return false;
  383. }
  384. }
  385. }
  386. // No non-static nodes found
  387. return true;
  388. }
  389. private static bool MemberHasNodeType(ITypeSymbol memberType, MarshalType marshalType)
  390. {
  391. if (marshalType == MarshalType.GodotObjectOrDerived)
  392. {
  393. return memberType.InheritsFrom("GodotSharp", GodotClasses.Node);
  394. }
  395. if (marshalType == MarshalType.GodotObjectOrDerivedArray)
  396. {
  397. var elementType = ((IArrayTypeSymbol)memberType).ElementType;
  398. return elementType.InheritsFrom("GodotSharp", GodotClasses.Node);
  399. }
  400. if (memberType is INamedTypeSymbol { IsGenericType: true } genericType)
  401. {
  402. return genericType.TypeArguments
  403. .Any(static typeArgument
  404. => typeArgument.InheritsFrom("GodotSharp", GodotClasses.Node));
  405. }
  406. return false;
  407. }
  408. private struct ExportedPropertyMetadata
  409. {
  410. public ExportedPropertyMetadata(string name, MarshalType type, ITypeSymbol typeSymbol, string? value)
  411. {
  412. Name = name;
  413. Type = type;
  414. TypeSymbol = typeSymbol;
  415. Value = value;
  416. }
  417. public string Name { get; }
  418. public MarshalType Type { get; }
  419. public ITypeSymbol TypeSymbol { get; }
  420. public string? Value { get; }
  421. }
  422. }
  423. }