quickjs-pure 0.11.0

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
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
//! What the VM actually does, asserted against fixed expectations.
//!
//! Every expected string here was taken from the reference implementation
//! (`qjs -e …`) on the release this port tracks, so the file is a checkpoint on
//! behaviour rather than on our own output. It is deliberately independent of the
//! reference binary: the differential harness in `quickjs-conformance` compares
//! against a build when one is available, and this file keeps working without it.

fn eval(source: &str) -> String {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    match ctx.eval(source) {
        Ok(_) => ctx.output().to_string(),
        Err(error) => panic!(
            "{source:?} failed: {error}\noutput so far:\n{}",
            ctx.output()
        ),
    }
}

fn value(source: &str) -> String {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    match ctx.eval(source) {
        Ok(value) => value.to_js_string(),
        Err(error) => panic!("{source:?} failed: {error}"),
    }
}

#[test]
fn arithmetic() {
    assert_eq!(eval("print(1+1)"), "2\n");
    assert_eq!(eval("print(7-2, 3*4, 8/2, 7%3, 2**10)"), "5 12 4 1 1024\n");
    // A result that does not fit an integer becomes a double.
    assert_eq!(eval("print(2147483647 + 1)"), "2147483648\n");
    assert_eq!(eval("print(1/0, -1/0, 0/0)"), "Infinity -Infinity NaN\n");
    // `-0` keeps its sign through division.
    assert_eq!(eval("print(1/-0)"), "-Infinity\n");
    assert_eq!(
        eval("print(1e21, 1e-7, 0.1+0.2)"),
        "1e+21 1e-7 0.30000000000000004\n"
    );
}

#[test]
fn strings_and_concat() {
    assert_eq!(eval(r#"print("a"+"b")"#), "ab\n");
    // `+` concatenates as soon as either side is a string.
    assert_eq!(eval(r#"print("a"+1, 1+"a", 1+1+"a")"#), "a1 1a 2a\n");
    assert_eq!(eval(r#"print("abc".length, "abc"[1])"#), "3 b\n");
}

#[test]
fn comparison_and_equality() {
    assert_eq!(
        eval(r#"print(1<2, 2<=2, 3>4, "10"<"9")"#),
        "true true false true\n"
    );
    assert_eq!(
        eval(r#"print(1 == "1", 1 === "1", null == undefined, null === undefined)"#),
        "true false true false\n"
    );
    assert_eq!(eval("print(NaN == NaN, NaN != NaN)"), "false true\n");
}

#[test]
fn typeof_covers_the_type_tags() {
    assert_eq!(
        eval(r#"print(typeof 1, typeof "s", typeof undefined, typeof null, typeof {})"#),
        "number string undefined object object\n"
    );
    assert_eq!(
        eval("print(typeof function(){}, typeof true)"),
        "function boolean\n"
    );
}

#[test]
fn variables_and_blocks() {
    assert_eq!(eval("var x = 5; print(x)"), "5\n");
    assert_eq!(eval("let y = 1; print(y)"), "1\n");
    assert_eq!(eval("{ let x = 1; print(x) }"), "1\n");
    // A `var` in a `for` head is the same binding as one in the body.
    assert_eq!(eval("for (var i = 0; i < 3; i++) print(i)"), "0\n1\n2\n");
    assert_eq!(
        eval("var s = 0; for (var i = 0; i < 3; i++) s += i; print(s)"),
        "3\n"
    );
}

#[test]
fn a_let_binding_is_in_the_dead_zone_until_its_initialiser_runs() {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    let error = ctx
        .eval("{ print(x); let x = 1; }")
        .expect_err("reading a dead binding throws");
    assert!(error.to_string().contains("ReferenceError"), "{error}");
}

#[test]
fn functions_and_recursion() {
    assert_eq!(eval("function add(a,b){return a+b} print(add(2,3))"), "5\n");
    assert_eq!(
        eval("function fib(n){return n<2?n:fib(n-1)+fib(n-2)} print(fib(20))"),
        "6765\n"
    );
    assert_eq!(
        eval("var f = function(x){ return x*2 }; print(f(21))"),
        "42\n"
    );
    // A missing argument is `undefined`, not an error.
    assert_eq!(
        eval("function f(a,b){ return b } print(f(1))"),
        "undefined\n"
    );
}

#[test]
fn closures_share_one_binding() {
    assert_eq!(
        eval(
            "function o(){ var n=0; return function(){ return ++n } } var c=o(); print(c(),c(),c())"
        ),
        "1 2 3\n"
    );
    // Each call of the outer function gets its own binding.
    assert_eq!(
        eval("function mk(n){ return function(){ return n*2 } } print(mk(3)(), mk(5)())"),
        "6 10\n"
    );
    assert_eq!(
        eval("function f(a){ return function(b){ return a+b } } print(f(1)(2))"),
        "3\n"
    );
}

#[test]
fn objects_and_arrays() {
    assert_eq!(eval(r#"var o={a:1,b:"x"}; print(o.a, o["b"])"#), "1 x\n");
    assert_eq!(eval("var o={}; o.x = 1; print(o.x)"), "1\n");
    assert_eq!(eval("var a=[1,2,3]; print(a[1], a.length)"), "2 3\n");
    assert_eq!(eval("var a=[1,2]; a[4]=5; print(a.length)"), "5\n");
    assert_eq!(eval(r#"var o={}; o["a b"]=1; print(o["a b"])"#), "1\n");
    // A method call passes its receiver.
    assert_eq!(
        eval("var o={f:function(){return this.x},x:7}; print(o.f())"),
        "7\n"
    );
}

#[test]
fn constructors_get_a_fresh_object_with_the_prototypes() {
    assert_eq!(
        eval("function C(x){this.x=x} var c=new C(3); print(c.x)"),
        "3\n"
    );
    assert_eq!(eval("function C(){} print(new C() instanceof C)"), "true\n");
    assert_eq!(
        eval("function C(){} print(C.prototype.constructor===C)"),
        "true\n"
    );
    // A constructor that returns an object overrides `this`; a primitive does not.
    assert_eq!(eval("function C(){return {a:1}} print(new C().a)"), "1\n");
    assert_eq!(
        eval("function C(){return 7} print(new C() instanceof C)"),
        "true\n"
    );
}

#[test]
fn loops_and_control_flow() {
    assert_eq!(eval("var i=0; while(i<3){ print(i); i++ }"), "0\n1\n2\n");
    assert_eq!(eval("for(;;){ print(1); break }"), "1\n");
    assert_eq!(
        eval("var s=0; for(var i=0;i<10;i++){ if(i==5) continue; if(i==8) break; s+=i } print(s)"),
        "23\n"
    );
    assert_eq!(
        eval("switch(2){case 1:print('a');break;case 2:print('b');break;default:print('c')}"),
        "b\n"
    );
    // A labelled `break` leaves both loops; a labelled `continue` skips the rest of
    // the labelled iteration, which is why the first loop prints one pair only.
    assert_eq!(
        eval("l: for(var i=0;i<3;i++){ for(var j=0;j<3;j++){ if(j==1) break l; print(i,j) } }"),
        "0 0\n"
    );
    assert_eq!(
        eval("o: for(var i=0;i<3;i++){ for(var j=0;j<3;j++){ if(i==1) continue o; print(i,j) } }"),
        "0 0\n0 1\n0 2\n2 0\n2 1\n2 2\n"
    );
}

#[test]
fn for_in_and_for_of() {
    assert_eq!(eval("for (var k in {x:1,y:2}) print(k)"), "x\ny\n");
    assert_eq!(eval("for (var k of [10,20]) print(k)"), "10\n20\n");
    // Integer-like keys come first, in ascending order.
    assert_eq!(eval("for (var k in {b:1,2:1,1:1}) print(k)"), "1\n2\nb\n");
    assert_eq!(
        eval("var t=0; for (var v of [1,2,3]) t+=v; print(t)"),
        "6\n"
    );
    // The "integer keys first" ordering is per object, not for the whole chain: a
    // prototype's `"4"` belongs after the target's own `x`/`y`.
    assert_eq!(
        eval(
            "var a={x:2,y:2,'1':3}, b={'4':3}; Object.setPrototypeOf(a,b);\n\
             var t=[]; for (var k in a) t.push(k); print(t.toString())"
        ),
        "1,x,y,4\n"
    );
    // A non-enumerable own property hides an enumerable one further up the chain.
    assert_eq!(
        eval(
            "var a={y:2,'1':3}; Object.defineProperty(a,'x',{value:1});\n\
             var b={x:3}; Object.setPrototypeOf(a,b);\n\
             var t=[]; for (var k in a) t.push(k); print(t.toString())"
        ),
        "1,y\n"
    );
    // A destructuring or member target stores each element instead of a binding.
    assert_eq!(
        eval(
            "var a=[], t=[];\n\
             for (a[0] in {p:1,q:2}) t.push(a[0]);\n\
             for (var [m] of [[1],[2]]) t.push(m);\n\
             for ([a[1]] of [[9]]) t.push(a[1]);\n\
             print(t.toString())"
        ),
        "p,q,1,2,9\n"
    );
}

#[test]
fn a_function_sees_a_var_declared_later_in_its_scope() {
    // Function bodies used to be compiled at their declaration, so a `var` written
    // further down the same scope was not declared yet and the read resolved to a
    // *global* instead of the enclosing slot.
    assert_eq!(
        eval("function f(){ function g(){ return t } var t; return g() } print(f())"),
        "undefined\n"
    );
    assert_eq!(
        eval("function f(){ function g(){ return t } var t='v'; return g() } print(f())"),
        "v\n"
    );
    assert_eq!(
        eval("function f(){ function g(){ t += 'x' } var t='a'; g(); return t } print(f())"),
        "ax\n"
    );
    // The same for a `let` in the body, which is a different binding again.
    assert_eq!(
        eval("function f(){ function g(){ return u } let u='L'; return g() } print(f())"),
        "L\n"
    );
    // Hoisting still works in the other direction: a call before the declaration.
    assert_eq!(
        eval("function f(){ return g() } function g(){ return 7 } print(f())"),
        "7\n"
    );
}

#[test]
fn exceptions() {
    assert_eq!(
        eval("try{ throw 1 }catch(e){ print('caught',e) }"),
        "caught 1\n"
    );
    // A runtime error is a catchable exception like any other.
    assert_eq!(eval("try{ null.x }catch(e){ print('ok') }"), "ok\n");
    assert_eq!(eval("try{ a() }catch(e){ print('ok') }"), "ok\n");
    // `finally` runs on the way out of a `return`.
    assert_eq!(
        eval("function f(){ try{ return 1 }finally{ print('fin') } } print(f())"),
        "fin\n1\n"
    );
    assert_eq!(
        eval("try{ try{ throw 1 }finally{ print('inner') } }catch(e){ print('outer',e) }"),
        "inner\nouter 1\n"
    );
}

#[test]
fn an_uncaught_exception_is_an_error_not_a_crash() {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    let error = ctx.eval("null.x").expect_err("throws");
    assert!(error.to_string().contains("TypeError"), "{error}");
    assert_eq!(ctx.output(), "");
}

#[test]
fn runaway_recursion_hits_our_own_limit() {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    // Deep JavaScript recursion must not overflow the Rust stack: frames live on
    // the heap, so the limit is the engine's own.
    let error = ctx
        .eval("function f(){ return f() } f()")
        .expect_err("a stack overflow is an exception");
    // The reference's wording, on the reference's error type: `js_throw_stack_overflow`
    // raises an `InternalError` whose message is `stack overflow`. This test used to
    // assert V8's string (`Maximum call stack size exceeded`), which is what the engine
    // threw before M12a — a *string*, so `catch (e) { e.name }` answered `undefined`.
    assert!(
        error.to_string().contains("InternalError: stack overflow"),
        "{error}"
    );
}

#[test]
fn a_stack_overflow_is_catchable_as_an_internal_error() {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    ctx.eval(
        "var seen = '';
         try { (function f(){ return f() })() }
         catch (e) { seen = [e.name, e.message, e instanceof InternalError].join('|') }",
    )
    .expect("the overflow is caught");
    ctx.eval("print(seen)").expect("print");
    assert_eq!(ctx.output(), "InternalError|stack overflow|true\n");
}

#[test]
fn the_stack_budget_follows_the_runtime_setting() {
    // A smaller budget must allow fewer frames: this is the `--stack-size` contract, and
    // without it the option would be decorative.
    fn depth(limit: Option<usize>) -> usize {
        let mut rt = quickjs::Runtime::new();
        rt.set_stack_size(limit);
        let mut ctx = quickjs::Context::new(&rt);
        ctx.eval("var d = 0; try { (function f(){ d++; f() })() } catch (e) {}")
            .expect("caught");
        ctx.eval("print(d)").expect("print");
        ctx.output().trim().parse().expect("a depth")
    }
    let small = depth(Some(64 * 1024));
    let large = depth(Some(256 * 1024));
    assert!(
        small < large,
        "64k allowed {small} frames, 256k allowed {large}"
    );
    assert!(
        small > 10,
        "a 64k budget must still allow a few frames: {small}"
    );
}

#[test]
fn print_matches_the_reference_formatting() {
    assert_eq!(eval("print()"), "\n");
    assert_eq!(eval("print(1,2,3)"), "1 2 3\n");
    // `print(-0)` keeps the sign while `String(-0)` does not.
    assert_eq!(eval("print(-0)"), "-0\n");
    assert_eq!(
        eval("print(undefined, null, true)"),
        "undefined null true\n"
    );
    assert_eq!(eval("console.log('x', 1)"), "x 1\n");
}

#[test]
fn a_script_reports_its_completion_value() {
    assert_eq!(value("1+1"), "2");
    assert_eq!(value("var x = 5"), "undefined");
    assert_eq!(value("'text'"), "text");
}

// ---------------------------------------------------------------------------
// Silent-wrong-answer regressions
//
// Each of these used to return a plausible but wrong value with no error. They
// were found by running the reference `test_builtin.js`, and each is asserted
// against what the reference prints.
// ---------------------------------------------------------------------------

#[test]
fn an_object_literal_keeps_both_halves_of_an_accessor() {
    // Defining the setter used to replace the property outright, dropping the
    // getter, so `a.z` read `undefined`.
    assert_eq!(
        eval("var a={get z(){return 4},set z(v){this.v=v}}; print(a.z, a.z=5, a.v)"),
        "4 5 5\n"
    );
    // The accessor functions are named `get z`/`set z`, which is what the
    // reference does and what a stack trace prints.
    assert_eq!(
        eval("var a={get z(){return 1},set z(v){}}; print(a.z.name !== '')"),
        "true\n"
    );
}

#[test]
fn new_on_a_bound_function_constructs_its_target() {
    // `new` has to unwrap `bind` and use the target's prototype; without that the
    // body ran with `this === null` and threw.
    assert_eq!(
        eval(
            "function C(a){this.x=a} var g=C.bind(null,1); var r=new g(); print(r.x, r instanceof C)"
        ),
        "1 true\n"
    );
}

#[test]
fn arithmetic_operators_run_to_primitive_on_objects() {
    // A bare tag check turned the operand into NaN and swallowed exceptions thrown
    // by `valueOf`.
    assert_eq!(
        eval("var o={valueOf:function(){return 3}}; print(2*o)"),
        "6\n"
    );
    assert_eq!(
        eval("var o={valueOf:function(){throw Error('p')}}; try{2*o}catch(e){print('caught')}"),
        "caught\n"
    );
    // The primitive coercions still behave.
    assert_eq!(
        eval(r#"print(2*"3", 2*"x", 2*null, 2*true)"#),
        "6 NaN 0 2\n"
    );
}

#[test]
fn a_strict_directive_is_scoped_to_its_own_function() {
    // The directive used to leak outwards, so a function declared *after* a strict
    // function lost its declaration status and calling it raised.
    assert_eq!(
        eval(
            r#"function a(){return b()} function c(){"use strict";return 1} function b(){return "b"} print(a(), c())"#
        ),
        "b 1\n"
    );
}

#[test]
fn a_call_before_its_function_declaration_still_resolves() {
    // `a` resolves `b` while `b` is still unknown; the guess has to be corrected
    // when the declaration is reached, or `b` does not exist at run time.
    assert_eq!(
        eval(r#"function a(){return b()} function b(){return 42} print(a())"#),
        "42\n"
    );
}

#[test]
fn assignment_to_an_undeclared_name_is_an_error_in_strict_mode() {
    assert_eq!(
        eval(r#""use strict"; try { not_def = 1; print("no") } catch(e) { print(e.name) }"#),
        "ReferenceError\n"
    );
    // Sloppy mode still creates the implicit global, and it stays deletable.
    assert_eq!(
        eval(r#"not_def = 1; print(not_def, delete not_def, typeof not_def)"#),
        "1 true undefined\n"
    );
}

#[test]
fn a_throw_in_tail_position_does_not_reuse_the_frame() {
    // The reference's `tail_call` still pushes a frame, so unbounded tail recursion
    // hits the stack limit rather than looping forever. Reusing the frame made
    // `function f(){return f()}` hang instead of reporting an overflow.
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    let error = ctx
        .eval("function f(n){ return n<=0 ? 'done' : f(n-1) } f(200000)")
        .expect_err("deep tail recursion overflows");
    assert!(error.to_string().contains("stack"), "{error}");
}

/// A store, a jump target, then a read of the same closure variable.
///
/// This is a regression test for a fold that deleted a jump target. The peephole turns
/// `dup; put_x; drop; get_x` into `set_x`, which is only equivalent when the `get_x` is
/// reached by falling through. When a jump lands *on* the `get_x` — an `if` body ending, a
/// `switch` case, a loop head — deleting it retargets the jump to whatever follows, and
/// `return` then runs with an empty stack. The store had already consumed the value it was
/// meant to leave behind, so the function answered `undefined`.
///
/// Every expectation below is `qjs -e` on the reference.
#[test]
fn a_jump_target_after_a_store_is_not_folded_away() {
    // Non-constant condition: independent of the (still missing) constant folding, so this
    // fails if the fold starts deleting label targets again.
    assert_eq!(
        eval(
            r#"
            var make = function () {
                var v = "";
                return function (c) { v = "x"; if (c) { v = "a"; } return v; };
            };
            var f = make();
            print(f(false), f(true), f(false));
            "#
        ),
        "x a x\n"
    );

    // A `switch` puts its labels on exactly these boundaries, which is where the
    // upstream suite caught it: test262's `statements/switch/S12.11_A1_T*`.
    assert_eq!(
        eval(
            r#"
            var make = function () {
                var v = "";
                return function (n) {
                    switch (n) { case 1: v = "one"; break; default: v = "other"; }
                    return v;
                };
            };
            var f = make();
            print(f(1), f(2));
            "#
        ),
        "one other\n"
    );

    // A loop head is the other place a label sits: the store, then the condition re-reads.
    assert_eq!(
        eval(
            r#"
            var make = function () {
                var v = "";
                return function (n) { v = "s"; while (n-- > 0) { v += "w"; } return v; };
            };
            var f = make();
            print(f(0), f(2));
            "#
        ),
        "s sww\n"
    );
}

/// The same shape with a *local* rather than a closure variable, which resolves to a
/// different slot but folds through the same rule.
#[test]
fn a_jump_target_after_a_local_store_is_not_folded_away() {
    assert_eq!(
        value(
            r#"
            (function () {
                var v = "";
                function f(c) { v = "x"; if (c) { v = "a"; } return v; }
                return [f(false), f(true)].join(",");
            })()
            "#
        ),
        "x,a"
    );
}

// -- fused instructions ----------------------------------------------------
//
// The interpreter collapses a few hot instruction groups (`x += 1`, `x++`, `x = k`, a
// loop header) into one dispatch. The integer case is the fast one; every other operand
// type falls back to the real instructions. These tests are the ones that would have
// caught the fusion bug that made `str.slice(0, p)` call `p`: the *semantics* of the
// group, for every operand type the fast path does not cover.

/// `x += k` for every operand type the fusion has to hand back to the generic path.
#[test]
fn compound_assignment_keeps_its_type() {
    assert_eq!(
        value(
            r#"
            (function () {
                var int = 1; int += 1;              // the fast path
                var float = 1.5; float += 1;         // Float, not Int
                var text = "a"; text += 1;           // string concatenation
                var bool = true; bool += 1;          // ToPrimitive then add
                var nothing = undefined; nothing += 1;
                var nul = null; nul += 1;
                var hole = []; hole[0] = 1; hole[0] += 1;
                return [int, float, text, bool, nothing, nul, hole[0]].join("|");
            })()
            "#
        ),
        "2|2.5|a1|2|NaN|1|2"
    );
}

/// `x += k` where the increment would overflow the integer representation, and where the
/// operand is a `BigInt` — which must throw rather than silently become a number.
#[test]
fn compound_assignment_handles_overflow_and_bigint() {
    assert_eq!(
        value(
            r#"
            (function () {
                var big = 2147483647; big += 1;
                var b = 1n;
                var threw = "-";
                try { b += 1 } catch (e) { threw = e.name }
                return [big, typeof big, threw, b].join("|");
            })()
            "#
        ),
        "2147483648|number|TypeError|1"
    );
}

/// `x++` as a statement: the local advances, the value is dropped, and a non-integer
/// operand goes through `ToNumeric` rather than through the integer fast path.
#[test]
fn post_increment_advances_every_operand_type() {
    assert_eq!(
        value(
            r#"
            (function () {
                var out = [];
                var i = 0; for (var k = 0; k < 3; k++) i++; out.push(i);
                var f = 1.5; f++; out.push(f);
                var s = "1"; s++; out.push(s);
                var b = true; b++; out.push(b);
                var big = 1n; big++; out.push(big);
                return out.join("|");
            })()
            "#
        ),
        "3|2.5|2|2|2"
    );
}

/// `x++` inside an expression must still yield the *old* value, which is why fusing it as
/// a statement is only done when the compiler dropped the result.
#[test]
fn post_increment_in_an_expression_yields_the_old_value() {
    assert_eq!(
        value(
            r#"
            (function () {
                var i = 0;
                var pair = [i++, i++, i];
                return pair.join("|");
            })()
            "#
        ),
        "0|1|2"
    );
}

/// The fused loop header must keep the comparison's three special cases: equal bounds run
/// zero times, a `NaN` bound runs zero times, and a negative bound runs zero times.
#[test]
fn a_fused_loop_header_respects_the_comparison() {
    assert_eq!(
        value(
            r#"
            (function () {
                var counts = [];
                var n;
                for (n = 0; n < 0; n++) counts.push("never");
                counts.push(n);
                for (n = 0; n < NaN; n++) counts.push("never");
                counts.push(n);
                for (n = 0; n < -1; n++) counts.push("never");
                counts.push(n);
                for (n = 0; n < 3; n++) counts.push(n);
                return counts.join(",");
            })()
            "#
        ),
        "0,0,0,0,1,2"
    );
}

/// A loop whose bound is a string or an object goes through `ToPrimitive` on both sides,
/// including when that conversion throws — the exception must reach the handler with the
/// loop abandoned, not silently compare.
#[test]
fn a_fused_loop_header_converts_its_operands() {
    assert_eq!(
        value(
            r#"
            (function () {
                var text = [];
                for (var i = 0; i < "3"; i++) text.push(i);
                var calls = 0;
                var boxed = { valueOf: function () { calls++; return 2 } };
                var seen = [];
                for (var j = 0; j < boxed; j++) seen.push(j);
                var boom = { valueOf: function () { throw new RangeError("no") } };
                var caught = "-";
                try { for (var k = 0; k < boom; k++) { } } catch (e) { caught = e.name }
                return [text.join(""), calls > 0, seen.join(""), caught].join("|");
            })()
            "#
        ),
        "012|true|01|RangeError"
    );
}

// -- global inline cache ---------------------------------------------------
//
// A `var` global is a property of the global object, so a read is a property read. One is
// remembered per binding slot, which is only safe because the check revalidates the slot
// and the name on every use. These tests are that claim.

/// A global whose *value* changes must report the new value: the cache remembers where the
/// property lives, not what it held.
#[test]
fn a_cached_global_reports_its_current_value() {
    assert_eq!(
        value(
            r#"
            (function () {
                var seen = "";
                function read() { return counter }
                for (var i = 0; i < 3; i++) { counter = i; seen += read(); }
                return seen;
            })()
            "#
        ),
        "012"
    );
}

/// A global that becomes an accessor must run its getter, every time. Caching an accessor
/// would answer a stale value and never call the getter at all.
#[test]
fn a_global_accessor_is_never_cached() {
    assert_eq!(
        value(
            r#"
            (function () {
                var calls = 0;
                Object.defineProperty(globalThis, "hot", {
                    configurable: true,
                    get: function () { calls++; return calls }
                });
                var a = hot, b = hot, c = hot;
                delete globalThis.hot;
                return [a, b, c, calls].join(",");
            })()
            "#
        ),
        "1,2,3,3"
    );
}

/// Deleting and re-creating a global moves its property, and the cache has to notice.
#[test]
fn a_deleted_global_is_not_answered_from_the_cache() {
    assert_eq!(
        value(
            r#"
            (function () {
                var first = "";
                function read() { return flaky }
                flaky = 1;
                first += read();
                delete globalThis.flaky;
                flaky = 2;
                first += read();
                return first;
            })()
            "#
        ),
        "12"
    );
}

/// A global inherited through the prototype chain is not an own property, so there is
/// nothing to remember — the lookup must still find it, on every read.
#[test]
fn an_inherited_global_is_read_through_the_chain() {
    assert_eq!(
        value(
            r#"
            (function () {
                Object.defineProperty(globalThis, "fromProto", {
                    configurable: true, writable: true, value: "p"
                });
                function read() { return fromProto }
                var seen = read() + read();
                Object.defineProperty(globalThis, "fromProto", {
                    configurable: true, writable: true, value: "q"
                });
                return seen + read();
            })()
            "#
        ),
        "ppq"
    );
}

/// A name declared by a direct `eval` shadows the global for a closure created next to it,
/// and that has to survive the cache's "no eval here" shortcut.
///
/// This is the upstream `test_with` shape: a nested function inside a `with` block reads a
/// variable that `eval("var z = …")` created. The first version of the shortcut asked only
/// the *current frame* for eval-declared variables, so the closure took the global path and
/// threw `ReferenceError: 'z' is not defined`. The upstream corpus caught it; this test
/// keeps it caught.
#[test]
fn an_eval_declared_variable_still_shadows_a_global_inside_a_with() {
    assert_eq!(
        value(
            r#"
            (function () {
                var o = { x: "from-with" };
                var out = [];
                eval('var z = "from-eval";');
                with (o) {
                    var f = function () { out.push(x, z) };
                }
                f();
                return out.join(",");
            })()
            "#
        ),
        "from-with,from-eval"
    );
}

// -- frame buffer recycling ------------------------------------------------
//
// A finished frame's `locals`, `passed` and operand stack go back into a pool, so the next
// call reuses their capacity. Two things have to hold: the buffers must be empty (a buffer
// full of values is a GC root — see the `FinalizationRegistry` test in `builtins.rs`), and
// a fresh frame must not see anything the previous one left behind.

/// A recycled frame must start with every slot `undefined`, not with the caller's leftovers.
#[test]
fn a_reused_frame_starts_clean() {
    assert_eq!(
        value(
            r#"
            (function () {
                function inner(a, b) { return [a, b, typeof c].join("|") }
                var out = [];
                for (var i = 0; i < 3; i++) {
                    // A different argument count each time, so the slots differ.
                    out.push(inner(1, 2, 3, 4));
                    out.push(inner(5));
                }
                return out.join(" ");
            })()
            "#
        ),
        // `join` renders `undefined` as an empty string, so the missing `b` shows as `||`.
        "1|2|undefined 5||undefined 1|2|undefined 5||undefined 1|2|undefined 5||undefined"
    );
}

/// `arguments` is built from what the caller passed, and it must not inherit the previous
/// call's arguments when the buffer is reused.
#[test]
fn a_reused_frame_gets_its_own_arguments() {
    assert_eq!(
        value(
            r#"
            (function () {
                function count() { return arguments.length + ":" + Array.prototype.join.call(arguments, ",") }
                var out = [];
                out.push(count(1, 2, 3));
                out.push(count());
                out.push(count("x"));
                return out.join(" ");
            })()
            "#
        ),
        "3:1,2,3 0: 1:x"
    );
}

/// A recursive function that both uses `arguments` and recurses: the pool is used for every
/// call in the chain, so a shared buffer would corrupt the parent's.
#[test]
fn recursion_with_arguments_is_not_corrupted_by_the_pool() {
    assert_eq!(
        value(
            r#"
            (function () {
                function walk(n, acc) {
                    if (n === 0) return acc;
                    var here = arguments.length;
                    var next = walk(n - 1, acc + here);
                    return next + ":" + here + ":" + arguments[1];
                }
                return walk(3, "");
            })()
            "#
        ),
        // `acc + here` concatenates a string and a number, so `acc` grows a digit per level.
        // The reference answers the same string — checked, not guessed.
        "222:2:22:2:2:2:"
    );
}

/// `x += "..."` in a loop grows one buffer, and the previous value must still be intact.
///
/// This is the shape the fused `AddAtomLoc`/`AddLocLoc`/`AddArgLoc` records exist for, and
/// each of these is a way the in-place append can be entered with a value it must not
/// touch: a second variable holding the same string, a non-string, an object, an argument.
#[test]
fn an_append_into_a_local_leaves_every_other_owner_intact() {
    // The slot is the only owner, so it grows in place — and the result is the same string
    // the copying implementation produced.
    assert_eq!(
        value(
            r#"(function () {
                var text = "";
                for (var i = 0; i < 3; i++) text += "abc";
                return text;
            })()"#
        ),
        "abcabcabc"
    );
    // `b` shares `a`'s bytes. Growing `b` in place would change `a` too, so this must copy.
    assert_eq!(
        value(
            r#"(function () {
                var a = "shared";
                var b = a;
                for (var i = 0; i < 2; i++) b += "!";
                return a + "|" + b;
            })()"#
        ),
        "shared|shared!!"
    );
    // The slot does not hold a string, so there is nothing to grow. Losing the value here
    // answered `"undefineda"` once.
    assert_eq!(
        value(
            r#"(function () {
            var x = 5;
            for (var i = 0; i < 1; i++) x += "a";
            return x;
        })()"#
        ),
        "5a"
    );
    // Numbers take the ordinary path either way.
    assert_eq!(
        value(
            r#"(function () {
            var n = 1;
            for (var i = 0; i < 4; i++) n += n;
            return n;
        })()"#
        ),
        "16"
    );
    // The right operand read from an argument, and from another local.
    assert_eq!(
        value(
            r#"(function () {
                function join(n, piece) {
                    var out = "";
                    for (var i = 0; i < n; i++) out += piece;
                    return out;
                }
                return join(3, "ab");
            })()"#
        ),
        "ababab"
    );
    assert_eq!(
        value(
            r#"(function () {
                var piece = "xy";
                var out = "";
                for (var i = 0; i < 2; i++) out += piece;
                return out;
            })()"#
        ),
        "xyxy"
    );
}

/// A string that has cached its code units must drop the cache when it grows.
///
/// `charCodeAt` builds a `Vec<u16>` once and answers from it afterwards, which is what makes
/// a scan linear instead of quadratic. An in-place append that left the cache alone would
/// keep answering with the characters that used to be there.
#[test]
fn an_in_place_append_invalidates_the_code_unit_cache() {
    assert_eq!(
        value(
            r#"(function () {
                var text = "ab";
                var before = text.charCodeAt(0);
                for (var i = 0; i < 2; i++) text += "cd";
                return before + "," + text.charCodeAt(2) + "," + text.charCodeAt(5) + "," + text.length;
            })()"#
        ),
        "97,99,100,6"
    );
}

/// Adding at a surrogate boundary must not concatenate bytes, because the two halves fold
/// into one astral code point.
///
/// `String.fromCharCode` is how a lone surrogate gets into a string — a literal cannot
/// (the atom table holds a Rust `String`, which has no room for one).
#[test]
fn an_append_refuses_to_join_a_split_surrogate_pair() {
    assert_eq!(
        value(
            r#"(function () {
                var high = String.fromCharCode(0xD800);
                var low = String.fromCharCode(0xDC00);
                var joined = high + low;
                var grown = high;
                for (var i = 0; i < 1; i++) grown += low;
                return (joined === grown) + "," + grown.length + "," +
                    (joined.length === 2);
            })()"#
        ),
        "true,2,true"
    );
}