ScriptPropertyDefValGenerator.cs 15 KB

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