ScriptMethodsGenerator.cs 17 KB

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