ScriptMethodsGenerator.cs 14 KB

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