nsh-js 0.1.1

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
//! The reactive graph JS runs on: the generic graph of
//! [`nsh_core::reactive`] with QuickJS values and functions, and the JS
//! objects and natives over it.
//!
//! Reading a signal or a memo is a call of a native callable object (a few
//! nanoseconds, cheaper than calling a JS function); writing one marks its
//! dependants and runs the effects in Rust; only the user's closures run in
//! the interpreter. The scheduling is Solid 1.9's (`nsh_core::reactive`),
//! which the runtime and apps rely on.
//!
//! Lifetimes: a signal lives as long as its JS object (the object's GC mark
//! reports the value, so cycles through it are collected); memos and
//! effects belong to the owner they were made under and are disposed with
//! it; a memo's object keeps reading its last value after that. Nothing
//! here holds a Rust reference across a call into JS (which may re-enter)
//! or across freeing a JS value (which may finalize a signal or memo object,
//! whose finalizer updates the graph): the graph is reached through the
//! context's opaque pointer, every access is short, and values leave their
//! node before they are freed.

use std::{
    ffi::{CStr, c_int, c_void},
    ptr,
};

use nsh_core::reactive::{self as r, Equals, Kind, NONE, UNOWNED};
#[cfg(test)]
use rquickjs::Ctx;
use rquickjs::qjs;

type JsValue = qjs::JSValue;
type JsContext = qjs::JSContext;

const UNDEFINED: JsValue = qjs::JS_UNDEFINED;

/// The graph's host: QuickJS values, functions as computations, equality
/// functions and cleanups, reached through the context's state.
#[derive(Clone, Copy)]
pub(crate) struct Js(pub(crate) *mut JsContext);

/// The graph JS runs on.
pub(crate) type Graph = r::Graph<Js>;

/// What the JS host keeps in the graph.
pub(crate) struct JsData {
    ctx: *mut JsContext,
    classes: Classes,
    /// The first exception of a round, thrown when the round ends.
    error: Option<JsValue>,
}

/// A context value set by a provider.
pub(crate) struct JsFrame {
    key: JsValue,
    value: JsValue,
    ctx: *mut JsContext,
}

impl Drop for JsFrame {
    fn drop(&mut self) {
        // SAFETY: frames only live in a graph, which is torn down before
        // its context.
        unsafe {
            qjs::JS_FreeValue(self.ctx, self.key);
            qjs::JS_FreeValue(self.ctx, self.value);
        }
    }
}

// SAFETY: the graph is reached through the context's state, and the
// generic graph and the natives here take only short borrows of it.
unsafe impl r::Host for Js {
    type Value = JsValue;
    type Func = JsValue;
    type Equals = JsValue;
    type Cleanup = JsValue;
    type Context = JsFrame;
    type Data = JsData;

    #[inline]
    unsafe fn graph<'a>(self) -> &'a mut Graph {
        // SAFETY: as the caller promises; a projection of the state's field.
        unsafe { &mut (*crate::state::state(self.0)).graph }
    }

    #[inline]
    fn empty() -> JsValue {
        UNDEFINED
    }

    #[inline]
    fn dup(self, v: &JsValue) -> JsValue {
        // SAFETY: a live value.
        unsafe { qjs::JS_DupValue(self.0, *v) }
    }

    #[inline]
    fn free(self, v: JsValue) {
        // SAFETY: an owned value.
        unsafe { qjs::JS_FreeValue(self.0, v) }
    }

    #[inline]
    fn dup_func(self, f: &JsValue) -> JsValue {
        self.dup(f)
    }

    #[inline]
    fn free_func(self, f: JsValue) {
        self.free(f)
    }

    fn dup_equals(self, e: &JsValue) -> JsValue {
        self.dup(e)
    }

    fn free_equals(self, e: JsValue) {
        self.free(e)
    }

    fn call(self, f: &JsValue, prev: JsValue) -> Option<JsValue> {
        let mut args = [prev];
        let r = call(self.0, *f, &mut args);
        self.free(args[0]);
        r.ok()
    }

    #[inline]
    fn same(self, a: &JsValue, b: &JsValue) -> bool {
        // SAFETY: live values; strict equality runs no JS.
        unsafe { qjs::JS_IsStrictEqual(self.0, *a, *b) }
    }

    #[inline]
    fn truthy(self, v: &JsValue) -> bool {
        // SAFETY: a live value; truthiness runs no JS.
        unsafe { qjs::JS_ToBool(self.0, *v) == 1 }
    }

    fn custom_changed(self, e: &JsValue, prev: JsValue, next: &JsValue) -> bool {
        let mut args = [prev, self.dup(next)];
        let r = call(self.0, *e, &mut args);
        self.free(args[0]);
        self.free(args[1]);
        match r {
            Ok(same) => {
                let changed = !self.truthy(&same);
                self.free(same);
                changed
            }
            // A comparison that throws counts as a change.
            Err(()) => true,
        }
    }

    fn run_cleanup(self, f: JsValue) {
        if let Ok(r) = call(self.0, f, &mut []) {
            self.free(r);
        }
        self.free(f);
    }

    fn free_cleanup(self, f: JsValue) {
        self.free(f);
    }

    fn runaway(self) {
        let message = c"potential infinite loop: an effect keeps changing what it reads";
        // SAFETY: a new error object; a short borrow of the graph.
        unsafe {
            let error = qjs::JS_NewError(self.0);
            let bytes = message.to_bytes();
            let text = qjs::JS_NewStringLen(self.0, bytes.as_ptr().cast(), bytes.len() as _);
            qjs::JS_SetPropertyStr(self.0, error, c"message".as_ptr(), text);
            let g = graph(self.0);
            if g.data.error.is_none() {
                g.data.error = Some(error);
            } else {
                qjs::JS_FreeValue(self.0, error);
            }
        }
    }
}

/// The class ids of the graph's JS objects.
#[derive(Clone, Copy)]
struct Classes {
    signal: qjs::JSClassID,
    setter: qjs::JSClassID,
    memo: qjs::JSClassID,
}

/// The graph of `ctx`.
///
/// # Safety
///
/// `ctx` has a state ([`crate::state::install`]), and the caller holds no
/// other reference to the graph.
#[inline]
pub(crate) unsafe fn graph<'a>(ctx: *mut JsContext) -> &'a mut Graph {
    // SAFETY: as the caller promises.
    unsafe { r::Host::graph(Js(ctx)) }
}

/// The graph of runtime `rt` (finalizers, GC marks), unless it is being
/// torn down.
fn graph_of_runtime<'a>(rt: *mut qjs::JSRuntime) -> Option<&'a mut Graph> {
    // SAFETY: a registered state is live; finalizers and marks run during
    // GC, when natives hold no reference to the graph.
    crate::state::of_runtime(rt).map(|p| unsafe { &mut (*p).graph })
}

/// Packs a node id and its generation into an opaque pointer (never null:
/// generations start at 1).
#[cfg(target_pointer_width = "64")]
fn pack(id: u32, generation: u32) -> *mut c_void {
    (((generation as u64) << 32) | id as u64) as usize as *mut c_void
}

#[cfg(target_pointer_width = "64")]
fn unpack(p: *mut c_void) -> (u32, u32) {
    let v = p as usize as u64;
    (v as u32, (v >> 32) as u32)
}

/// The bits of a generation an opaque pointer keeps.
#[cfg(target_pointer_width = "64")]
const GENERATION_MASK: u32 = u32::MAX;

/// 32-bit pointers (WebAssembly) hold 20 bits of id and the low 11 bits of
/// the generation, under a set top bit (never null). Stale handles are
/// still caught unless a node was reused a multiple of 2048 times.
#[cfg(target_pointer_width = "32")]
const GENERATION_MASK: u32 = 0x7ff;

#[cfg(target_pointer_width = "32")]
fn pack(id: u32, generation: u32) -> *mut c_void {
    debug_assert!(id < 1 << 20, "node ids fit in 20 bits");
    ((1 << 31) | ((generation & GENERATION_MASK) << 20) | (id & 0xf_ffff)) as usize as *mut c_void
}

#[cfg(target_pointer_width = "32")]
fn unpack(p: *mut c_void) -> (u32, u32) {
    let v = p as usize as u32;
    (v & 0xf_ffff, (v >> 20) & GENERATION_MASK)
}

/// An exception of a JS call: kept as the round's error (the first wins).
fn take_exception(ctx: *mut JsContext) {
    // SAFETY: an exception is pending.
    let exception = unsafe { qjs::JS_GetException(ctx) };
    // SAFETY: no other reference to the graph is live here.
    let g = unsafe { graph(ctx) };
    if g.data.error.is_none() {
        g.data.error = Some(exception);
    } else {
        // SAFETY: ours.
        unsafe { qjs::JS_FreeValue(ctx, exception) };
    }
}

/// Calls `f` with `args`, keeping an exception as the round's error.
/// `Err` when it threw.
fn call(ctx: *mut JsContext, f: JsValue, args: &mut [JsValue]) -> Result<JsValue, ()> {
    // SAFETY: `f` and `args` are live values; the call may re-enter the
    // graph, which holds no reference here.
    let r = unsafe { qjs::JS_Call(ctx, f, UNDEFINED, args.len() as c_int, args.as_mut_ptr()) };
    // SAFETY: inline tag check.
    if unsafe { qjs::JS_IsException(r) } {
        take_exception(ctx);
        Err(())
    } else {
        Ok(r)
    }
}

// --- The JS objects -------------------------------------------------------

/// The node a signal / setter / memo object names, if it is still live.
unsafe fn node_of(ctx: *mut JsContext, obj: JsValue, class: qjs::JSClassID) -> Option<u32> {
    // SAFETY: an object of `class` holds a packed handle.
    let p = unsafe { qjs::JS_GetOpaque(obj, class) };
    if p.is_null() {
        return None;
    }
    let (id, generation) = unpack(p);
    unsafe { graph(ctx) }
        .live(id, generation, GENERATION_MASK)
        .then_some(id)
}

unsafe extern "C" fn signal_call(
    ctx: *mut JsContext,
    func: JsValue,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _flags: c_int,
) -> JsValue {
    let classes = unsafe { graph(ctx) }.data.classes;
    let id =
        unsafe { node_of(ctx, func, classes.signal).or_else(|| node_of(ctx, func, classes.memo)) };
    match id {
        Some(id) => {
            let value = r::read(Js(ctx), id);
            finish(ctx, value)
        }
        None => UNDEFINED,
    }
}

unsafe extern "C" fn setter_call(
    ctx: *mut JsContext,
    func: JsValue,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    _flags: c_int,
) -> JsValue {
    let class = unsafe { graph(ctx) }.data.classes.setter;
    let Some(id) = (unsafe { node_of(ctx, func, class) }) else {
        return UNDEFINED;
    };
    let mut value = if argc > 0 {
        unsafe { qjs::JS_DupValue(ctx, *argv) }
    } else {
        UNDEFINED
    };
    // An updater gets the previous value.
    if unsafe { qjs::JS_IsFunction(ctx, value) } {
        let prev = unsafe { qjs::JS_DupValue(ctx, *graph(ctx).value(id)) };
        let mut args = [prev];
        let r = unsafe { qjs::JS_Call(ctx, value, UNDEFINED, 1, args.as_mut_ptr()) };
        unsafe {
            qjs::JS_FreeValue(ctx, args[0]);
            qjs::JS_FreeValue(ctx, value);
        }
        if unsafe { qjs::JS_IsException(r) } {
            return r;
        }
        value = r;
    }
    let returned = unsafe { qjs::JS_DupValue(ctx, value) };
    r::write(Js(ctx), id, value);
    finish(ctx, returned)
}

/// Returns `value`, or throws the error a round kept.
fn finish(ctx: *mut JsContext, value: JsValue) -> JsValue {
    // SAFETY: short borrow.
    let g = unsafe { graph(ctx) };
    if g.in_round() {
        // Still in a round: its end throws.
        return value;
    }
    g.reset_runs();
    match g.data.error.take() {
        Some(error) => unsafe {
            qjs::JS_FreeValue(ctx, value);
            qjs::JS_Throw(ctx, error)
        },
        None => value,
    }
}

unsafe extern "C" fn finalize(rt: *mut qjs::JSRuntime, obj: JsValue) {
    let Some(g) = graph_of_runtime(rt) else {
        return;
    };
    let class = unsafe { qjs::JS_GetClassID(obj) };
    if class == g.data.classes.setter {
        return;
    }
    let p = unsafe { qjs::JS_GetOpaque(obj, class) };
    if p.is_null() {
        return;
    }
    let (id, generation) = unpack(p);
    if !g.live(id, generation, GENERATION_MASK) {
        return;
    }
    let ctx = g.data.ctx;
    // Freed now, as QuickJS's cycle collection expects of finalizers.
    if let Some(held) = g.drop_handle(id) {
        held.free(Js(ctx));
    }
}

unsafe extern "C" fn gc_mark(rt: *mut qjs::JSRuntime, obj: JsValue, mark: qjs::JS_MarkFunc) {
    let Some(g) = graph_of_runtime(rt) else {
        return;
    };
    let class = unsafe { qjs::JS_GetClassID(obj) };
    let p = unsafe { qjs::JS_GetOpaque(obj, class) };
    if p.is_null() {
        return;
    }
    let (id, generation) = unpack(p);
    if g.live(id, generation, GENERATION_MASK) {
        unsafe { qjs::JS_MarkValue(rt, *g.value(id), mark) };
        if let Some(f) = g.custom_equals(id) {
            unsafe { qjs::JS_MarkValue(rt, *f, mark) };
        }
    }
}

/// A new object of `class` naming node `id`.
fn object(ctx: *mut JsContext, class: qjs::JSClassID, id: u32) -> JsValue {
    // SAFETY: a registered class; the opaque is a packed handle.
    unsafe {
        let generation = graph(ctx).generation(id);
        let obj = qjs::JS_NewObjectClass(ctx, class);
        qjs::JS_SetOpaque(obj, pack(id, generation));
        obj
    }
}

// --- Natives --------------------------------------------------------------

pub(crate) fn arg(argc: c_int, argv: *mut JsValue, i: usize) -> JsValue {
    if (i as c_int) < argc {
        // SAFETY: QuickJS passes `argc` values.
        unsafe { *argv.add(i) }
    } else {
        UNDEFINED
    }
}

/// `equals` of an options object.
fn equals_option(ctx: *mut JsContext, options: JsValue) -> Equals<JsValue> {
    // SAFETY: reading a property of a live value.
    unsafe {
        if !qjs::JS_IsObject(options) {
            return Equals::Default;
        }
        let e = qjs::JS_GetPropertyStr(ctx, options, c"equals".as_ptr());
        if qjs::JS_IsFunction(ctx, e) {
            Equals::Custom(e)
        } else {
            let never = qjs::JS_IsBool(e) && !qjs::JS_VALUE_GET_BOOL(e);
            qjs::JS_FreeValue(ctx, e);
            if never {
                Equals::Never
            } else {
                Equals::Default
            }
        }
    }
}

pub(crate) type Native =
    unsafe extern "C" fn(*mut JsContext, JsValue, c_int, *mut JsValue) -> JsValue;

/// A new signal node holding `value` (borrowed), with `options`' equality.
fn new_signal_node(ctx: *mut JsContext, value: JsValue, options: JsValue) -> u32 {
    let value = unsafe { qjs::JS_DupValue(ctx, value) };
    let equals = equals_option(ctx, options);
    unsafe { graph(ctx) }.signal(value, equals)
}

/// `createSignal(value, options)`: `[read, write]`.
#[cfg(test)]
unsafe extern "C" fn create_signal(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let id = new_signal_node(ctx, arg(argc, argv, 0), arg(argc, argv, 1));
    let classes = unsafe { graph(ctx) }.data.classes;
    let mut pair = [
        object(ctx, classes.signal, id),
        object(ctx, classes.setter, id),
    ];
    unsafe { qjs::JS_NewArrayFrom(ctx, 2, pair.as_mut_ptr()) }
}

/// `createMemo(fn, value, options)`.
unsafe extern "C" fn create_memo(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let (func, value) = unsafe {
        (
            qjs::JS_DupValue(ctx, arg(argc, argv, 0)),
            qjs::JS_DupValue(ctx, arg(argc, argv, 1)),
        )
    };
    let equals = equals_option(ctx, arg(argc, argv, 2));
    let id = r::memo(Js(ctx), func, value, equals, true);
    let class = unsafe { graph(ctx) }.data.classes.memo;
    let obj = object(ctx, class, id);
    finish(ctx, obj)
}

fn create_effect(ctx: *mut JsContext, argc: c_int, argv: *mut JsValue, kind: Kind) -> JsValue {
    let (func, value) = unsafe {
        (
            qjs::JS_DupValue(ctx, arg(argc, argv, 0)),
            qjs::JS_DupValue(ctx, arg(argc, argv, 1)),
        )
    };
    r::effect(Js(ctx), kind, func, value);
    finish(ctx, UNDEFINED)
}

/// `createRenderEffect(fn, value)`.
#[cfg(test)]
unsafe extern "C" fn create_render_effect(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    create_effect(ctx, argc, argv, Kind::Effect)
}

/// `createEffect(fn, value)`.
unsafe extern "C" fn create_user_effect(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    create_effect(ctx, argc, argv, Kind::UserEffect)
}

/// The owner a handle names (`getOwner()`'s value), `UNOWNED` for others.
#[cfg(test)]
fn owner_of(ctx: *mut JsContext, handle: JsValue) -> Option<u32> {
    // SAFETY: inline tag checks.
    unsafe {
        if qjs::JS_IsUndefined(handle) {
            return None;
        }
        let mut v = 0f64;
        if !qjs::JS_IsNumber(handle) || qjs::JS_ToFloat64(ctx, &mut v, handle) != 0 {
            return Some(UNOWNED);
        }
        let bits = v as u64;
        let (id, generation) = (bits as u32, (bits >> 32) as u32);
        let g = graph(ctx);
        Some(if g.live(id, generation, u32::MAX) && !g.disposed(id) {
            id
        } else {
            UNOWNED
        })
    }
}

#[cfg(test)]
unsafe extern "C" fn dispose_root(
    ctx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    let handle = unsafe { *data };
    if let Some(id) = owner_of(ctx, handle).filter(|&id| id != UNOWNED) {
        // Untracked: disposing reads nothing.
        r::dispose_owner(Js(ctx), id);
    }
    finish(ctx, UNDEFINED)
}

/// `createRoot(fn, owner)`: `fn(dispose)` (a root without the parameter
/// is never disposed and owns nothing).
#[cfg(test)]
unsafe extern "C" fn create_root(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let func = arg(argc, argv, 0);
    let detached = owner_of(ctx, arg(argc, argv, 1));
    let mut length = 0i32;
    unsafe {
        let l = qjs::JS_GetPropertyStr(ctx, func, c"length".as_ptr());
        qjs::JS_ToInt32(ctx, &mut length, l);
        qjs::JS_FreeValue(ctx, l);
    }
    let (root, args) = if length == 0 {
        (UNOWNED, Vec::new())
    } else {
        let g = unsafe { graph(ctx) };
        let previous = detached.map(|owner| g.set_owner(owner));
        let id = g.root();
        if let Some(previous) = previous {
            g.set_owner(previous);
        }
        let mut data = [handle_value(ctx, id)];
        let dispose = unsafe {
            qjs::JS_NewCFunctionData(ctx, Some(dispose_root), 0, 0, 1, data.as_mut_ptr())
        };
        (id, vec![dispose])
    };
    let mut args = args;
    let func = unsafe { qjs::JS_DupValue(ctx, func) };
    let result = r::with_owner(Js(ctx), root, || call(ctx, func, &mut args));
    unsafe {
        qjs::JS_FreeValue(ctx, func);
        for a in args {
            qjs::JS_FreeValue(ctx, a);
        }
    }
    finish(ctx, result.unwrap_or(UNDEFINED))
}

/// An owner handle: a number packing the node and its generation.
#[cfg(test)]
fn handle_value(ctx: *mut JsContext, id: u32) -> JsValue {
    let generation = unsafe { graph(ctx) }.generation(id);
    qjs::JS_NewFloat64((((generation as u64) << 32) | id as u64) as f64)
}

/// `untrack(fn)`.
pub(crate) unsafe extern "C" fn untrack(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    r::untracked(Js(ctx), || unsafe {
        qjs::JS_Call(ctx, arg(argc, argv, 0), UNDEFINED, 0, ptr::null_mut())
    })
}

/// `batch(fn)`.
pub(crate) unsafe extern "C" fn batch(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let func = unsafe { qjs::JS_DupValue(ctx, arg(argc, argv, 0)) };
    let r = r::batch(Js(ctx), || call(ctx, func, &mut []));
    unsafe { qjs::JS_FreeValue(ctx, func) };
    finish(ctx, r.unwrap_or(UNDEFINED))
}

/// `onCleanup(fn)`: runs before the owner runs again or is disposed.
pub(crate) unsafe extern "C" fn on_cleanup(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let f = arg(argc, argv, 0);
    let owned = unsafe { qjs::JS_DupValue(ctx, f) };
    if let Err(owned) = unsafe { graph(ctx) }.on_cleanup(owned) {
        unsafe { qjs::JS_FreeValue(ctx, owned) };
    }
    unsafe { qjs::JS_DupValue(ctx, f) }
}

/// `getOwner()`: a handle, or `undefined`.
#[cfg(test)]
unsafe extern "C" fn get_owner(
    ctx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
) -> JsValue {
    let owner = unsafe { graph(ctx) }.owner();
    if owner == NONE || owner == UNOWNED {
        UNDEFINED
    } else {
        handle_value(ctx, owner)
    }
}

/// `runWithOwner(owner, fn)`.
#[cfg(test)]
unsafe extern "C" fn run_with_owner(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let owner = owner_of(ctx, arg(argc, argv, 0)).unwrap_or(UNOWNED);
    let func = unsafe { qjs::JS_DupValue(ctx, arg(argc, argv, 1)) };
    let r = r::with_owner(Js(ctx), owner, || call(ctx, func, &mut []));
    unsafe { qjs::JS_FreeValue(ctx, func) };
    finish(ctx, r.unwrap_or(UNDEFINED))
}

/// `setContext(key, value)`: the current owner and what is made under it
/// from now on see `value` for `key`.
unsafe extern "C" fn set_context(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let frame = unsafe {
        JsFrame {
            key: qjs::JS_DupValue(ctx, arg(argc, argv, 0)),
            value: qjs::JS_DupValue(ctx, arg(argc, argv, 1)),
            ctx,
        }
    };
    // The frame replaced (or the new one, without an owner) is dropped
    // once the graph is no longer borrowed.
    let replaced = unsafe { graph(ctx) }.provide(frame);
    drop(replaced);
    UNDEFINED
}

/// The value of `key` in the current owner's context (owned), if set.
pub(crate) fn lookup(ctx: *mut JsContext, key: JsValue) -> Option<JsValue> {
    let mut frame = unsafe { graph(ctx) }.context();
    while let Some(f) = frame {
        if unsafe { qjs::JS_IsStrictEqual(ctx, f.data.key, key) } {
            return Some(unsafe { qjs::JS_DupValue(ctx, f.data.value) });
        }
        frame = f.parent.clone();
    }
    None
}

/// `useContext(key)`: the nearest value set for `key`, or `undefined`.
#[cfg(test)]
unsafe extern "C" fn use_context(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    lookup(ctx, arg(argc, argv, 0)).unwrap_or(UNDEFINED)
}

/// A graph for context `raw`, with its classes registered.
pub(crate) fn new_graph(raw: *mut JsContext) -> Graph {
    // SAFETY: registering classes on the context's runtime.
    unsafe {
        let rt = qjs::JS_GetRuntime(raw);
        let function_proto = qjs::JS_GetFunctionProto(raw);
        let class = |name: &'static CStr, call: qjs::JSClassCall, mark: bool, proto: JsValue| {
            let mut id: qjs::JSClassID = 0;
            qjs::JS_NewClassID(rt, &mut id);
            let def = qjs::JSClassDef {
                class_name: name.as_ptr(),
                finalizer: Some(finalize),
                gc_mark: if mark { Some(gc_mark) } else { None },
                call,
                exotic: ptr::null_mut(),
            };
            qjs::JS_NewClass(rt, id, &def);
            // Calls of their objects are function calls (`typeof` is
            // "function"); `proto` is taken.
            qjs::JS_SetClassProto(raw, id, proto);
            id
        };
        // A signal's methods: `count.set(1)`, `count.update(n => n + 1)`.
        let signal_proto = qjs::JS_NewObjectProto(raw, function_proto);
        for (name, f, length) in [
            (c"set", signal_set as Native, 1),
            (c"update", signal_update as Native, 1),
        ] {
            let func = new_function(raw, name, f, length);
            qjs::JS_SetPropertyStr(raw, signal_proto, name.as_ptr(), func);
        }
        let classes = Classes {
            signal: class(c"Signal", Some(signal_call), true, signal_proto),
            setter: class(
                c"SignalSetter",
                Some(setter_call),
                false,
                qjs::JS_DupValue(raw, function_proto),
            ),
            memo: class(
                c"Memo",
                Some(signal_call),
                true,
                qjs::JS_DupValue(raw, function_proto),
            ),
        };
        qjs::JS_FreeValue(raw, function_proto);
        Graph::new(JsData {
            ctx: raw,
            classes,
            error: None,
        })
    }
}

/// Frees every JS value the graph holds (the state is unregistered:
/// finalizers that run meanwhile leave the graph alone).
pub(crate) fn free_all(graph: &mut Graph, raw: *mut JsContext) {
    graph.free_all(Js(raw));
    if let Some(e) = graph.data.error.take() {
        // SAFETY: the graph's own value; no JS runs from here on.
        unsafe { qjs::JS_FreeValue(raw, e) };
    }
}

/// A native function named `name`.
pub(crate) fn new_function(ctx: *mut JsContext, name: &CStr, f: Native, length: c_int) -> JsValue {
    // SAFETY: a plain C function.
    unsafe {
        qjs::JS_NewCFunction2(
            ctx,
            Some(f),
            name.as_ptr(),
            length,
            qjs::JSCFunctionEnum_JS_CFUNC_generic,
            0,
        )
    }
}

/// The graph's primitives as `globalThis.__nsh_reactive`, for tests that
/// drive owners and roots directly.
#[cfg(test)]
pub(crate) fn install_globals(ctx: &Ctx<'_>) {
    let raw = ctx.as_raw().as_ptr();
    // SAFETY: natives on the global object.
    unsafe {
        let obj = qjs::JS_NewObject(raw);
        let natives: [(&CStr, Native, c_int); 13] = [
            (c"createSignal", create_signal, 2),
            (c"createMemo", create_memo, 3),
            (c"createRenderEffect", create_render_effect, 2),
            (c"createEffect", create_user_effect, 2),
            (c"createRoot", create_root, 2),
            (c"untrack", untrack, 1),
            (c"batch", batch, 1),
            (c"onCleanup", on_cleanup, 1),
            (c"getOwner", get_owner, 0),
            (c"runWithOwner", run_with_owner, 2),
            (c"setContext", set_context, 2),
            (c"useContext", use_context, 1),
            (c"isAccessor", is_accessor, 1),
        ];
        for (name, f, length) in natives {
            let func = new_function(raw, name, f, length);
            qjs::JS_SetPropertyStr(raw, obj, name.as_ptr(), func);
        }
        let global = qjs::JS_GetGlobalObject(raw);
        qjs::JS_SetPropertyStr(raw, global, c"__nsh_reactive".as_ptr(), obj);
        qjs::JS_FreeValue(raw, global);
    }
}

/// `isAccessor(value)`: whether `value` is a signal or memo object.
#[cfg(test)]
unsafe extern "C" fn is_accessor(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let v = arg(argc, argv, 0);
    let classes = unsafe { graph(ctx) }.data.classes;
    let class = unsafe { qjs::JS_GetClassID(v) };
    let yes = class == classes.signal || class == classes.memo;
    if yes { qjs::JS_TRUE } else { qjs::JS_FALSE }
}

// --- `nsh`'s API ------------------------------------------------------------

/// `signal(value, options)`: a signal object, read by calling it.
pub(crate) unsafe extern "C" fn signal(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let id = new_signal_node(ctx, arg(argc, argv, 0), arg(argc, argv, 1));
    let class = unsafe { graph(ctx) }.data.classes.signal;
    object(ctx, class, id)
}

/// The signal `this` names, or a thrown `TypeError`.
fn this_signal(ctx: *mut JsContext, this: JsValue) -> Result<u32, JsValue> {
    let class = unsafe { graph(ctx) }.data.classes.signal;
    match unsafe { node_of(ctx, this, class) } {
        Some(id) => Ok(id),
        // SAFETY: throwing on a live context.
        None => Err(unsafe { qjs::JS_ThrowTypeError(ctx, c"not a live signal".as_ptr()) }),
    }
}

/// `signal.set(value)`.
unsafe extern "C" fn signal_set(
    ctx: *mut JsContext,
    this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let id = match this_signal(ctx, this) {
        Ok(id) => id,
        Err(e) => return e,
    };
    let value = unsafe { qjs::JS_DupValue(ctx, arg(argc, argv, 0)) };
    r::write(Js(ctx), id, value);
    finish(ctx, UNDEFINED)
}

/// `signal.update(fn)`: sets `fn(current value)`.
unsafe extern "C" fn signal_update(
    ctx: *mut JsContext,
    this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let id = match this_signal(ctx, this) {
        Ok(id) => id,
        Err(e) => return e,
    };
    let f = arg(argc, argv, 0);
    let prev = unsafe { qjs::JS_DupValue(ctx, *graph(ctx).value(id)) };
    let mut args = [prev];
    // SAFETY: a live value; the graph is not borrowed across the call.
    let next = unsafe { qjs::JS_Call(ctx, f, UNDEFINED, 1, args.as_mut_ptr()) };
    unsafe { qjs::JS_FreeValue(ctx, args[0]) };
    if unsafe { qjs::JS_IsException(next) } {
        return next;
    }
    r::write(Js(ctx), id, next);
    finish(ctx, UNDEFINED)
}

/// `computed(fn, options)`: a memo object, read by calling it.
pub(crate) unsafe extern "C" fn computed(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let mut args = [arg(argc, argv, 0), UNDEFINED, arg(argc, argv, 1)];
    // SAFETY: borrowed arguments, as `createMemo` takes them.
    unsafe { create_memo(ctx, UNDEFINED, 3, args.as_mut_ptr()) }
}

/// `effect(fn)`: runs `fn` after rendering, and again when what it read
/// changes.
pub(crate) unsafe extern "C" fn effect(
    ctx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let mut args = [arg(argc, argv, 0)];
    // SAFETY: as above.
    unsafe { create_user_effect(ctx, UNDEFINED, 1, args.as_mut_ptr()) }
}

// --- For the renderer -------------------------------------------------------

/// Makes a render effect running `func` (owned) under the current owner,
/// runs it, and returns the value of that first run (owned).
pub(crate) fn render_effect(ctx: *mut JsContext, func: JsValue) -> JsValue {
    let id = r::effect(Js(ctx), Kind::Effect, func, UNDEFINED);
    // SAFETY: a dup of the node's value (a disposed node holds undefined).
    unsafe { qjs::JS_DupValue(ctx, *graph(ctx).value(id)) }
}

/// A new signal object holding `value` (borrowed).
pub(crate) fn new_signal(ctx: *mut JsContext, value: JsValue) -> JsValue {
    let mut args = [value];
    // SAFETY: borrowed arguments, as `signal` takes them.
    unsafe { signal(ctx, UNDEFINED, 1, args.as_mut_ptr()) }
}

/// Writes `value` (owned) to signal object `obj` (does nothing for a dead
/// one).
pub(crate) fn set_signal(ctx: *mut JsContext, obj: JsValue, value: JsValue) {
    match this_signal(ctx, obj) {
        Ok(id) => r::write(Js(ctx), id, value),
        Err(e) => unsafe {
            // Not reachable for the renderer's own signals; drop the error.
            qjs::JS_FreeValue(ctx, e);
            qjs::JS_FreeValue(ctx, qjs::JS_GetException(ctx));
            qjs::JS_FreeValue(ctx, value);
        },
    }
}

/// The number signal object `obj` holds (untracked), if it holds one.
pub(crate) fn peek_number(ctx: *mut JsContext, obj: JsValue) -> Option<f64> {
    let v = peek(ctx, obj);
    // SAFETY: an inline check and a conversion of a live value.
    unsafe {
        if !qjs::JS_IsNumber(v) {
            return None;
        }
        let mut n = 0f64;
        qjs::JS_ToFloat64(ctx, &mut n, v);
        Some(n)
    }
}

/// The current value of signal object `obj` (borrowed; untracked), if live.
pub(crate) fn peek(ctx: *mut JsContext, obj: JsValue) -> JsValue {
    let class = unsafe { graph(ctx) }.data.classes.signal;
    match unsafe { node_of(ctx, obj, class) } {
        Some(id) => *unsafe { graph(ctx) }.value(id),
        None => UNDEFINED,
    }
}

/// Makes a memo of `func` (owned) under the current owner and returns its
/// object.
pub(crate) fn memo(ctx: *mut JsContext, func: JsValue, equals_truthy: bool) -> JsValue {
    let equals = if equals_truthy {
        Equals::Truthiness
    } else {
        Equals::Default
    };
    let id = r::memo(Js(ctx), func, UNDEFINED, equals, true);
    let class = unsafe { graph(ctx) }.data.classes.memo;
    object(ctx, class, id)
}

/// Runs `f` as one batch: its writes apply together at the end.
pub(crate) fn batch_with<R>(ctx: *mut JsContext, f: impl FnOnce() -> R) -> R {
    r::batch(Js(ctx), f)
}

/// Runs `f` with no listener (untracked).
pub(crate) fn untracked_with<R>(ctx: *mut JsContext, f: impl FnOnce() -> R) -> R {
    r::untracked(Js(ctx), f)
}

/// Runs `f` in a new root owner, under the current one (context passes
/// through it); returns the root and `f`'s result. The root is disposed
/// with [`dispose_owner`].
pub(crate) fn with_root<R>(ctx: *mut JsContext, f: impl FnOnce() -> R) -> (u32, R) {
    r::with_root(Js(ctx), f)
}

/// Whether something owns what runs now (a component, an effect, a
/// root): its cleanups run when it goes.
pub(crate) fn has_owner(ctx: *mut JsContext) -> bool {
    let owner = unsafe { graph(ctx) }.owner();
    owner != NONE && owner != UNOWNED
}

/// The current owner (for [`with_root_under`] later).
pub(crate) fn current_owner(ctx: *mut JsContext) -> u32 {
    unsafe { graph(ctx) }.owner()
}

/// [`with_root`] as if run under `owner` (from [`current_owner`]): rows a
/// list makes later see the list's context.
pub(crate) fn with_root_under<R>(
    ctx: *mut JsContext,
    owner: u32,
    f: impl FnOnce() -> R,
) -> (u32, R) {
    r::with_root_under(Js(ctx), owner, f)
}

/// Disposes owner `id` (a root from [`with_root`]), untracked.
pub(crate) fn dispose_owner(ctx: *mut JsContext, id: u32) {
    r::dispose_owner(Js(ctx), id);
}

/// Sets `key` to `value` (both borrowed) in the current owner's context.
pub(crate) fn provide(ctx: *mut JsContext, key: JsValue, value: JsValue) {
    let mut args = [key, value];
    // SAFETY: borrowed arguments.
    unsafe { set_context(ctx, UNDEFINED, 2, args.as_mut_ptr()) };
}

/// Throws the error the last round kept, if any (natives that ran JS
/// through the graph end with this).
pub(crate) fn finish_value(ctx: *mut JsContext, value: JsValue) -> JsValue {
    finish(ctx, value)
}

#[cfg(test)]
mod tests {
    use rquickjs::{Context, Runtime};

    /// Runs `code` with the natives as `R` and returns its value as JSON.
    fn run(code: &str) -> String {
        let rt = Runtime::new().unwrap();
        let ctx = Context::full(&rt).unwrap();
        ctx.with(|ctx| {
            crate::state::install(&ctx, std::rc::Rc::default(), &[]);
            super::install_globals(&ctx);
            let out: String = ctx
                .eval(format!(
                    "(() => {{ const R = globalThis.__nsh_reactive; const out = (() => {{ {code} }})(); return JSON.stringify(out); }})()"
                ))
                .unwrap_or_else(|e| match e {
                    rquickjs::Error::Exception => format!("threw {:?}", ctx.catch()),
                    e => format!("error {e}"),
                });
            crate::state::uninstall(&ctx);
            out
        })
    }

    #[test]
    fn memos_are_glitch_free_and_lazy_reads_are_current() {
        // A diamond: the effect sees each change once, consistent.
        assert_eq!(
            run(r#"
                const [a, setA] = R.createSignal(1);
                const b = R.createMemo(() => a() * 2);
                const c = R.createMemo(() => a() + 1);
                const log = [];
                R.createRoot(() => R.createRenderEffect(() => log.push(`${b()}/${c()}`)));
                setA(2);
                // Read inside a batch: memos are current before it ends.
                R.batch(() => { setA(3); log.push(`read ${b()}`); });
                return log;
            "#),
            r#"["2/2","4/3","read 6","6/4"]"#
        );
    }

    #[test]
    fn batch_untrack_and_equality() {
        assert_eq!(
            run(r#"
                const [a, setA] = R.createSignal(0);
                const [b, setB] = R.createSignal(0);
                const [c, setC] = R.createSignal({}, { equals: false });
                const [d, setD] = R.createSignal(1, { equals: (x, y) => x % 2 === y % 2 });
                const log = [];
                R.createRoot(() => {
                    R.createRenderEffect(() => log.push(`ab ${a()} ${R.untrack(b)}`));
                    R.createRenderEffect(() => { c(); log.push("c"); });
                    R.createRenderEffect(() => log.push(`d ${d()}`));
                });
                R.batch(() => { setA(1); setA(2); setB(5); });
                setB(6);          // untracked: nothing
                setC(c());        // equals: false: runs again
                setD(3);          // same parity: nothing
                setD(4);
                return log;
            "#),
            r#"["ab 0 0","c","d 1","ab 2 5","c","d 4"]"#
        );
    }

    #[test]
    fn owners_clean_up_and_dispose_what_they_own() {
        assert_eq!(
            run(r#"
                const [show, setShow] = R.createSignal(true);
                const [n, setN] = R.createSignal(0);
                const log = [];
                const dispose = R.createRoot((dispose) => {
                    R.createRenderEffect(() => {
                        if (!show()) return;
                        R.onCleanup(() => log.push("outer cleanup"));
                        R.createRenderEffect(() => {
                            log.push(`inner ${n()}`);
                            R.onCleanup(() => log.push(`inner cleanup ${n()}`));
                        });
                    });
                    return dispose;
                });
                setN(1);
                setShow(false);   // disposes the inner effect
                setN(2);          // nothing runs
                setShow(true);
                dispose();
                setN(3);          // disposed: nothing
                return log;
            "#),
            // Cleanups read the signal when they run.
            r#"["inner 0","inner cleanup 1","inner 1","inner cleanup 1","outer cleanup","inner 2","inner cleanup 2","outer cleanup"]"#
        );
    }

    #[test]
    fn context_owners_and_user_effects() {
        assert_eq!(
            run(r#"
                const key = Symbol("k");
                const log = [];
                let owner;
                // A root with `dispose` (one without is unowned: no context).
                R.createRoot((dispose) => {
                    R.setContext(key, "root");
                    R.createRenderEffect(() => {
                        log.push(`render ${R.useContext(key)}`);
                        R.setContext(key, "inner");
                        owner = R.getOwner();
                    });
                    R.createEffect(() => log.push("user after render"));
                    R.createRenderEffect(() => log.push("render 2"));
                });
                R.runWithOwner(owner, () => log.push(`with owner ${R.useContext(key)}`));
                log.push(`outside ${R.useContext(key)}`);
                return log;
            "#),
            r#"["render root","render 2","user after render","with owner inner","outside undefined"]"#
        );
    }

    #[test]
    fn a_throwing_effect_throws_from_the_write_and_the_graph_goes_on() {
        assert_eq!(
            run(r#"
                const [a, setA] = R.createSignal(0);
                const log = [];
                R.createRoot(() => {
                    R.createRenderEffect(() => { if (a() === 1) throw new Error("boom"); log.push(`ok ${a()}`); });
                    R.createRenderEffect(() => log.push(`other ${a()}`));
                });
                try { setA(1); } catch (e) { log.push(`caught ${e.message}`); }
                setA(2);
                return log;
            "#),
            r#"["ok 0","other 0","other 1","caught boom","ok 2","other 2"]"#
        );
    }

    #[test]
    fn unreachable_signals_are_collected() {
        let out = run(r#"
            const [s, set] = R.createSignal(0);
            let last;
            for (let i = 0; i < 20000; i++) {
                const [g, w] = R.createSignal({ i });
                // A cycle through the value: the signal holds a closure over itself.
                w({ get: g });
                last = g;
            }
            return last().get === last;
        "#);
        assert_eq!(out, "true");
        // Collected (also during the loop): slots are reused, none is left.
        let rt = rquickjs::Runtime::new().unwrap();
        let ctx = rquickjs::Context::full(&rt).unwrap();
        // The nodes the state itself keeps (the environment's).
        let live = |raw| {
            // SAFETY: the graph `install` made; no JS runs meanwhile.
            let g = unsafe { super::graph(raw) };
            g.slots()
        };
        let before = ctx.with(|ctx| {
            crate::state::install(&ctx, std::rc::Rc::default(), &[]);
            super::install_globals(&ctx);
            let before = live(ctx.as_raw().as_ptr()).0;
            let _: () = ctx
                .eval("const R = globalThis.__nsh_reactive; for (let i = 0; i < 5000; i++) { const [g, w] = R.createSignal(0); w({ g }); }")
                .unwrap();
            before
        });
        rt.run_gc();
        let (after, slots) = ctx.with(|ctx| {
            let counts = live(ctx.as_raw().as_ptr());
            crate::state::uninstall(&ctx);
            counts
        });
        assert!(slots < 5000, "{slots} nodes for 5000 signals");
        assert_eq!(after, before, "every signal collected");
    }

    #[test]
    fn effects_made_untracked_in_a_root_still_track() {
        // The renderer's shape: `render` (a root), `createComponent`
        // (untrack), `insert` (a render effect reading an accessor).
        assert_eq!(
            run(r#"
                const [c, setC] = R.createSignal(0);
                const log = [];
                R.createRoot((dispose) => {
                    R.untrack(() => {
                        R.createRenderEffect((cur) => { const v = c(); log.push(v); return v; });
                    });
                });
                setC(1);
                return log;
            "#),
            "[0,1]"
        );
    }

    #[test]
    fn a_memo_bumped_in_a_batch_updates_its_readers() {
        // Hot reload's component proxies: a memo of a version signal.
        assert_eq!(
            run(r#"
                const [v, setV] = R.createSignal(0);
                let fn = () => "a";
                const log = [];
                R.createRoot((dispose) => {
                    const m = R.createMemo(() => { v(); return R.untrack(() => fn()); });
                    R.createRenderEffect(() => log.push(m()));
                });
                fn = () => "b";
                R.batch(() => setV((x) => x + 1));
                return log;
            "#),
            r#"["a","b"]"#
        );
    }

    #[test]
    fn computations_made_during_an_update_run_at_once() {
        // A provider made while a list renders a new item returns what its
        // render effect produced, so the effect must not wait in the queue.
        assert_eq!(
            run(r#"
                const [items, setItems] = R.createSignal([0]);
                const log = [];
                R.createRoot(() => {
                    R.createRenderEffect(() => {
                        for (const i of items()) {
                            let made;
                            R.createRenderEffect(() => { made = i; });
                            const m = R.createMemo(() => i * 10);
                            log.push([made, m()]);
                        }
                    });
                });
                setItems([0, 1]);
                return log;
            "#),
            r#"[[0,0],[0,0],[1,10]]"#
        );
    }

    #[test]
    fn effects_follow_signals() {
        assert_eq!(
            run(r#"
                const [c, setC] = R.createSignal(0);
                const log = [];
                R.createRoot(() => { R.createRenderEffect(() => log.push(c())); });
                setC(1);
                setC((n) => n + 1);
                setC(2);
                return log;
            "#),
            "[0,1,2]"
        );
    }
}