-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathemit_csharp.py
More file actions
1609 lines (1398 loc) · 67.4 KB
/
Copy pathemit_csharp.py
File metadata and controls
1609 lines (1398 loc) · 67.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2026 Fernando Sahmkow
"""IR -> idiomatic C# bindings.
Output layout (per module M):
bindings/csharp/Whiteout/<M>/
NativeMethods.<M>.cs internal partial class: every LibraryImport
<Enum>.cs public enum
<Class>.cs public sealed class : WhiteoutHandle
Methods are mapped to PascalCase C# methods on the public class. Each
generated public method calls into the `NativeMethods` LibraryImport stub
and handles marshalling (NativeBytes copy-and-free, optional handle
wrapping, ReadOnlySpan<byte> pinning, enum casts, bool ↔ int32).
Method shapes the C emitter exposes today and how we lower them:
C++ C# public Native (LibraryImport)
---------------------------------- -------------------------- --------------------------
uint32_t width() uint Width() uint whiteout_M_C_width(...)
int32_t isSrgb() bool IsSrgb() [MarshalAs(I4)] bool ...
Type type() // enum Type Type() cast int → enum
std::optional<Texture> parse(span) Texture? Parse(ROS<byte>) IntPtr (null = empty)
std::vector<u8> write(Texture) byte[] Write(Texture) NativeBytes (free after)
std::optional<vec<u8>> tryWrite() byte[]? TryWrite() NativeBytes (null = empty)
std::string lastError() string LastError() NativeCString
Texture create2D(...) static Texture Create2D(.) IntPtr → new Texture(h)
Skipped (silently — Phase 3+):
- methods with `interfaces::X*` callback params (WorkerPool, HttpHandler)
- methods with `std::vector<Class>` params
- methods with `std::span<const T>` for T != u8
- methods with `std::vector<T>` returns where T != u8
- move-only return types where ownership semantics aren't clear
"""
from __future__ import annotations
import re
from io import StringIO
from .ir import (
BindClass, BindEnum, BindField, BindMethod, BindMethodParam, BindModule,
TypeKind, TypeRef,
)
from .parser import _short_name
from .emit_c import (
_c_handle_name, _module_prefix,
_is_method_supported, _is_byte_vector_param, _is_field_supported,
_is_interface_pointer_param, _is_span_const_u8,
_resolve_handle_short, _known_class_short_names,
_is_vector_string_return,
_is_owned_string_list_return,
_module_has_string_list,
_ctor_overloads_named,
)
# ── Naming ─────────────────────────────────────────────────────────────────
def _pascal(name: str) -> str:
"""`mdx` → `Mdx`; `parseBufferFormat` → `ParseBufferFormat`."""
if not name:
return name
parts = re.split(r'[_\s]+', name)
out = ''.join(p[:1].upper() + p[1:] for p in parts if p)
return out[:1].upper() + out[1:]
def _ns(module: BindModule) -> str:
return f'Whiteout.{_pascal(module.name)}'
def _strip_prefix(js_name: str, prefix: str) -> str:
if prefix and js_name.startswith(prefix):
return js_name[len(prefix):] or js_name
return js_name
def _cs_type_name(js_name: str, module: BindModule) -> str:
return _strip_prefix(js_name, module.js_prefix)
# ── Math types ────────────────────────────────────────────────────────────
#
# Recognised math types are aliased (via global using in
# Whiteout.Common/MathTypes.cs) to System.Numerics value-type structs:
# Vector2f → System.Numerics.Vector2 (8 bytes, 2 floats)
# Vector3f → System.Numerics.Vector3 (12 bytes, 3 floats)
# Vector4f → System.Numerics.Vector4 (16 bytes, 4 floats)
# Quaternion → System.Numerics.Quaternion (16 bytes, X/Y/Z/W floats)
#
# The C ABI exposes them as opaque pointer-to-struct handles. The C# side
# reads/writes the underlying 12/16 bytes directly via `Unsafe.Read<T>` /
# `Unsafe.Write<T>` so the value semantics work without a SafeHandle dance
# at every read.
_MATH_TYPES: dict[str, tuple[str, int]] = {
# short_name → (C# struct type, size in bytes)
'Vector2f': ('Vector2f', 8),
'Vector3f': ('Vector3f', 12),
'Vector4f': ('Vector4f', 16),
'Quaternion': ('Quaternion', 16),
}
def _math_info(cpp_text: str) -> tuple[str, int] | None:
"""If `cpp_text` references a recognised math type, return its
(C#-type, byte-size). Otherwise None."""
short = cpp_text.split('::')[-1].split('<')[0]
return _MATH_TYPES.get(short)
# ── Primitive type maps ────────────────────────────────────────────────────
_CS_PRIMITIVE = {
'u8': 'byte', 'u16': 'ushort', 'u32': 'uint', 'u64': 'ulong',
'i8': 'sbyte', 'i16': 'short', 'i32': 'int', 'i64': 'long',
'f32': 'float', 'f64': 'double',
'bool': 'bool',
'unsigned char': 'byte',
'unsigned short': 'ushort',
'unsigned int': 'uint',
'unsigned long long': 'ulong',
'signed char': 'sbyte',
'short': 'short',
'int': 'int',
'long long': 'long',
'float': 'float',
'double': 'double',
'char': 'sbyte',
# See emit_java._JAVA_PRIMITIVE for the rationale: `size_t` is preserved
# by the parser to keep JNI overrides honest, so emitters must map it
# to the same C# type we used to emit (when it was canonicalised to
# `u64` → `ulong`). The marshaller treats it as 8 bytes on every
# platform the package ships for (Windows x64 / Linux x64 / macOS arm64).
'size_t': 'ulong',
'std::size_t': 'ulong',
}
# C ABI primitives → C# native types for LibraryImport. Bool crosses the
# ABI as int32 with a MarshalAs marshaller applied externally.
_CS_NATIVE_PRIMITIVE = dict(_CS_PRIMITIVE)
_CS_NATIVE_PRIMITIVE['bool'] = 'int' # raw native side; public side stays bool
def _is_known_handle(cpp_text: str, module: BindModule) -> bool:
return _c_handle_name(cpp_text) in _known_class_short_names(module)
# ── Type lowering ─────────────────────────────────────────────────────────
# Method names that collide with members of the System.Runtime.InteropServices.SafeHandle
# base. Generated methods using these names need the `new` keyword to suppress CS0108.
_SAFE_HANDLE_RESERVED = frozenset({
'Close', # SafeHandle.Close() — aliases Dispose. Domain methods like
# mpq::Storage::close() shouldn't pretend to be Dispose.
'Dispose',
})
_TRAMPOLINED_INTERFACES = {
# cpp_text → (C# managed base class, fully qualified)
'whiteout::interfaces::VirtualPathFileSystem': 'Whiteout.Host.VirtualPathFileSystem',
'whiteout::interfaces::HttpHandler': 'Whiteout.Host.HttpHandler',
'whiteout::interfaces::WorkerPool': 'Whiteout.Host.WorkerPool',
}
# Per trampolined base: the method names that exist as abstracts/virtuals
# on the managed base. When the codegen-emitted class derives from one of
# these bases, methods with matching names use `override` instead of being
# emitted fresh; methods missing entirely from the C ABI get a throwing
# stub so the derived class isn't left abstract.
#
# Entry: cpp method name → kind ('method' or 'prop')
_TRAMPOLINED_BASE_MEMBERS: dict[str, dict[str, str]] = {
'Whiteout.Host.VirtualPathFileSystem': {
'readFile': 'method',
'writeFile': 'method',
'fileExists': 'method',
},
'Whiteout.Host.HttpHandler': {
'capabilities': 'prop',
'getAsync': 'method',
'getRangeAsync': 'method',
},
'Whiteout.Host.WorkerPool': {
'submit': 'method',
'waitIdle': 'method',
'threadCount': 'prop',
},
}
def _trampolined_base_for_class(c: BindClass) -> str | None:
"""If `c` derives from a trampolined interface, return the C# managed
base class name."""
if not c.base_class:
return None
return _TRAMPOLINED_INTERFACES.get(c.base_class)
# Throwing-stub signatures for abstract methods missing from a concrete
# class's bound C ABI. Indexed by (base_class_short, member_name) → full
# C# declaration line (without the leading ` public override `).
_THROWING_STUBS: dict[tuple[str, str], str] = {
('VirtualPathFileSystem', 'readFile'):
'byte[] ReadFile(string path) => throw new NotSupportedException("native dispatch");',
('VirtualPathFileSystem', 'writeFile'):
'bool WriteFile(string path, ReadOnlySpan<byte> data) => throw new NotSupportedException("native dispatch");',
('VirtualPathFileSystem', 'fileExists'):
'bool FileExists(string path) => throw new NotSupportedException("native dispatch");',
('HttpHandler', 'getAsync'):
'void GetAsync(string url, Action<Whiteout.Host.HttpResponse> callback) => throw new NotSupportedException("native dispatch");',
('HttpHandler', 'getRangeAsync'):
'void GetRangeAsync(string url, ulong start, ulong end, Action<Whiteout.Host.HttpResponse> callback) => throw new NotSupportedException("native dispatch");',
('WorkerPool', 'submit'):
'void Submit(Whiteout.Host.WorkerTask task) => throw new NotSupportedException("native dispatch");',
('WorkerPool', 'waitIdle'):
'void WaitIdle() => throw new NotSupportedException("native dispatch");',
('WorkerPool', 'threadCount'):
'ulong ThreadCount => throw new NotSupportedException("native dispatch");',
}
def _trampolined_interface(p: BindMethodParam) -> str | None:
"""If `p` is a reference/pointer to a managed-subclassable abstract
interface (currently only VirtualPathFileSystem), return the C# base
class name to surface in the public API. Other interface params
(HttpHandler, WorkerPool) still skip until their trampolines land."""
if not _is_interface_pointer_param(p):
return None
return _TRAMPOLINED_INTERFACES.get(p.type.cpp_text)
def _native_param(p: BindMethodParam, module: BindModule) -> str | None:
"""Render one method parameter for the LibraryImport stub. Returns the
full declaration string (one or two comma-separated params) or None if
we can't lower this parameter shape."""
t = p.type
if p.span_scalar is not None:
# std::span<const T> for some primitive T. Skip for now — we only
# ship byte spans in Phase 2.
if p.span_scalar[0] not in ('u8', 'unsigned char'):
return None
return f'ReadOnlySpan<byte> {p.name}, nuint {p.name}_size'
if _trampolined_interface(p) is not None:
return f'IntPtr {p.name}'
if _is_interface_pointer_param(p):
return None
if t.kind == TypeKind.PRIMITIVE:
short = _short_name(t.cpp_text)
cs = _CS_NATIVE_PRIMITIVE.get(short)
if cs is None:
return None
return f'{cs} {p.name}'
if t.kind == TypeKind.STRING:
return f'[MarshalAs(UnmanagedType.LPUTF8Str)] string {p.name}'
if t.kind == TypeKind.ENUM:
return f'int {p.name}'
if _is_byte_vector_param(p):
return f'ReadOnlySpan<byte> {p.name}, nuint {p.name}_size'
if t.kind in (TypeKind.NESTED, TypeKind.UNKNOWN):
if t.cpp_text.startswith('std::'):
return None
if not _is_known_handle(t.cpp_text, module):
return None
return f'IntPtr {p.name}'
return None
def _native_return(m: BindMethod, module: BindModule) -> str | None:
"""Render the LibraryImport stub return type. Returns None when we
can't model the return — caller should skip the method."""
r = m.return_type
if r.cpp_text == 'void':
return 'void'
if r.kind == TypeKind.PRIMITIVE:
short = _short_name(r.cpp_text)
cs = _CS_NATIVE_PRIMITIVE.get(short)
return cs
if r.kind == TypeKind.ENUM:
return 'int'
if r.kind == TypeKind.STRING:
return 'Whiteout.Common.NativeCString'
if r.kind == TypeKind.NESTED:
if r.cpp_text.startswith('std::'):
return None
if not _is_known_handle(r.cpp_text, module):
return None
return 'IntPtr'
if r.kind == TypeKind.UNKNOWN:
if _is_span_const_u8(r):
return 'Whiteout.Common.NativeBytes'
if r.cpp_text.startswith('std::'):
return None
if not _is_known_handle(r.cpp_text, module):
return None
return 'IntPtr'
if r.kind == TypeKind.OPTIONAL:
e = r.element
if e.kind == TypeKind.NESTED and _is_known_handle(e.cpp_text, module):
return 'IntPtr'
if e.kind == TypeKind.STRING:
return 'Whiteout.Common.NativeCString'
if e.kind == TypeKind.VECTOR and \
_short_name(e.element.cpp_text) in ('u8', 'unsigned char'):
return 'Whiteout.Common.NativeBytes'
# optional<scalar> is an int32 has-value flag plus an out-param;
# see `_optional_scalar_cs` and `_emit_native_method`.
if _optional_scalar_cs(m) is not None:
return 'int'
return None
if r.kind == TypeKind.VECTOR:
if _short_name(r.element.cpp_text) in ('u8', 'unsigned char'):
return 'Whiteout.Common.NativeBytes'
return None
return None
def _public_return(m: BindMethod, module: BindModule) -> tuple[str, str] | None:
"""(public C# return type, internal classification tag). The tag drives
how the wrapper marshals the native call back to managed land:
'void' void return
'prim' primitive (incl. int-as-bool)
'bool' bool: native int32, public bool
'enum:X' public enum X (cast from int)
'bytes' non-nullable byte[]
'bytes?' nullable byte[]?
'string' string
'string?' nullable string?
'handle:X' non-nullable handle wrapper X
'handle?:X' nullable handle wrapper X?
"""
r = m.return_type
if r.cpp_text == 'void':
return 'void', 'void'
if r.kind == TypeKind.PRIMITIVE:
short = _short_name(r.cpp_text)
cs = _CS_PRIMITIVE.get(short)
if cs is None:
return None
return (cs, 'bool' if short == 'bool' else 'prim')
if r.kind == TypeKind.ENUM:
# Resolve enum short name (strips ns + js_prefix)
name = _resolve_enum_cs_name(r.cpp_text, module)
if name is None:
return None
return name, f'enum:{name}'
if r.kind == TypeKind.STRING:
return 'string', 'string'
if r.kind == TypeKind.NESTED:
if r.cpp_text.startswith('std::'):
return None
if not _is_known_handle(r.cpp_text, module):
return None
name = _wrapper_name(r.cpp_text, module)
return name, f'handle:{name}'
if r.kind == TypeKind.UNKNOWN:
if _is_span_const_u8(r):
return 'byte[]', 'bytes'
if r.cpp_text.startswith('std::'):
return None
if not _is_known_handle(r.cpp_text, module):
return None
name = _wrapper_name(r.cpp_text, module)
return name, f'handle:{name}'
if r.kind == TypeKind.OPTIONAL:
e = r.element
if e.kind == TypeKind.NESTED and _is_known_handle(e.cpp_text, module):
name = _wrapper_name(e.cpp_text, module)
return f'{name}?', f'handle?:{name}'
if e.kind == TypeKind.STRING:
return 'string?', 'string?'
if e.kind == TypeKind.VECTOR and \
_short_name(e.element.cpp_text) in ('u8', 'unsigned char'):
return 'byte[]?', 'bytes?'
if _optional_scalar_cs(m) is not None:
if e.kind == TypeKind.ENUM:
name = _resolve_enum_cs_name(e.cpp_text, module)
return None if name is None else (f'{name}?', f'opt_enum:{name}')
short = _short_name(e.cpp_text)
cs = _CS_PRIMITIVE.get(short)
if cs is None:
return None
# `bool` crosses the ABI as int32 (see _CS_NATIVE_PRIMITIVE), so
# the out-param needs a comparison rather than a straight return.
return (f'{cs}?', 'opt_bool' if short == 'bool' else f'opt_prim:{cs}')
return None
if r.kind == TypeKind.VECTOR:
if _short_name(r.element.cpp_text) in ('u8', 'unsigned char'):
return 'byte[]', 'bytes'
return None
return None
def _optional_scalar_cs(m: BindMethod) -> str | None:
"""`std::optional<T>` for a scalar T — returns the C# type of the C ABI's
`T* out_value` param. Mirrors emit_c's `_optional_primitive_return`: the
C function returns an int32 has-value flag and writes the value out."""
r = m.return_type
if r.kind != TypeKind.OPTIONAL or r.element is None:
return None
if r.element.kind == TypeKind.ENUM:
return 'int'
if r.element.kind != TypeKind.PRIMITIVE:
return None
return _CS_NATIVE_PRIMITIVE.get(_short_name(r.element.cpp_text))
def _resolve_enum_cs_name(cpp_text: str, module: BindModule) -> str | None:
"""Find the C# enum name corresponding to a C++ enum cpp_text reference."""
short = cpp_text.split('::')[-1]
for e in module.enums:
if e.cpp_qualifier.split('::')[-1] == short or e.js_name == short:
return _cs_type_name(e.js_name, module)
return None
def _native_ctor_params(ctor, module: BindModule) -> str | None:
"""LibraryImport signature for a non-default constructor."""
decls: list[str] = []
for p in ctor.params:
t = p.type
# Trampolined interfaces (WorkerPool, HttpHandler, ...) cross as an
# opaque handle, same as in `_native_param`. These are what the
# parallel-decode ctors — BlpWriter(pool), JpegParser(pool) — take.
if _trampolined_interface(p) is not None:
decls.append(f'IntPtr {p.name}')
continue
if _is_interface_pointer_param(p):
return None
if t.kind == TypeKind.STRING:
decls.append(f'[MarshalAs(UnmanagedType.LPUTF8Str)] string {p.name}')
continue
if t.kind == TypeKind.PRIMITIVE:
short = _short_name(t.cpp_text)
cs = _CS_NATIVE_PRIMITIVE.get(short)
if cs is None:
return None
decls.append(f'{cs} {p.name}')
continue
if t.kind == TypeKind.ENUM:
decls.append(f'int {p.name}')
continue
if t.kind in (TypeKind.NESTED, TypeKind.UNKNOWN) \
and not t.cpp_text.startswith('std::') \
and _is_known_handle(t.cpp_text, module):
decls.append(f'IntPtr {p.name}')
continue
return None
return ', '.join(decls)
def _cs_ctor_params(ctor, module: BindModule) -> tuple[str, str] | tuple[None, None]:
"""Render a non-default constructor's parameters for the C# public ctor.
Returns (cs_param_list, cs_arg_list_for_native_call) or (None, None) if
any parameter type isn't representable. Mirrors the subset of C ABI
constructor param types the C emitter handles."""
decls: list[str] = []
args: list[str] = []
for p in ctor.params:
t = p.type
# A managed WorkerPool / HttpHandler subclass is passed straight
# through; the trampoline on the C++ side calls back into it.
# Nullable rather than defaulted — a defaulted param here would be
# illegal when a required one follows, as in JpegWriter(quality,
# pool, progressive). The no-arg ctor already covers "no pool".
trampolined = _trampolined_interface(p)
if trampolined is not None:
decls.append(f'{trampolined}? {p.name}')
args.append(f'{p.name}?.DangerousGet() ?? IntPtr.Zero')
continue
if _is_interface_pointer_param(p):
return None, None
if t.kind == TypeKind.STRING:
decls.append(f'string {p.name}')
args.append(p.name)
continue
if t.kind == TypeKind.PRIMITIVE:
short = _short_name(t.cpp_text)
cs = _CS_PRIMITIVE.get(short)
if cs is None:
return None, None
decls.append(f'{cs} {p.name}')
# bool is `int` on the native side (_CS_NATIVE_PRIMITIVE).
args.append(f'{p.name} ? 1 : 0' if short == 'bool' else p.name)
continue
if t.kind == TypeKind.ENUM:
name = _resolve_enum_cs_name(t.cpp_text, module)
if name is None:
return None, None
decls.append(f'{name} {p.name}')
args.append(f'(int){p.name}')
continue
# Class-handle ctor params (e.g. MpqFileSystem(Storage&)) need a
# known handle to extract DangerousGet() from.
if t.kind in (TypeKind.NESTED, TypeKind.UNKNOWN) \
and not t.cpp_text.startswith('std::') \
and _is_known_handle(t.cpp_text, module):
wrapper = _wrapper_name(t.cpp_text, module)
decls.append(f'{wrapper} {p.name}')
args.append(f'{p.name}.DangerousGet()')
continue
return None, None
return ', '.join(decls), ', '.join(args)
def _wrapper_name(cpp_text: str, module: BindModule) -> str:
"""Resolve the public C# type name for a class referenced by cpp_text.
Math types short-circuit to their `Whiteout.Common` alias name
(`Vector3f` → `System.Numerics.Vector3` at use sites). Otherwise the
normal cross-class lookup applies — the C emitter's
`_resolve_handle_short` maps the short spelling (e.g. `ApngFrameInfo`)
to the bound JS name (`PngApngFrameInfo`)."""
info = _math_info(cpp_text)
if info is not None:
return info[0]
resolved = _resolve_handle_short(cpp_text, module)
for c in module.classes:
if _c_handle_name(c.js_name) == resolved:
return _cs_type_name(c.js_name, module)
return _strip_prefix(resolved, module.js_prefix)
# ── Public-method parameters ───────────────────────────────────────────────
def _public_param(p: BindMethodParam, module: BindModule) -> tuple[str, str, str] | None:
"""(C# parameter decl, native arg expression, optional prologue stmt).
`native arg expression` is what we pass into NativeMethods.* at the
call site. The prologue is empty for trivial conversions and non-empty
when we need a temporary variable (e.g. enum cast, bool→int)."""
t = p.type
pname = p.name
if p.span_scalar is not None:
if p.span_scalar[0] not in ('u8', 'unsigned char'):
return None
return (f'ReadOnlySpan<byte> {pname}',
f'{pname}, (nuint){pname}.Length', '')
managed_iface = _trampolined_interface(p)
if managed_iface is not None:
return (f'{managed_iface} {pname}',
f'{pname}.DangerousGet()', '')
if _is_interface_pointer_param(p):
return None
if t.kind == TypeKind.PRIMITIVE:
short = _short_name(t.cpp_text)
cs = _CS_PRIMITIVE.get(short)
if cs is None:
return None
if short == 'bool':
# public bool → native int32
return (f'bool {pname}',
f'{pname} ? 1 : 0', '')
return (f'{cs} {pname}', pname, '')
if t.kind == TypeKind.ENUM:
name = _resolve_enum_cs_name(t.cpp_text, module)
if name is None:
return None
return (f'{name} {pname}', f'(int){pname}', '')
if t.kind == TypeKind.STRING:
return (f'string {pname}', pname, '')
if _is_byte_vector_param(p):
return (f'ReadOnlySpan<byte> {pname}',
f'{pname}, (nuint){pname}.Length', '')
if t.kind in (TypeKind.NESTED, TypeKind.UNKNOWN):
if t.cpp_text.startswith('std::'):
return None
if not _is_known_handle(t.cpp_text, module):
return None
name = _wrapper_name(t.cpp_text, module)
return (f'{name} {pname}', f'{pname}.DangerousGet()', '')
return None
# ── Method emission ────────────────────────────────────────────────────────
# ── vector<record> returns ────────────────────────────────────────────────
#
# `@bind record` classes have no handle: the C ABI lowers a vector<record>
# return to a snapshot plus per-field index accessors (see emit_c), and the
# managed side materialises them into immutable C# records.
def _find_record_class(module: BindModule, cpp_text: str) -> BindClass | None:
short = cpp_text.split('::')[-1].strip()
for c in module.classes:
if c.is_record and (c.cpp_qualifier.split('::')[-1] == short
or c.js_name == short):
return c
return None
def _is_vector_record_return(m: BindMethod, module: BindModule) -> bool:
r = m.return_type
return (r.kind == TypeKind.VECTOR and r.element is not None
and _find_record_class(module, r.element.cpp_text) is not None)
def _record_field_kind(f: BindField) -> str | None:
"""'prim' / 'enum' / 'string' / 'bytes' (std::array<u8,N>), or None when
the field shape isn't representable in a record."""
t = f.type
if t.kind == TypeKind.PRIMITIVE:
return 'prim'
if t.kind == TypeKind.ENUM:
return 'enum'
if t.kind == TypeKind.STRING:
return 'string'
if t.kind == TypeKind.ARRAY and t.element is not None \
and t.element.kind == TypeKind.PRIMITIVE \
and _short_name(t.element.cpp_text) in ('u8', 'unsigned char'):
return 'bytes'
return None
def _record_fields(rec: BindClass) -> list[BindField]:
return [f for f in rec.fields if _record_field_kind(f) is not None]
def _record_field_native_ret(f: BindField) -> str:
k = _record_field_kind(f)
if k == 'prim':
return _CS_NATIVE_PRIMITIVE.get(_short_name(f.type.cpp_text), 'int')
if k == 'enum':
return 'int'
if k == 'string':
return 'Whiteout.Common.NativeCString'
return 'Whiteout.Common.NativeBytes'
def _record_field_public_type(f: BindField, module: BindModule) -> str:
k = _record_field_kind(f)
if k == 'prim':
return _CS_PRIMITIVE.get(_short_name(f.type.cpp_text), 'int')
if k == 'enum':
return _resolve_enum_cs_name(f.type.cpp_text, module) or 'int'
if k == 'string':
return 'string'
return 'byte[]'
def _can_emit_method(m: BindMethod, c: BindClass, module: BindModule) -> bool:
if not _is_method_supported(m, module):
return False
if _is_vector_string_return(m):
# Lowered to (count, at) pair — no other constraints to check.
return True
if _is_vector_record_return(m, module):
# Lowered to snapshot + per-field index accessors.
return True
if _native_return(m, module) is None:
return False
if _public_return(m, module) is None:
return False
for p in m.params:
if _native_param(p, module) is None:
return False
if _public_param(p, module) is None:
return False
return True
def _emit_native_method(buf: StringIO, m: BindMethod, c: BindClass,
module: BindModule) -> None:
prefix = _module_prefix(module)
short = _c_handle_name(c.js_name)
sym = f'{prefix}_{short}_{m.name}'
if _is_vector_string_return(m):
# Lowered pair on the C ABI: count + at.
buf.write(f' [LibraryImport(Runtime.LibraryName)]\n')
buf.write(f' internal static partial nuint {sym}_count(IntPtr self);\n\n')
buf.write(f' [LibraryImport(Runtime.LibraryName)]\n')
buf.write(f' internal static partial Whiteout.Common.NativeCString {sym}_at(IntPtr self, nuint index);\n\n')
if _is_owned_string_list_return(m):
# By-value returns also get the owned-list variant, which is what
# the wrapper actually calls — see `_emit_public_method`.
buf.write(f' [LibraryImport(Runtime.LibraryName)]\n')
buf.write(f' internal static partial IntPtr {sym}(IntPtr self);\n\n')
return
if _is_vector_record_return(m, module):
# Lowered on the C ABI to: snapshot + count + per-field _at + free.
rec = _find_record_class(module, m.return_type.element.cpp_text)
buf.write(f' [LibraryImport(Runtime.LibraryName)]\n')
buf.write(f' internal static partial IntPtr {sym}_snapshot(IntPtr self);\n\n')
buf.write(f' [LibraryImport(Runtime.LibraryName)]\n')
buf.write(f' internal static partial nuint {sym}_count(IntPtr snapshot);\n\n')
for f in _record_fields(rec):
buf.write(f' [LibraryImport(Runtime.LibraryName)]\n')
buf.write(f' internal static partial {_record_field_native_ret(f)} '
f'{sym}_{f.name}_at(IntPtr snapshot, nuint index);\n\n')
buf.write(f' [LibraryImport(Runtime.LibraryName)]\n')
buf.write(f' internal static partial void {sym}_free(IntPtr snapshot);\n\n')
return
ret = _native_return(m, module)
parts: list[str] = []
if not m.is_static:
parts.append('IntPtr self')
for p in m.params:
np = _native_param(p, module)
assert np is not None
parts.append(np)
opt_scalar = _optional_scalar_cs(m)
if opt_scalar is not None:
parts.append(f'out {opt_scalar} out_value')
sig = ', '.join(parts)
buf.write(f' [LibraryImport(Runtime.LibraryName)]\n')
if ret == 'int' and _native_return_is_bool(m):
# Special-case bool returns: MarshalAs on the return value sits on
# the method, not the parameter list.
buf.write(f' [return: MarshalAs(UnmanagedType.I4)]\n')
buf.write(f' internal static partial {ret} {sym}({sig});\n\n')
def _native_return_is_bool(m: BindMethod) -> bool:
return (m.return_type.kind == TypeKind.PRIMITIVE
and _short_name(m.return_type.cpp_text) == 'bool')
# ── Getter promotion + getter/setter pairing ──────────────────────────────
#
# C# idiom is to expose accessor pairs as properties. This pass:
# 1. Detects no-arg const methods returning primitive/enum/bool as getters
# → emit `T Foo { get; }` (read-only property).
# 2. Detects matching setters (`setFoo` taking one arg of type T) → fold
# into the same property as a setter: `T Foo { get; set; }`.
#
# Methods returning byte[] / string / handles are NOT promoted — they do
# nontrivial work and properties are expected to be cheap.
def _is_getter_candidate(m: BindMethod) -> bool:
if m.is_static or not m.is_const:
return False
if m.params:
return False
if m.return_type.kind == TypeKind.PRIMITIVE:
return True
if m.return_type.kind == TypeKind.ENUM:
return True
return False
def _matching_setter_name(getter_name: str) -> str:
"""`width` → `setWidth`; `isSrgb` → `setSrgb` (strip the `is` prefix
and re-capitalise). The C++ side uses both conventions."""
g = getter_name
if g[:2] == 'is' and len(g) > 2 and g[2].isupper():
# isFoo → setFoo (drop "is", keep capitalisation)
return 'set' + g[2:]
if g[:3] == 'has' and len(g) > 3 and g[3].isupper():
return 'set' + g[3:]
return 'set' + g[:1].upper() + g[1:]
def _is_matching_setter(m: BindMethod, getter: BindMethod) -> bool:
"""A setter for `getter` is non-const, takes exactly one parameter of
the same type as the getter's return, returns void, and is named per
`_matching_setter_name`."""
if m.is_static or m.is_const:
return False
if m.return_type.cpp_text != 'void':
return False
if len(m.params) != 1:
return False
if m.name != _matching_setter_name(getter.name):
return False
p = m.params[0]
# Match by kind + spelling so `bool ↔ bool`, `u32 ↔ u32`, enum ↔ same
# enum. We don't bother with cross-enum / -primitive coercion.
return (p.type.kind == getter.return_type.kind
and _short_name(p.type.cpp_text)
== _short_name(getter.return_type.cpp_text))
def _property_name(getter_name: str) -> str:
"""`width` → `Width`; `isSrgb` → `IsSrgb`; `hasIssues` → `HasIssues`;
`frameCount` → `FrameCount`."""
return _pascal(getter_name)
def _is_matching_overload_setter(m: BindMethod, getter: BindMethod) -> bool:
"""C++-side: same method name, non-const overload taking one parameter
of the getter's return type, returning void. The IR renames the second
overload (`format` → `format_overload2`) but preserves `cpp_name` so
we can match by it."""
if m is getter:
return False
if m.cpp_name != getter.cpp_name:
return False
if m.is_static or m.is_const:
return False
if m.return_type.cpp_text != 'void':
return False
if len(m.params) != 1:
return False
p = m.params[0]
return (p.type.kind == getter.return_type.kind
and _short_name(p.type.cpp_text)
== _short_name(getter.return_type.cpp_text))
def _pair_properties(methods: list[BindMethod], module: BindModule
) -> tuple[list[tuple[BindMethod, BindMethod | None, str]], set[int]]:
"""Walk the method list and identify getter / setter pairs.
Returns (props, consumed_method_ids):
- props: list of (getter, setter_or_None, property_name) tuples
- consumed_method_ids: id() of every method already represented as a
property, so the regular method emitter can skip them.
Two pairing rules — same-cpp_name overloads first (highest signal),
then the `setFoo` naming convention:
1. `T foo() const` + `void foo(T)` (overload pair)
2. `T foo() const` + `void setFoo(T)` (Java-bean convention)
3. `T isFoo() const` + `void setFoo(T)` (boolean convention)
"""
props: list[tuple[BindMethod, BindMethod | None, str]] = []
consumed: set[int] = set()
methods_by_name = {m.name: m for m in methods}
for m in methods:
if id(m) in consumed:
continue
if not _is_getter_candidate(m):
continue
if _public_return(m, module) is None:
continue
# Rule 1: same-cpp_name overload pair.
overload_setter = None
for other in methods:
if id(other) in consumed:
continue
if _is_matching_overload_setter(other, m):
sp = _public_param(other.params[0], module)
if sp is not None:
overload_setter = other
break
if overload_setter is not None:
prop_name = _pascal(m.cpp_name)
props.append((m, overload_setter, prop_name))
consumed.add(id(m))
consumed.add(id(overload_setter))
continue
# Rules 2 + 3: setFoo naming convention.
setter = methods_by_name.get(_matching_setter_name(m.name))
if setter is not None and id(setter) not in consumed \
and _is_matching_setter(setter, m):
sp = _public_param(setter.params[0], module)
if sp is not None and _public_return(setter, module) == ('void', 'void'):
props.append((m, setter, _property_name(m.name)))
consumed.add(id(m))
consumed.add(id(setter))
continue
# Getter-only.
props.append((m, None, _property_name(m.name)))
consumed.add(id(m))
return props, consumed
def _emit_property_from_methods(buf: StringIO, getter: BindMethod,
setter: BindMethod | None, prop_name: str,
c: BindClass, module: BindModule,
native_class: str, override: bool = False) -> None:
prefix = _module_prefix(module)
short = _c_handle_name(c.js_name)
get_sym = f'{native_class}.{prefix}_{short}_{getter.name}'
pub_ret, ret_tag = _public_return(getter, module)
if getter.doc:
_write_xmldoc(buf, getter.doc, indent=' ')
override_kw = 'override ' if override else ''
buf.write(f' public {override_kw}{pub_ret} {prop_name}\n')
buf.write(' {\n')
if ret_tag == 'prim':
buf.write(f' get => {get_sym}(DangerousGet());\n')
elif ret_tag == 'bool':
buf.write(f' get => {get_sym}(DangerousGet()) != 0;\n')
elif ret_tag.startswith('enum:'):
enum_name = ret_tag[len('enum:'):]
buf.write(f' get => ({enum_name}){get_sym}(DangerousGet());\n')
else:
# Belt-and-suspenders: _is_getter_candidate gates these tags out.
buf.write(f' get => default!;\n')
if setter is not None:
set_sym = f'{native_class}.{prefix}_{short}_{setter.name}'
sp = _public_param(setter.params[0], module)
assert sp is not None
_, native_arg_expr, _ = sp
# The native_arg_expr is computed off the parameter's declared name
# (e.g. `srgb` or `value`); substitute the C# property's `value`
# keyword in.
value_expr = native_arg_expr.replace(setter.params[0].name, 'value')
buf.write(f' set => {set_sym}(DangerousGet(), {value_expr});\n')
buf.write(' }\n\n')
def _emit_public_method(buf: StringIO, m: BindMethod, c: BindClass,
module: BindModule, native_class: str, override: bool = False) -> None:
prefix = _module_prefix(module)
short = _c_handle_name(c.js_name)
sym = f'{prefix}_{short}_{m.name}'
if _is_vector_string_return(m):
cs_prop_name = _pascal(m.name)
if cs_prop_name.startswith('Get') and len(cs_prop_name) > 3 \
and cs_prop_name[3].isupper():
# `getIssues` → property `Issues` (drop the `Get` prefix).
cs_prop_name = cs_prop_name[3:]
if m.doc:
_write_xmldoc(buf, m.doc, indent=' ')
if _is_owned_string_list_return(m):
# The C++ method returns by value, so the count/at pair would
# re-run the whole query for every index — O(n^2), and ruinous
# for something like a 135k-entry CASC listing. Materialise the
# list once instead and read it O(1) per element.
ls = f'{native_class}.{prefix}_StringList'
buf.write(f' public IReadOnlyList<string> {cs_prop_name}\n')
buf.write(' {\n')
buf.write(' get\n')
buf.write(' {\n')
buf.write(f' IntPtr __list = {native_class}.{sym}(DangerousGet());\n')
buf.write(' if (__list == IntPtr.Zero) return System.Array.Empty<string>();\n')
buf.write(' try\n')
buf.write(' {\n')
buf.write(f' int __n = checked((int){ls}_size(__list));\n')
buf.write(' var __out = new string[__n];\n')
buf.write(' for (int __i = 0; __i < __n; __i++)\n')
buf.write(f' __out[__i] = {ls}_at(__list, (nuint)__i)\n')
buf.write(' .ToManagedString(freeAfter: false);\n')
buf.write(' return __out;\n')
buf.write(' }\n')
buf.write(' finally\n')
buf.write(' {\n')
buf.write(f' {ls}_delete(__list);\n')
buf.write(' }\n')
buf.write(' }\n')
buf.write(' }\n\n')
return
cnt_sym = f'{native_class}.{sym}_count'
at_sym = f'{native_class}.{sym}_at'
buf.write(f' public IReadOnlyList<string> {cs_prop_name} =>\n')
buf.write(f' new NativeListView<string>(\n')
buf.write(f' DangerousGet(),\n')
buf.write(f' {cnt_sym},\n')
buf.write(f' (h, i) => {at_sym}(h, i).ToManagedString());\n\n')
return
pub_ret, ret_tag = _public_return(m, module)
public_params: list[str] = []
native_args: list[str] = []
prologue: list[str] = []
for p in m.params:
pp = _public_param(p, module)
assert pp is not None
decl, arg, pre = pp
public_params.append(decl)
native_args.append(arg)
if pre:
prologue.append(pre)
cs_name = _pascal(m.name)
static_kw = 'static ' if m.is_static else ''
self_arg = 'DangerousGet()' if not m.is_static else ''
call_args = [self_arg] + native_args if self_arg else native_args
if ret_tag.startswith('opt_prim:') or ret_tag.startswith('opt_enum:') \
or ret_tag == 'opt_bool':
call_args = call_args + ['out var __v']
call = f'{native_class}.{sym}({", ".join(a for a in call_args if a)})'
if m.doc:
_write_xmldoc(buf, m.doc, indent=' ')