ScriptMethodsGenerator.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Text;
  4. using Microsoft.CodeAnalysis;
  5. using Microsoft.CodeAnalysis.CSharp.Syntax;
  6. using Microsoft.CodeAnalysis.Text;
  7. namespace Godot.SourceGenerators
  8. {
  9. [Generator]
  10. public class ScriptMethodsGenerator : ISourceGenerator
  11. {
  12. public void Initialize(GeneratorInitializationContext context)
  13. {
  14. }
  15. public void Execute(GeneratorExecutionContext context)
  16. {
  17. if (context.IsGodotSourceGeneratorDisabled("ScriptMethods"))
  18. return;
  19. INamedTypeSymbol[] godotClasses = context
  20. .Compilation.SyntaxTrees
  21. .SelectMany(tree =>
  22. tree.GetRoot().DescendantNodes()
  23. .OfType<ClassDeclarationSyntax>()
  24. .SelectGodotScriptClasses(context.Compilation)
  25. // Report and skip non-partial classes
  26. .Where(x =>
  27. {
  28. if (x.cds.IsPartial())
  29. {
  30. if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out var typeMissingPartial))
  31. {
  32. Common.ReportNonPartialGodotScriptOuterClass(context, typeMissingPartial!);
  33. return false;
  34. }
  35. return true;
  36. }
  37. Common.ReportNonPartialGodotScriptClass(context, x.cds, x.symbol);
  38. return false;
  39. })
  40. .Select(x => x.symbol)
  41. )
  42. .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
  43. .ToArray();
  44. if (godotClasses.Length > 0)
  45. {
  46. var typeCache = new MarshalUtils.TypeCache(context.Compilation);
  47. foreach (var godotClass in godotClasses)
  48. {
  49. VisitGodotScriptClass(context, typeCache, godotClass);
  50. }
  51. }
  52. }
  53. private class MethodOverloadEqualityComparer : IEqualityComparer<GodotMethodData>
  54. {
  55. public bool Equals(GodotMethodData x, GodotMethodData y)
  56. => x.ParamTypes.Length == y.ParamTypes.Length && x.Method.Name == y.Method.Name;
  57. public int GetHashCode(GodotMethodData obj)
  58. {
  59. unchecked
  60. {
  61. return (obj.ParamTypes.Length.GetHashCode() * 397) ^ obj.Method.Name.GetHashCode();
  62. }
  63. }
  64. }
  65. private static void VisitGodotScriptClass(
  66. GeneratorExecutionContext context,
  67. MarshalUtils.TypeCache typeCache,
  68. INamedTypeSymbol symbol
  69. )
  70. {
  71. INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
  72. string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
  73. namespaceSymbol.FullQualifiedNameOmitGlobal() :
  74. string.Empty;
  75. bool hasNamespace = classNs.Length != 0;
  76. bool isInnerClass = symbol.ContainingType != null;
  77. string uniqueHint = symbol.FullQualifiedNameOmitGlobal().SanitizeQualifiedNameForUniqueHint()
  78. + "_ScriptMethods.generated";
  79. var source = new StringBuilder();
  80. source.Append("using Godot;\n");
  81. source.Append("using Godot.NativeInterop;\n");
  82. source.Append("\n");
  83. if (hasNamespace)
  84. {
  85. source.Append("namespace ");
  86. source.Append(classNs);
  87. source.Append(" {\n\n");
  88. }
  89. if (isInnerClass)
  90. {
  91. var containingType = symbol.ContainingType;
  92. AppendPartialContainingTypeDeclarations(containingType);
  93. void AppendPartialContainingTypeDeclarations(INamedTypeSymbol? containingType)
  94. {
  95. if (containingType == null)
  96. return;
  97. AppendPartialContainingTypeDeclarations(containingType.ContainingType);
  98. source.Append("partial ");
  99. source.Append(containingType.GetDeclarationKeyword());
  100. source.Append(" ");
  101. source.Append(containingType.NameWithTypeParameters());
  102. source.Append("\n{\n");
  103. }
  104. }
  105. source.Append("partial class ");
  106. source.Append(symbol.NameWithTypeParameters());
  107. source.Append("\n{\n");
  108. var members = symbol.GetMembers();
  109. var methodSymbols = members
  110. .Where(s => s.Kind == SymbolKind.Method && !s.IsImplicitlyDeclared)
  111. .Cast<IMethodSymbol>()
  112. .Where(m => m.MethodKind == MethodKind.Ordinary);
  113. var godotClassMethods = methodSymbols.WhereHasGodotCompatibleSignature(typeCache)
  114. .Distinct(new MethodOverloadEqualityComparer())
  115. .ToArray();
  116. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  117. source.Append(" /// <summary>\n")
  118. .Append(" /// Cached StringNames for the methods contained in this class, for fast lookup.\n")
  119. .Append(" /// </summary>\n");
  120. source.Append(
  121. $" public new class MethodName : {symbol.BaseType!.FullQualifiedNameIncludeGlobal()}.MethodName {{\n");
  122. // Generate cached StringNames for methods and properties, for fast lookup
  123. var distinctMethodNames = godotClassMethods
  124. .Select(m => m.Method.Name)
  125. .Distinct()
  126. .ToArray();
  127. foreach (string methodName in distinctMethodNames)
  128. {
  129. source.Append(" /// <summary>\n")
  130. .Append(" /// Cached name for the '")
  131. .Append(methodName)
  132. .Append("' method.\n")
  133. .Append(" /// </summary>\n");
  134. source.Append(" public new static readonly global::Godot.StringName ");
  135. source.Append(methodName);
  136. source.Append(" = \"");
  137. source.Append(methodName);
  138. source.Append("\";\n");
  139. }
  140. source.Append(" }\n"); // class GodotInternal
  141. // Generate GetGodotMethodList
  142. if (godotClassMethods.Length > 0)
  143. {
  144. const string listType = "global::System.Collections.Generic.List<global::Godot.Bridge.MethodInfo>";
  145. source.Append(" /// <summary>\n")
  146. .Append(" /// Get the method information for all the methods declared in this class.\n")
  147. .Append(" /// This method is used by Godot to register the available methods in the editor.\n")
  148. .Append(" /// Do not call this method.\n")
  149. .Append(" /// </summary>\n");
  150. source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
  151. source.Append(" internal new static ")
  152. .Append(listType)
  153. .Append(" GetGodotMethodList()\n {\n");
  154. source.Append(" var methods = new ")
  155. .Append(listType)
  156. .Append("(")
  157. .Append(godotClassMethods.Length)
  158. .Append(");\n");
  159. foreach (var method in godotClassMethods)
  160. {
  161. var methodInfo = DetermineMethodInfo(method);
  162. AppendMethodInfo(source, methodInfo);
  163. }
  164. source.Append(" return methods;\n");
  165. source.Append(" }\n");
  166. }
  167. source.Append("#pragma warning restore CS0109\n");
  168. // Generate InvokeGodotClassMethod
  169. if (godotClassMethods.Length > 0)
  170. {
  171. source.Append(" /// <inheritdoc/>\n");
  172. source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
  173. source.Append(" protected override bool InvokeGodotClassMethod(in godot_string_name method, ");
  174. source.Append("NativeVariantPtrArgs args, out godot_variant ret)\n {\n");
  175. foreach (var method in godotClassMethods)
  176. {
  177. GenerateMethodInvoker(method, source);
  178. }
  179. source.Append(" return base.InvokeGodotClassMethod(method, args, out ret);\n");
  180. source.Append(" }\n");
  181. }
  182. // Generate InvokeGodotClassStaticMethod
  183. var godotClassStaticMethods = godotClassMethods.Where(m => m.Method.IsStatic).ToArray();
  184. if (godotClassStaticMethods.Length > 0)
  185. {
  186. source.Append("#pragma warning disable CS0109 // Disable warning about redundant 'new' keyword\n");
  187. source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
  188. source.Append(" internal new static bool InvokeGodotClassStaticMethod(in godot_string_name method, ");
  189. source.Append("NativeVariantPtrArgs args, out godot_variant ret)\n {\n");
  190. foreach (var method in godotClassStaticMethods)
  191. {
  192. GenerateMethodInvoker(method, source);
  193. }
  194. source.Append(" ret = default;\n");
  195. source.Append(" return false;\n");
  196. source.Append(" }\n");
  197. source.Append("#pragma warning restore CS0109\n");
  198. }
  199. // Generate HasGodotClassMethod
  200. if (distinctMethodNames.Length > 0)
  201. {
  202. source.Append(" /// <inheritdoc/>\n");
  203. source.Append(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n");
  204. source.Append(" protected override bool HasGodotClassMethod(in godot_string_name method)\n {\n");
  205. bool isFirstEntry = true;
  206. foreach (string methodName in distinctMethodNames)
  207. {
  208. GenerateHasMethodEntry(methodName, source, isFirstEntry);
  209. isFirstEntry = false;
  210. }
  211. source.Append(" return base.HasGodotClassMethod(method);\n");
  212. source.Append(" }\n");
  213. }
  214. source.Append("}\n"); // partial class
  215. if (isInnerClass)
  216. {
  217. var containingType = symbol.ContainingType;
  218. while (containingType != null)
  219. {
  220. source.Append("}\n"); // outer class
  221. containingType = containingType.ContainingType;
  222. }
  223. }
  224. if (hasNamespace)
  225. {
  226. source.Append("\n}\n");
  227. }
  228. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  229. }
  230. private static void AppendMethodInfo(StringBuilder source, MethodInfo methodInfo)
  231. {
  232. source.Append(" methods.Add(new(name: MethodName.")
  233. .Append(methodInfo.Name)
  234. .Append(", returnVal: ");
  235. AppendPropertyInfo(source, methodInfo.ReturnVal);
  236. source.Append(", flags: (global::Godot.MethodFlags)")
  237. .Append((int)methodInfo.Flags)
  238. .Append(", arguments: ");
  239. if (methodInfo.Arguments is { Count: > 0 })
  240. {
  241. source.Append("new() { ");
  242. foreach (var param in methodInfo.Arguments)
  243. {
  244. AppendPropertyInfo(source, param);
  245. // C# allows colon after the last element
  246. source.Append(", ");
  247. }
  248. source.Append(" }");
  249. }
  250. else
  251. {
  252. source.Append("null");
  253. }
  254. source.Append(", defaultArguments: null));\n");
  255. }
  256. private static void AppendPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
  257. {
  258. source.Append("new(type: (global::Godot.Variant.Type)")
  259. .Append((int)propertyInfo.Type)
  260. .Append(", name: \"")
  261. .Append(propertyInfo.Name)
  262. .Append("\", hint: (global::Godot.PropertyHint)")
  263. .Append((int)propertyInfo.Hint)
  264. .Append(", hintString: \"")
  265. .Append(propertyInfo.HintString)
  266. .Append("\", usage: (global::Godot.PropertyUsageFlags)")
  267. .Append((int)propertyInfo.Usage)
  268. .Append(", exported: ")
  269. .Append(propertyInfo.Exported ? "true" : "false");
  270. if (propertyInfo.ClassName != null)
  271. {
  272. source.Append(", className: new global::Godot.StringName(\"")
  273. .Append(propertyInfo.ClassName)
  274. .Append("\")");
  275. }
  276. source.Append(")");
  277. }
  278. private static MethodInfo DetermineMethodInfo(GodotMethodData method)
  279. {
  280. PropertyInfo returnVal;
  281. if (method.RetType != null)
  282. {
  283. returnVal = DeterminePropertyInfo(method.RetType.Value.MarshalType,
  284. method.RetType.Value.TypeSymbol,
  285. name: string.Empty);
  286. }
  287. else
  288. {
  289. returnVal = new PropertyInfo(VariantType.Nil, string.Empty, PropertyHint.None,
  290. hintString: null, PropertyUsageFlags.Default, exported: false);
  291. }
  292. int paramCount = method.ParamTypes.Length;
  293. List<PropertyInfo>? arguments;
  294. if (paramCount > 0)
  295. {
  296. arguments = new(capacity: paramCount);
  297. for (int i = 0; i < paramCount; i++)
  298. {
  299. arguments.Add(DeterminePropertyInfo(method.ParamTypes[i],
  300. method.Method.Parameters[i].Type,
  301. name: method.Method.Parameters[i].Name));
  302. }
  303. }
  304. else
  305. {
  306. arguments = null;
  307. }
  308. MethodFlags flags = MethodFlags.Default;
  309. if (method.Method.IsStatic)
  310. {
  311. flags |= MethodFlags.Static;
  312. }
  313. return new MethodInfo(method.Method.Name, returnVal, flags, arguments,
  314. defaultArguments: null);
  315. }
  316. private static PropertyInfo DeterminePropertyInfo(MarshalType marshalType, ITypeSymbol typeSymbol, string name)
  317. {
  318. var memberVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(marshalType)!.Value;
  319. var propUsage = PropertyUsageFlags.Default;
  320. if (memberVariantType == VariantType.Nil)
  321. propUsage |= PropertyUsageFlags.NilIsVariant;
  322. string? className = null;
  323. if (memberVariantType == VariantType.Object && typeSymbol is INamedTypeSymbol namedTypeSymbol)
  324. {
  325. className = namedTypeSymbol.GetGodotScriptNativeClassName();
  326. }
  327. return new PropertyInfo(memberVariantType, name,
  328. PropertyHint.None, string.Empty, propUsage, className, exported: false);
  329. }
  330. private static void GenerateHasMethodEntry(
  331. string methodName,
  332. StringBuilder source,
  333. bool isFirstEntry
  334. )
  335. {
  336. source.Append(" ");
  337. if (!isFirstEntry)
  338. source.Append("else ");
  339. source.Append("if (method == MethodName.");
  340. source.Append(methodName);
  341. source.Append(") {\n return true;\n }\n");
  342. }
  343. private static void GenerateMethodInvoker(
  344. GodotMethodData method,
  345. StringBuilder source
  346. )
  347. {
  348. string methodName = method.Method.Name;
  349. source.Append(" if (method == MethodName.");
  350. source.Append(methodName);
  351. source.Append(" && args.Count == ");
  352. source.Append(method.ParamTypes.Length);
  353. source.Append(") {\n");
  354. if (method.RetType != null)
  355. source.Append(" var callRet = ");
  356. else
  357. source.Append(" ");
  358. source.Append(methodName);
  359. source.Append("(");
  360. for (int i = 0; i < method.ParamTypes.Length; i++)
  361. {
  362. if (i != 0)
  363. source.Append(", ");
  364. source.AppendNativeVariantToManagedExpr(string.Concat("args[", i.ToString(), "]"),
  365. method.ParamTypeSymbols[i], method.ParamTypes[i]);
  366. }
  367. source.Append(");\n");
  368. if (method.RetType != null)
  369. {
  370. source.Append(" ret = ");
  371. source.AppendManagedToNativeVariantExpr("callRet",
  372. method.RetType.Value.TypeSymbol, method.RetType.Value.MarshalType);
  373. source.Append(";\n");
  374. source.Append(" return true;\n");
  375. }
  376. else
  377. {
  378. source.Append(" ret = default;\n");
  379. source.Append(" return true;\n");
  380. }
  381. source.Append(" }\n");
  382. }
  383. }
  384. }