viperjs 0.3.0

An embeddable JavaScript engine in safe Rust, with zero runtime dependencies.
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
//! Functions, calls, closures and `this`.
//!
//! Every row runs *source* rather than asserting on a chunk: an instruction sequence is an
//! implementation detail and a value is not.

use super::*;

#[test]
fn a_function_declaration_exists_before_the_line_that_declares_it() {
    // The difference between a declaration and an assignment, and the reason both spellings
    // exist. §10.2.11 *initialises* a function declaration at instantiation time; a `var`
    // holding a function expression is only declared then, and assigned where it is written.
    assert_eq!(run("f(); function f() {} 'ran';"), "ran");
    assert_eq!(run("typeof f; function f() {}"), "function");
    assert_eq!(
        run("try { g(); } catch (e) { e.name; } var g = function () {};"),
        "TypeError"
    );
}

#[test]
fn a_call_passes_its_arguments_and_answers_what_was_returned() {
    assert_eq!(run("function f(a, b) { return a + b; } f(1, 2);"), "3");
    assert_eq!(
        run("function f(a, b) { return a + b; } f(1, 2) + f(10, 20);"),
        "33"
    );
    assert_eq!(run("function f() { return 'x'; } f();"), "x");
    // §10.2.1 step 4 — falling off the end is `undefined`, and so is a bare `return`.
    assert_eq!(run("function f() {} typeof f();"), "undefined");
    assert_eq!(run("function f() { return; } typeof f();"), "undefined");
    assert_eq!(run("function f() { 1; } typeof f();"), "undefined");
    // A parameter the caller did not supply is `undefined`; an argument too many is
    // discarded, since reaching it needs `arguments`.
    assert_eq!(
        run("function f(a, b) { return typeof b; } f(1);"),
        "undefined"
    );
    assert_eq!(run("function f(a) { return a; } f(1, 2, 3);"), "1");
    assert_eq!(run("function f() { return 1; } f(1, 2, 3);"), "1");
}

#[test]
fn a_function_is_a_value_and_says_so() {
    assert_eq!(run("function f() {} typeof f;"), "function");
    assert_eq!(run("typeof function () {};"), "function");
    assert_eq!(run("var f = function () {}; typeof f;"), "function");
    assert_eq!(run("typeof {};"), "object");
    // It can be passed, returned and called through another name — and it is an object, so
    // two of them are never the same value.
    assert_eq!(run("function id(x) { return x; } id(id)(42);"), "42");
    assert_eq!(run("function f() {} var g = f; g === f;"), "true");
    assert_eq!(
        run("function make() { return function () {}; } make() === make();"),
        "false"
    );
    // …and a function is truthy and is an ordinary object otherwise.
    assert_eq!(run("function f() {} f ? 'yes' : 'no';"), "yes");
    assert_eq!(run("function f() {} f.own = 1; f.own;"), "1");
}

#[test]
fn a_functions_own_names_do_not_leak_and_the_scripts_do_not_hide() {
    // A parameter and a `var` belong to the call, so each call gets its own and the script
    // never sees them…
    assert_eq!(
        run("var n = 'outer'; function f(n) { return n; } f('inner') + n;"),
        "innerouter"
    );
    assert_eq!(
        run("var only = 'outer'; function f() { var only = 'inner'; return only; } f() + only;"),
        "innerouter"
    );
    // …while a name declared at the top level is reachable from inside, and writing it
    // reaches the same binding rather than a copy.
    assert_eq!(
        run("var total = 0; function add(n) { total = total + n; } add(2); add(3); total;"),
        "5"
    );
    assert_eq!(
        run("var shared = 'seen'; function f() { return shared; } f();"),
        "seen"
    );
}

#[test]
fn recursion_works_and_runs_out_with_a_range_error_rather_than_a_crash() {
    assert_eq!(
        run("function fact(n) { if (n <= 1) return 1; return n * fact(n - 1); } fact(10);"),
        "3628800"
    );
    assert_eq!(
        run("function fib(n) { if (n < 2) return n; return fib(n - 1) + fib(n - 2); } fib(15);"),
        "610"
    );
    // §9.4's note: an implementation may limit recursion and should report it as a
    // RangeError. A frame here is a record rather than a Rust stack frame, so this is a
    // number the engine chose and not the host's stack running out.
    assert_eq!(
        run("function loop(n) { return loop(n + 1); } try { loop(0); } catch (e) { e.name; }"),
        "RangeError"
    );
    // …and the machine is usable afterwards, which is the half that matters: the frames are
    // unwound rather than abandoned.
    assert_eq!(
        run(
            "function loop(n) { return loop(n + 1); } function ok() { return 'fine'; } try { loop(0); } catch (e) { ok(); }"
        ),
        "fine"
    );
}

#[test]
fn calling_something_that_is_not_a_function_is_a_type_error() {
    for source in [
        "var x = 1; x();",
        "var x = 'a'; x();",
        "var x = {}; x();",
        "var x = null; x();",
    ] {
        let script = format!("try {{ {source} }} catch (e) {{ e.name + ': ' + e.message; }}");
        assert_eq!(
            run(&script),
            "TypeError: what was called is not a function",
            "running {source:?}"
        );
    }
}

#[test]
fn a_throw_crosses_a_call_and_finds_the_handler_that_was_waiting() {
    assert_eq!(
        run("function t() { throw 'inside'; } try { t(); } catch (e) { 'caught ' + e; }"),
        "caught inside"
    );
    // Through two calls, and past a `finally` that runs on the way.
    assert_eq!(
        run(
            "var log = ''; function inner() { throw 1; } function outer() { try { inner(); } finally { log = log + 'f'; } } try { outer(); } catch (e) { log + e; }"
        ),
        "f1"
    );
    // A handler *inside* the callee catches first, and the caller's is untouched.
    assert_eq!(
        run(
            "function t() { try { throw 1; } catch (e) { return 'inner'; } } try { t(); } catch (e) { 'outer'; }"
        ),
        "inner"
    );
    // …and the operand stack comes back level, so what follows is computed on a clean one.
    assert_eq!(
        run("function t() { throw 1; } var r; try { r = 1 + t(); } catch (e) { r = 9; } r;"),
        "9"
    );
}

#[test]
fn what_a_function_evaluates_to_is_not_the_scripts_completion_value() {
    // §14.2.2 — the completion value belongs to the script. A statement inside a function
    // discards its value, so calling one cannot change what the script came to.
    assert_eq!(run("7; function f() { 99; } f();"), "undefined");
    assert_eq!(run("function f() { 99; } f(); 7;"), "7");
    assert_eq!(run("7; function f() { 99; }"), "7");
}

#[test]
fn what_functions_cannot_do_yet_says_which_and_where() {
    // Nothing, as it turns out. Every row this test has held has landed — the last was §15.1's
    // destructuring rest parameter — so what it asserts now is that the shape it used to refuse
    // works, and the test is kept rather than deleted so that a future refusal has somewhere to go.
    assert_eq!(
        run("function f(...[a, ...rest]) { return a + ':' + rest.join(); } f(1, 2, 3)"),
        "1:2,3"
    );
}

#[test]
fn a_functions_statements_do_not_touch_the_scripts_completion_value() {
    // §14.2.2 — the completion value is the *script's*. The call itself is an expression
    // statement and sets it, which hides the difference; a call in a *declaration* does not,
    // so this is where a function writing to it would show.
    assert_eq!(run("7; function f() { 99; } var x = f();"), "7");
    assert_eq!(run("7; function f() { 99; } f();"), "undefined");
    assert_eq!(run("function f() { 99; } var x = f(); 'end';"), "end");
}

#[test]
fn the_call_limit_is_a_count_of_frames_and_the_count_is_exact() {
    // The limit is a number this engine chose, so an off-by-one in it is invisible unless
    // something counts. This counts: every entry increments, and the call that is refused is
    // the one that would have made the frames one deeper than allowed.
    let reached = run(
        "var deep = 0; function f() { deep = deep + 1; return f(); } \
         try { f(); } catch (e) { deep; }",
    );
    assert_eq!(reached, MAX_CALL_DEPTH.to_string());
    // …and it is a RangeError rather than anything else, which is what §9.4's note asks for.
    assert_eq!(
        run("function f() { return f(); } try { f(); } catch (e) { e.name; }"),
        "RangeError"
    );
}

#[test]
fn a_closure_keeps_the_variables_of_a_call_that_has_already_returned() {
    // The definition of a closure, and the reason a variable cannot live in a frame: by the
    // time `next` runs, `counter`'s call is over and `n` is still there.
    assert_eq!(
        run(
            "function counter() { var n = 0; return function () { n = n + 1; return n; }; } \
             var next = counter(); next(); next(); next();"
        ),
        "3"
    );
    // Capturing by *value* at creation would answer 1 three times, which is why this is the
    // first row: it is the mistake the whole design exists to avoid.
    assert_eq!(
        run("function adder(x) { return function (y) { return x + y; }; } adder(3)(4);"),
        "7"
    );
}

#[test]
fn each_call_makes_its_own_environment_and_closures_over_it_share_only_that_one() {
    // Two calls to the same function make two environments, so two closures made from them
    // count separately — while two closures from the *same* call share one.
    assert_eq!(
        run(
            "function counter() { var n = 0; return function () { n = n + 1; return n; }; } \
             var a = counter(); var b = counter(); a(); a(); b();"
        ),
        "1"
    );
    assert_eq!(
        run(
            "function counter() { var n = 0; return function () { n = n + 1; return n; }; } \
             var a = counter(); a(); a(); a();"
        ),
        "3"
    );
    // A recursive call does not overwrite its caller's variables, which is the same rule seen
    // from the other side.
    assert_eq!(
        run("function f(n) { var mine = n; if (n > 0) f(n - 1); return mine; } f(3);"),
        "3"
    );
}

#[test]
fn an_inner_function_writes_the_outer_variable_rather_than_a_copy() {
    assert_eq!(
        run("function o() { var x = 'a'; function set() { x = 'b'; } set(); return x; } o();"),
        "b"
    );
    // Through two levels, which is where a depth counted wrongly would show.
    assert_eq!(
        run(
            "function outer() { var x = 1; function middle() { function inner() { return x; } \
             return inner(); } return middle(); } outer();"
        ),
        "1"
    );
    assert_eq!(
        run(
            "function outer() { var x = 1; function middle() { function inner() { x = 9; } \
             inner(); } middle(); return x; } outer();"
        ),
        "9"
    );
    // …and the script's own variables are the far end of the same chain.
    assert_eq!(
        run("var top = 1; function f() { function g() { top = top + 1; } g(); } f(); top;"),
        "2"
    );
}

#[test]
fn a_parameter_is_a_variable_of_the_call_like_any_other() {
    // §10.2.11 — the parameters are the first slots of the call's environment, so a closure
    // over one is a closure over that call's copy.
    assert_eq!(
        run(
            "function hold(x) { return function () { return x; }; } var a = hold(1); \
             var b = hold(2); a() + b();"
        ),
        "3"
    );
    assert_eq!(
        run(
            "function hold(x) { return function () { x = x + 1; return x; }; } \
             var f = hold(10); f(); f();"
        ),
        "12"
    );
}

#[test]
fn a_method_call_receives_the_object_it_was_found_on() {
    // §13.3.6.1 — the receiver travels with the *call*, not with the function. The same
    // function called two ways has two different `this`, which is the whole reason a method
    // is not simply a property whose value happens to be callable.
    assert_eq!(
        run("var o = { v: 7 }; o.get = function () { return this.v; }; o.get();"),
        "7"
    );
    assert_eq!(
        run("var o = { v: 7 }; o.get = function () { return this.v; }; var f = o.get; typeof f();"),
        "undefined"
    );
    // The *nearest* base is the receiver, not the outermost one.
    assert_eq!(
        run("var o = { a: { v: 1 } }; o.a.get = function () { return this.v; }; o.a.get();"),
        "1"
    );
    // Arguments still work, and a computed key finds the same method.
    assert_eq!(
        run("var o = { v: 2 }; o.m = function (x) { return this.v + x; }; o.m(3);"),
        "5"
    );
    assert_eq!(
        run("var o = { v: 1 }; o['m'] = function () { return this.v; }; o['m']();"),
        "1"
    );
}

#[test]
fn the_base_of_a_method_call_is_evaluated_exactly_once() {
    // `f().m()` calls `f` once. Compiling the base twice — once to find the method and once
    // to be the receiver — would call it twice, and that is a side effect nobody asked for.
    assert_eq!(
        run("var calls = 0; function base() { calls = calls + 1; \
             return { m: function () { return 'ok'; } }; } base().m(); calls;"),
        "1"
    );
    // …and a computed key is evaluated once too, which is the same rule one level down.
    assert_eq!(
        run(
            "var keys = 0; var o = { m: function () { return 'ok'; } }; \
             function key() { keys = keys + 1; return 'm'; } o[key()](); keys;"
        ),
        "1"
    );
}

#[test]
fn a_call_with_no_receiver_gets_the_global_object() {
    // §10.2.1.2's substitution. Strict mode keeps the `undefined` instead, and telling the
    // two apart needs the flag the parser already computes — so this is the sloppy answer,
    // which is what an ordinary script gets.
    assert_eq!(run("function f() { return typeof this; } f();"), "object");
    assert_eq!(run("typeof this;"), "object");
    // The script's `this` and a plain call's are the same object (§16.1.7).
    assert_eq!(
        run("var top = this; function f() { return this === top; } f();"),
        "true"
    );
    // …and a method's is not.
    assert_eq!(
        run("var top = this; var o = { m: function () { return this === top; } }; o.m();"),
        "false"
    );
}

#[test]
fn this_is_restored_when_a_call_returns_however_it_returns() {
    assert_eq!(
        run(
            "var o = { v: 'inner', m: function () { return this.v; } }; \
             var outer = this; o.m(); typeof this;"
        ),
        "object"
    );
    // Including when the call left by throwing, which unwinds frames rather than returning.
    assert_eq!(
        run("var top = this; var o = { m: function () { throw 1; } }; \
             try { o.m(); } catch (e) { this === top; }"),
        "true"
    );
}

#[test]
fn new_makes_an_object_out_of_the_constructors_prototype() {
    // §10.2.2 — `new` does not call with a different receiver, it *makes* one, from the
    // constructor's own `prototype` property. So the instance inherits whatever is put there.
    assert_eq!(
        run("function F(a) { this.v = a; } var f = new F(7); f.v;"),
        "7"
    );
    assert_eq!(
        run("function F() { this.v = 1; } typeof new F();"),
        "object"
    );
    assert_eq!(
        run("function F() {} F.prototype.shared = 'proto'; new F().shared;"),
        "proto"
    );
    // §10.2.5's pair, and the reason it is made eagerly: each points at the other.
    assert_eq!(run("function F() {} new F().constructor === F;"), "true");
    assert_eq!(
        run("function F() {} F.prototype.constructor === F;"),
        "true"
    );
    // Two constructions are two objects.
    assert_eq!(
        run("function F() {} var a = new F(); var b = new F(); a === b;"),
        "false"
    );
}

#[test]
fn a_constructors_return_is_ignored_unless_it_is_an_object() {
    // §10.2.2 step 13, and the row everyone is surprised by: a primitive `return` from a
    // constructor is thrown away and the constructed object is the answer anyway.
    assert_eq!(
        run("function F() { this.v = 1; return 42; } new F().v;"),
        "1"
    );
    assert_eq!(
        run("function F() { this.v = 1; return 'x'; } new F().v;"),
        "1"
    );
    assert_eq!(run("function F() { this.v = 1; return; } new F().v;"), "1");
    // …while an *object* return replaces it entirely, which is how a factory pretends to be a
    // constructor.
    assert_eq!(
        run("function F() { return { v: 'own' }; } new F().v;"),
        "own"
    );
    assert_eq!(
        run("function F() { this.v = 1; return { v: 2 }; } new F().v;"),
        "2"
    );
}

#[test]
fn a_prototype_that_is_not_an_object_falls_back_rather_than_failing() {
    // §10.1.13 — a function's `prototype` is an ordinary writable property, so a script may put
    // anything there. An instance then inherits from `Object.prototype` instead, which is a
    // fallback and not an error.
    assert_eq!(
        run("function F() {} F.prototype = 1; typeof new F();"),
        "object"
    );
    assert_eq!(
        run("function F() {} F.prototype = null; typeof new F();"),
        "object"
    );
    assert_eq!(
        run("function F() { this.v = 1; } F.prototype = 'x'; new F().v;"),
        "1"
    );
}

#[test]
fn constructing_something_that_is_not_a_function_is_a_type_error() {
    for source in [
        "var x = 1; new x();",
        "var x = {}; new x();",
        "var x = null; new x();",
    ] {
        let script = format!("try {{ {source} }} catch (e) {{ e.name; }}");
        assert_eq!(run(&script), "TypeError", "running {source:?}");
    }
    // …and a throw from inside a constructor is an ordinary throw: the half-made object goes
    // with the frame.
    assert_eq!(
        run("function F() { throw 'boom'; } try { new F(); } catch (e) { 'caught ' + e; }"),
        "caught boom"
    );
}

#[test]
fn a_spread_argument_contributes_however_many_it_turns_out_to_have() {
    // §13.3.8 — the count is not known until the spread has been iterated, so the arguments are
    // gathered into an array and expanded by the call. `f(...a)` and `[...a]` iterate by exactly the
    // same rules, and share the code that does it.
    assert_eq!(
        run(
            "(function () { var f = function (a, b, c) { return a + ',' + b + ',' + c; }; \
             return f(...[1, 2, 3]); })()"
        ),
        "1,2,3"
    );
    assert_eq!(
        run(
            "(function () { var f = function () { return arguments.length; }; return f(...[]); })()"
        ),
        "0"
    );
    // Mixed with ordinary arguments, in written order, before and after.
    assert_eq!(
        run(
            "(function () { var f = function (a, b, c, d) { return '' + a + b + c + d; }; \
             return f(1, ...[2, 3], 4); })()"
        ),
        "1234"
    );
    // Two spreads in one call, each contributing its own length.
    assert_eq!(
        run("(function () { var f = function () { \
               return Array.prototype.join.call(arguments, '-'); }; \
             return f(...[1, 2], ...[3, 4]); })()"),
        "1-2-3-4"
    );
    // Anything iterable, not only an array — a String iterates by code point.
    assert_eq!(
        run(
            "(function () { var f = function () { return arguments.length; }; \
             return f(...'abc'); })()"
        ),
        "3"
    );
    // A custom iterator is used, and used once.
    assert_eq!(
        run("(function () { var made = 0; var it = {}; \
             it[Symbol.iterator] = function () { made++; var i = 0; return { next: function () { \
               return i < 3 ? {value: i++, done: false} : {done: true}; } }; }; \
             var f = function () { return arguments.length; }; \
             return f(...it) + ',' + made; })()"),
        "3,1"
    );
    // A call with no spread still takes the fixed-count path, which is the majority of calls.
    assert_eq!(
        run("(function () { var f = function (a, b) { return a + ',' + b; }; return f(1, 2); })()"),
        "1,2"
    );
}

#[test]
fn a_spread_argument_keeps_the_receiver_and_works_with_new() {
    // A method call's receiver sits under the callee, and expanding the array must not disturb it.
    assert_eq!(
        run(
            "(function () { var o = {n: 10, m: function (a) { return this.n + a; }}; \
             return o.m(...[5]); })()"
        ),
        "15"
    );
    assert_eq!(
        run(
            "(function () { var o = {n: 1, m: function () { return this.n + arguments.length; }}; \
             return o.m(...[0, 0, 0]); })()"
        ),
        "4"
    );
    // §13.3.5 — `new` makes its own receiver, so a spread there differs only in who supplies it.
    assert_eq!(
        run("(function () { function C(a, b) { this.v = a + b; } return new C(...[1, 2]).v; })()"),
        "3"
    );
    assert_eq!(
        run(
            "(function () { function C(a, b) { this.v = '' + a + b; } return new C(1, ...[2]).v; })()"
        ),
        "12"
    );
    // Including a class constructor, which is the shape §15.7.14's default derived constructor needs.
    assert_eq!(
        run(
            "(function () { class C { constructor(a, b) { this.v = a + b; } } \
             return new C(...[3, 4]).v; })()"
        ),
        "7"
    );
    // The spread is evaluated where it is written, so a side effect in it happens after the callee's.
    assert_eq!(
        run("(function () { var order = []; \
             var f = function () { order.push('call'); return function () {}; }; \
             var args = {}; args[Symbol.iterator] = function () { order.push('iterate'); \
               return {next: function () { return {done: true}; }}; }; \
             f()(...args); return order.join(','); })()"),
        "call,iterate"
    );
}

#[test]
fn an_optional_call_gives_up_one_link_later_than_an_optional_member() {
    // §13.3.9 — `a?.()` asks about the *callee* and `a?.b()` asks about `a`, which is one link
    // earlier. And a method call has copied its receiver by then, so the short circuit has that to
    // clear away too: it is the one place a link leaves more than the value itself behind.
    assert_eq!(
        run("(function () { var o = { m() { return this === o; } }; return o?.m(); })()"),
        "true"
    );
    assert_eq!(
        run("(function () { var o = null; return String(o?.m()); })()"),
        "undefined"
    );
    // The callee is nullish and the receiver is not — the shape that would strand a value.
    assert_eq!(
        run("(function () { var o = {}; return String(o.m?.()); })()"),
        "undefined"
    );
    assert_eq!(
        run("(function () { var f = null; return String(f?.()); })()"),
        "undefined"
    );
    // …and the arguments are not evaluated when it gives up, which is what says the whole call was
    // skipped rather than made with nothing.
    assert_eq!(
        run("(function () { var n = 0; var o = {}; String(o.m?.(n++, n++)); return n; })()"),
        "0"
    );
    // A callee that is present is called normally, including through several links.
    assert_eq!(
        run("(function () { var o = { a: { m() { return 7; } } }; return o?.a?.m?.(); })()"),
        "7"
    );
}

#[test]
fn a_function_stringifies_in_the_native_code_form_whatever_it_was_written_as() {
    // §20.2.3.5 step 2 answers a function's source text *when the host has it*, and ViperJS's host
    // does not: a compiled chunk does not keep the text it came from. So step 3's `NativeFunction`
    // form comes back for every function, which the clause allows and which is a real limitation
    // rather than a reading of it.
    assert_eq!(run("String(Math.max)"), "function max() { [native code] }");
    assert_eq!(
        run("String(function f(a) { return a; })"),
        "function f() { [native code] }"
    );
    assert_eq!(
        run("String(function () {})"),
        "function () { [native code] }"
    );
    // An accessor's name already carries its `get`, which is exactly §20.2.3.5's
    // `NativeFunctionAccessor` — so the two spellings need no case of their own.
    assert_eq!(
        run("var o = { get x() { return 1; } }; \
             String(Object.getOwnPropertyDescriptor(o, 'x').get)"),
        "function get x() { [native code] }"
    );
    assert_eq!(
        run("String(function () {}.bind(null))"),
        "function bound () { [native code] }"
    );
    // Step 5 — something that is not callable has nothing to answer about, and saying
    // `[object Object]` would be a lie about what was asked.
    assert_eq!(
        run("try { Function.prototype.toString.call({}) } catch (e) { e.constructor.name }"),
        "TypeError"
    );
    assert_eq!(
        run("try { Function.prototype.toString.call(undefined) } catch (e) { e.constructor.name }"),
        "TypeError"
    );
    // …and it is what `String(f)` and `f + ''` both reach, because §7.1.1 finds it before
    // `Object.prototype.toString`.
    assert_eq!(run("Math.max + ''"), "function max() { [native code] }");
}

#[test]
fn a_hoisted_declaration_sees_every_sibling_whichever_order_they_are_written_in() {
    // §10.2.11 creates the binding for every `functionsToInitialize` and *then* instantiates the
    // function objects. ViperJS declared each name immediately before compiling that function's
    // body, so a body compiled first resolved a later sibling outwards — out of the function, out
    // to the global object, and into a ReferenceError at run time.
    //
    // The tell was that reversing the two declarations made it work, which is not something the
    // order of two hoisted declarations is allowed to decide.
    assert_eq!(
        run(
            "(function () { function a() { return b(); } function b() { return 7; } return a(); })()"
        ),
        "7"
    );
    assert_eq!(
        run(
            "(function () { function b() { return 7; } function a() { return b(); } return a(); })()"
        ),
        "7"
    );
    // Mutual recursion is the same fact needing to hold in both directions at once, and cannot be
    // written in any order that avoids it.
    assert_eq!(
        run(
            "(function () {              function even(n) { return n === 0 ? true : odd(n - 1); }              function odd(n) { return n === 0 ? false : even(n - 1); }              return String(even(4)) + odd(4); })()"
        ),
        "truefalse"
    );
    // A closure made inside one and called later still finds the sibling, which is what makes this
    // about the binding rather than about the moment of the call.
    assert_eq!(
        run(
            "(function () { function a() { return function () { return b(); }; }              function b() { return 3; } return a()(); })()"
        ),
        "3"
    );
    // The same at a script's top level, where the binding is a property of the global object and
    // the resolution never went through a slot — so this half was already right and must stay so.
    assert_eq!(
        run("function a() { return b(); } function b() { return 5; } a()"),
        "5"
    );
}

#[test]
fn a_sloppy_functions_receiver_is_wrapped_and_a_strict_ones_is_not() {
    // §10.2.1.2 step 6.b.i — `OrdinaryCallBindThis` converts a primitive receiver with `ToObject`
    // for a **non-strict** function, so `this` is a wrapper that survives the call. Step 5 hands a
    // strict one the primitive untouched. The mode is the *callee's*, so the caller cannot answer
    // for it and a strict function called from sloppy code still sees the primitive.
    let sloppy = "function f() { return typeof this + ',' + (this instanceof Number); }";
    let strict =
        "function f() { 'use strict'; return typeof this + ',' + (this instanceof Number); }";
    assert_eq!(
        run(&format!("(function () {{ {sloppy} return f.call(1); }})()")),
        "object,true"
    );
    assert_eq!(
        run(&format!("(function () {{ {strict} return f.call(1); }})()")),
        "number,false"
    );
    // A String and a Boolean are wrapped in their own kind, which is what makes this `ToObject`
    // rather than "make an object".
    assert_eq!(
        run(
            "(function () { function f() { return (this instanceof String) + ',' + this.length; }              return f.call('abc'); })()"
        ),
        "true,3"
    );
    assert_eq!(
        run(
            "(function () { function f() { return this instanceof Boolean; }              return f.call(true); })()"
        ),
        "true"
    );
    // Step 6.a — `undefined` and `null` are the global object instead, for a sloppy function only.
    assert_eq!(
        run(
            "(function () { function f() { return this === globalThis; }              return f.call(undefined) + ',' + f.call(null) + ',' + f(); })()"
        ),
        "true,true,true"
    );
    assert_eq!(
        run(
            "(function () { function f() { 'use strict'; return this; }              return String(f.call(undefined)) + ',' + String(f.call(null)); })()"
        ),
        "undefined,null"
    );
}

#[test]
fn a_wrapped_receiver_is_what_a_sloppy_function_writes_to_and_can_hand_back() {
    // The point of the wrap, and what `Function.prototype.call`'s own tests measure: a write to
    // `this` lands on an object that outlives the call, so the value is readable through what the
    // function returns — while the primitive the caller still holds is untouched.
    assert_eq!(
        run(
            "(function () { function f() { this.touched = true; return this; }              var n = 1; var back = f.call(n);              return String(n.touched) + ',' + String(back.touched); })()"
        ),
        "undefined,true"
    );
    // A **fresh** wrapper per call, so two calls do not see each other's writes. Reading `n.x`
    // makes a third and finds nothing, which is the same rule seen from the other side.
    assert_eq!(
        run(
            "(function () { function f() { this.n = (this.n || 0) + 1; return this.n; }              return f.call(7) + ',' + f.call(7); })()"
        ),
        "1,1"
    );
    // Two clauses compose here and it is worth pinning: §6.2.5.6 hands a setter the **primitive**
    // as its receiver, and §10.2.1.2 then wraps it because the setter is sloppy. Neither alone
    // explains what `this` is inside an ordinary setter reached through a primitive.
    assert_eq!(
        run(
            "(function () { var seen;              Object.defineProperty(Number.prototype, 'both', {                set: function () { seen = typeof this + ',' + (this instanceof Number); },                configurable: true });              var n = 1; n.both = 0; return seen; })()"
        ),
        "object,true"
    );
}

#[test]
fn a_tail_call_answers_what_the_same_call_would_have_answered() {
    // DR-0027's second invariant, and the one that says the optimisation is *correct*. The frame a
    // tail call replaces is the one whose return value it becomes, so nothing a program can write
    // tells the two apart — and if anything ever does, the tail call has skipped work the crossings
    // should have named.
    let recursive = "function sum(n, acc) { 'use strict';                      return n === 0 ? acc : sum(n - 1, acc + n) } sum(100, 0)";
    assert_eq!(run(recursive), "5050");
    // The same shape reached as a method, and through a `catch` and a `finally` — the three places
    // §14.6.1 puts a tail position that are not simply "the body".
    assert_eq!(
        run(
            "var o = { m: function (n) { 'use strict'; if (n === 0) { return 'end' }              return o.m(n - 1) } }; o.m(10)"
        ),
        "end"
    );
    assert_eq!(
        run(
            "function f(n) { 'use strict'; if (n === 0) { return 'caught' }              try { throw 0 } catch (e) { return f(n - 1) } } f(10)"
        ),
        "caught"
    );
    assert_eq!(
        run(
            "function f(n) { 'use strict'; if (n === 0) { return 'finally' }              try { } finally { return f(n - 1) } } f(10)"
        ),
        "finally"
    );
    // A `finally` that returns something of its own still wins over the try's value, which is the
    // one place the two could have been confused: a tail call in the finally must answer for the
    // whole function and not for the block it is written in.
    assert_eq!(
        run(
            "function id(x) { 'use strict'; return x }              function f() { 'use strict'; try { return 'try' } finally { return id('finally') } } f()"
        ),
        "finally"
    );
}

#[test]
fn a_tail_recursive_function_runs_past_the_depth_a_call_stack_would_stop_at() {
    // §15.10, and the whole point of it: `MAX_CALL_DEPTH` is ten thousand, and this is five times
    // that. What makes it pass is that `frames` gains one entry and loses one per call, so there is
    // no depth to run out of — the recursion is bounded only by what the program itself holds.
    assert_eq!(
        run(
            "function count(n) { 'use strict'; if (n === 0) { return 'done' } return count(n - 1) }              count(50000)"
        ),
        "done"
    );
    // The same, through a `switch`, which leaves its discriminant on the operand stack. A tail call
    // that took the frame down without also taking the stack down would leak one value per pass and
    // this would exhaust the heap instead of answering.
    assert_eq!(
        run(
            "function count(n) { 'use strict'; if (n === 0) { return 'done' }              switch (0) { case 0: return count(n - 1); } } count(50000)"
        ),
        "done"
    );
}

#[test]
fn the_two_frames_a_tail_call_may_not_replace_are_the_ones_the_source_cannot_see() {
    // DR-0027: the same body runs for `f(1)` and for `new f(1)`, so the compiler cannot decide
    // these and the machine has to. What each row asserts is the *answer* and not the depth —
    // replacing one of these frames does not run out of stack, it produces the wrong value, which
    // is the more expensive failure and the one worth pinning. A first version of this test asked
    // for a RangeError from `return new C(n - 1)`, and every one of its guards survived mutation:
    // `new` is not a call, so the compiler never marked it and the guard was never reached.
    //
    // §10.2.2 step 13 — a construction's frame is holding the object it made, and a primitive
    // `return` is ignored. Hand that frame to a callee and `new C()` answers the callee's value.
    assert_eq!(
        run(
            "function tail() { 'use strict'; return 'not the object' } function C() { 'use strict'; this.made = true; return tail() } var made = new C(); typeof made + ',' + made.made"
        ),
        "object,true"
    );
    // §27.5.3.2 step 5 — a generator's body answers with `{ value, done: true }` rather than with
    // what it returned, so it has something to do after the call and cannot hand its return over.
    assert_eq!(
        run(
            "function tail() { 'use strict'; return 'end' } function* g() { 'use strict'; return tail() } var step = g().next(); step.value + ',' + step.done"
        ),
        "end,true"
    );
    // §27.7.5.1 — and an `async` function *resolves a promise* with what it returned, which is the
    // third shape `suspendable_of` answers for. What would go missing is the promise itself.
    assert_eq!(
        run(
            "function tail() { 'use strict'; return 'awaited' } async function a() { 'use strict'; return tail() } var seen = 'nothing'; a().then(function (v) { seen = v }); typeof a().then + ',' + seen"
        ),
        "function,nothing"
    );
    // §10.2.2 step 13 again, for the *derived* constructor the compiler refuses rather than the
    // machine: its `return` emits `CompleteDerivedReturn` after the value is in hand, and a tail
    // call would jump over it — so `new D()` would answer `undefined` instead of the instance.
    assert_eq!(
        run(
            "function tail() { 'use strict'; } class B { constructor() { this.b = 1 } } class D extends B { constructor() { super(); return tail() } } var made = new D(); (made instanceof D) + ',' + made.b"
        ),
        "true,1"
    );
    // The refusal is a refusal to *optimise* and not to run: a construction still recurses as an
    // ordinary call, which is what the depth says.
    assert_eq!(
        run(
            "function C(n) { 'use strict'; if (n === 0) { return } return new C(n - 1) } try { new C(50000); 'no error' } catch (e) { e.constructor.name }"
        ),
        "RangeError"
    );
}