ScriptPropertyDefValGenerator.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 (!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. value = propertyDeclarationSyntax.Initializer.Value.FullQualifiedSyntax(sm);
  187. }
  188. else
  189. {
  190. var propertyGet = propertyDeclarationSyntax.AccessorList?.Accessors
  191. .FirstOrDefault(a => a.Keyword.IsKind(SyntaxKind.GetKeyword));
  192. if (propertyGet != null)
  193. {
  194. if (propertyGet.ExpressionBody != null)
  195. {
  196. if (propertyGet.ExpressionBody.Expression is IdentifierNameSyntax identifierNameSyntax)
  197. {
  198. var sm = context.Compilation.GetSemanticModel(identifierNameSyntax.SyntaxTree);
  199. var fieldSymbol = sm.GetSymbolInfo(identifierNameSyntax).Symbol as IFieldSymbol;
  200. EqualsValueClauseSyntax? initializer = fieldSymbol?.DeclaringSyntaxReferences
  201. .Select(r => r.GetSyntax())
  202. .OfType<VariableDeclaratorSyntax>()
  203. .Select(s => s.Initializer)
  204. .FirstOrDefault(i => i != null);
  205. if (initializer != null)
  206. {
  207. sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  208. value = initializer.Value.FullQualifiedSyntax(sm);
  209. }
  210. }
  211. }
  212. else
  213. {
  214. var returns = propertyGet.DescendantNodes().OfType<ReturnStatementSyntax>();
  215. if (returns.Count() == 1)
  216. {
  217. // Generate only single return
  218. var returnStatementSyntax = returns.Single();
  219. if (returnStatementSyntax.Expression is IdentifierNameSyntax identifierNameSyntax)
  220. {
  221. var sm = context.Compilation.GetSemanticModel(identifierNameSyntax.SyntaxTree);
  222. var fieldSymbol = sm.GetSymbolInfo(identifierNameSyntax).Symbol as IFieldSymbol;
  223. EqualsValueClauseSyntax? initializer = fieldSymbol?.DeclaringSyntaxReferences
  224. .Select(r => r.GetSyntax())
  225. .OfType<VariableDeclaratorSyntax>()
  226. .Select(s => s.Initializer)
  227. .FirstOrDefault(i => i != null);
  228. if (initializer != null)
  229. {
  230. sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  231. value = initializer.Value.FullQualifiedSyntax(sm);
  232. }
  233. }
  234. }
  235. }
  236. }
  237. }
  238. }
  239. exportedMembers.Add(new ExportedPropertyMetadata(
  240. property.Name, marshalType.Value, propertyType, value));
  241. }
  242. foreach (var field in exportedFields)
  243. {
  244. if (field.IsStatic)
  245. {
  246. context.ReportDiagnostic(Diagnostic.Create(
  247. Common.ExportedMemberIsStaticRule,
  248. field.Locations.FirstLocationWithSourceTreeOrDefault(),
  249. field.ToDisplayString()
  250. ));
  251. continue;
  252. }
  253. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  254. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  255. if (field.IsReadOnly)
  256. {
  257. context.ReportDiagnostic(Diagnostic.Create(
  258. Common.ExportedMemberIsReadOnlyRule,
  259. field.Locations.FirstLocationWithSourceTreeOrDefault(),
  260. field.ToDisplayString()
  261. ));
  262. continue;
  263. }
  264. var fieldType = field.Type;
  265. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(fieldType, typeCache);
  266. if (marshalType == null)
  267. {
  268. context.ReportDiagnostic(Diagnostic.Create(
  269. Common.ExportedMemberTypeIsNotSupportedRule,
  270. field.Locations.FirstLocationWithSourceTreeOrDefault(),
  271. field.ToDisplayString()
  272. ));
  273. continue;
  274. }
  275. if (!isNode && MemberHasNodeType(fieldType, marshalType.Value))
  276. {
  277. context.ReportDiagnostic(Diagnostic.Create(
  278. Common.OnlyNodesShouldExportNodesRule,
  279. field.Locations.FirstLocationWithSourceTreeOrDefault()
  280. ));
  281. continue;
  282. }
  283. EqualsValueClauseSyntax? initializer = field.DeclaringSyntaxReferences
  284. .Select(r => r.GetSyntax())
  285. .OfType<VariableDeclaratorSyntax>()
  286. .Select(s => s.Initializer)
  287. .FirstOrDefault(i => i != null);
  288. // This needs to be fully qualified to avoid issues with namespaces.
  289. string? value = null;
  290. if (initializer != null)
  291. {
  292. var sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  293. value = initializer.Value.FullQualifiedSyntax(sm);
  294. }
  295. exportedMembers.Add(new ExportedPropertyMetadata(
  296. field.Name, marshalType.Value, fieldType, value));
  297. }
  298. // Generate GetGodotExportedProperties
  299. if (exportedMembers.Count > 0)
  300. {
  301. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  302. const string DictionaryType =
  303. "global::System.Collections.Generic.Dictionary<global::Godot.StringName, global::Godot.Variant>";
  304. source.Append("#if TOOLS\n");
  305. source.Append(" /// <summary>\n")
  306. .Append(" /// Get the default values for all properties declared in this class.\n")
  307. .Append(" /// This method is used by Godot to determine the value that will be\n")
  308. .Append(" /// used by the inspector when resetting properties.\n")
  309. .Append(" /// Do not call this method.\n")
  310. .Append(" /// </summary>\n");
  311. source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
  312. source.Append(" internal new static ");
  313. source.Append(DictionaryType);
  314. source.Append(" GetGodotPropertyDefaultValues()\n {\n");
  315. source.Append(" var values = new ");
  316. source.Append(DictionaryType);
  317. source.Append("(");
  318. source.Append(exportedMembers.Count);
  319. source.Append(");\n");
  320. foreach (var exportedMember in exportedMembers)
  321. {
  322. string defaultValueLocalName = string.Concat("__", exportedMember.Name, "_default_value");
  323. source.Append(" ");
  324. source.Append(exportedMember.TypeSymbol.FullQualifiedNameIncludeGlobal());
  325. source.Append(" ");
  326. source.Append(defaultValueLocalName);
  327. source.Append(" = ");
  328. source.Append(exportedMember.Value ?? "default");
  329. source.Append(";\n");
  330. source.Append(" values.Add(PropertyName.@");
  331. source.Append(exportedMember.Name);
  332. source.Append(", ");
  333. source.AppendManagedToVariantExpr(defaultValueLocalName,
  334. exportedMember.TypeSymbol, exportedMember.Type);
  335. source.Append(");\n");
  336. }
  337. source.Append(" return values;\n");
  338. source.Append(" }\n");
  339. source.Append("#endif // TOOLS\n");
  340. source.Append("#pragma warning restore CS0109\n");
  341. }
  342. source.Append("}\n"); // partial class
  343. if (isInnerClass)
  344. {
  345. var containingType = symbol.ContainingType;
  346. while (containingType != null)
  347. {
  348. source.Append("}\n"); // outer class
  349. containingType = containingType.ContainingType;
  350. }
  351. }
  352. if (hasNamespace)
  353. {
  354. source.Append("\n}\n");
  355. }
  356. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  357. }
  358. private static bool MemberHasNodeType(ITypeSymbol memberType, MarshalType marshalType)
  359. {
  360. if (marshalType == MarshalType.GodotObjectOrDerived)
  361. {
  362. return memberType.InheritsFrom("GodotSharp", GodotClasses.Node);
  363. }
  364. if (marshalType == MarshalType.GodotObjectOrDerivedArray)
  365. {
  366. var elementType = ((IArrayTypeSymbol)memberType).ElementType;
  367. return elementType.InheritsFrom("GodotSharp", GodotClasses.Node);
  368. }
  369. if (memberType is INamedTypeSymbol { IsGenericType: true } genericType)
  370. {
  371. return genericType.TypeArguments
  372. .Any(static typeArgument
  373. => typeArgument.InheritsFrom("GodotSharp", GodotClasses.Node));
  374. }
  375. return false;
  376. }
  377. private struct ExportedPropertyMetadata
  378. {
  379. public ExportedPropertyMetadata(string name, MarshalType type, ITypeSymbol typeSymbol, string? value)
  380. {
  381. Name = name;
  382. Type = type;
  383. TypeSymbol = typeSymbol;
  384. Value = value;
  385. }
  386. public string Name { get; }
  387. public MarshalType Type { get; }
  388. public ITypeSymbol TypeSymbol { get; }
  389. public string? Value { get; }
  390. }
  391. }
  392. }