ScriptMethodsGenerator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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(
  115. $" public new class MethodName : {symbol.BaseType.FullQualifiedNameIncludeGlobal()}.MethodName {{\n");
  116. // Generate cached StringNames for methods and properties, for fast lookup
  117. var distinctMethodNames = godotClassMethods
  118. .Select(m => m.Method.Name)
  119. .Distinct()
  120. .ToArray();
  121. foreach (string methodName in distinctMethodNames)
  122. {
  123. source.Append(" public new static readonly global::Godot.StringName ");
  124. source.Append(methodName);
  125. source.Append(" = \"");
  126. source.Append(methodName);
  127. source.Append("\";\n");
  128. }
  129. source.Append(" }\n"); // class GodotInternal
  130. // Generate GetGodotMethodList
  131. if (godotClassMethods.Length > 0)
  132. {
  133. const string listType = "global::System.Collections.Generic.List<global::Godot.Bridge.MethodInfo>";
  134. source.Append(" internal new static ")
  135. .Append(listType)
  136. .Append(" GetGodotMethodList()\n {\n");
  137. source.Append(" var methods = new ")
  138. .Append(listType)
  139. .Append("(")
  140. .Append(godotClassMethods.Length)
  141. .Append(");\n");
  142. foreach (var method in godotClassMethods)
  143. {
  144. var methodInfo = DetermineMethodInfo(method);
  145. AppendMethodInfo(source, methodInfo);
  146. }
  147. source.Append(" return methods;\n");
  148. source.Append(" }\n");
  149. }
  150. source.Append("#pragma warning restore CS0109\n");
  151. // Generate InvokeGodotClassMethod
  152. if (godotClassMethods.Length > 0)
  153. {
  154. source.Append(" protected override bool InvokeGodotClassMethod(in godot_string_name method, ");
  155. source.Append("NativeVariantPtrArgs args, out godot_variant ret)\n {\n");
  156. foreach (var method in godotClassMethods)
  157. {
  158. GenerateMethodInvoker(method, source);
  159. }
  160. source.Append(" return base.InvokeGodotClassMethod(method, args, out ret);\n");
  161. source.Append(" }\n");
  162. }
  163. // Generate HasGodotClassMethod
  164. if (distinctMethodNames.Length > 0)
  165. {
  166. source.Append(" protected override bool HasGodotClassMethod(in godot_string_name method)\n {\n");
  167. bool isFirstEntry = true;
  168. foreach (string methodName in distinctMethodNames)
  169. {
  170. GenerateHasMethodEntry(methodName, source, isFirstEntry);
  171. isFirstEntry = false;
  172. }
  173. source.Append(" return base.HasGodotClassMethod(method);\n");
  174. source.Append(" }\n");
  175. }
  176. source.Append("}\n"); // partial class
  177. if (isInnerClass)
  178. {
  179. var containingType = symbol.ContainingType;
  180. while (containingType != null)
  181. {
  182. source.Append("}\n"); // outer class
  183. containingType = containingType.ContainingType;
  184. }
  185. }
  186. if (hasNamespace)
  187. {
  188. source.Append("\n}\n");
  189. }
  190. context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
  191. }
  192. private static void AppendMethodInfo(StringBuilder source, MethodInfo methodInfo)
  193. {
  194. source.Append(" methods.Add(new(name: MethodName.")
  195. .Append(methodInfo.Name)
  196. .Append(", returnVal: ");
  197. AppendPropertyInfo(source, methodInfo.ReturnVal);
  198. source.Append(", flags: (global::Godot.MethodFlags)")
  199. .Append((int)methodInfo.Flags)
  200. .Append(", arguments: ");
  201. if (methodInfo.Arguments is { Count: > 0 })
  202. {
  203. source.Append("new() { ");
  204. foreach (var param in methodInfo.Arguments)
  205. {
  206. AppendPropertyInfo(source, param);
  207. // C# allows colon after the last element
  208. source.Append(", ");
  209. }
  210. source.Append(" }");
  211. }
  212. else
  213. {
  214. source.Append("null");
  215. }
  216. source.Append(", defaultArguments: null));\n");
  217. }
  218. private static void AppendPropertyInfo(StringBuilder source, PropertyInfo propertyInfo)
  219. {
  220. source.Append("new(type: (global::Godot.Variant.Type)")
  221. .Append((int)propertyInfo.Type)
  222. .Append(", name: \"")
  223. .Append(propertyInfo.Name)
  224. .Append("\", hint: (global::Godot.PropertyHint)")
  225. .Append((int)propertyInfo.Hint)
  226. .Append(", hintString: \"")
  227. .Append(propertyInfo.HintString)
  228. .Append("\", usage: (global::Godot.PropertyUsageFlags)")
  229. .Append((int)propertyInfo.Usage)
  230. .Append(", exported: ")
  231. .Append(propertyInfo.Exported ? "true" : "false");
  232. if (propertyInfo.ClassName != null)
  233. {
  234. source.Append(", className: new global::Godot.StringName(\"")
  235. .Append(propertyInfo.ClassName)
  236. .Append("\")");
  237. }
  238. source.Append(")");
  239. }
  240. private static MethodInfo DetermineMethodInfo(GodotMethodData method)
  241. {
  242. PropertyInfo returnVal;
  243. if (method.RetType != null)
  244. {
  245. returnVal = DeterminePropertyInfo(method.RetType.Value.MarshalType,
  246. method.RetType.Value.TypeSymbol,
  247. name: string.Empty);
  248. }
  249. else
  250. {
  251. returnVal = new PropertyInfo(VariantType.Nil, string.Empty, PropertyHint.None,
  252. hintString: null, PropertyUsageFlags.Default, exported: false);
  253. }
  254. int paramCount = method.ParamTypes.Length;
  255. List<PropertyInfo>? arguments;
  256. if (paramCount > 0)
  257. {
  258. arguments = new(capacity: paramCount);
  259. for (int i = 0; i < paramCount; i++)
  260. {
  261. arguments.Add(DeterminePropertyInfo(method.ParamTypes[i],
  262. method.Method.Parameters[i].Type,
  263. name: method.Method.Parameters[i].Name));
  264. }
  265. }
  266. else
  267. {
  268. arguments = null;
  269. }
  270. return new MethodInfo(method.Method.Name, returnVal, MethodFlags.Default, arguments,
  271. defaultArguments: null);
  272. }
  273. private static PropertyInfo DeterminePropertyInfo(MarshalType marshalType, ITypeSymbol typeSymbol, string name)
  274. {
  275. var memberVariantType = MarshalUtils.ConvertMarshalTypeToVariantType(marshalType)!.Value;
  276. var propUsage = PropertyUsageFlags.Default;
  277. if (memberVariantType == VariantType.Nil)
  278. propUsage |= PropertyUsageFlags.NilIsVariant;
  279. string? className = null;
  280. if (memberVariantType == VariantType.Object && typeSymbol is INamedTypeSymbol namedTypeSymbol)
  281. {
  282. className = namedTypeSymbol.GetGodotScriptNativeClassName();
  283. }
  284. return new PropertyInfo(memberVariantType, name,
  285. PropertyHint.None, string.Empty, propUsage, className, exported: false);
  286. }
  287. private static void GenerateHasMethodEntry(
  288. string methodName,
  289. StringBuilder source,
  290. bool isFirstEntry
  291. )
  292. {
  293. source.Append(" ");
  294. if (!isFirstEntry)
  295. source.Append("else ");
  296. source.Append("if (method == MethodName.");
  297. source.Append(methodName);
  298. source.Append(") {\n return true;\n }\n");
  299. }
  300. private static void GenerateMethodInvoker(
  301. GodotMethodData method,
  302. StringBuilder source
  303. )
  304. {
  305. string methodName = method.Method.Name;
  306. source.Append(" if (method == MethodName.");
  307. source.Append(methodName);
  308. source.Append(" && args.Count == ");
  309. source.Append(method.ParamTypes.Length);
  310. source.Append(") {\n");
  311. if (method.RetType != null)
  312. source.Append(" var callRet = ");
  313. else
  314. source.Append(" ");
  315. source.Append(methodName);
  316. source.Append("(");
  317. for (int i = 0; i < method.ParamTypes.Length; i++)
  318. {
  319. if (i != 0)
  320. source.Append(", ");
  321. source.AppendNativeVariantToManagedExpr(string.Concat("args[", i.ToString(), "]"),
  322. method.ParamTypeSymbols[i], method.ParamTypes[i]);
  323. }
  324. source.Append(");\n");
  325. if (method.RetType != null)
  326. {
  327. source.Append(" ret = ");
  328. source.AppendManagedToNativeVariantExpr("callRet",
  329. method.RetType.Value.TypeSymbol, method.RetType.Value.MarshalType);
  330. source.Append(";\n");
  331. source.Append(" return true;\n");
  332. }
  333. else
  334. {
  335. source.Append(" ret = default;\n");
  336. source.Append(" return true;\n");
  337. }
  338. source.Append(" }\n");
  339. }
  340. }
  341. }