-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc_api.zig
More file actions
2748 lines (2389 loc) · 125 KB
/
Copy pathc_api.zig
File metadata and controls
2748 lines (2389 loc) · 125 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
//! JavaScriptCore-shaped C API subset, implemented in pure Zig.
//!
//! These `export fn` symbols mirror Apple's `<JavaScriptCore/JSValueRef.h>` and
//! `<JSObjectRef.h>` names closely enough for embedders that only use the
//! implemented public subset to try this library in place of
//! `JavaScriptCore.framework` (e.g. `~/Code/Home/lang`'s
//! `packages/runtime/src/jsc/extern_fns.zig`). Pre-stabilization API cleanup
//! should prefer clear zig-js contracts over preserving inert compatibility
//! parameters.
//!
//! Internally a `JSValueRef` is a pointer to a `Boxed` value living in the
//! Context arena; a `JSStringRef` is a reference-counted `JsString`.
//!
//! ## Threading rules
//!
//! Every handle is affine to the context and thread that created it:
//! a `JSContextRef` — and every `JSValueRef`/`JSObjectRef` obtained through it —
//! may only be used on the thread that called `JSGlobalContextCreate`.
//! `JSValueRef`/`JSObjectRef` boxes carry their owning context, and context-taking
//! C APIs reject handles from a different context. Cross-thread use is still
//! undefined behavior (the arena, object graph, and microtask queue are
//! unsynchronized by design); debug builds panic on it.
//! The supported multithreading pattern is one context per thread, sharing
//! only `SharedArrayBuffer` storage — see docs/threads/bindings.md and
//! https://github.com/zig-utils/zig-js/issues/1 for the worker/agent roadmap.
//! The `JSWorker*` surface (below) spawns such per-thread contexts and moves
//! values between them as structured-clone bytes.
//! `JSStringRef`s are immutable and retain/release is atomic, so references may
//! be created, retained, and released on any thread.
const std = @import("std");
const builtin = @import("builtin");
const gc_mod = @import("gc.zig");
const value = @import("value.zig");
const ContextMod = @import("context.zig");
const interp = @import("interpreter.zig");
const promise = @import("promise.zig");
const strcell = @import("strcell.zig");
const WorkerMod = @import("worker.zig");
const JsString = @import("jsstring.zig").JsString;
const Context = ContextMod.Context;
const Value = value.Value;
const Object = value.Object;
/// Global allocator for C-API-created contexts and strings. `page_allocator`
/// needs no libc and is always available; a tuned allocator can replace it.
const gpa = std.heap.page_allocator;
/// Boxed interpreter value handed across the C boundary as a `JSValueRef`.
/// Handles are realm-affine: APIs that receive a `JSContextRef` reject boxes
/// created by another context instead of silently mixing arenas/object graphs.
const Boxed = struct {
/// Keep `value` first: the GC root scanner treats a protected `*Boxed` as
/// a `*Value` when tracing C-API handles.
value: Value,
owner: *Context,
};
/// JSC-shaped `JSType`. Values 0..6 match Apple's public enum; `bigint` and
/// `invalid` are zig-js extensions so the C boundary does not misreport BigInt
/// primitives or null handles as generic/undefined values.
pub const JSType = enum(c_uint) {
undefined = 0,
null = 1,
boolean = 2,
number = 3,
string = 4,
object = 5,
symbol = 6,
bigint = 7,
invalid = 8,
};
pub const JSValueRef = ?*anyopaque;
pub const JSObjectRef = ?*anyopaque;
pub const JSContextRef = ?*anyopaque;
pub const JSStringRef = ?*anyopaque;
pub const ExceptionRef = [*c]JSValueRef;
pub const JSObjectCallAsFunctionCallback = ?*const fn (
ctx: JSContextRef,
function: JSObjectRef,
this_object: JSObjectRef,
argument_count: usize,
arguments: [*c]const JSValueRef,
exception: ExceptionRef,
) callconv(.c) JSValueRef;
pub const kJSPropertyAttributeNone: c_uint = 0;
pub const kJSPropertyAttributeReadOnly: c_uint = 1 << 1;
pub const kJSPropertyAttributeDontEnum: c_uint = 1 << 2;
pub const kJSPropertyAttributeDontDelete: c_uint = 1 << 3;
// ---- internal helpers --------------------------------------------------
fn ctxRawFrom(ref: JSContextRef) ?*Context {
return @ptrCast(@alignCast(ref orelse return null));
}
fn ctxFrom(ref: JSContextRef) ?*Context {
const c = ctxRawFrom(ref) orelse return null;
// Single funnel for every C-API entry point: enforce context thread
// affinity in debug builds (see "Threading rules" above).
c.assertOwnerThread();
return c;
}
fn ctxForHandleInspection(ref: JSContextRef) ?*Context {
const c = ctxRawFrom(ref) orelse return null;
if (comptime builtin.mode == .Debug) {
if (!c.isOwnerThread()) std.debug.panic(
"Context is single-thread-affine: used from thread {d}, owned by thread {d} (docs/threads/bindings.md)",
.{ std.Thread.getCurrentId(), c.owner_thread },
);
}
return c;
}
fn ctxForEvaluation(ref: JSContextRef) ?*Context {
const c = ctxRawFrom(ref) orelse return null;
if (comptime builtin.mode == .Debug) {
// Serialized threaded contexts acquire the GIL inside
// `Context.evaluateWithThis`, then assert that ownership there. For
// non-threaded and true-parallel C contexts, preserve the documented
// C-handle affinity before touching the unsynchronized host boundary.
if (c.gil == null or c.parallel_js) {
if (!c.isOwnerThread()) std.debug.panic(
"Context is single-thread-affine: used from thread {d}, owned by thread {d} (docs/threads/bindings.md)",
.{ std.Thread.getCurrentId(), c.owner_thread },
);
}
}
return c;
}
fn ctxForLifecycle(ref: JSContextRef) ?*Context {
const c = ctxRawFrom(ref) orelse return null;
if (comptime builtin.mode == .Debug) {
// Retain/release are host lifecycle operations, not VM execution. They
// must preserve context thread-affinity without requiring the serialized
// GIL to already be held.
if (!c.isOwnerThread()) std.debug.panic(
"Context is single-thread-affine: used from thread {d}, owned by thread {d} (docs/threads/bindings.md)",
.{ std.Thread.getCurrentId(), c.owner_thread },
);
}
return c;
}
fn box(ctx: *Context, v: Value) JSValueRef {
const b = ctx.arena().create(Boxed) catch return null;
b.* = .{ .value = v, .owner = ctx };
return @ptrCast(b);
}
fn boxedFrom(ref: JSValueRef) ?*Boxed {
return @ptrCast(@alignCast(ref orelse return null));
}
fn valueFromContext(ctx: *Context, ref: JSValueRef) ?Value {
const b = boxedFrom(ref) orelse return null;
if (b.owner != ctx) return null;
return b.value;
}
fn objectFromHandleInspection(ref: JSObjectRef) ?*Object {
const b = boxedFrom(ref) orelse return null;
if (comptime builtin.mode == .Debug) {
if (!b.owner.isOwnerThread()) std.debug.panic(
"Context is single-thread-affine: used from thread {d}, owned by thread {d} (docs/threads/bindings.md)",
.{ std.Thread.getCurrentId(), b.owner.owner_thread },
);
}
return if (b.value.isObject()) b.value.asObj() else null;
}
fn valueArgFrom(ctx: *Context, ref: JSValueRef, exception: ExceptionRef) ?Value {
if (valueFromContext(ctx, ref)) |v| return v;
setException(ctx, exception, "TypeError: value is not a value");
return null;
}
fn strFrom(ref: JSStringRef) ?*JsString {
return @ptrCast(@alignCast(ref orelse return null));
}
fn setException(ctx: *Context, exc: ExceptionRef, message: []const u8) void {
if (exc != null) {
const v = Value.strAlloc(ctx.arena(), message) catch Value.staticStr("OutOfMemory");
exc[0] = box(ctx, v);
}
}
fn setExceptionValue(ctx: *Context, exc: ExceptionRef, exception_value: Value) void {
if (exc != null) exc[0] = box(ctx, exception_value);
}
fn boxResult(ctx: *Context, exception: ExceptionRef, result: Value) JSValueRef {
return box(ctx, result) orelse {
setException(ctx, exception, "OutOfMemory");
return null;
};
}
fn isEvaluationParseError(err: anyerror) bool {
return switch (err) {
error.UnexpectedCharacter,
error.UnterminatedString,
error.UnterminatedComment,
error.InvalidNumber,
error.UnexpectedToken,
error.ExpectedToken,
error.InvalidAssignmentTarget,
=> true,
else => false,
};
}
fn setDiagnosticField(ctx: *Context, obj: *Object, name: []const u8, field_value: Value) !void {
try obj.setOwn(ctx.arena(), ctx.root_shape, name, field_value);
try obj.setAttr(ctx.arena(), name, .{ .writable = true, .enumerable = false, .configurable = true });
}
fn makeEvaluationSyntaxError(
ctx: *Context,
message: []const u8,
source_name: []const u8,
line: usize,
column: usize,
byte_offset: usize,
) !Value {
const gc_saved = gc_mod.setActiveHeap(ctx.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(ctx.arena());
defer _ = strcell.setActiveArena(sa_saved);
var machine = ctx.interpreter();
try ctx.pushActiveInterpreter(&machine);
defer ctx.popActiveInterpreter(&machine);
const err = try machine.makeError("SyntaxError", message);
const obj = err.asObj();
const source_name_copy = try ctx.arena().dupe(u8, source_name);
try setDiagnosticField(ctx, obj, "sourceURL", try Value.strOwned(ctx.arena(), source_name_copy));
try setDiagnosticField(ctx, obj, "line", Value.num(@floatFromInt(line)));
try setDiagnosticField(ctx, obj, "column", Value.num(@floatFromInt(column)));
try setDiagnosticField(ctx, obj, "byteOffset", Value.num(@floatFromInt(byte_offset)));
return err;
}
fn evaluationSourceName(source_url: JSStringRef) []const u8 {
return if (strFrom(source_url)) |s|
if (s.bytes.len == 0) "<eval>" else s.bytes
else
"<eval>";
}
fn attachEvaluationRuntimeSourceMetadata(
ctx: *Context,
thrown: Value,
source_url: JSStringRef,
starting_line_number: c_int,
) !void {
if (!thrown.isObject()) return;
const obj = thrown.asObj();
if (!obj.is_error) return;
if (source_url == null and starting_line_number <= 0) return;
const gc_saved = gc_mod.setActiveHeap(ctx.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(ctx.arena());
defer _ = strcell.setActiveArena(sa_saved);
const source_name = evaluationSourceName(source_url);
const source_name_copy = try ctx.arena().dupe(u8, source_name);
try setDiagnosticField(ctx, obj, "sourceURL", try Value.strOwned(ctx.arena(), source_name_copy));
try setDiagnosticField(ctx, obj, "startingLineNumber", Value.num(@floatFromInt(if (starting_line_number > 0) starting_line_number else 1)));
}
fn setEvaluationException(ctx: *Context, exc: ExceptionRef, err: anyerror, source_url: JSStringRef, starting_line_number: c_int) void {
if (isEvaluationParseError(err)) {
if (ctx.last_evaluation_diagnostic) |loc| {
const source_name = evaluationSourceName(source_url);
const base_line: usize = if (starting_line_number > 0) @intCast(starting_line_number) else 1;
const line = loc.line + base_line - 1;
const message = std.fmt.allocPrint(ctx.arena(), "{s}: {s}:{d}:{d}", .{
@errorName(err),
source_name,
line,
loc.column,
}) catch {
setException(ctx, exc, @errorName(err));
return;
};
const syntax_error = makeEvaluationSyntaxError(ctx, message, source_name, line, loc.column, loc.byte_offset) catch {
setException(ctx, exc, message);
return;
};
setExceptionValue(ctx, exc, syntax_error);
return;
}
}
setException(ctx, exc, @errorName(err));
}
fn propAttrFromC(attrs: c_uint) value.PropAttr {
return .{
.writable = (attrs & kJSPropertyAttributeReadOnly) == 0,
.enumerable = (attrs & kJSPropertyAttributeDontEnum) == 0,
.configurable = (attrs & kJSPropertyAttributeDontDelete) == 0,
};
}
// ---- VM lifecycle ------------------------------------------------------
export fn JSGarbageCollect(ctx: JSContextRef) callconv(.c) void {
// Real precise mark-sweep when the context has the GC enabled; a no-op on
// the default arena engine. Sound here because the C-API entry point is a
// quiescent point (no JS executing); embedder-held `JSValueRef`s that must
// survive this call are rooted by JSValueProtect's counted handle table.
const c = ctxFrom(ctx) orelse return;
c.collectGarbage();
}
export fn JSGlobalContextCreate(global_class: ?*anyopaque) callconv(.c) JSContextRef {
if (global_class != null) return null;
const ctx = Context.create(gpa) catch return null;
ctx.initCApiRef();
return @ptrCast(ctx);
}
/// zig-js extension (issue #1): create a context with the `Thread` API enabled.
/// With `gil == false` — the default execution model — spawned `Thread`s run
/// TRUE-parallel (no GIL), backed by the GC-managed thread-safe cell allocator;
/// with `gil == true` they're serialized behind the per-context GIL. Returns null
/// on failure. (`JSGlobalContextCreate` stays single-threaded for JSC parity.)
export fn ZJSGlobalContextCreateThreaded(gil: bool) callconv(.c) JSContextRef {
const ctx = Context.createWith(gpa, .{ .enable_threads = true, .gil = gil }) catch return null;
ctx.initCApiRef();
return @ptrCast(ctx);
}
export fn JSGlobalContextRelease(ctx: JSContextRef) callconv(.c) void {
// A `.gil = true` threaded context is released from outside JS execution;
// `Context.destroy()` performs the serialized teardown itself.
const c = ctxForLifecycle(ctx) orelse return;
if (c.releaseCApiRef()) c.destroy();
}
export fn JSGlobalContextRetain(ctx: JSContextRef) callconv(.c) JSContextRef {
const c = ctxForLifecycle(ctx) orelse return null;
if (!c.retainCApiRef()) return null;
return ctx;
}
export fn JSContextGetGlobalObject(ctx: JSContextRef) callconv(.c) JSObjectRef {
const c = ctxFrom(ctx) orelse return null;
return box(c, Value.obj(c.global_object));
}
export fn JSEvaluateScript(
ctx: JSContextRef,
script: JSStringRef,
this_object: JSObjectRef,
source_url: JSStringRef,
starting_line_number: c_int,
exception: ExceptionRef,
) callconv(.c) JSValueRef {
// `Context.evaluate()` acquires/releases the per-context GIL for serialized
// threaded contexts, so this uses the evaluation-specific C-boundary helper
// instead of `ctxFrom` while still preserving debug affinity checks for
// non-threaded and true-parallel C contexts.
const c = ctxForEvaluation(ctx) orelse return null;
const s = strFrom(script) orelse {
setException(c, exception, "TypeError: script is null");
return null;
};
const this_value = if (this_object) |_|
Value.obj(objectArgFrom(c, this_object, exception) orelse return null)
else
Value.obj(c.global_object);
const result = c.evaluateWithThis(s.bytes, this_value) catch |err| {
// A JS `throw` surfaces the actual thrown value; host failures (parse
// errors, OOM) surface their error name as a string.
if (err == error.Throw) {
const thrown = c.exception orelse Value.str("uncaught exception");
attachEvaluationRuntimeSourceMetadata(c, thrown, source_url, starting_line_number) catch {};
if (exception != null) exception[0] = box(c, thrown);
} else {
setEvaluationException(c, exception, err, source_url, starting_line_number);
}
return null;
};
return boxResult(c, exception, result);
}
// ---- JSValue inspection ------------------------------------------------
export fn JSValueGetType(ctx: JSContextRef, v: JSValueRef) callconv(.c) JSType {
const c = ctxForHandleInspection(ctx) orelse return .invalid;
const uv = valueFromContext(c, v) orelse return .invalid;
return switch (uv.kind()) {
.undefined => .undefined,
.null => .null,
.boolean => .boolean,
.number => .number,
.string => .string,
.object => if (uv.asObj().is_symbol) .symbol else if (uv.asObj().is_bigint) .bigint else .object,
};
}
export fn JSValueIsUndefined(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
return if (valueFromContext(c, v)) |uv| uv.isUndefined() else false;
}
export fn JSValueIsNull(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
return if (valueFromContext(c, v)) |uv| uv.isNull() else false;
}
export fn JSValueIsBoolean(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
return if (valueFromContext(c, v)) |uv| uv.isBoolean() else false;
}
export fn JSValueIsNumber(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
return if (valueFromContext(c, v)) |uv| uv.isNumber() else false;
}
export fn JSValueIsString(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
return if (valueFromContext(c, v)) |uv| uv.isString() else false;
}
export fn JSValueIsObject(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
const uv = valueFromContext(c, v) orelse return false;
return uv.isObject() and !uv.asObj().is_symbol and !uv.asObj().is_bigint;
}
export fn JSValueIsArray(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
const uv = valueFromContext(c, v) orelse return false;
return uv.isObject() and uv.asObj().is_array;
}
export fn JSValueIsDate(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
const uv = valueFromContext(c, v) orelse return false;
return uv.isObject() and uv.asObj().is_date;
}
export fn JSValueIsEqual(ctx: JSContextRef, a: JSValueRef, b: JSValueRef, exception: ExceptionRef) callconv(.c) bool {
const c = ctxFrom(ctx) orelse return false;
const lhs = valueArgFrom(c, a, exception) orelse return false;
const rhs = valueArgFrom(c, b, exception) orelse return false;
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var machine = c.interpreter();
c.pushActiveInterpreter(&machine) catch {
setException(c, exception, "OutOfMemory");
return false;
};
defer c.popActiveInterpreter(&machine);
const result = machine.applyBinary(.eq, lhs, rhs) catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, machine.exception);
} else {
setException(c, exception, @errorName(err));
}
return false;
};
return result.toBoolean();
}
export fn JSValueIsStrictEqual(ctx: JSContextRef, a: JSValueRef, b: JSValueRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
const lhs = valueFromContext(c, a) orelse return false;
const rhs = valueFromContext(c, b) orelse return false;
return value.strictEquals(lhs, rhs);
}
// ---- JSValue constructors ---------------------------------------------
export fn JSValueMakeUndefined(ctx: JSContextRef) callconv(.c) JSValueRef {
const c = ctxFrom(ctx) orelse return null;
return box(c, Value.undef());
}
export fn JSValueMakeNull(ctx: JSContextRef) callconv(.c) JSValueRef {
const c = ctxFrom(ctx) orelse return null;
return box(c, Value.nul());
}
export fn JSValueMakeBoolean(ctx: JSContextRef, b: bool) callconv(.c) JSValueRef {
const c = ctxFrom(ctx) orelse return null;
return box(c, Value.boolVal(b));
}
export fn JSValueMakeNumber(ctx: JSContextRef, n: f64) callconv(.c) JSValueRef {
const c = ctxFrom(ctx) orelse return null;
return box(c, Value.num(n));
}
export fn JSValueMakeString(ctx: JSContextRef, str: JSStringRef) callconv(.c) JSValueRef {
const c = ctxFrom(ctx) orelse return null;
const s = strFrom(str) orelse return null;
const copy = c.arena().dupe(u8, s.bytes) catch return null;
return box(c, Value.strOwned(c.arena(), copy) catch return null);
}
// ---- JSValue coercion -------------------------------------------------
export fn JSValueToBoolean(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
return if (valueFromContext(c, v)) |uv| uv.toBoolean() else false;
}
export fn JSValueToNumber(ctx: JSContextRef, v: JSValueRef, exception: ExceptionRef) callconv(.c) f64 {
const c = ctxFrom(ctx) orelse return std.math.nan(f64);
const val = valueArgFrom(c, v, exception) orelse return std.math.nan(f64);
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var machine = c.interpreter();
c.pushActiveInterpreter(&machine) catch {
setException(c, exception, "OutOfMemory");
return std.math.nan(f64);
};
defer c.popActiveInterpreter(&machine);
return machine.toNumberV(val) catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, machine.exception);
} else {
setException(c, exception, @errorName(err));
}
return std.math.nan(f64);
};
}
export fn JSValueToStringCopy(ctx: JSContextRef, v: JSValueRef, exception: ExceptionRef) callconv(.c) JSStringRef {
const c = ctxFrom(ctx) orelse return null;
const val = valueArgFrom(c, v, exception) orelse return null;
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var machine = c.interpreter();
c.pushActiveInterpreter(&machine) catch {
setException(c, exception, "OutOfMemory");
return null;
};
defer c.popActiveInterpreter(&machine);
const s = machine.toStringV(val) catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, machine.exception);
} else {
setException(c, exception, @errorName(err));
}
return null;
};
const js = JsString.create(gpa, s) catch {
setException(c, exception, "OutOfMemory");
return null;
};
return @ptrCast(js);
}
export fn JSValueToObject(ctx: JSContextRef, v: JSValueRef, exception: ExceptionRef) callconv(.c) JSObjectRef {
const c = ctxFrom(ctx) orelse return null;
const val = valueArgFrom(c, v, exception) orelse return null;
if (val.isObject() and !val.asObj().is_symbol and !val.asObj().is_bigint) return v;
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var machine = c.interpreter();
c.pushActiveInterpreter(&machine) catch {
setException(c, exception, "OutOfMemory");
return null;
};
defer c.popActiveInterpreter(&machine);
const obj = machine.toObject(val) catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, machine.exception);
} else {
setException(c, exception, @errorName(err));
}
return null;
};
return boxResult(c, exception, Value.obj(obj));
}
export fn JSValueProtect(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxFrom(ctx) orelse return false;
const boxed = boxedFrom(v) orelse return false;
if (boxed.owner != c) return false;
const raw = v.?;
if (c.gc == null) return true; // arena contexts keep values for the context lifetime.
// `c_api_handles` is read by the mid-script parallel collector; guard it
// under `realm_lock` (a no-op outside parallel_js).
c.realmLock();
defer c.realmUnlock();
for (c.c_api_handles.items) |*h| {
if (h.ref == raw) {
h.count = std.math.add(usize, h.count, 1) catch return false;
return true;
}
}
c.reserveCApiHandlesLocked(1) catch return false;
c.c_api_handles.appendAssumeCapacity(.{ .ref = raw, .count = 1 });
return true;
}
export fn JSValueUnprotect(ctx: JSContextRef, v: JSValueRef) callconv(.c) bool {
const c = ctxFrom(ctx) orelse return false;
const boxed = boxedFrom(v) orelse return false;
if (boxed.owner != c) return false;
const raw = v.?;
if (c.gc == null) return true;
c.realmLock();
defer c.realmUnlock();
for (c.c_api_handles.items, 0..) |*h, i| {
if (h.ref != raw) continue;
if (h.count > 1) {
h.count -= 1;
} else {
_ = c.c_api_handles.swapRemove(i);
}
return true;
}
return false;
}
// ---- JSObject construction & properties --------------------------------
export fn JSObjectMake(ctx: JSContextRef, class: ?*anyopaque, data: ?*anyopaque) callconv(.c) JSObjectRef {
if (class != null) return null;
const c = ctxFrom(ctx) orelse return null;
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var machine = c.interpreter();
c.pushActiveInterpreter(&machine) catch return null;
defer c.popActiveInterpreter(&machine);
const value_obj = machine.newObject() catch return null;
const obj = value_obj.asObj();
obj.private_data = data;
obj.private_data_tag = .host;
return box(c, Value.obj(obj));
}
export fn JSObjectGetPrivate(object: JSObjectRef) callconv(.c) ?*anyopaque {
const obj = objectFromHandleInspection(object) orelse return null;
return if (obj.private_data_tag == .host) obj.private_data else null;
}
export fn JSObjectSetPrivate(object: JSObjectRef, data: ?*anyopaque) callconv(.c) bool {
const obj = objectFromHandleInspection(object) orelse return false;
if (obj.private_data_tag == .host) {
obj.private_data = data;
return true;
}
if (obj.private_data_tag == .none and obj.private_data == null) {
obj.private_data = data;
obj.private_data_tag = .host;
return true;
}
return false;
}
fn collectArgs(c: *Context, argc: usize, argv: [*c]const JSValueRef, exception: ExceptionRef) ?[]Value {
const args = c.arena().alloc(Value, argc) catch {
setException(c, exception, "OutOfMemory");
return null;
};
var i: usize = 0;
while (i < argc) : (i += 1) {
args[i] = valueArgFrom(c, argv[i], exception) orelse return null;
}
return args;
}
export fn JSObjectMakeArray(ctx: JSContextRef, argc: usize, argv: [*c]const JSValueRef, exception: ExceptionRef) callconv(.c) JSObjectRef {
const c = ctxFrom(ctx) orelse return null;
if (argc > 0 and argv == null) {
setException(c, exception, "TypeError: argc > 0 requires non-null argv");
return null;
}
const args = collectArgs(c, argc, argv, exception) orelse return null;
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var machine = c.interpreter();
c.pushActiveInterpreter(&machine) catch {
setException(c, exception, "OutOfMemory");
return null;
};
defer c.popActiveInterpreter(&machine);
const arr = machine.newArray() catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, machine.exception);
} else {
setException(c, exception, @errorName(err));
}
return null;
};
const obj = arr.asObj();
var i: usize = 0;
while (i < argc) : (i += 1) {
obj.appendElement(c.arena(), args[i]) catch {
setException(c, exception, "OutOfMemory");
return null;
};
}
return boxResult(c, exception, arr);
}
export fn JSObjectMakeDeferredPromise(ctx: JSContextRef, resolve: [*c]JSObjectRef, reject: [*c]JSObjectRef, exception: ExceptionRef) callconv(.c) JSObjectRef {
const c = ctxFrom(ctx) orelse return null;
if (resolve == null or reject == null) {
setException(c, exception, "TypeError: resolve and reject out pointers are required");
return null;
}
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var machine = c.interpreter();
c.pushActiveInterpreter(&machine) catch {
setException(c, exception, "OutOfMemory");
return null;
};
defer c.popActiveInterpreter(&machine);
const obj = promise.newPromise(&machine) catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, machine.exception);
} else setException(c, exception, @errorName(err));
return null;
};
const p: *promise.Promise = @ptrCast(@alignCast(obj.promiseData().?));
const capability = promise.nativeResolveReject(&machine, p) catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, machine.exception);
} else setException(c, exception, @errorName(err));
return null;
};
resolve[0] = box(c, capability.resolve) orelse {
setException(c, exception, "OutOfMemory");
return null;
};
reject[0] = box(c, capability.reject) orelse {
setException(c, exception, "OutOfMemory");
return null;
};
return box(c, Value.obj(obj)) orelse {
setException(c, exception, "OutOfMemory");
return null;
};
}
fn objectArgFrom(ctx: *Context, object: JSObjectRef, exception: ExceptionRef) ?*Object {
const value_ref = valueArgFrom(ctx, object, exception) orelse return null;
return if (value_ref.isObject()) value_ref.asObj() else {
setException(ctx, exception, "TypeError: object is not an object");
return null;
};
}
export fn JSObjectGetProperty(ctx: JSContextRef, object: JSObjectRef, name: JSStringRef, exception: ExceptionRef) callconv(.c) JSValueRef {
const c = ctxFrom(ctx) orelse return null;
const obj = objectArgFrom(c, object, exception) orelse return null;
const key = strFrom(name) orelse {
setException(c, exception, "TypeError: property name is null");
return null;
};
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var machine = c.interpreter();
c.pushActiveInterpreter(&machine) catch {
setException(c, exception, "OutOfMemory");
return null;
};
defer c.popActiveInterpreter(&machine);
const result = machine.getProperty(Value.obj(obj), key.bytes) catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, machine.exception);
} else {
setException(c, exception, @errorName(err));
}
return null;
};
return boxResult(c, exception, result);
}
export fn JSObjectSetProperty(ctx: JSContextRef, object: JSObjectRef, name: JSStringRef, val: JSValueRef, attrs: c_uint, exception: ExceptionRef) callconv(.c) void {
const c = ctxFrom(ctx) orelse return;
const obj = objectArgFrom(c, object, exception) orelse return;
const key = strFrom(name) orelse {
setException(c, exception, "TypeError: property name is null");
return;
};
const property_value = valueArgFrom(c, val, exception) orelse return;
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
switch (obj.deleteAccessorOwn(c.arena(), key.bytes) catch {
setException(c, exception, "OutOfMemory");
return;
}) {
.absent, .removed_continue, .deleted => {},
.blocked => {
setException(c, exception, "TypeError: cannot redefine non-configurable accessor");
return;
},
}
obj.setOwn(c.arena(), c.root_shape, key.bytes, property_value) catch {
setException(c, exception, "OutOfMemory");
return;
};
obj.setAttr(c.arena(), key.bytes, propAttrFromC(attrs)) catch {
setException(c, exception, "OutOfMemory");
return;
};
}
export fn JSObjectGetPropertyAtIndex(ctx: JSContextRef, object: JSObjectRef, index: c_uint, exception: ExceptionRef) callconv(.c) JSValueRef {
const c = ctxFrom(ctx) orelse return null;
const obj = objectArgFrom(c, object, exception) orelse return null;
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
const key = std.fmt.allocPrint(c.arena(), "{d}", .{index}) catch {
setException(c, exception, "OutOfMemory");
return null;
};
var machine = c.interpreter();
c.pushActiveInterpreter(&machine) catch {
setException(c, exception, "OutOfMemory");
return null;
};
defer c.popActiveInterpreter(&machine);
const result = machine.getProperty(Value.obj(obj), key) catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, machine.exception);
} else {
setException(c, exception, @errorName(err));
}
return null;
};
return boxResult(c, exception, result);
}
export fn JSObjectCallAsFunction(ctx: JSContextRef, function: JSObjectRef, this_object: JSObjectRef, argc: usize, argv: [*c]const JSValueRef, exception: ExceptionRef) callconv(.c) JSValueRef {
const c = ctxFrom(ctx) orelse return null;
if (argc > 0 and argv == null) {
setException(c, exception, "TypeError: argc > 0 requires non-null argv");
return null;
}
const obj = objectArgFrom(c, function, exception) orelse {
setException(c, exception, "TypeError: value is not a function");
return null;
};
const this_ref = if (this_object) |_|
if (objectArgFrom(c, this_object, exception) != null) this_object else return null
else
box(c, Value.obj(c.global_object)) orelse {
setException(c, exception, "OutOfMemory");
return null;
};
const args = collectArgs(c, argc, argv, exception) orelse return null;
// C-ABI host callbacks run directly across the FFI boundary.
if (obj.hostCallback()) |cb| {
const result = cb(ctx, function, this_ref, argc, argv, exception);
if (result) |ref| {
_ = valueArgFrom(c, ref, exception) orelse return null;
return result;
}
if (exception != null and exception[0] != null) {
_ = valueArgFrom(c, exception[0], exception) orelse return null;
return null;
}
setException(c, exception, "TypeError: host callback returned null without exception");
return null;
}
// JS functions / native builtins / error constructors run on the interpreter.
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var interpreter = c.interpreter();
c.pushActiveInterpreter(&interpreter) catch {
setException(c, exception, "OutOfMemory");
return null;
};
defer c.popActiveInterpreter(&interpreter);
const this_value = valueArgFrom(c, this_ref, exception) orelse return null;
const res = interpreter.callValueWithThis(Value.obj(obj), args, this_value) catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, interpreter.exception);
} else setException(c, exception, @errorName(err));
return null;
};
return boxResult(c, exception, res);
}
fn hostCallbackNative(ctx: *anyopaque, this: Value, args: []const Value) value.HostError!Value {
const machine: *interp.Interpreter = @ptrCast(@alignCast(ctx));
const obj = machine.active_native orelse {
machine.exception = Value.str("TypeError: host callback missing callee");
return error.Throw;
};
const cb = obj.hostCallback() orelse {
machine.exception = Value.str("TypeError: host callback missing callback");
return error.Throw;
};
const c: *Context = @ptrCast(@alignCast(obj.hostCallbackContext() orelse {
machine.exception = Value.str("TypeError: host callback missing context");
return error.Throw;
}));
const js_args = try machine.arena.alloc(JSValueRef, args.len);
for (args, js_args) |arg, *slot| slot.* = box(c, arg);
var exception: JSValueRef = null;
const result = cb(@ptrCast(c), box(c, Value.obj(obj)), box(c, this), args.len, js_args.ptr, &exception);
if (result) |ref| return valueFromContext(c, ref) orelse return machine.throwError("TypeError", "host callback returned invalid value");
if (exception) |ref| {
machine.exception = valueFromContext(c, ref) orelse Value.str("TypeError: host callback set invalid exception");
return error.Throw;
}
return machine.throwError("TypeError", "host callback returned null without exception");
}
export fn JSObjectMakeFunctionWithCallback(ctx: JSContextRef, name: JSStringRef, callback: JSObjectCallAsFunctionCallback) callconv(.c) JSObjectRef {
const c = ctxFrom(ctx) orelse return null;
const cb = callback orelse return null;
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var machine = c.interpreter();
c.pushActiveInterpreter(&machine) catch return null;
defer c.popActiveInterpreter(&machine);
const obj = gc_mod.allocObject(c.gc, c.arena()) catch return null;
obj.* = .{ .native = hostCallbackNative, .proto = machine.functionProto() };
obj.setHostCallback(c.arena(), cb, c) catch return null;
const name_bytes = if (strFrom(name)) |s| s.bytes else "";
const name_copy = c.arena().dupe(u8, name_bytes) catch return null;
obj.setOwn(c.arena(), c.root_shape, "name", Value.strOwned(c.arena(), name_copy) catch return null) catch return null;
obj.setAttr(c.arena(), "name", .{ .writable = false, .enumerable = false, .configurable = true }) catch return null;
return box(c, Value.obj(obj));
}
export fn JSObjectCallAsConstructor(ctx: JSContextRef, constructor: JSObjectRef, argc: usize, argv: [*c]const JSValueRef, exception: ExceptionRef) callconv(.c) JSObjectRef {
const c = ctxFrom(ctx) orelse return null;
if (argc > 0 and argv == null) {
setException(c, exception, "TypeError: argc > 0 requires non-null argv");
return null;
}
const obj = objectArgFrom(c, constructor, exception) orelse {
setException(c, exception, "TypeError: value is not a constructor");
return null;
};
const args = collectArgs(c, argc, argv, exception) orelse return null;
const gc_saved = gc_mod.setActiveHeap(c.gc);
defer _ = gc_mod.setActiveHeap(gc_saved);
const sa_saved = strcell.setActiveArena(c.arena());
defer _ = strcell.setActiveArena(sa_saved);
var interpreter = c.interpreter();
c.pushActiveInterpreter(&interpreter) catch {
setException(c, exception, "OutOfMemory");
return null;
};
defer c.popActiveInterpreter(&interpreter);
const res = interpreter.construct(Value.obj(obj), args) catch |err| {
if (err == error.Throw) {
if (exception != null) exception[0] = box(c, interpreter.exception);
} else setException(c, exception, @errorName(err));
return null;
};
return boxResult(c, exception, res);
}
export fn JSObjectIsFunction(ctx: JSContextRef, object: JSObjectRef) callconv(.c) bool {
const c = ctxForHandleInspection(ctx) orelse return false;
const val = valueFromContext(c, object) orelse return false;
return val.isObject() and val.asObj().isCallableObject();