ScriptPropertyDefValGenerator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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.AreGodotSourceGeneratorsDisabled())
  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. while (containingType != null)
  79. {
  80. source.Append("partial ");
  81. source.Append(containingType.GetDeclarationKeyword());
  82. source.Append(" ");
  83. source.Append(containingType.NameWithTypeParameters());
  84. source.Append("\n{\n");
  85. containingType = containingType.ContainingType;
  86. }
  87. }
  88. source.Append("partial class ");
  89. source.Append(symbol.NameWithTypeParameters());
  90. source.Append("\n{\n");
  91. var exportedMembers = new List<ExportedPropertyMetadata>();
  92. var members = symbol.GetMembers();
  93. var exportedProperties = members
  94. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Property)
  95. .Cast<IPropertySymbol>()
  96. .Where(s => s.GetAttributes()
  97. .Any(a => a.AttributeClass?.IsGodotExportAttribute() ?? false))
  98. .ToArray();
  99. var exportedFields = members
  100. .Where(s => !s.IsStatic && s.Kind == SymbolKind.Field && !s.IsImplicitlyDeclared)
  101. .Cast<IFieldSymbol>()
  102. .Where(s => s.GetAttributes()
  103. .Any(a => a.AttributeClass?.IsGodotExportAttribute() ?? false))
  104. .ToArray();
  105. foreach (var property in exportedProperties)
  106. {
  107. if (property.IsStatic)
  108. {
  109. Common.ReportExportedMemberIsStatic(context, property);
  110. continue;
  111. }
  112. if (property.IsIndexer)
  113. {
  114. Common.ReportExportedMemberIsIndexer(context, property);
  115. continue;
  116. }
  117. // TODO: We should still restore read-only properties after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  118. // Ignore properties without a getter, without a setter or with an init-only setter. Godot properties must be both readable and writable.
  119. if (property.IsWriteOnly)
  120. {
  121. Common.ReportExportedMemberIsWriteOnly(context, property);
  122. continue;
  123. }
  124. if (property.IsReadOnly || property.SetMethod!.IsInitOnly)
  125. {
  126. Common.ReportExportedMemberIsReadOnly(context, property);
  127. continue;
  128. }
  129. if (property.ExplicitInterfaceImplementations.Length > 0)
  130. {
  131. Common.ReportExportedMemberIsExplicitInterfaceImplementation(context, property);
  132. continue;
  133. }
  134. var propertyType = property.Type;
  135. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(propertyType, typeCache);
  136. if (marshalType == null)
  137. {
  138. Common.ReportExportedMemberTypeNotSupported(context, property);
  139. continue;
  140. }
  141. var propertyDeclarationSyntax = property.DeclaringSyntaxReferences
  142. .Select(r => r.GetSyntax() as PropertyDeclarationSyntax).FirstOrDefault();
  143. // Fully qualify the value to avoid issues with namespaces.
  144. string? value = null;
  145. if (propertyDeclarationSyntax != null)
  146. {
  147. if (propertyDeclarationSyntax.Initializer != null)
  148. {
  149. var sm = context.Compilation.GetSemanticModel(propertyDeclarationSyntax.Initializer.SyntaxTree);
  150. value = propertyDeclarationSyntax.Initializer.Value.FullQualifiedSyntax(sm);
  151. }
  152. else
  153. {
  154. var propertyGet = propertyDeclarationSyntax.AccessorList?.Accessors
  155. .Where(a => a.Keyword.IsKind(SyntaxKind.GetKeyword)).FirstOrDefault();
  156. if (propertyGet != null)
  157. {
  158. if (propertyGet.ExpressionBody != null)
  159. {
  160. if (propertyGet.ExpressionBody.Expression is IdentifierNameSyntax identifierNameSyntax)
  161. {
  162. var sm = context.Compilation.GetSemanticModel(identifierNameSyntax.SyntaxTree);
  163. var fieldSymbol = sm.GetSymbolInfo(identifierNameSyntax).Symbol as IFieldSymbol;
  164. EqualsValueClauseSyntax? initializer = fieldSymbol?.DeclaringSyntaxReferences
  165. .Select(r => r.GetSyntax())
  166. .OfType<VariableDeclaratorSyntax>()
  167. .Select(s => s.Initializer)
  168. .FirstOrDefault(i => i != null);
  169. if (initializer != null)
  170. {
  171. sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  172. value = initializer.Value.FullQualifiedSyntax(sm);
  173. }
  174. }
  175. }
  176. else
  177. {
  178. var returns = propertyGet.DescendantNodes().OfType<ReturnStatementSyntax>();
  179. if (returns.Count() == 1)
  180. {
  181. // Generate only single return
  182. var returnStatementSyntax = returns.Single();
  183. if (returnStatementSyntax.Expression is IdentifierNameSyntax identifierNameSyntax)
  184. {
  185. var sm = context.Compilation.GetSemanticModel(identifierNameSyntax.SyntaxTree);
  186. var fieldSymbol = sm.GetSymbolInfo(identifierNameSyntax).Symbol as IFieldSymbol;
  187. EqualsValueClauseSyntax? initializer = fieldSymbol?.DeclaringSyntaxReferences
  188. .Select(r => r.GetSyntax())
  189. .OfType<VariableDeclaratorSyntax>()
  190. .Select(s => s.Initializer)
  191. .FirstOrDefault(i => i != null);
  192. if (initializer != null)
  193. {
  194. sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  195. value = initializer.Value.FullQualifiedSyntax(sm);
  196. }
  197. }
  198. }
  199. }
  200. }
  201. }
  202. }
  203. exportedMembers.Add(new ExportedPropertyMetadata(
  204. property.Name, marshalType.Value, propertyType, value));
  205. }
  206. foreach (var field in exportedFields)
  207. {
  208. if (field.IsStatic)
  209. {
  210. Common.ReportExportedMemberIsStatic(context, field);
  211. continue;
  212. }
  213. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  214. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  215. if (field.IsReadOnly)
  216. {
  217. Common.ReportExportedMemberIsReadOnly(context, field);
  218. continue;
  219. }
  220. var fieldType = field.Type;
  221. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(fieldType, typeCache);
  222. if (marshalType == null)
  223. {
  224. Common.ReportExportedMemberTypeNotSupported(context, field);
  225. continue;
  226. }
  227. EqualsValueClauseSyntax? initializer = field.DeclaringSyntaxReferences
  228. .Select(r => r.GetSyntax())
  229. .OfType<VariableDeclaratorSyntax>()
  230. .Select(s => s.Initializer)
  231. .FirstOrDefault(i => i != null);
  232. // This needs to be fully qualified to avoid issues with namespaces.
  233. string? value = null;
  234. if (initializer != null)
  235. {
  236. var sm = context.Compilation.GetSemanticModel(initializer.SyntaxTree);
  237. value = initializer.Value.FullQualifiedSyntax(sm);
  238. }
  239. exportedMembers.Add(new ExportedPropertyMetadata(
  240. field.Name, marshalType.Value, fieldType, value));
  241. }
  242. // Generate GetGodotExportedProperties
  243. if (exportedMembers.Count > 0)
  244. {
  245. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  246. string dictionaryType =
  247. "global::System.Collections.Generic.Dictionary<global::Godot.StringName, global::Godot.Variant>";
  248. source.Append("#if TOOLS\n");
  249. source.Append(" internal new static ");
  250. source.Append(dictionaryType);
  251. source.Append(" GetGodotPropertyDefaultValues()\n {\n");
  252. source.Append(" var values = new ");
  253. source.Append(dictionaryType);
  254. source.Append("(");
  255. source.Append(exportedMembers.Count);
  256. source.Append(");\n");
  257. foreach (var exportedMember in exportedMembers)
  258. {
  259. string defaultValueLocalName = string.Concat("__", exportedMember.Name, "_default_value");
  260. source.Append(" ");
  261. source.Append(exportedMember.TypeSymbol.FullQualifiedNameIncludeGlobal());
  262. source.Append(" ");
  263. source.Append(defaultValueLocalName);
  264. source.Append(" = ");
  265. source.Append(exportedMember.Value ?? "default");
  266. source.Append(";\n");
  267. source.Append(" values.Add(PropertyName.");
  268. source.Append(exportedMember.Name);
  269. source.Append(", ");
  270. source.AppendManagedToVariantExpr(defaultValueLocalName,
  271. exportedMember.TypeSymbol, exportedMember.Type);
  272. source.Append(");\n");
  273. }
  274. source.Append(" return values;\n");
  275. source.Append(" }\n");
  276. source.Append("#endif\n");
  277. source.Append("#pragma warning restore CS0109\n");
  278. }
  279. source.Append("}\n"); // partial class
  280. if (isInnerClass)
  281. {
  282. var containingType = symbol.ContainingType;
  283. while (containingType != null)
  284. {
  285. source.Append("}\n"); // outer class
  286. containingType = containingType.ContainingType;
  287. }
  288. }
  289. if (hasNamespace)
  290. {
  291. source.Append("\n}\n");
  292. }
  293. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  294. }
  295. private struct ExportedPropertyMetadata
  296. {
  297. public ExportedPropertyMetadata(string name, MarshalType type, ITypeSymbol typeSymbol, string? value)
  298. {
  299. Name = name;
  300. Type = type;
  301. TypeSymbol = typeSymbol;
  302. Value = value;
  303. }
  304. public string Name { get; }
  305. public MarshalType Type { get; }
  306. public ITypeSymbol TypeSymbol { get; }
  307. public string? Value { get; }
  308. }
  309. }
  310. }