ScriptMethodsGenerator.cs 16 KB

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