-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemit_java.py
More file actions
2784 lines (2490 loc) · 141 KB
/
Copy pathemit_java.py
File metadata and controls
2784 lines (2490 loc) · 141 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 Java FFM bindings.
The output is a single Java package — `whiteout.<module>` — with one
.java file per generated type:
whiteout/textures/Native.java // private: SymbolLookup + handles
whiteout/textures/PixelFormat.java // enum
whiteout/textures/AttributeClass.java // enum
whiteout/textures/Texture.java // AutoCloseable class
whiteout/textures/BlpParser.java // AutoCloseable class
whiteout/textures/PngParser.java
...
Each class:
- Implements `java.lang.AutoCloseable`.
- Holds an opaque `MemorySegment` handle.
- Routes calls through the `Native` class which owns the
`Linker`/`MethodHandle`s for the whole module.
This codegen targets JDK 22+ (stable FFM). No external tools (jextract)
needed — we already understand the C++ surface via libclang.
"""
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 as _c_handle_name_ext,
_is_method_supported as _is_method_supported_c,
_is_field_supported as _is_field_supported_c,
_known_class_short_names,
_resolve_handle_short,
_is_span_const_u8,
_is_bulk_flat_inner,
_bulk_components,
_SHARED_MATH_TYPES,
_SHARED_MATH_BYTE_SIZES,
)
# JNI helpers reused for emitting stubs that satisfy
# `whiteout.interfaces.*` abstract methods Panama can't yet expose
# (typically callback-bearing). Sharing keeps the stub signatures in
# lock-step with the canonical interface declarations emit_jni.py
# produces.
from .emit_jni import (
_value_records_referenced as _jni_value_records,
_supported_methods as _jni_supported_methods,
_java_method_signature as _jni_java_method_signature,
)
# ── Direct-memory layout helpers ──────────────────────────────────────────
#
# When libclang gave us a field's byte_offset (and the class's byte_size),
# we can read/write that field straight out of the MemorySegment via
# `handle.get(LAYOUT, offset)` / `handle.set(LAYOUT, offset, value)`,
# bypassing the FFM downcall through the C wrapper. The JIT lowers these
# to a single load/store instruction.
#
# Eligibility is per-FIELD, not per-class: a Sequence whose `name`
# std::string we can't touch still gets direct access for its `u32` fields.
_PRIMITIVE_DIRECT = {
'u8': ('byte', 'ValueLayout.JAVA_BYTE'),
'i8': ('byte', 'ValueLayout.JAVA_BYTE'),
'u16': ('short', 'ValueLayout.JAVA_SHORT'),
'i16': ('short', 'ValueLayout.JAVA_SHORT'),
'u32': ('int', 'ValueLayout.JAVA_INT'),
'i32': ('int', 'ValueLayout.JAVA_INT'),
'u64': ('long', 'ValueLayout.JAVA_LONG'),
'i64': ('long', 'ValueLayout.JAVA_LONG'),
'f32': ('float', 'ValueLayout.JAVA_FLOAT'),
'f64': ('double', 'ValueLayout.JAVA_DOUBLE'),
'bool':('byte', 'ValueLayout.JAVA_BYTE'),
# `size_t` is preserved as its typedef by the parser (see
# `parser._PRESERVE_TYPEDEFS`); without an entry here the FFM emitter
# would drop every constructor/method that takes `size_t`, including
# `SimpleThreadPool(size_t nThreads)`. The wheels target only 64-bit
# platforms (Win x64, Linux x64, macOS arm64) where size_t is 8 bytes,
# so JAVA_LONG matches every shipping ABI.
'size_t': ('long', 'ValueLayout.JAVA_LONG'),
'std::size_t': ('long', 'ValueLayout.JAVA_LONG'),
}
def _primitive_direct_info(t: TypeRef) -> tuple[str, str] | None:
"""For a PRIMITIVE TypeRef, return `(java_type, ValueLayout)` for direct
segment access. `None` for types we can't safely lay out."""
short = _short_name(t.cpp_text)
return _PRIMITIVE_DIRECT.get(short)
def _nested_byte_size(t: TypeRef, module: BindModule) -> int | None:
"""Byte size of a NESTED type, for direct sub-slicing. Looks first
in the shared math table (those sizes are fixed) and then in the
current module's IR (libclang-computed)."""
short = _resolve_handle_short(t.cpp_text, module)
if short in _SHARED_MATH_BYTE_SIZES:
return _SHARED_MATH_BYTE_SIZES[short]
for c in module.classes:
if _c_handle_name_ext(c.js_name) == short and c.byte_size:
return c.byte_size
return None
def _construct_handle_wrap(java_cls: str, seg_expr: str, owned: str) -> str:
"""Construct a handle-backed wrapper from a MemorySegment.
Per-module classes only — `whiteout.common.internal.Handles` is
the entry point for shared math types because their package-
private constructors are reached via reflection, not direct
name access."""
return f'new {java_cls}({seg_expr}, {owned})'
def _java_ctor_param_info(p, module: BindModule | None = None) -> tuple[str, str, str, str] | None:
"""For a constructor parameter, return
`(java_type, layout, marshal_setup, native_arg)`.
- `java_type` — what users see at the Java call site (`String`, `long`, …)
- `layout` — the FunctionDescriptor value layout
(`ValueLayout.ADDRESS`, `ValueLayout.JAVA_LONG`, …)
- `marshal_setup` — Java statement(s) that turn the user-facing param
into the call-site argument; empty when no setup
is needed
- `native_arg` — the expression passed to `MethodHandle.invoke`
Returns `None` for types the Java side can't surface as a constructor
parameter (e.g. raw pointers, classes / vectors without a known
wrapper). The caller skips such ctors when emitting factories.
"""
if p.type.kind == TypeKind.STRING:
# const char* on the C side; Java users pass a String. Allocate
# off a confined arena so the C++ ctor (called inside `invoke`)
# sees a NUL-terminated UTF-8 buffer that doesn't survive the
# call. UTF-8 matches whiteout's path-handling convention.
return ('String',
'ValueLayout.ADDRESS',
f'MemorySegment __seg_{p.name} = __arena.allocateFrom('
f'{p.name}, StandardCharsets.UTF_8);',
f'__seg_{p.name}')
if p.type.kind == TypeKind.PRIMITIVE:
from .parser import _short_name as _sn
short = _sn(p.type.cpp_text)
if short in _PRIMITIVE_DIRECT:
java_t, layout = _PRIMITIVE_DIRECT[short]
return (java_t, layout, '', p.name)
if p.type.kind == TypeKind.ENUM:
if module is None:
return None
enum_short = _resolve_java_name(p.type.cpp_text, module)
return (enum_short, 'ValueLayout.JAVA_INT', '', f'{p.name}.value')
if _is_interface_pointer_param(p):
iface_short = _interface_short_name_for_param(p)
helper_fqn = f'whiteout.host.{iface_short}s'
handle_var = f'__{p.name}_h'
seg_var = f'__{p.name}_seg'
# Owner = impl itself: the constructed wrapper relies on the user
# keeping the impl alive while the C++ object holds the pointer.
setup = (f'long {handle_var} = {p.name} == null ? 0L\n'
f' : {helper_fqn}.resolveNative({p.name}, {p.name});\n'
f' MemorySegment {seg_var} = {handle_var} == 0L\n'
f' ? MemorySegment.NULL : MemorySegment.ofAddress({handle_var});')
return (f'{_INTERFACES_PKG}.{iface_short}',
'ValueLayout.ADDRESS', setup, seg_var)
if p.type.kind in (TypeKind.NESTED, TypeKind.UNKNOWN) \
and not p.type.cpp_text.startswith('std::') and module is not None:
# Class-handle param (e.g. `mpq.FileSystem(Storage storage)`).
# Java users pass the wrapper; we forward `.handle` to the C ctor.
cls_short = _resolve_java_name(p.type.cpp_text, module)
return (cls_short, 'ValueLayout.ADDRESS', '',
f'{p.name} == null ? MemorySegment.NULL : {p.name}.handle')
return None
def _nested_is_pod(t: TypeRef, module: BindModule) -> bool:
"""True when a NESTED field's target type is bitwise-copyable. POD
types can use direct memcpy in setters; non-POD must route through
the C wrapper so the C++ copy-assignment runs (calling destructors,
deep-copying owned `std::string`/`std::vector` buffers, etc.).
Shared math types are POD by construction."""
short = _resolve_handle_short(t.cpp_text, module)
if short in _SHARED_MATH_BYTE_SIZES:
return True
for c in module.classes:
if _c_handle_name_ext(c.js_name) == short:
return c.is_pod
return False
def _bulk_component_short(t: TypeRef) -> str:
"""Short scalar name (`u8`/`f32`/`i32`/…) for each component of a
bulk-flat vector element. Vectors of Vector*/Quaternion split into
a flat `float` strip; vectors of enums marshal as int32."""
if t.kind == TypeKind.PRIMITIVE:
return _short_name(t.cpp_text)
if t.kind == TypeKind.ENUM:
return 'i32'
return 'f32'
# Shared math types live in `whiteout.common` so cross-module Java
# files import them under one canonical name.
_COMMON_PKG = 'whiteout.common'
# Marshalling / FFM-handle plumbing for shared math lives one level
# deeper, in a JPMS-internal package that's NOT exported by
# module-info.java. User code on the classpath or modulepath can't
# reach types in this package, so MemorySegment never leaks out of
# the public surface.
_COMMON_INTERNAL_PKG = 'whiteout.common.internal'
def _module_internal_pkg(module: BindModule) -> str:
"""`whiteout.<module>.internal` — also not exported. Holds the
per-module FFM-handle registry."""
return f'whiteout.{module.name}.internal'
def _c_handle_short(cpp_qualifier: str) -> str:
"""`whiteout::textures::png::Parser` -> `Parser`."""
return cpp_qualifier.split('::')[-1]
# ── Type mapping ──────────────────────────────────────────────────────────
_JAVA_PRIMITIVE = {
'u8': 'byte', 'u16': 'short', 'u32': 'int', 'u64': 'long',
'i8': 'byte', 'i16': 'short', 'i32': 'int', 'i64': 'long',
'f32': 'float', 'f64': 'double', 'bool': 'boolean',
'unsigned char': 'byte', 'unsigned short': 'short',
'unsigned int': 'int', 'unsigned long long': 'long',
'signed char': 'byte', 'short': 'short',
'int': 'int', 'long long': 'long',
'float': 'float', 'double': 'double', 'char': 'byte',
# `size_t` is preserved as its typedef name by the parser (see
# `_PRESERVE_TYPEDEFS`) so the JNI bridge can emit overrides whose
# return type exactly matches the interface — `u64`-aliased overrides
# fail to override on LP64 (Linux/macOS). Map both to the same
# 8-byte Java `long` we used to emit when size_t was canonicalised.
'size_t': 'long', 'std::size_t': 'long',
}
def _java_primitive(t: TypeRef) -> str:
short = _short_name(t.cpp_text)
return _JAVA_PRIMITIVE.get(short, 'int')
# Per-element marshalling info for `std::span<const X>` parameters.
# Maps the scalar's short name (as `_SPAN_SCALAR_TABLE` in parser.py
# produces) to (Java element type, FFM layout, byte size). Used to turn
# `byte[] for any span` into properly-typed `float[]`/`int[]`/`long[]`
# bindings.
_SPAN_ELEM_INFO = {
'u8': ('byte', 'ValueLayout.JAVA_BYTE', 1),
'i8': ('byte', 'ValueLayout.JAVA_BYTE', 1),
'u16': ('short', 'ValueLayout.JAVA_SHORT', 2),
'i16': ('short', 'ValueLayout.JAVA_SHORT', 2),
'u32': ('int', 'ValueLayout.JAVA_INT', 4),
'i32': ('int', 'ValueLayout.JAVA_INT', 4),
'u64': ('long', 'ValueLayout.JAVA_LONG', 8),
'i64': ('long', 'ValueLayout.JAVA_LONG', 8),
'f32': ('float', 'ValueLayout.JAVA_FLOAT', 4),
'f64': ('double', 'ValueLayout.JAVA_DOUBLE', 8),
}
def _span_elem(span_scalar: tuple[str, str]) -> tuple[str, str, int]:
return _SPAN_ELEM_INFO[span_scalar[0]]
def _java_layout(t: TypeRef) -> str:
"""ValueLayout for a primitive used inside FunctionDescriptor."""
name = _java_primitive(t)
return {
'byte': 'ValueLayout.JAVA_BYTE',
'short': 'ValueLayout.JAVA_SHORT',
'int': 'ValueLayout.JAVA_INT',
'long': 'ValueLayout.JAVA_LONG',
'float': 'ValueLayout.JAVA_FLOAT',
'double': 'ValueLayout.JAVA_DOUBLE',
'boolean': 'ValueLayout.JAVA_INT', # 0/1 over the wire
}[name]
def _java_strip_prefix(name: str, module: BindModule) -> str:
"""`MdxSequence` in module `mdx` → `Sequence`; the package itself
disambiguates so the JS-style prefix is just noise in Java. Refuses
to strip when the result would start with a lowercase letter (which
would imply we'd swallowed the first capital of a real type name)."""
p = module.js_prefix
if p and name.startswith(p):
rest = name[len(p):]
if rest and rest[0].isupper():
return rest
return name
def _java_handle_map(module: BindModule) -> dict[str, str]:
"""Memoised map of `cpp_text` variants → Java class/enum short name
(with the module's js_prefix stripped). Covers both classes and
enums so a TypeRef referencing `Sequence::Flag` resolves to
`SequenceFlag` rather than the ambiguous `Flag`."""
cached = getattr(module, '_java_name_map', None)
if cached is not None:
return cached
m: dict[str, str] = {}
def _add(keys: set[str], java_short: str) -> None:
for k in keys:
m[k] = java_short
# `cpp_qualifier` and its short form aren't included as map keys —
# they collide across sub-namespaces (every per-format parser has
# cpp_qualifier "Parser"), and libclang gives us fully-qualified
# canonical spellings in TypeRef cpp_text anyway. The js_name (which
# is unique by construction) plus the fully-qualified path are
# enough to resolve every cross-class reference.
for c in module.classes:
java_short = _java_strip_prefix(_c_handle_name_ext(c.js_name), module)
keys = {_c_handle_name_ext(c.js_name)}
if c.cpp_namespace:
keys.add(f'{c.cpp_namespace}::{c.cpp_qualifier}')
_add(keys, java_short)
for e in module.enums:
java_short = _java_strip_prefix(e.js_name, module)
keys = {e.js_name}
if e.cpp_namespace:
keys.add(f'{e.cpp_namespace}::{e.cpp_qualifier}')
_add(keys, java_short)
# Shared math types keep their short name (no module prefix in
# `whiteout.common` to strip in the first place).
for name in _SHARED_MATH_TYPES:
m[name] = name
m[f'whiteout::{name}'] = name
module._java_name_map = m
return m
def _resolve_java_name(cpp_text: str, module: BindModule) -> str:
"""Look up the Java class/enum name for a cpp_text. Falls back to
the C handle short name when the type isn't in this module's IR —
cross-module references almost always go through shared math, which
is registered explicitly above."""
m = _java_handle_map(module)
if cpp_text in m:
return m[cpp_text]
short = _c_handle_name_ext(cpp_text)
return m.get(short, short)
def _resolve_java_class(cpp_text: str, module: BindModule,
classes_in_module: dict[str, str]) -> str:
"""Back-compat shim — keeps the existing call sites compiling
while the per-module dict argument is being phased out."""
return _resolve_java_name(cpp_text, module)
# Public Java types for return/parameter signatures.
def _java_type(t: TypeRef, module: BindModule,
classes_in_module: dict[str, str]) -> str:
if t.cpp_text == 'void':
return 'void'
if t.kind == TypeKind.PRIMITIVE:
# bool surfaces as boolean on the Java side, even though we ship it
# as int32 over the wire.
return _java_primitive(t)
if t.kind == TypeKind.ENUM:
return _resolve_java_class(t.cpp_text, module, classes_in_module)
if t.kind in (TypeKind.NESTED, TypeKind.UNKNOWN):
# `std::span<const u8>` surfaces on the Java side as byte[] —
# the C wrapper has already packed it into a whiteout_Bytes view.
if _is_span_const_u8(t):
return 'byte[]'
return _resolve_java_class(t.cpp_text, module, classes_in_module)
if t.kind == TypeKind.STRING:
return 'String'
if t.kind == TypeKind.OPTIONAL:
# std::optional<class> -> java.util.Optional<T> so callers can
# use the idiomatic ifPresent/orElse/map chain instead of
# null-checking. Java's primitive Optional* types are skipped
# because no `std::optional<f32>` etc. reaches our C ABI today.
if t.element.kind in (TypeKind.NESTED, TypeKind.UNKNOWN):
inner = _java_type(t.element, module, classes_in_module)
return f'java.util.Optional<{inner}>'
if t.element.kind == TypeKind.STRING:
return 'java.util.Optional<String>'
if t.element.kind == TypeKind.VECTOR \
and _short_name(t.element.element.cpp_text) in ('u8', 'unsigned char'):
return 'byte[]'
return _java_type(t.element, module, classes_in_module)
if t.kind == TypeKind.VECTOR:
if _short_name(t.element.cpp_text) in ('u8', 'unsigned char'):
return 'byte[]'
if t.element.kind in (TypeKind.NESTED, TypeKind.UNKNOWN) \
and not t.element.cpp_text.startswith('std::'):
inner = _resolve_java_name(t.element.cpp_text, module)
return f'{inner}[]'
return 'byte[]'
return 'Object'
def _param_javadoc_type(p, module: BindModule,
classes_in_module: dict[str, str]) -> str:
"""Compute the human-readable Java type spelling for a parameter,
matching what the signature actually generates. Used in @param tags
so the doc matches the type the caller sees."""
if p.span_scalar is not None:
jt, _layout, _sz = _span_elem(p.span_scalar)
return f'{jt}[]'
return _java_type(p.type, module, classes_in_module)
# ── File emission ────────────────────────────────────────────────────────
# ── whiteout.common emit (shared math types) ─────────────────────────────
# ── Try/catch elision post-processor ────────────────────────────────────────
#
# The C library is exception-free, so every generated wrapper's `try { ... }
# catch (Throwable __ex) { throw new RuntimeException(__ex); }` is dead code.
# Java still forces handling because `MethodHandle.invoke(...)` declares
# `throws Throwable`, so each `Native.X.invoke(args)` call is rewritten to
# `NativeCommon.invokeNative(Native.X, args)` (which handles the rethrow in
# one place) and the surrounding try/catch is removed.
#
# NativeCommon.java keeps its own try/catch (it defines `invokeNative`); and
# the static initialiser in `Handles.java` catches `ReflectiveOperationException`
# from `MethodHandles.privateLookupIn` / `findVarHandle` — both are required
# by Java's checked-exception type system and aren't touched by the
# Throwable-only patterns below.
_INVOKE_PATTERN = re.compile(r'(Native\.\w+|CTOR_\w+)\.invoke\(')
def _route_through_invoke_native(java: str) -> str:
"""Rewrite every `Native.X.invoke(args)` → `NativeCommon.invokeNative(Native.X, args)`,
handling nested parentheses in the argument expressions."""
out: list[str] = []
i = 0
while i < len(java):
m = _INVOKE_PATTERN.search(java, i)
if not m:
out.append(java[i:])
break
handle_expr = m.group(1)
out.append(java[i:m.start()])
# Scan forward to the matching close-paren for the `.invoke(`.
depth = 1
j = m.end()
while j < len(java) and depth:
c = java[j]
if c == '(':
depth += 1
elif c == ')':
depth -= 1
if depth == 0:
break
j += 1
if j >= len(java):
# Unterminated — bail out unchanged.
out.append(java[m.start():])
break
args = java[m.end():j].strip()
if args:
out.append(f'NativeCommon.invokeNative({handle_expr}, {args})')
else:
out.append(f'NativeCommon.invokeNative({handle_expr})')
i = j + 1
return ''.join(out)
# Multi-line: `<indent>try {<NL>...body...<NL><indent>} catch (Throwable __ex) ...<NL>`.
# The body's negative lookahead skips lines containing *any* `} catch (` so we
# never match across a nested try (e.g. the static initialiser's
# ReflectiveOperationException catch).
_TRY_THROWABLE_MULTI = re.compile(
r'^([ \t]*)try \{\n'
r'((?:(?!^[ \t]*\} catch \().*\n)*?)'
r'^\1\} catch \(Throwable __ex\) \{ throw new RuntimeException\(__ex\); \}\n',
re.MULTILINE,
)
# Two-line: `<indent>try { body; }<NL><indent>catch (Throwable __ex) ...<NL>`.
_TRY_THROWABLE_TWOLINE = re.compile(
r'^([ \t]*)try \{ (.+?) \}\n'
r'^\1catch \(Throwable __ex\) \{ throw new RuntimeException\(__ex\); \}\n',
re.MULTILINE,
)
# Inline opener with multi-line body: `<indent>try { stmt1;\n<indent> stmt2; }\n<indent>catch (Throwable __ex) ...`.
# Captures the body (between `try { ` and ` }` allowing newlines).
_TRY_THROWABLE_INLINE_OPEN_MULTI = re.compile(
r'^([ \t]*)try \{ (.+?) \}\n'
r'^\1catch \(Throwable __ex\) \{ throw new RuntimeException\(__ex\); \}\n',
re.MULTILINE | re.DOTALL,
)
# Inline (single line): `try { body; } catch (Throwable __ex) ...;`.
_TRY_THROWABLE_INLINE = re.compile(
r'try \{ (.+?) \} catch \(Throwable __ex\) \{ throw new RuntimeException\(__ex\); \}'
)
# Standalone closing catch — appears when the opening was a try-with-resources
# (`try (Arena arena = …) { … } catch (Throwable __ex) …`) whose body the
# multi-line pattern can't consume. Strip the catch but keep the brace that
# closes the try.
_STANDALONE_THROWABLE_CATCH = re.compile(
r'^([ \t]*)\} catch \(Throwable __ex\) \{ throw new RuntimeException\(__ex\); \}\n',
re.MULTILINE,
)
def _strip_try_throwable(java: str) -> str:
"""Remove try { ... } catch (Throwable __ex) { throw new RuntimeException(__ex); }
wrappers, dedenting the body by one indent level."""
def _replace_multi(m: re.Match) -> str:
indent = m.group(1)
body = m.group(2)
# Dedent each body line by 4 spaces if it begins with indent+' '.
dedented: list[str] = []
for line in body.splitlines(keepends=True):
if line.startswith(indent + ' '):
dedented.append(indent + line[len(indent) + 4:])
else:
dedented.append(line)
return ''.join(dedented)
def _replace_inline_open_multi(m: re.Match) -> str:
indent = m.group(1)
body = m.group(2)
# Normalise each body line to the try's indent — flattens the
# inline-opener's mid-line code onto its own line.
normalised = [indent + line.lstrip() for line in body.split('\n')]
return '\n'.join(normalised) + '\n'
java = _TRY_THROWABLE_MULTI.sub(_replace_multi, java)
java = _TRY_THROWABLE_INLINE_OPEN_MULTI.sub(_replace_inline_open_multi, java)
java = _TRY_THROWABLE_TWOLINE.sub(lambda m: f'{m.group(1)}{m.group(2)}\n', java)
java = _TRY_THROWABLE_INLINE.sub(lambda m: m.group(1), java)
# Any `} catch (Throwable __ex)` line still present must belong to a
# try-with-resources; strip the catch and keep the closing brace.
java = _STANDALONE_THROWABLE_CATCH.sub(lambda m: f'{m.group(1)}}}\n', java)
return java
def _ensure_native_common_import(java: str) -> str:
"""Make sure `import whiteout.common.internal.NativeCommon;` is present
whenever the body references `NativeCommon.`."""
if 'NativeCommon.' not in java:
return java
if 'import whiteout.common.internal.NativeCommon;' in java:
return java
# Prefer to slot in next to an existing whiteout.common.internal import.
if re.search(r'import whiteout\.common\.internal\.', java):
return re.sub(
r'(import whiteout\.common\.internal\.\w+;\n)',
r'\1import whiteout.common.internal.NativeCommon;\n',
java, count=1,
)
# Otherwise insert after the package line.
return re.sub(
r'(package [^\n]+;\n)',
r'\1\nimport whiteout.common.internal.NativeCommon;\n',
java, count=1,
)
def _postprocess_java_files(files: dict[str, str]) -> dict[str, str]:
"""Apply the invoke→invokeNative rewrite and strip Throwable-catching
try/catch from each generated Java file. NativeCommon.java defines the
helper and is left untouched."""
out: dict[str, str] = {}
for path, content in files.items():
if path.endswith('NativeCommon.java'):
out[path] = content
continue
new_content = _route_through_invoke_native(content)
new_content = _strip_try_throwable(new_content)
new_content = _ensure_native_common_import(new_content)
out[path] = new_content
return out
def emit_common_java() -> dict[str, str]:
"""Files for the `whiteout.common` Java package — one class per
shared math type plus the `NativeCommon` FFM glue. Mirrors the C
side's `whiteout_c_common.{h,cpp}`."""
from .emit_c import (
_SHARED_MATH_FIELDS,
_SHARED_MATH_METHODS,
_MATRIX_DIMS,
_SHARED_MATH_FREE_FUNCTIONS,
_PRIMITIVES_PASSTHRU,
)
base_public = 'bindings/java/src/main/java/whiteout/common'
base_internal = 'bindings/java/src/main/java/whiteout/common/internal'
files: dict[str, str] = {
# Public surface — Vector*, Quaternion, Matrix* — emitted below.
# Internal — JPMS-hidden plumbing.
f'{base_internal}/NativeCommon.java': _emit_native_common(),
f'{base_internal}/Native.java': _emit_common_native_handles(
_SHARED_MATH_FIELDS, _SHARED_MATH_METHODS, _MATRIX_DIMS,
_SHARED_MATH_FREE_FUNCTIONS, _PRIMITIVES_PASSTHRU),
f'{base_internal}/Handles.java': _emit_common_handles(
list(_SHARED_MATH_FIELDS.keys() | set(_MATRIX_DIMS.keys()))),
}
# Free functions get inlined as static methods on their primary
# type's class (e.g. `whiteout::cross` becomes `Vector3f.cross`).
# The host is the first argument's type — that's the conceptual
# "self" of an operation like `cross(a, b)` or `transform_point(v, m)`.
free_by_owner: dict[str, list] = {}
for ff in _SHARED_MATH_FREE_FUNCTIONS:
fname, ret, params = ff
owner = params[0][0] if params else ret
free_by_owner.setdefault(owner, []).append(ff)
for name in _SHARED_MATH_FIELDS.keys() | set(_MATRIX_DIMS.keys()):
files[f'{base_public}/{name}.java'] = _emit_common_class(
name, _SHARED_MATH_FIELDS.get(name, []),
_SHARED_MATH_METHODS.get(name, []),
_MATRIX_DIMS.get(name),
_PRIMITIVES_PASSTHRU,
free_by_owner.get(name, []))
files['bindings/java/src/main/java/module-info.java'] = _emit_module_info()
return _postprocess_java_files(files)
def _emit_common_handles(type_names: list[str]) -> str:
"""`whiteout.common.internal.Handles` — the only place in the
library that can hand out a Vector3f's underlying MemorySegment or
construct a Vector3f from one. Uses MethodHandles.privateLookupIn
at static init to reach the package-private `handle` field and
`(MemorySegment, boolean)` constructor of each shared math class.
Because the package is not exported by module-info.java, external
code can't reference this class — Java's strong encapsulation
keeps the reflective backdoor module-private."""
buf = StringIO()
buf.write('// SPDX-License-Identifier: BSD-3-Clause\n')
buf.write('// AUTOGENERATED by tools/codegen/emit_java.py - do not edit.\n')
buf.write(f'package {_COMMON_INTERNAL_PKG};\n\n')
buf.write('import java.lang.foreign.MemorySegment;\n')
buf.write('import java.lang.invoke.MethodHandle;\n')
buf.write('import java.lang.invoke.MethodHandles;\n')
buf.write('import java.lang.invoke.MethodType;\n')
buf.write('import java.lang.invoke.VarHandle;\n')
buf.write(f'import {_COMMON_PKG}.*;\n\n')
buf.write('public final class Handles {\n')
buf.write(' private Handles() {}\n\n')
# Reflect into each shared-math class once at static init. The
# privateLookupIn lookup works without `opens` because the target
# class is in the same JPMS module as this Handles class.
for name in sorted(type_names):
buf.write(f' private static final VarHandle VH_{name.upper()};\n')
buf.write(f' private static final MethodHandle CTOR_{name.upper()};\n')
buf.write(' static {\n')
buf.write(' try {\n')
buf.write(' var __lookup = MethodHandles.lookup();\n')
for name in sorted(type_names):
buf.write(f' var __p_{name} = MethodHandles.privateLookupIn({name}.class, __lookup);\n')
buf.write(f' VH_{name.upper()} = __p_{name}.findVarHandle({name}.class, "handle", MemorySegment.class);\n')
buf.write(f' CTOR_{name.upper()} = __p_{name}.findConstructor({name}.class,\n')
buf.write(' MethodType.methodType(void.class, MemorySegment.class, boolean.class));\n')
buf.write(' } catch (ReflectiveOperationException __ex) {\n')
buf.write(' throw new ExceptionInInitializerError(__ex);\n')
buf.write(' }\n')
buf.write(' }\n\n')
for name in sorted(type_names):
buf.write(f' /** Borrowed handle to {name}\'s underlying native struct. */\n')
buf.write(f' public static MemorySegment segmentOf({name} value) {{\n')
buf.write(f' return value == null ? MemorySegment.NULL : (MemorySegment) VH_{name.upper()}.get(value);\n')
buf.write(' }\n')
buf.write(f' /** Wrap a foreign MemorySegment as a {name}. Caller decides ownership. */\n')
buf.write(f' public static {name} wrap{name}(MemorySegment seg, boolean owned) {{\n')
buf.write(' try {\n')
buf.write(f' return ({name}) CTOR_{name.upper()}.invoke(seg, owned);\n')
buf.write(' } catch (Throwable __ex) { throw new RuntimeException(__ex); }\n')
buf.write(' }\n\n')
buf.write('}\n')
return buf.getvalue()
def _emit_module_info() -> str:
"""`module-info.java` — exports only user-facing packages. The
`whiteout.<mod>.internal` subpackages stay module-private, hiding
every FFM detail (MemorySegment, MethodHandle, VarHandle, the
Handles reflection bridge, ...) from anything outside this module.
"""
buf = StringIO()
buf.write('// SPDX-License-Identifier: BSD-3-Clause\n')
buf.write('// AUTOGENERATED by tools/codegen/emit_java.py - do not edit.\n\n')
buf.write('module whiteout {\n')
buf.write(' requires java.base;\n\n')
buf.write(' // Public Java API — every module-info update should\n')
buf.write(' // only add `exports` lines, never `opens`.\n')
buf.write(' exports whiteout.common;\n')
buf.write(' exports whiteout.textures;\n')
buf.write(' exports whiteout.mdx;\n')
buf.write(' exports whiteout.m2;\n')
buf.write(' exports whiteout.m3;\n')
buf.write(' exports whiteout.utils;\n')
buf.write(' exports whiteout.host;\n')
buf.write(' exports whiteout.interfaces;\n')
buf.write(' exports whiteout.mpq;\n')
buf.write(' exports whiteout.casc;\n')
buf.write('}\n')
return buf.getvalue()
def _math_layout(t: str, primitives_passthru: set[str]) -> str:
if t == 'float': return 'ValueLayout.JAVA_FLOAT'
if t == 'int': return 'ValueLayout.JAVA_INT'
if t == 'bool': return 'ValueLayout.JAVA_INT'
if t == 'size_t': return 'ValueLayout.JAVA_LONG'
if t in primitives_passthru:
return 'ValueLayout.JAVA_INT'
return 'ValueLayout.ADDRESS'
def _math_java_type(t: str, primitives_passthru: set[str]) -> str:
if t == 'bool': return 'boolean'
if t == 'size_t': return 'long'
if t in primitives_passthru: return t
return t # math handle types resolve to their class name
def _emit_common_native_handles(fields_map, methods_map, matrix_dims,
free_funcs, primitives_passthru) -> str:
buf = StringIO()
buf.write('// SPDX-License-Identifier: BSD-3-Clause\n')
buf.write('// AUTOGENERATED by tools/codegen/emit_java.py - do not edit.\n')
buf.write(f'package {_COMMON_INTERNAL_PKG};\n\n')
buf.write('import java.lang.foreign.*;\n')
buf.write('import java.lang.invoke.MethodHandle;\n\n')
# Public — so same-module callers in other packages can reach the
# MethodHandles. Package is not exported, so external code can't
# see this class at all.
buf.write('public final class Native {\n')
buf.write(' private Native() {}\n\n')
buf.write(' static MethodHandle find(String name, FunctionDescriptor fd) {\n')
buf.write(' return NativeCommon.find(name, fd);\n')
buf.write(' }\n\n')
all_types = sorted(set(fields_map.keys()) | set(matrix_dims.keys()))
for name in all_types:
addr = 'ValueLayout.ADDRESS'
buf.write(f' // ── {name} ─────────────────────────────────────────\n')
buf.write(f' public static final MethodHandle whiteout_{name}_new = find("whiteout_{name}_new",\n')
buf.write(f' FunctionDescriptor.of({addr}));\n')
buf.write(f' public static final MethodHandle whiteout_{name}_delete = find("whiteout_{name}_delete",\n')
buf.write(f' FunctionDescriptor.ofVoid({addr}));\n')
for fld in fields_map.get(name, []):
buf.write(f' public static final MethodHandle whiteout_{name}_get_{fld} = find("whiteout_{name}_get_{fld}",\n')
buf.write(f' FunctionDescriptor.of(ValueLayout.JAVA_FLOAT, {addr}));\n')
buf.write(f' public static final MethodHandle whiteout_{name}_set_{fld} = find("whiteout_{name}_set_{fld}",\n')
buf.write(f' FunctionDescriptor.ofVoid({addr}, ValueLayout.JAVA_FLOAT));\n')
if name in matrix_dims:
buf.write(f' public static final MethodHandle whiteout_{name}_dim = find("whiteout_{name}_dim",\n')
buf.write(' FunctionDescriptor.of(ValueLayout.JAVA_LONG));\n')
buf.write(f' public static final MethodHandle whiteout_{name}_get_at = find("whiteout_{name}_get_at",\n')
buf.write(f' FunctionDescriptor.of(ValueLayout.JAVA_FLOAT, {addr}, ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG));\n')
buf.write(f' public static final MethodHandle whiteout_{name}_set_at = find("whiteout_{name}_set_at",\n')
buf.write(f' FunctionDescriptor.ofVoid({addr}, ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.JAVA_FLOAT));\n')
for m in methods_map.get(name, []):
mname, ret, params, is_static, _is_const = m[:5]
layouts = []
if not is_static:
layouts.append(addr)
for p_t, _ in params:
layouts.append(_math_layout(p_t, primitives_passthru))
ret_layout = (
'void' if ret == 'void'
else _math_layout(ret, primitives_passthru)
)
if ret_layout == 'void':
desc = f'FunctionDescriptor.ofVoid({", ".join(layouts)})'
else:
desc = f'FunctionDescriptor.of({", ".join([ret_layout] + layouts)})'
buf.write(f' public static final MethodHandle whiteout_{name}_{mname} = find("whiteout_{name}_{mname}", {desc});\n')
if free_funcs:
buf.write(' // ── Free functions ──────────────────────────────\n')
addr = 'ValueLayout.ADDRESS'
for fname, ret, params in free_funcs:
layouts = [_math_layout(t, primitives_passthru) for t, _ in params]
ret_layout = ('void' if ret == 'void'
else _math_layout(ret, primitives_passthru))
if ret_layout == 'void':
desc = f'FunctionDescriptor.ofVoid({", ".join(layouts)})'
else:
desc = f'FunctionDescriptor.of({", ".join([ret_layout] + layouts)})'
buf.write(f' public static final MethodHandle whiteout_{fname} = find("whiteout_{fname}", {desc});\n')
buf.write('}\n')
return buf.getvalue()
def _snake_to_camel(name: str) -> str:
"""`transform_point` → `transformPoint`. Used to rename the inlined
free functions so they read as idiomatic Java statics on the host
class."""
parts = name.split('_')
return parts[0] + ''.join(p[:1].upper() + p[1:] for p in parts[1:])
def _emit_common_class(name, fields, methods, matrix_dim,
primitives_passthru, inline_free_funcs=()) -> str:
"""Emit a shared-math handle-backed class.
Public API: math methods, equals/hashCode/toString, user-facing
constructors and factories. No MemorySegment, no Arena, no
`handle()` accessor, no `wrap()` factory.
Cross-package access (other modules in the same JPMS module) goes
through `whiteout.common.internal.Handles`, which uses
MethodHandles.privateLookupIn to reach the package-private handle
field and constructor. External code can't reference Handles
because `whiteout.common.internal` is NOT exported by
module-info.java.
"""
buf = StringIO()
buf.write('// SPDX-License-Identifier: BSD-3-Clause\n')
buf.write('// AUTOGENERATED by tools/codegen/emit_java.py - do not edit.\n')
buf.write(f'package {_COMMON_PKG};\n\n')
buf.write('import java.lang.foreign.*;\n')
buf.write('import java.lang.invoke.VarHandle;\n')
buf.write('import java.util.Objects;\n')
buf.write(f'import {_COMMON_INTERNAL_PKG}.Native;\n\n')
is_vector = bool(fields)
n_components = len(fields) if is_vector else None
# Class-level Javadoc — describes the type and the lifecycle
# contract every shared-math class shares.
if is_vector:
comps_phrase = ', '.join(f'`{f}`' for f in fields)
type_purpose = (
f'A {len(fields)}-component single-precision vector backed by a native'
f' C struct. Components ({comps_phrase}) are stored as a packed'
f' `float[{len(fields)}]` and accessed directly through VarHandles —'
f' no JNI round-trip per `getX()`/`setX()`.'
)
elif matrix_dim is not None:
type_purpose = (
f'A {matrix_dim}×{matrix_dim} row-major single-precision matrix backed'
f' by a native C struct ({matrix_dim * matrix_dim * 4} bytes of packed'
f' `float`). Use {{@link #getAt(int,int)}} and {{@link #setAt(int,int,float)}}'
f' for element access; static factories ({{@link #identity()}},'
f' {{@link #zero()}}, …) wrap the native constructors.'
)
else:
type_purpose = 'Native math type.'
buf.write('/**\n')
buf.write(f' * {type_purpose}\n')
buf.write(' *\n')
buf.write(' * <p><b>Lifecycle.</b> Instances own a native allocation and must be\n')
buf.write(' * released with {@link #close()} (try-with-resources). Math methods\n')
buf.write(f' * that return a fresh {name} allocate new native memory which the\n')
buf.write(' * caller likewise owns.\n')
buf.write(' *\n')
buf.write(' * <p><b>Thread-safety.</b> Instances are not thread-safe. Don\'t share\n')
buf.write(' * the same instance across threads without external synchronization.\n')
buf.write(' */\n')
buf.write(f'public final class {name} implements AutoCloseable {{\n')
# ── Direct-memory field access via Project Panama ──────────────────
# Private — internal to the class. VarHandle reads/writes bypass
# MethodHandle.invoke for per-component access. Math operations
# still cross the FFM boundary because the C++ side has the
# authoritative implementations.
if fields:
buf.write(' private static final MemoryLayout LAYOUT = MemoryLayout.structLayout(\n')
for i, f in enumerate(fields):
sep = ',' if i < len(fields) - 1 else ''
buf.write(f' ValueLayout.JAVA_FLOAT.withName("{f}"){sep}\n')
buf.write(' );\n')
for f in fields:
buf.write(f' private static final VarHandle VH_{f.upper()} = '
f'LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("{f}"));\n')
buf.write('\n')
elif matrix_dim is not None:
n = matrix_dim
buf.write(f' private static final long BYTES = {n * n * 4}L;\n\n')
# ── State (package-private so Handles can reflect into it) ────────
buf.write(' final MemorySegment handle;\n')
buf.write(' final boolean owned;\n\n')
# Package-private wrap constructor — only whiteout.common can call
# it directly. Cross-package codegen reaches it via Handles.
buf.write(f' {name}(MemorySegment seg, boolean owned) {{\n')
if fields or matrix_dim is not None:
size_expr = 'LAYOUT.byteSize()' if fields else 'BYTES'
buf.write(' this.handle = (seg == null || seg.equals(MemorySegment.NULL))\n')
buf.write(f' ? seg : seg.reinterpret({size_expr});\n')
else:
buf.write(' this.handle = seg;\n')
buf.write(' this.owned = owned;\n')
buf.write(' }\n\n')
# Public no-arg ctor — allocates a fresh native instance.
buf.write(f' public {name}() {{\n')
buf.write(' try {\n')
buf.write(f' MemorySegment __raw = (MemorySegment) Native.whiteout_{name}_new.invoke();\n')
if fields or matrix_dim is not None:
size_expr = 'LAYOUT.byteSize()' if fields else 'BYTES'
buf.write(f' this.handle = __raw.reinterpret({size_expr});\n')
else:
buf.write(' this.handle = __raw;\n')
buf.write(' this.owned = true;\n')
buf.write(' } catch (Throwable __ex) { throw new RuntimeException(__ex); }\n')
buf.write(' }\n\n')
# Convenience constructor + static factory for vectors.
if fields:
ctor_params = ', '.join(f'float {f}' for f in fields)
buf.write(f' public {name}({ctor_params}) {{\n')
buf.write(' this();\n')
for f in fields:
buf.write(f' set{_cap(f)}({f});\n')
buf.write(' }\n\n')
buf.write(f' public static {name} of({ctor_params}) {{\n')
buf.write(f' return new {name}({", ".join(fields)});\n')
buf.write(' }\n\n')
buf.write(' @Override\n')
buf.write(' public void close() {\n')
buf.write(' if (!owned) return;\n')
buf.write(' if (handle != null && !handle.equals(MemorySegment.NULL)) {\n')
buf.write(f' try {{ Native.whiteout_{name}_delete.invoke(handle); }}\n')
buf.write(' catch (Throwable __ex) { throw new RuntimeException(__ex); }\n')
buf.write(' }\n')
buf.write(' }\n\n')
# ── Field accessors — direct VarHandle / segment indexing ─────────
for fld in fields:
cap = _cap(fld)
buf.write(f' public float get{cap}() {{ return (float) VH_{fld.upper()}.get(handle, 0L); }}\n')
buf.write(f' public void set{cap}(float value) {{ VH_{fld.upper()}.set(handle, 0L, value); }}\n')
if matrix_dim is not None:
n = matrix_dim
buf.write(f' public static int dim() {{ return {n}; }}\n')
buf.write(' public float getAt(int row, int col) {\n')
buf.write(f' return handle.get(ValueLayout.JAVA_FLOAT, ((long) row * {n} + col) * 4L);\n')
buf.write(' }\n')
buf.write(' public void setAt(int row, int col, float value) {\n')
buf.write(f' handle.set(ValueLayout.JAVA_FLOAT, ((long) row * {n} + col) * 4L, value);\n')
buf.write(' }\n')
# ── Methods (native via the internal Native handles) ──────────────
for m in methods:
if m[0] == 'equals':
continue # routed through Object.equals override below
_emit_class_math_method(buf, name, m, primitives_passthru)
for fname, ret, params in inline_free_funcs:
_emit_class_math_free(buf, fname, ret, params, primitives_passthru)
# ── Object overrides ─────────────────────────────────────────────
has_native_equals = any(m[0] == 'equals' for m in methods)
if fields:
_emit_math_equals_hashcode_tostring(buf, name, fields, has_native_equals)
elif matrix_dim is not None:
_emit_math_matrix_tostring(buf, name, matrix_dim)
buf.write('}\n')
return buf.getvalue()
# Hand-curated brief descriptions for shared-math methods. Keys are the
# raw snake_case method names (matching the C++/_SHARED_MATH_METHODS
# entries). Missing entries fall back to a generated brief based on the
# name alone.
_MATH_METHOD_BRIEFS: dict[str, str] = {
'dot': 'Dot product with {other}.',
'length': 'Euclidean length (magnitude).',
'length_squared':'Squared Euclidean length — avoids the {@code sqrt} of {@link #length()}.',
'normalize': 'In-place normalize to unit length (no-op when length is zero).',