ScriptMethodsGenerator.cs 17 KB

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