forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcppbind.ts
More file actions
1186 lines (1088 loc) · 40.9 KB
/
Copy pathcppbind.ts
File metadata and controls
1186 lines (1088 loc) · 40.9 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
/*
cppbind - C++ binding generator for Bun
This tool automatically generates Rust bindings for C++ functions marked with [[ZIG_EXPORT(...)]] attributes.
It runs automatically when C++ files change during the build process.
To run manually:
bun src/codegen/cppbind src build/debug/codegen
## USAGE
### Basic Export Tags
1. **nothrow** - Function that never throws exceptions:
```cpp
extern "C" [[ZIG_EXPORT(nothrow)]] void hello_world() {
printf("hello world\n");
}
```
Rust usage: `bun_jsc::cpp::hello_world();`
2. **zero_is_throw** - Function returns JSValue, where .zero indicates an exception:
```cpp
extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSValue create_object(JSGlobalObject* globalThis) {
auto scope = DECLARE_THROW_SCOPE();
// ...
RETURN_IF_EXCEPTION(scope, {});
return result;
}
```
Rust usage: `bun_jsc::cpp::create_object(global_this)?;`
3. **check_slow** - Function that may throw, performs runtime exception checking:
```cpp
extern "C" [[ZIG_EXPORT(check_slow)]] void process_data(JSGlobalObject* globalThis) {
auto scope = DECLARE_THROW_SCOPE();
// ...
RETURN_IF_EXCEPTION(scope, );
}
```
Rust usage: `bun_jsc::cpp::process_data(global_this)?;`
### Parameters
- **[[ZIG_NONNULL]]** - Mark pointer parameters as non-nullable:
```cpp
[[ZIG_EXPORT(nothrow)]] void process([[ZIG_NONNULL]] JSGlobalObject* globalThis,
[[ZIG_NONNULL]] JSValue* values,
size_t count) { ... }
```
Generates: `pub extern fn process(globalThis: *jsc.JSGlobalObject, values: [*]const jsc.JSValue) void;`
*/
const start = Date.now();
let isInstalled = false;
try {
const grammarfile = await Bun.file("node_modules/@lezer/cpp/src/cpp.grammar").text();
isInstalled = true;
} catch (e) {}
if (!isInstalled) {
if (process.argv.includes("--already-installed")) {
console.error("Lezer C++ grammar is not installed. Please run `bun install` to install it.");
process.exit(1);
}
const r = Bun.spawnSync([process.argv[0], "install", "--frozen-lockfile"], {
stdio: ["ignore", "pipe", "pipe"],
});
if (r.exitCode !== 0) {
console.error(r.stdout.toString());
console.error(r.stderr.toString());
process.exit(r.exitCode ?? 1);
}
const r2 = Bun.spawnSync([...process.argv, "--already-installed"], { stdio: ["inherit", "inherit", "inherit"] });
process.exit(r2.exitCode ?? 1);
}
type SyntaxNode = import("@lezer/common").SyntaxNode;
const { parser: cppParser } = await import("@lezer/cpp");
const { mkdir } = await import("fs/promises");
const { join, relative } = await import("path");
const { bannedTypes, sharedTypes, typeDeclarations } = await import("./shared-types");
type Point = {
line: number;
column: number;
};
type Srcloc = {
file: string;
start: Point;
end: Point;
};
type CppFn = {
name: string;
returnType: CppType;
parameters: CppParameter[];
position: Srcloc;
tag: ExportTag;
};
type CppParameter = {
type: CppType;
name: string;
};
type CppType =
| {
type: "pointer";
child: CppType;
position: Srcloc;
isConst: boolean;
isMany: boolean;
isNonNull: boolean;
}
| {
type: "named";
name: string;
position: Srcloc;
}
| {
type: "fn";
parameters: CppParameter[];
returnType: CppType;
position: Srcloc;
};
type PositionedError = {
position: Srcloc;
message: string;
notes: { position: Srcloc; message: string }[];
};
const errors: PositionedError[] = [];
function appendError(position: Srcloc, message: string): PositionedError {
const error: PositionedError = { position, message, notes: [] };
errors.push(error);
return error;
}
function appendErrorFromCatch(error: unknown, position: Srcloc): PositionedError {
if (error instanceof PositionedErrorClass) {
errors.push(error);
return error;
}
if (error instanceof Error) {
return appendError(position, error.message);
}
return appendError(position, "unknown error: " + JSON.stringify(error));
}
function throwError(position: Srcloc, message: string): never {
throw new PositionedErrorClass(position, message);
}
class PositionedErrorClass extends Error {
notes: { position: Srcloc; message: string }[] = [];
constructor(
public position: Srcloc,
message: string,
) {
super(message);
}
}
// Lezer works with offsets, but our errors need line/column. This utility handles the conversion.
class LineInfo {
private lineStarts: number[];
constructor(private source: string) {
this.lineStarts = [0];
for (let i = 0; i < source.length; i++) {
if (source[i] === "\n") {
this.lineStarts.push(i + 1);
}
}
}
get(offset: number): Point {
// A binary search would be faster, but this is fine for files of this size.
let line = 1;
let lineStart = 0;
for (let i = this.lineStarts.length - 1; i >= 0; i--) {
if (this.lineStarts[i] <= offset) {
line = i + 1;
lineStart = this.lineStarts[i];
break;
}
}
const column = offset - lineStart + 1;
return { line, column };
}
}
// A context object to pass around file-specific parsing information.
type ParseContext = {
file: string;
sourceCode: string;
lineInfo: LineInfo;
};
function nodePosition(node: SyntaxNode, ctx: ParseContext): Srcloc {
return {
file: ctx.file,
start: ctx.lineInfo.get(node.from),
end: ctx.lineInfo.get(node.to),
};
}
const text = (node: SyntaxNode, ctx: ParseContext) => ctx.sourceCode.slice(node.from, node.to);
function assertNever(value: never): never {
throw new Error("assertNever");
}
export function prettyPrintLezerNode(node: SyntaxNode, sourceCode: string): string {
const lines: string[] = [];
const printRecursive = (currentNode: SyntaxNode, prefix: string, isLast: boolean) => {
// Determine the connector shape
const connector = isLast ? "└─ " : "├─ ";
const linePrefix = prefix + connector;
// Get the node's text, escape newlines, and truncate for readability
const nodeText = sourceCode.slice(currentNode.from, currentNode.to);
let truncatedText = nodeText.replace(/\n/g, "\\n");
if (truncatedText.length > 50) {
truncatedText = truncatedText.slice(0, 50) + "...";
}
// Format and add the current node's line
lines.push(`${linePrefix}${currentNode.name} [${currentNode.from}..${currentNode.to}] "${truncatedText}"`);
if (currentNode.name === "CompoundStatement") {
lines.push(prefix + " └─ ...");
return;
}
// Prepare the prefix for the children
const childPrefix = prefix + (isLast ? " " : "│ ");
// Recurse for children
const children: SyntaxNode[] = [];
const cursor = currentNode.cursor();
if (cursor.firstChild()) {
do {
children.push(cursor.node);
} while (cursor.nextSibling());
}
children.forEach((child, index) => {
printRecursive(child, childPrefix, index === children.length - 1);
});
};
// Start the process for the root node without any prefix/connector
const rootText = sourceCode.slice(node.from, node.to).replace(/\n/g, "\\n").slice(0, 50);
lines.push(`${node.name} [${node.from}..${node.to}] "${rootText}${rootText.length === 50 ? "..." : ""}"`);
const children: SyntaxNode[] = [];
const cursor = node.cursor();
if (cursor.firstChild()) {
do {
children.push(cursor.node);
} while (cursor.nextSibling());
}
children.forEach((child, index) => {
printRecursive(child, "", index === children.length - 1);
});
return lines.join("\n");
}
function getChildren(node: SyntaxNode): SyntaxNode[] {
const children: SyntaxNode[] = [];
let child = node.firstChild;
while (child) {
children.push(child);
child = child.nextSibling;
}
return children;
}
const allowedLezerTypes = new Set(["PrimitiveType", "ScopedTypeIdentifier", "TypeIdentifier", "SizedTypeSpecifier"]);
function processRootmostType(ctx: ParseContext, node: SyntaxNode): CppType {
const children = getChildren(node);
for (const child of children) {
if (allowedLezerTypes.has(child.type.name)) {
return { type: "named", name: text(child, ctx), position: nodePosition(child, ctx) };
}
}
throwError(nodePosition(node, ctx), "no valid type found:\n" + prettyPrintLezerNode(node, ctx.sourceCode));
}
function processDeclarator(
ctx: ParseContext,
node: SyntaxNode, // Initially a FunctionDefinition/ParameterDeclaration, then recursively a Declarator variant
rootmostType?: CppType,
): { type: CppType; final: SyntaxNode } {
// Initial entry point with a definition/declaration, find the top-level declarator
if (node.name === "FunctionDefinition" || node.name === "ParameterDeclaration") {
rootmostType ??= processRootmostType(ctx, node);
} else {
if (!rootmostType)
throwError(
nodePosition(node, ctx),
"no rootmost type provided to declarator:\n" + prettyPrintLezerNode(node, ctx.sourceCode),
);
}
const children = getChildren(node);
const declarators = children.filter(child => child.name.endsWith("Declarator") || child.name === "Identifier");
if (declarators.length !== 1) {
throwError(
nodePosition(node, ctx),
"no or multiple declarators found:\n" + prettyPrintLezerNode(node, ctx.sourceCode),
);
}
const declarator = declarators[0]!;
// Recursively peel off pointers
if (declarator?.name === "PointerDeclarator") {
if (!rootmostType) throwError(nodePosition(declarator, ctx), "no rootmost type provided to PointerDeclarator");
const isConst = !!declarator.parent?.getChild("const") || rootmostType.type === "fn";
const parentAttributes = declarator.parent?.getChildren("Attribute") ?? [];
const isNonNull = parentAttributes.some(attr => text(attr.getChild("AttributeName")!, ctx) === "ZIG_NONNULL");
return processDeclarator(ctx, declarator, {
type: "pointer",
child: rootmostType,
position: nodePosition(declarator, ctx),
isConst,
isNonNull,
isMany: false,
});
} else if (declarator?.name === "ReferenceDeclarator") {
throwError(nodePosition(declarator, ctx), "references are not allowed");
} else if (declarator?.name === "FunctionDeclarator" && !declarator.getChild("Identifier")) {
const lhs = declarator.getChild("ParenthesizedDeclarator");
const rhs = declarator.getChild("ParameterList");
if (!lhs || !rhs) {
throwError(
nodePosition(declarator, ctx),
"FunctionDeclarator has neither Identifier nor ParenthesizedDeclarator:\n" +
prettyPrintLezerNode(declarator, ctx.sourceCode),
);
}
const fnType: CppType = {
type: "fn",
parameters: [],
returnType: rootmostType,
position: nodePosition(declarator, ctx),
};
for (const arg of rhs.getChildren("ParameterDeclaration")) {
const paramDeclarator = processDeclarator(ctx, arg);
fnType.parameters.push({ type: paramDeclarator.type, name: text(paramDeclarator.final, ctx) });
}
return processDeclarator(ctx, lhs, fnType);
}
return { type: rootmostType, final: declarator };
}
function processFunction(ctx: ParseContext, node: SyntaxNode, tag: ExportTag): CppFn {
// `node` is a FunctionDefinition
const declarator = processDeclarator(ctx, node);
const final = declarator.final;
if (final.name !== "FunctionDeclarator") {
throwError(nodePosition(final, ctx), "not a function_declarator: " + final.name);
}
const nameNode = final.getChild("Identifier");
if (!nameNode) throwError(nodePosition(final, ctx), "no name found:\n" + prettyPrintLezerNode(final, ctx.sourceCode));
const parameterList = final.getChild("ParameterList");
if (!parameterList) throwError(nodePosition(final, ctx), "no parameter list found");
const parameters: CppParameter[] = [];
for (const parameter of parameterList.getChildren("ParameterDeclaration")) {
const paramDeclarator = processDeclarator(ctx, parameter);
const name = paramDeclarator.final;
if (name.name !== "Identifier") {
throwError(nodePosition(name, ctx), "parameter name is not an identifier: " + name.name);
}
parameters.push({ type: paramDeclarator.type, name: text(name, ctx) });
}
for (let i = 0; i < parameters.length; i++) {
const param = parameters[i];
const next = parameters[i + 1];
if (param.type.type === "pointer" && next?.type.type === "named" && next.type.name === "size_t") {
param.type.isMany = true;
i++;
}
}
return {
returnType: declarator.type,
name: text(nameNode, ctx),
parameters,
position: nodePosition(nameNode, ctx),
tag,
};
}
type ExportTag = "check_slow" | "zero_is_throw" | "false_is_throw" | "null_is_throw" | "nothrow";
// ─────────────────────────── Rust output (cpp.rs) ───────────────────────────
//
// Each `[[ZIG_EXPORT(mode)]]` C++
// function gets a typed `pub fn` in `bun_jsc::cpp` that wraps the raw extern in
// the appropriate exception scope and converts to `JsResult`. The wrapper opens
// the scope *before* calling into C++ so the callee's `DECLARE_THROW_SCOPE` dtor
// (which sets `vm.m_needExceptionCheck` under `validateExceptionChecks=1`) is
// satisfied by the Rust scope's `exception()` query — without this, the next
// `JSGlobalObject__hasException` ctor asserts.
//
// Parameter and return types are emitted as raw C-ABI Rust types (pointers stay
// `*mut`/`*const`, no `&T` upgrade) so the wrappers compose with whatever
// newtypes the per-type ergonomic shims (`JSValue::get`, `JSPromise::resolve`,
// …) hold; those shims forward into `crate::cpp::*`.
// C++ named-type → Rust path. Unlisted types fall back to `core::ffi::c_void`
// (only ever appears behind a pointer in `extern "C"` signatures, so layout is
// irrelevant; the per-type shim casts back).
const rustSharedTypes: Record<string, string> = {
// Primitives
"bool": "bool",
// `char` signedness is platform-dependent (signed on x86_64-linux/windows,
// unsigned on aarch64); use `core::ffi::c_char` so a future by-value return
// doesn't silently sign-flip.
"char": "core::ffi::c_char",
"unsigned char": "u8",
"signed char": "i8",
"char16_t": "u16",
"short": "core::ffi::c_short",
"unsigned short": "core::ffi::c_ushort",
"int": "core::ffi::c_int",
"unsigned": "core::ffi::c_uint",
"unsigned int": "core::ffi::c_uint",
"long": "core::ffi::c_long",
"unsigned long": "core::ffi::c_ulong",
"long long": "core::ffi::c_longlong",
"unsigned long long": "core::ffi::c_ulonglong",
"float": "f32",
"double": "f64",
"size_t": "usize",
"ssize_t": "isize",
"int8_t": "i8",
"uint8_t": "u8",
"int16_t": "i16",
"uint16_t": "u16",
"int32_t": "i32",
"uint32_t": "u32",
"int64_t": "i64",
"uint64_t": "u64",
// JSC / Bun
"BunString": "bun_core::String",
"JSC::EncodedJSValue": "crate::JSValue",
"EncodedJSValue": "crate::JSValue",
"JSC::JSGlobalObject": "crate::JSGlobalObject",
"Zig::GlobalObject": "crate::JSGlobalObject",
"ZigException": "crate::zig_exception::ZigException",
"ZigString": "bun_core::ZigString",
"JSC::VM": "crate::VM",
"JSC::JSPromise": "crate::JSPromise",
"JSC::JSMap": "crate::JSMap",
"JSC::CustomGetterSetter": "crate::CustomGetterSetter",
"JSC::SourceProvider": "crate::SourceProvider",
"JSC::CallFrame": "crate::CallFrame",
"JSC::JSObject": "crate::JSObject",
"JSC::JSString": "crate::JSString",
"JSC::Exception": "crate::Exception",
"JSC::JSInternalPromise": "crate::JSInternalPromise",
"WTF::StringImpl": "core::ffi::c_void",
"WebCore::DOMURL": "crate::DOMURL",
"WebCore::EventLoopTask": "crate::cpp_task::CppTask",
// HTTPServerAgent / inspector types only show up in `nothrow` exports;
// emit as opaque so the raw extern still type-checks.
"Inspector::InspectorHTTPServerAgent": "core::ffi::c_void",
// C++: `typedef int ServerId; typedef int HotReloadId;` (InspectorHTTPServerAgent.cpp)
"HotReloadId": "core::ffi::c_int",
"ServerId": "core::ffi::c_int",
"Route": "core::ffi::c_void",
};
// Reserved words that can't be used as Rust identifiers verbatim.
const rustReserved = new Set([
"as",
"break",
"const",
"continue",
"crate",
"else",
"enum",
"extern",
"false",
"fn",
"for",
"if",
"impl",
"in",
"let",
"loop",
"match",
"mod",
"move",
"mut",
"pub",
"ref",
"return",
"self",
"Self",
"static",
"struct",
"super",
"trait",
"true",
"type",
"unsafe",
"use",
"where",
"while",
"async",
"await",
"dyn",
"abstract",
"become",
"box",
"do",
"final",
"macro",
"override",
"priv",
"typeof",
"unsized",
"virtual",
"yield",
"try",
]);
function rustIdent(name: string): string {
if (!name.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) return "_" + name.replace(/[^a-zA-Z0-9_]/g, "_");
if (rustReserved.has(name)) return name + "_";
return name;
}
function generateRustType(type: CppType, parent: CppType | null): string {
if (type.type === "pointer") {
const constKw = type.isConst ? "*const " : "*mut ";
return constKw + generateRustType(type.child, type);
}
if (type.type === "fn") {
// Function pointers are nullable in C; model as Option<extern "C" fn(...)>.
const params = type.parameters.map(p => generateRustType(p.type, null)).join(", ");
return `Option<unsafe extern "C" fn(${params}) -> ${generateRustType(type.returnType, null)}>`;
}
if (type.type === "named" && type.name === "void") {
if (parent?.type === "pointer") return "core::ffi::c_void";
if (!parent) return "()";
throwError(type.position, "void must have a pointer parent or no parent");
}
if (type.type === "named") {
const t = rustSharedTypes[type.name];
if (t) return t;
// Unknown opaque — only valid behind a pointer (the per-type shim casts the
// pointee). Behind a pointer we degrade to c_void; in by-value position that
// would emit `-> core::ffi::c_void` (a ZST in Rust → silent ABI corruption),
// so fail loudly at the C++ source location.
if (parent?.type === "pointer") return "core::ffi::c_void";
throwError(
type.position,
`unmapped C++ type '${type.name}' in by-value position; add to rustSharedTypes or pass by pointer`,
);
}
assertNever(type);
}
function isGlobalObjectPtr(t: CppType): boolean {
return (
t.type === "pointer" &&
t.child.type === "named" &&
(t.child.name === "JSC::JSGlobalObject" || t.child.name === "Zig::GlobalObject")
);
}
// C++ named types that map to opaque ZST handles in `bun_jsc`
// (`#[repr(C)] struct X { _p: UnsafeCell<[u8; 0]> }`). A `&X` covers zero
// Rust-visible bytes, so passing it to C++ that mutates the underlying GC
// cell never violates Stacked Borrows — these can always be lifted from
// `*mut X` to `&X` in wrapper signatures, mirroring the existing
// `JSGlobalObject*` → `&JSGlobalObject` rule.
const rustOpaqueHandles = new Set([
"JSC::JSGlobalObject",
"Zig::GlobalObject",
"JSC::VM",
"JSC::JSPromise",
"JSC::JSInternalPromise",
"JSC::JSMap",
"JSC::JSObject",
"JSC::JSString",
"JSC::Exception",
"JSC::CallFrame",
"JSC::CustomGetterSetter",
"JSC::SourceProvider",
"WebCore::DOMURL",
]);
function opaqueHandleRustType(t: CppType): string | null {
if (t.type !== "pointer" || t.child.type !== "named") return null;
if (!rustOpaqueHandles.has(t.child.name)) return null;
return rustSharedTypes[t.child.name] ?? null;
}
function generateRustFn(fn: CppFn, rustRaw: string[], rustWrap: string[]): void {
const ret = generateRustType(fn.returnType, null);
const rawParams = fn.parameters.map(p => `${rustIdent(p.name)}: ${generateRustType(p.type, null)}`).join(", ");
rustRaw.push(` pub fn ${fn.name}(${rawParams})${ret === "()" ? "" : ` -> ${ret}`};`);
// Compute wrapper parameter list: opaque-ZST handle pointers become `&T`;
// everything else passes through verbatim. The wrapper is `pub fn` (safe)
// iff no raw pointer survives — otherwise the caller is still responsible
// for the pointer's validity invariants and the wrapper stays `unsafe fn`.
let needsUnsafe = false;
const wrapParams: string[] = [];
const callArgs: string[] = [];
for (const p of fn.parameters) {
const ident = rustIdent(p.name);
const handle = opaqueHandleRustType(p.type);
if (handle) {
wrapParams.push(`${ident}: &${handle}`);
callArgs.push(
p.type.type === "pointer" && p.type.isConst
? `core::ptr::from_ref(${ident})`
: `core::ptr::from_ref(${ident}).cast_mut()`,
);
} else if (p.type.type === "pointer" || p.type.type === "fn") {
needsUnsafe = true;
wrapParams.push(`${ident}: ${generateRustType(p.type, null)}`);
callArgs.push(ident);
} else {
wrapParams.push(`${ident}: ${generateRustType(p.type, null)}`);
callArgs.push(ident);
}
}
const safeKw = needsUnsafe ? "unsafe " : "";
const wrapParamsStr = wrapParams.join(", ");
const callArgsStr = callArgs.join(", ");
if (fn.tag === "nothrow") {
// No scope needed. If every param is by-value or `&OpaqueHandle`, emit a
// safe `pub fn`; otherwise the raw extern is already an `unsafe fn` with
// the right signature, so re-export it directly.
if (needsUnsafe) {
rustWrap.push(`pub use self::raw::${fn.name};`);
} else {
rustWrap.push(
`#[inline]`,
`pub fn ${fn.name}(${wrapParamsStr})${ret === "()" ? "" : ` -> ${ret}`} {`,
` // SAFETY: \`[[ZIG_EXPORT(nothrow)]]\` extern; ref args are opaque-ZST handles valid for the call.`,
` unsafe { raw::${fn.name}(${callArgsStr}) }`,
`}`,
);
}
return;
}
const globalArg = fn.parameters.find(p => isGlobalObjectPtr(p.type));
if (!globalArg) {
// Emit a stub so the module still
// compiles and the symbol name is greppable.
rustWrap.push(`// skipped ${fn.name}: ${fn.tag} requires a JSGlobalObject* parameter`);
return;
}
const gname = rustIdent(globalArg.name);
if (fn.tag === "check_slow") {
// Inline the `top_scope!` body (rather than the `call_check_slow` *function* form,
// which routes `SourceLocation::from_caller()` → thread-local intern probe per call
// in debug builds). This is the highest-volume mode — keep it as cheap as the
// zero/false/null arms below. `src!()` resolves to the wrapper file/line;
// `#[track_caller]` would be a no-op
// against a syntactic `file!()`, so don't emit it.
rustWrap.push(
`#[inline]`,
`pub ${safeKw}fn ${fn.name}(${wrapParamsStr}) -> crate::JsResult<${ret}> {`,
` crate::top_scope!(__scope, ${gname});`,
` // SAFETY: \`[[ZIG_EXPORT(check_slow)]]\` extern; ref args are opaque-ZST handles valid for the call;`,
` // any raw-pointer args are forwarded under the wrapper's own \`unsafe fn\` contract.`,
` let __r = unsafe { raw::${fn.name}(${callArgsStr}) };`,
` __scope.return_if_exception()?;`,
` Ok(__r)`,
`}`,
);
return;
}
let okExpr: string;
let errCond: string;
let okType: string;
if (fn.tag === "zero_is_throw") {
errCond = `__v == crate::JSValue::ZERO`;
okExpr = `__v`;
okType = `crate::JSValue`;
} else if (fn.tag === "false_is_throw") {
errCond = `!__v`;
okExpr = `()`;
okType = `()`;
} else if (fn.tag === "null_is_throw") {
errCond = `__v.is_null()`;
okExpr =
`\n // SAFETY: \`__v.is_null()\` checked in the branch above.\n` +
` unsafe { core::ptr::NonNull::new_unchecked(__v) }`;
okType = `core::ptr::NonNull<${generateRustType((fn.returnType as CppType & { type: "pointer" }).child, fn.returnType)}>`;
} else assertNever(fn.tag);
// `validation_scope!` expands `src!()` syntactically (resolves to this generated
// file/line). `#[track_caller]`
// can't influence a compile-time `file!()`, so don't emit it.
rustWrap.push(
`#[inline]`,
`pub ${safeKw}fn ${fn.name}(${wrapParamsStr}) -> crate::JsResult<${okType}> {`,
` crate::validation_scope!(__scope, ${gname});`,
` // SAFETY: \`[[ZIG_EXPORT(${fn.tag})]]\` extern; ref args are opaque-ZST handles valid for the call;`,
` // any raw-pointer args are forwarded under the wrapper's own \`unsafe fn\` contract.`,
` let __v = unsafe { raw::${fn.name}(${callArgsStr}) };`,
` __scope.assert_exception_presence_matches(${errCond});`,
` if ${errCond} { Err(crate::JsError::Thrown) } else { Ok(${okExpr}) }`,
`}`,
);
}
const sharedTypesText = await Bun.file("src/codegen/shared-types.ts").text();
const sharedTypesLines = sharedTypesText.split("\n");
let sharedTypesLine = 0;
let sharedTypesColumn = 0;
let sharedTypesColumnEnd = 0;
for (const line of sharedTypesLines) {
sharedTypesLine++;
if (line.includes("export const sharedTypes")) {
sharedTypesColumn = line.indexOf("sharedTypes") + 1;
sharedTypesColumnEnd = sharedTypesColumn + "sharedTypes".length;
break;
}
}
const errorsForTypes: Map<string, PositionedError> = new Map();
function generateZigType(type: CppType, parent: CppType | null) {
if (type.type === "pointer") {
const optionalChar = type.isNonNull ? "" : "?";
const ptrChar = type.isMany ? "[*]" : "*";
const constChar = type.isConst ? "const " : "";
return `${optionalChar}${ptrChar}${constChar}${generateZigType(type.child, type)}`;
}
if (type.type === "fn") {
return `fn(${type.parameters.map(p => formatZigName(p.name) + ": " + generateZigType(p.type, null)).join(", ")}) callconv(.c) ${generateZigType(type.returnType, null)}`;
}
if (type.type === "named" && type.name === "void") {
if (parent?.type === "pointer") return "anyopaque";
if (!parent) return "void";
throwError(type.position, "void must have a pointer parent or no parent");
}
if (type.type === "named") {
const bannedType = bannedTypes[type.name];
if (bannedType) {
appendError(type.position, bannedType);
return "anyopaque";
}
const sharedType = sharedTypes[type.name];
if (sharedType) return sharedType;
const error = errorsForTypes.has(type.name)
? errorsForTypes.get(type.name)!
: appendError(
{
file: "src/codegen/shared-types.ts",
start: { line: sharedTypesLine, column: sharedTypesColumn },
end: { line: sharedTypesLine, column: sharedTypesColumnEnd },
},
"sharedTypes is missing type: " + JSON.stringify(type.name),
);
errorsForTypes.set(type.name, error);
error.notes.push({ position: type.position, message: "used in exported function here" });
return "anyopaque";
}
assertNever(type);
}
function formatZigName(name: string): string {
if (name.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) return name;
return "@" + JSON.stringify(name);
}
function generateZigParameterList(parameters: CppParameter[], globalThisArg?: CppParameter): string {
return parameters
.map(p => {
if (p === globalThisArg) {
return `${formatZigName(p.name)}: *jsc.JSGlobalObject`;
} else {
return `${formatZigName(p.name)}: ${generateZigType(p.type, null)}`;
}
})
.join(", ");
}
function generateZigSourceComment(cfg: Cfg, resultSourceLinks: string[], fn: CppFn): string {
const fileName = relative(cfg.dstDir, fn.position.file);
resultSourceLinks.push(`${fn.name}:${fileName}:${fn.position.start.line}:${fn.position.start.column}`);
return `/// Source: ${fn.name}`;
}
function closest(node: SyntaxNode | null, type: string): SyntaxNode | null {
while (node) {
if (node.name === type) return node;
node = node.parent;
}
return null;
}
type CppParser = typeof cppParser;
async function processFile(parser: CppParser, file: string, allFunctions: CppFn[]) {
const sourceCode = await Bun.file(file).text();
if (!sourceCode.includes("[[ZIG_EXPORT(")) return;
const sourceCodeLines = sourceCode.split("\n");
const manualFindLines = new Set<number>();
for (let i = 0; i < sourceCodeLines.length; i++) {
if (sourceCodeLines[i].includes("[[ZIG_EXPORT(")) {
manualFindLines.add(i + 1);
}
}
const tree = parser.parse(sourceCode);
const lineInfo = new LineInfo(sourceCode);
const ctx: ParseContext = { file, sourceCode, lineInfo };
if (!tree) {
appendError({ file, start: { line: 0, column: 0 }, end: { line: 0, column: 0 } }, "no tree found");
for (const lineNumber of manualFindLines) {
const lineContent = sourceCodeLines[lineNumber - 1];
const column = lineContent.indexOf("[[ZIG_EXPORT(") + 3;
appendError(
{
file,
start: { line: lineNumber, column },
end: { line: lineNumber, column: column + "ZIG_EXPORT(".length },
},
"ZIG_EXPORT found, but Lezer failed to parse the file.",
);
}
return;
}
const queryFoundLines = new Set<number>();
tree.iterate({
enter: nodeRef => {
if (nodeRef.name !== "FunctionDefinition") {
return true; // Continue traversal
}
// console.log(
// `\n--- Found ZIG_EXPORT on function in ${file} at line ${lineInfo.get(nodeRef.node.from).line} ---\n`,
// );
// // Use the new pretty-printer to log the tree structure of the matched function
// console.log(prettyPrintLezerNode(nodeRef.node, ctx.sourceCode));
// console.log(`-------------------------------------------------------------------\n`);
const fnNode = nodeRef.node;
let zigExportAttr: SyntaxNode | null = null;
let tagIdentifier: SyntaxNode | null = null;
for (const attr of fnNode.getChildren("Attribute")) {
const attrNameNode = attr.getChild("AttributeName");
if (attrNameNode && text(attrNameNode, ctx) === "ZIG_EXPORT") {
zigExportAttr = attr;
const args = attr.getChild("AttributeArgs");
if (args) {
tagIdentifier = args.getChild("Identifier");
}
break;
}
}
if (!zigExportAttr || !tagIdentifier) {
return false; // Not an exported function, prune search
}
queryFoundLines.add(lineInfo.get(zigExportAttr.from).line);
// disabled because lezer parses (extern "C") separately to the function definition / block
/* const linkage = closest(fnNode, "LinkageSpecification");
const linkageString = linkage?.getChild("String");
if (!linkage || !linkageString || text(linkageString, ctx) !== '"C"') {
appendError(
nodePosition(fnNode, ctx),
'exported function must be extern "C":\n' +
(linkage ? prettyPrintLezerNode(linkage, ctx.sourceCode) : "no linkage"),
);
} */
const tagStr = text(tagIdentifier, ctx);
let tag: ExportTag | undefined;
if (
tagStr === "nothrow" ||
tagStr === "zero_is_throw" ||
tagStr === "check_slow" ||
tagStr === "false_is_throw" ||
tagStr === "null_is_throw"
) {
tag = tagStr;
} else if (tagStr === "print") {
console.log(prettyPrintLezerNode(fnNode, ctx.sourceCode));
appendError(nodePosition(tagIdentifier, ctx), "'print' tags are only for debugging cppbind");
tag = "nothrow";
} else {
appendError(
nodePosition(tagIdentifier, ctx),
"tag must be nothrow, zero_is_throw, check_slow, false_is_throw, or null_is_throw: " + tagStr,
);
tag = "nothrow";
}
try {
const result = processFunction(ctx, fnNode, tag);
allFunctions.push(result);
} catch (e) {
appendErrorFromCatch(e, nodePosition(fnNode, ctx));
}
return false; // Don't descend into function body
},
});
for (const lineNumber of manualFindLines) {
if (!queryFoundLines.has(lineNumber)) {
const lineContent = sourceCodeLines[lineNumber - 1];
const column = lineContent.indexOf("[[ZIG_EXPORT(") + 3;
const position: Srcloc = {
file,
start: { line: lineNumber, column },
end: { line: lineNumber, column: column + "ZIG_EXPORT(".length },
};
appendError(
position,
"ZIG_EXPORT was found on this line, but the Lezer parser did not find a valid C++ attribute on a function definition. Ensure it's in the form `[[ZIG_EXPORT(tag)]]` before a function definition.",
);
}
}
}
async function renderError(position: Srcloc, message: string, label: string, color: string) {
const fileContent = await Bun.file(position.file).text();
const lines = fileContent.split("\n");
const line = lines[position.start.line - 1];
if (line === undefined) return;
console.error(
`\x1b[m${position.file}:${position.start.line}:${position.start.column}: ${color}\x1b[1m${label}:\x1b[m ${message}`,
);
const before = `${position.start.line} | ${line.substring(0, position.start.column - 1)}`;
const after = line.substring(position.start.column - 1);
console.error(`\x1b[90m${before}${after}\x1b[m`);
let length = position.start.line === position.end.line ? position.end.column - position.start.column : 1;
console.error(`\x1b[m${" ".repeat(Bun.stringWidth(before))}${color}^${"~".repeat(Math.max(length - 1, 0))}\x1b[m`);
}
type Cfg = {
dstDir: string;
};
function generateZigFn(
fn: CppFn,
resultRaw: string[],
resultBindings: string[],
resultSourceLinks: string[],
cfg: Cfg,
): void {
let returnType = generateZigType(fn.returnType, null);
if (resultBindings.length) resultBindings.push("");
resultBindings.push(generateZigSourceComment(cfg, resultSourceLinks, fn));
if (fn.tag === "nothrow") {
resultBindings.push(
`pub extern fn ${formatZigName(fn.name)}(${generateZigParameterList(fn.parameters)}) ${returnType};`,
);
return;
}
resultRaw.push(` extern fn ${formatZigName(fn.name)}(${generateZigParameterList(fn.parameters)}) ${returnType};`);
let globalThisArg: CppParameter | undefined;
for (const param of fn.parameters) {
const type = generateZigType(param.type, null);
if (type === "?*jsc.JSGlobalObject") {
globalThisArg = param;
break;
}
}
if (!globalThisArg) throwError(fn.position, "no globalThis argument found (required for " + fn.tag + ")");
if (fn.tag === "check_slow") {
if (returnType === "jsc.JSValue") {
appendError(
fn.position,
"Use ZIG_EXPORT(zero_is_throw) instead of ZIG_EXPORT(check_slow) for functions that return JSValue",
);
}
resultBindings.push(
`pub fn ${formatZigName(fn.name)}(${generateZigParameterList(fn.parameters, globalThisArg)}) error{JSError}!${returnType} {`,
` if (comptime Environment.ci_assert) {`,
` var scope: jsc.TopExceptionScope = undefined;`,
` scope.init(${formatZigName(globalThisArg.name)}, @src());`,
` defer scope.deinit();`,