UnmanagedCallbacksGenerator.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. using System.Text;
  2. using System.Linq;
  3. using Microsoft.CodeAnalysis;
  4. using Microsoft.CodeAnalysis.Text;
  5. using Microsoft.CodeAnalysis.CSharp;
  6. using Microsoft.CodeAnalysis.CSharp.Syntax;
  7. namespace Godot.SourceGenerators.Internal;
  8. [Generator]
  9. public class UnmanagedCallbacksGenerator : ISourceGenerator
  10. {
  11. public void Initialize(GeneratorInitializationContext context)
  12. {
  13. context.RegisterForPostInitialization(ctx => { GenerateAttribute(ctx); });
  14. }
  15. public void Execute(GeneratorExecutionContext context)
  16. {
  17. INamedTypeSymbol[] unmanagedCallbacksClasses = context
  18. .Compilation.SyntaxTrees
  19. .SelectMany(tree =>
  20. tree.GetRoot().DescendantNodes()
  21. .OfType<ClassDeclarationSyntax>()
  22. .SelectUnmanagedCallbacksClasses(context.Compilation)
  23. // Report and skip non-partial classes
  24. .Where(x =>
  25. {
  26. if (x.cds.IsPartial())
  27. {
  28. if (x.cds.IsNested() && !x.cds.AreAllOuterTypesPartial(out var typeMissingPartial))
  29. {
  30. Common.ReportNonPartialUnmanagedCallbacksOuterClass(context, typeMissingPartial!);
  31. return false;
  32. }
  33. return true;
  34. }
  35. Common.ReportNonPartialUnmanagedCallbacksClass(context, x.cds, x.symbol);
  36. return false;
  37. })
  38. .Select(x => x.symbol)
  39. )
  40. .Distinct<INamedTypeSymbol>(SymbolEqualityComparer.Default)
  41. .ToArray();
  42. foreach (var symbol in unmanagedCallbacksClasses)
  43. {
  44. var attr = symbol.GetGenerateUnmanagedCallbacksAttribute();
  45. if (attr == null || attr.ConstructorArguments.Length != 1)
  46. {
  47. // TODO: Report error or throw exception, this is an invalid case and should never be reached
  48. System.Diagnostics.Debug.Fail("FAILED!");
  49. continue;
  50. }
  51. var funcStructType = (INamedTypeSymbol?)attr.ConstructorArguments[0].Value;
  52. if (funcStructType == null)
  53. {
  54. // TODO: Report error or throw exception, this is an invalid case and should never be reached
  55. System.Diagnostics.Debug.Fail("FAILED!");
  56. continue;
  57. }
  58. var data = new CallbacksData(symbol, funcStructType);
  59. GenerateInteropMethodImplementations(context, data);
  60. GenerateUnmanagedCallbacksStruct(context, data);
  61. }
  62. }
  63. private void GenerateAttribute(GeneratorPostInitializationContext context)
  64. {
  65. string source = @"using System;
  66. namespace Godot.SourceGenerators.Internal
  67. {
  68. internal class GenerateUnmanagedCallbacksAttribute : Attribute
  69. {
  70. public Type FuncStructType { get; }
  71. public GenerateUnmanagedCallbacksAttribute(Type funcStructType)
  72. {
  73. FuncStructType = funcStructType;
  74. }
  75. }
  76. }";
  77. context.AddSource("GenerateUnmanagedCallbacksAttribute.generated",
  78. SourceText.From(source, Encoding.UTF8));
  79. }
  80. private void GenerateInteropMethodImplementations(GeneratorExecutionContext context, CallbacksData data)
  81. {
  82. var symbol = data.NativeTypeSymbol;
  83. INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
  84. string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
  85. namespaceSymbol.FullQualifiedNameOmitGlobal() :
  86. string.Empty;
  87. bool hasNamespace = classNs.Length != 0;
  88. bool isInnerClass = symbol.ContainingType != null;
  89. var source = new StringBuilder();
  90. var methodSource = new StringBuilder();
  91. var methodCallArguments = new StringBuilder();
  92. var methodSourceAfterCall = new StringBuilder();
  93. source.Append(
  94. @"using System;
  95. using System.Diagnostics.CodeAnalysis;
  96. using System.Runtime.CompilerServices;
  97. using System.Runtime.InteropServices;
  98. using Godot.Bridge;
  99. using Godot.NativeInterop;
  100. #pragma warning disable CA1707 // Disable warning: Identifiers should not contain underscores
  101. ");
  102. if (hasNamespace)
  103. {
  104. source.Append("namespace ");
  105. source.Append(classNs);
  106. source.Append("\n{\n");
  107. }
  108. if (isInnerClass)
  109. {
  110. var containingType = symbol.ContainingType;
  111. AppendPartialContainingTypeDeclarations(containingType);
  112. void AppendPartialContainingTypeDeclarations(INamedTypeSymbol? containingType)
  113. {
  114. if (containingType == null)
  115. return;
  116. AppendPartialContainingTypeDeclarations(containingType.ContainingType);
  117. source.Append("partial ");
  118. source.Append(containingType.GetDeclarationKeyword());
  119. source.Append(" ");
  120. source.Append(containingType.NameWithTypeParameters());
  121. source.Append("\n{\n");
  122. }
  123. }
  124. source.Append("[System.Runtime.CompilerServices.SkipLocalsInit]\n");
  125. source.Append($"unsafe partial class {symbol.Name}\n");
  126. source.Append("{\n");
  127. source.Append($" private static {data.FuncStructSymbol.FullQualifiedNameIncludeGlobal()} _unmanagedCallbacks;\n\n");
  128. foreach (var callback in data.Methods)
  129. {
  130. methodSource.Clear();
  131. methodCallArguments.Clear();
  132. methodSourceAfterCall.Clear();
  133. source.Append(" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]\n");
  134. source.Append($" {SyntaxFacts.GetText(callback.DeclaredAccessibility)} ");
  135. if (callback.IsStatic)
  136. source.Append("static ");
  137. source.Append("partial ");
  138. source.Append(callback.ReturnType.FullQualifiedNameIncludeGlobal());
  139. source.Append(' ');
  140. source.Append(callback.Name);
  141. source.Append('(');
  142. for (int i = 0; i < callback.Parameters.Length; i++)
  143. {
  144. var parameter = callback.Parameters[i];
  145. AppendRefKind(source, parameter.RefKind);
  146. source.Append(' ');
  147. source.Append(parameter.Type.FullQualifiedNameIncludeGlobal());
  148. source.Append(' ');
  149. source.Append(parameter.Name);
  150. if (parameter.RefKind == RefKind.Out)
  151. {
  152. // Only assign default if the parameter won't be passed by-ref or copied later.
  153. if (IsGodotInteropStruct(parameter.Type))
  154. methodSource.Append($" {parameter.Name} = default;\n");
  155. }
  156. if (IsByRefParameter(parameter))
  157. {
  158. if (IsGodotInteropStruct(parameter.Type))
  159. {
  160. methodSource.Append(" ");
  161. AppendCustomUnsafeAsPointer(methodSource, parameter, out string varName);
  162. methodCallArguments.Append(varName);
  163. }
  164. else if (parameter.Type.IsValueType)
  165. {
  166. methodSource.Append(" ");
  167. AppendCopyToStackAndGetPointer(methodSource, parameter, out string varName);
  168. methodCallArguments.Append($"&{varName}");
  169. if (parameter.RefKind is RefKind.Out or RefKind.Ref)
  170. {
  171. methodSourceAfterCall.Append($" {parameter.Name} = {varName};\n");
  172. }
  173. }
  174. else
  175. {
  176. // If it's a by-ref param and we can't get the pointer
  177. // just pass it by-ref and let it be pinned.
  178. AppendRefKind(methodCallArguments, parameter.RefKind)
  179. .Append(' ')
  180. .Append(parameter.Name);
  181. }
  182. }
  183. else
  184. {
  185. methodCallArguments.Append(parameter.Name);
  186. }
  187. if (i < callback.Parameters.Length - 1)
  188. {
  189. source.Append(", ");
  190. methodCallArguments.Append(", ");
  191. }
  192. }
  193. source.Append(")\n");
  194. source.Append(" {\n");
  195. source.Append(methodSource);
  196. source.Append(" ");
  197. if (!callback.ReturnsVoid)
  198. {
  199. if (methodSourceAfterCall.Length != 0)
  200. source.Append($"{callback.ReturnType.FullQualifiedNameIncludeGlobal()} ret = ");
  201. else
  202. source.Append("return ");
  203. }
  204. source.Append($"_unmanagedCallbacks.{callback.Name}(");
  205. source.Append(methodCallArguments);
  206. source.Append(");\n");
  207. if (methodSourceAfterCall.Length != 0)
  208. {
  209. source.Append(methodSourceAfterCall);
  210. if (!callback.ReturnsVoid)
  211. source.Append(" return ret;\n");
  212. }
  213. source.Append(" }\n\n");
  214. }
  215. source.Append("}\n");
  216. if (isInnerClass)
  217. {
  218. var containingType = symbol.ContainingType;
  219. while (containingType != null)
  220. {
  221. source.Append("}\n"); // outer class
  222. containingType = containingType.ContainingType;
  223. }
  224. }
  225. if (hasNamespace)
  226. source.Append("\n}");
  227. source.Append("\n\n#pragma warning restore CA1707\n");
  228. context.AddSource($"{data.NativeTypeSymbol.FullQualifiedNameOmitGlobal().SanitizeQualifiedNameForUniqueHint()}.generated",
  229. SourceText.From(source.ToString(), Encoding.UTF8));
  230. }
  231. private void GenerateUnmanagedCallbacksStruct(GeneratorExecutionContext context, CallbacksData data)
  232. {
  233. var symbol = data.FuncStructSymbol;
  234. INamespaceSymbol namespaceSymbol = symbol.ContainingNamespace;
  235. string classNs = namespaceSymbol != null && !namespaceSymbol.IsGlobalNamespace ?
  236. namespaceSymbol.FullQualifiedNameOmitGlobal() :
  237. string.Empty;
  238. bool hasNamespace = classNs.Length != 0;
  239. bool isInnerClass = symbol.ContainingType != null;
  240. var source = new StringBuilder();
  241. source.Append(
  242. @"using System.Runtime.InteropServices;
  243. using Godot.NativeInterop;
  244. #pragma warning disable CA1707 // Disable warning: Identifiers should not contain underscores
  245. ");
  246. if (hasNamespace)
  247. {
  248. source.Append("namespace ");
  249. source.Append(classNs);
  250. source.Append("\n{\n");
  251. }
  252. if (isInnerClass)
  253. {
  254. var containingType = symbol.ContainingType;
  255. AppendPartialContainingTypeDeclarations(containingType);
  256. void AppendPartialContainingTypeDeclarations(INamedTypeSymbol? containingType)
  257. {
  258. if (containingType == null)
  259. return;
  260. AppendPartialContainingTypeDeclarations(containingType.ContainingType);
  261. source.Append("partial ");
  262. source.Append(containingType.GetDeclarationKeyword());
  263. source.Append(" ");
  264. source.Append(containingType.NameWithTypeParameters());
  265. source.Append("\n{\n");
  266. }
  267. }
  268. source.Append("[StructLayout(LayoutKind.Sequential)]\n");
  269. source.Append($"unsafe partial struct {symbol.Name}\n{{\n");
  270. foreach (var callback in data.Methods)
  271. {
  272. source.Append(" ");
  273. source.Append(callback.DeclaredAccessibility == Accessibility.Public ? "public " : "internal ");
  274. source.Append("delegate* unmanaged<");
  275. foreach (var parameter in callback.Parameters)
  276. {
  277. if (IsByRefParameter(parameter))
  278. {
  279. if (IsGodotInteropStruct(parameter.Type) || parameter.Type.IsValueType)
  280. {
  281. AppendPointerType(source, parameter.Type);
  282. }
  283. else
  284. {
  285. // If it's a by-ref param and we can't get the pointer
  286. // just pass it by-ref and let it be pinned.
  287. AppendRefKind(source, parameter.RefKind)
  288. .Append(' ')
  289. .Append(parameter.Type.FullQualifiedNameIncludeGlobal());
  290. }
  291. }
  292. else
  293. {
  294. source.Append(parameter.Type.FullQualifiedNameIncludeGlobal());
  295. }
  296. source.Append(", ");
  297. }
  298. source.Append(callback.ReturnType.FullQualifiedNameIncludeGlobal());
  299. source.Append($"> {callback.Name};\n");
  300. }
  301. source.Append("}\n");
  302. if (isInnerClass)
  303. {
  304. var containingType = symbol.ContainingType;
  305. while (containingType != null)
  306. {
  307. source.Append("}\n"); // outer class
  308. containingType = containingType.ContainingType;
  309. }
  310. }
  311. if (hasNamespace)
  312. source.Append("}\n");
  313. source.Append("\n#pragma warning restore CA1707\n");
  314. context.AddSource($"{symbol.FullQualifiedNameOmitGlobal().SanitizeQualifiedNameForUniqueHint()}.generated",
  315. SourceText.From(source.ToString(), Encoding.UTF8));
  316. }
  317. private static bool IsGodotInteropStruct(ITypeSymbol type) =>
  318. _godotInteropStructs.Contains(type.FullQualifiedNameOmitGlobal());
  319. private static bool IsByRefParameter(IParameterSymbol parameter) =>
  320. parameter.RefKind is RefKind.In or RefKind.Out or RefKind.Ref;
  321. private static StringBuilder AppendRefKind(StringBuilder source, RefKind refKind) =>
  322. refKind switch
  323. {
  324. RefKind.In => source.Append("in"),
  325. RefKind.Out => source.Append("out"),
  326. RefKind.Ref => source.Append("ref"),
  327. _ => source,
  328. };
  329. private static void AppendPointerType(StringBuilder source, ITypeSymbol type)
  330. {
  331. source.Append(type.FullQualifiedNameIncludeGlobal());
  332. source.Append('*');
  333. }
  334. private static void AppendCustomUnsafeAsPointer(StringBuilder source, IParameterSymbol parameter,
  335. out string varName)
  336. {
  337. varName = $"{parameter.Name}_ptr";
  338. AppendPointerType(source, parameter.Type);
  339. source.Append(' ');
  340. source.Append(varName);
  341. source.Append(" = ");
  342. source.Append('(');
  343. AppendPointerType(source, parameter.Type);
  344. source.Append(')');
  345. if (parameter.RefKind == RefKind.In)
  346. source.Append("CustomUnsafe.ReadOnlyRefAsPointer(in ");
  347. else
  348. source.Append("CustomUnsafe.AsPointer(ref ");
  349. source.Append(parameter.Name);
  350. source.Append(");\n");
  351. }
  352. private static void AppendCopyToStackAndGetPointer(StringBuilder source, IParameterSymbol parameter,
  353. out string varName)
  354. {
  355. varName = $"{parameter.Name}_copy";
  356. source.Append(parameter.Type.FullQualifiedNameIncludeGlobal());
  357. source.Append(' ');
  358. source.Append(varName);
  359. if (parameter.RefKind is RefKind.In or RefKind.Ref)
  360. {
  361. source.Append(" = ");
  362. source.Append(parameter.Name);
  363. }
  364. source.Append(";\n");
  365. }
  366. private static readonly string[] _godotInteropStructs =
  367. {
  368. "Godot.NativeInterop.godot_ref",
  369. "Godot.NativeInterop.godot_variant_call_error",
  370. "Godot.NativeInterop.godot_variant",
  371. "Godot.NativeInterop.godot_string",
  372. "Godot.NativeInterop.godot_string_name",
  373. "Godot.NativeInterop.godot_node_path",
  374. "Godot.NativeInterop.godot_signal",
  375. "Godot.NativeInterop.godot_callable",
  376. "Godot.NativeInterop.godot_array",
  377. "Godot.NativeInterop.godot_dictionary",
  378. "Godot.NativeInterop.godot_packed_byte_array",
  379. "Godot.NativeInterop.godot_packed_int32_array",
  380. "Godot.NativeInterop.godot_packed_int64_array",
  381. "Godot.NativeInterop.godot_packed_float32_array",
  382. "Godot.NativeInterop.godot_packed_float64_array",
  383. "Godot.NativeInterop.godot_packed_string_array",
  384. "Godot.NativeInterop.godot_packed_vector2_array",
  385. "Godot.NativeInterop.godot_packed_vector3_array",
  386. "Godot.NativeInterop.godot_packed_vector4_array",
  387. "Godot.NativeInterop.godot_packed_color_array",
  388. };
  389. }