Debian Codegraph @

modules/mono/glue/GodotSharp/Godot.SourceGenerators.Internal/UnmanagedCallbacksGenerator.cs

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