ScriptMethodsGenerator.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. foreach (string methodName in distinctMethodNames)
  204. {
  205. GenerateHasMethodEntry(methodName, source);
  206. }
  207. source.Append(" return base.HasGodotClassMethod(method);\n");
  208. source.Append(" }\n");
  209. }
  210. source.Append("}\n"); // partial class
  211. if (isInnerClass)
  212. {
  213. var containingType = symbol.ContainingType;
  214. while (containingType != null)
  215. {
  216. source.Append("}\n"); // outer class
  217. containingType = containingType.ContainingType;
  218. }
  219. }
  220. if (hasNamespace)
  221. {
  222. source.Append("\n}\n");
  223. }
  224. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  225. }
  226. private static void AppendMethodInfo(StringBuilder source, MethodInfo methodInfo)
  227. {
  228. source.Append(" methods.Add(new(name: MethodName.@")
  229. .Append(methodInfo.Name)
  230. .Append(", returnVal: ");
  231. AppendPropertyInfo(source, methodInfo.ReturnVal);
  232. source.Append(", flags: (global::Godot.MethodFlags)")
  233. .Append((int)methodInfo.Flags)
  234. .Append(", arguments: ");
  235. if (methodInfo.Arguments is { Count: > 0 })
  236. {
  237. source.Append("new() { ");
  238. foreach (var param in methodInfo.Arguments)
  239. {
  240. AppendPropertyInfo(source, param);
  241. // C# allows colon after the last element
  242. source.Append(", ");
  243. }
  244. source.Append(" }");
  245. }
  246. else
  247. {
  248. source.Append("null");
  249. }
  250. source.Append(", defaultArguments: null));\n");
  251. }
  252. private static void AppendPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
  253. {
  254. source.Append("new(type: (global::Godot.Variant.Type)")
  255. .Append((int)propertyInfo.Type)
  256. .Append(", name: \"")
  257. .Append(propertyInfo.Name)
  258. .Append("\", hint: (global::Godot.PropertyHint)")
  259. .Append((int)propertyInfo.Hint)
  260. .Append(", hintString: \"")
  261. .Append(propertyInfo.HintString)
  262. .Append("\", usage: (global::Godot.PropertyUsageFlags)")
  263. .Append((int)propertyInfo.Usage)
  264. .Append(", exported: ")
  265. .Append(propertyInfo.Exported ? "true" : "false");
  266. if (propertyInfo.ClassName != null)
  267. {
  268. source.Append(", className: new global::Godot.StringName(\"")
  269. .Append(propertyInfo.ClassName)
  270. .Append("\")");
  271. }
  272. source.Append(")");
  273. }
  274. private static MethodInfo DetermineMethodInfo(GodotMethodData method)
  275. {
  276. PropertyInfo returnVal;
  277. if (method.RetType != null)
  278. {
  279. returnVal = DeterminePropertyInfo(method.RetType.Value.MarshalType,
  280. method.RetType.Value.TypeSymbol,
  281. name: string.Empty);
  282. }
  283. else
  284. {
  285. returnVal = new PropertyInfo(VariantType.Nil, string.Empty, PropertyHint.None,
  286. hintString: null, PropertyUsageFlags.Default, exported: false);
  287. }
  288. int paramCount = method.ParamTypes.Length;
  289. List<PropertyInfo>? arguments;
  290. if (paramCount > 0)
  291. {
  292. arguments = new(capacity: paramCount);
  293. for (int i = 0; i < paramCount; i++)
  294. {
  295. arguments.Add(DeterminePropertyInfo(method.ParamTypes[i],
  296. method.Method.Parameters[i].Type,
  297. name: method.Method.Parameters[i].Name));
  298. }
  299. }
  300. else
  301. {
  302. arguments = null;
  303. }
  304. MethodFlags flags = MethodFlags.Default;
  305. if (method.Method.IsStatic)
  306. {
  307. flags |= MethodFlags.Static;
  308. }
  309. return new MethodInfo(method.Method.Name, returnVal, flags, arguments,
  310. defaultArguments: null);
  311. }
  312. private static PropertyInfo DeterminePropertyInfo(MarshalType marshalType, ITypeSymbol typeSymbol, string name)
  313. {
  314. var memberVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(marshalType)!.Value;
  315. var propUsage = PropertyUsageFlags.Default;
  316. if (memberVariantType == VariantType.Nil)
  317. propUsage |= PropertyUsageFlags.NilIsVariant;
  318. string? className = null;
  319. if (memberVariantType == VariantType.Object && typeSymbol is INamedTypeSymbol namedTypeSymbol)
  320. {
  321. className = namedTypeSymbol.GetGodotScriptNativeClassName();
  322. }
  323. return new PropertyInfo(memberVariantType, name,
  324. PropertyHint.None, string.Empty, propUsage, className, exported: false);
  325. }
  326. private static void GenerateHasMethodEntry(
  327. string methodName,
  328. StringBuilder source
  329. )
  330. {
  331. source.Append(" ");
  332. source.Append("if (method == MethodName.@");
  333. source.Append(methodName);
  334. source.Append(") {\n return true;\n }\n");
  335. }
  336. private static void GenerateMethodInvoker(
  337. GodotMethodData method,
  338. StringBuilder source
  339. )
  340. {
  341. string methodName = method.Method.Name;
  342. source.Append(" if (method == MethodName.@");
  343. source.Append(methodName);
  344. source.Append(" && args.Count == ");
  345. source.Append(method.ParamTypes.Length);
  346. source.Append(") {\n");
  347. if (method.RetType != null)
  348. source.Append(" var callRet = ");
  349. else
  350. source.Append(" ");
  351. source.Append("@");
  352. source.Append(methodName);
  353. source.Append("(");
  354. for (int i = 0; i < method.ParamTypes.Length; i++)
  355. {
  356. if (i != 0)
  357. source.Append(", ");
  358. source.AppendNativeVariantToManagedExpr(string.Concat("args[", i.ToString(), "]"),
  359. method.ParamTypeSymbols[i], method.ParamTypes[i]);
  360. }
  361. source.Append(");\n");
  362. if (method.RetType != null)
  363. {
  364. source.Append(" ret = ");
  365. source.AppendManagedToNativeVariantExpr("callRet",
  366. method.RetType.Value.TypeSymbol, method.RetType.Value.MarshalType);
  367. source.Append(";\n");
  368. source.Append(" return true;\n");
  369. }
  370. else
  371. {
  372. source.Append(" ret = default;\n");
  373. source.Append(" return true;\n");
  374. }
  375. source.Append(" }\n");
  376. }
  377. }
  378. }