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
//! The property inline cache must never answer a value the slow path would not.
//!
//! `Interp::read_field_cached` remembers own data properties *and* prototype hits. The
//! second kind is what makes `a.push(i)` cheap — `push` lives on `Array.prototype`, so
//! without it every method call walked the chain and compared ~40 names.
//!
//! A cache is a wrong-answer machine unless every way the answer can change invalidates
//! it, so each test below changes something *between* two lookups that hit the same cache
//! entry. Every expected value was taken from the reference implementation
//! (`oracle/quickjs-master/qjs`) on the release this port tracks.
//!
//! ## Why the shape of these tests matters
//!
//! The cache slot is derived from the object's address, the key **and the bytecode site**
//! (`Interp::field_cache_slot`). Two syntactically separate `o.x` expressions are two
//! sites and two slots, so priming one and reading the other would pass even with the
//! invalidation guard removed entirely — the second read would simply miss. Each test
//! therefore reads through *one* function, called many times, which is the only shape
//! that can observe a stale hit. (Verified by breaking the guard on purpose: with a
//! one-level-only check and separate sites, all of these still passed.)

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()
        ),
    }
}

/// Prime one property site `n` times, run `mutate`, then read through the *same* site.
///
/// `setup` must define whatever `read_expr` and `mutate` refer to. The read expression
/// lives inside one function, so that every call — priming and final — executes one
/// `get_field` at one bytecode site, and therefore one cache slot.
fn probe_after(setup: &str, prime: usize, mutate: &str, read_expr: &str) -> String {
    eval(&format!(
        "{setup}
         function probe() {{ return {read_expr}; }}
         for (var i = 0; i < {prime}; i++) probe();
         {mutate}
         print(probe());"
    ))
}

#[test]
fn a_shadowing_property_on_an_intermediate_prototype_is_seen() {
    // The cached entry says "level 2 answers"; adding `m` to level 1 must shadow it.
    // This is the case a single-level guard misses, and the reason the cache records the
    // whole walked chain rather than only the object that answered.
    assert_eq!(
        probe_after(
            "function f(){ return 1; }
             var base = { m: f };
             var mid = Object.create(base);
             var leaf = Object.create(mid);",
            200,
            "mid.m = function () { return 2; };",
            "leaf.m()"
        ),
        "2\n"
    );
}

#[test]
fn deleting_the_shadowing_property_falls_back_to_the_cached_one() {
    let source = "var base = { m: function () { return 1; } };\n\
         var mid = Object.create(base);\n\
         var leaf = Object.create(mid);\n\
         function probe() { return leaf.m(); }\n\
         for (var i = 0; i < 200; i++) probe();\n\
         mid.m = function () { return 2; };\n\
         probe();\n\
         delete mid.m;\n\
         print(probe());";
    assert_eq!(eval(source), "1\n");
}

#[test]
fn replacing_a_data_property_with_an_accessor_runs_the_getter() {
    // A same-length redefinition does *not* move `props_len`, so the length guard alone
    // would keep serving the old value. `cached_data_property` refusing an accessor is
    // what saves it.
    assert_eq!(
        probe_after(
            "var proto = { m: function () { return 1; } };
             var o = Object.create(proto);",
            200,
            "Object.defineProperty(proto, 'm', { get: function () { return 99; } });",
            "o.m"
        ),
        "99\n"
    );
}

#[test]
fn a_getter_caches_nothing_and_receives_the_receiver_as_this() {
    let source = "var proto = { get v() { return this.tag; } };\n\
         var o = Object.create(proto);\n\
         o.tag = 'mine';\n\
         function probe() { return o.v; }\n\
         for (var i = 0; i < 200; i++) probe();\n\
         print(probe());";
    assert_eq!(eval(source), "mine\n");
}

#[test]
fn overriding_array_prototype_push_is_seen() {
    // The real-world shape `array:push` exercises: the cache entry points at
    // `Array.prototype`'s `push`, and replacing it must not keep calling the old one.
    // Both loops call `push` from the same site inside `fill`.
    let source = "function fill(a, n) { for (var i = 0; i < n; i++) a.push(i); }\n\
         var a = []; fill(a, 200);\n\
         var original = Array.prototype.push;\n\
         Array.prototype.push = function (v) { return original.call(this, v * 2); };\n\
         var b = []; fill(b, 200);\n\
         Array.prototype.push = original;\n\
         print(b[3]);";
    assert_eq!(eval(source), "6\n");
}

#[test]
fn a_missing_property_is_not_cached_as_undefined() {
    let source = "var o = {};\n\
         function probe() { return o.nope; }\n\
         for (var i = 0; i < 200; i++) probe();\n\
         Object.setPrototypeOf(o, { nope: 'now' });\n\
         print(probe());";
    assert_eq!(eval(source), "now\n");
}

#[test]
fn a_chain_deeper_than_the_cache_holds_still_answers() {
    // Five links, the cache remembers three: the lookup is simply never recorded, and
    // every read walks. Correctness must not depend on the chain fitting.
    let source = "var a = { k: 'A' };\n\
         var b = Object.create(a), c = Object.create(b),\n\
             d = Object.create(c), e = Object.create(d);\n\
         function probe() { return e.k; }\n\
         for (var i = 0; i < 200; i++) probe();\n\
         print(probe());";
    assert_eq!(eval(source), "A\n");
}

#[test]
fn own_properties_still_shadow_the_prototype_and_cache() {
    let source = "var proto = { tag: 'proto' };\n\
         var o = Object.create(proto);\n\
         o.tag = 'own';\n\
         function probe() { return o.tag; }\n\
         for (var i = 0; i < 200; i++) probe();\n\
         o.tag = 'changed';\n\
         print(probe());";
    assert_eq!(eval(source), "changed\n");
}

#[test]
fn changing_the_prototype_itself_invalidates_the_entry() {
    // `Object.setPrototypeOf` swaps the whole link, which must not leave the old
    // prototype's answer in place.
    let source = "var first = { m: function () { return 1; } };\n\
         var second = { m: function () { return 2; } };\n\
         var o = Object.create(first);\n\
         function probe() { return o.m(); }\n\
         for (var i = 0; i < 200; i++) probe();\n\
         Object.setPrototypeOf(o, second);\n\
         print(probe());";
    assert_eq!(eval(source), "2\n");
}

#[test]
fn array_elements_do_not_go_through_the_property_cache() {
    // `a[i]` has its own fast path (`Interp::fast_array_get`); this pins that the two
    // paths agree, including on a hole falling through to the prototype.
    let source = "var a = [7, 8, 9];\n\
         Array.prototype[0] = 'proto';\n\
         var b = []; b[1] = 1;\n\
         function probe() { return a[1] + ',' + b[0]; }\n\
         for (var i = 0; i < 200; i++) probe();\n\
         print(probe());\n\
         delete Array.prototype[0];";
    assert_eq!(eval(source), "8,proto\n");
}

#[test]
fn the_fast_loop_and_the_slow_arm_agree_on_every_lookup() {
    // `run_fast` answers a `get_field` hit without leaving the loop; the slow arm answers
    // everything else. Both must return what `read_field_key` would, so this is the
    // agreement test: each case below is first *primed* inside a loop (where the fast
    // path runs) and then observed through the same bytecode site.
    //
    // The site matters twice over. The fast loop passes `pc + width` as the cache site and
    // the slow arm passes `next`; if those two ever disagree every fast lookup misses,
    // records the same entry again and stays slow — wrong only in speed, which no
    // correctness test would notice, but `property:monomorphic` would.
    //
    // Every expected value comes from `oracle/quickjs-master/qjs`.
    let cases = [
        // A plain own data property, the monomorphic case the fast path exists for.
        ("var o = { x: 1 };", 200, "", "o.x", "1"),
        // The receiver answering through the fast loop repeatedly, then disappearing.
        ("var o = { x: 1 };", 200, "delete o.x;", "o.x", "undefined"),
        // An accessor must never be answered from the cache; the fast arm has to miss.
        ("var o = { get x() { return 7; } };", 200, "", "o.x", "7"),
        // …and an own data property turned into an accessor between two reads.
        (
            "var o = { x: 1 };",
            200,
            "Object.defineProperty(o, 'x', { get: function () { return 9; } });",
            "o.x",
            "9",
        ),
        // A proxy traps the lookup, so no entry ever describes it.
        (
            "var o = new Proxy({ x: 1 }, { get: function (t, k) { return 42; } });",
            200,
            "",
            "o.x",
            "42",
        ),
        // A getter that changes the object it is called on, per read.
        (
            "var n = 0; var o = { get x() { return ++n; } };",
            200,
            "",
            "o.x",
            "201",
        ),
        // A prototype hit, which is what `a.push(i)` depends on.
        (
            "function F() {} F.prototype.p = 3; var o = new F();",
            200,
            "",
            "o.p",
            "3",
        ),
        // A shadow added on the receiver over a cached prototype hit.
        (
            "function F() {} F.prototype.p = 3; var o = new F();",
            200,
            "o.p = 8;",
            "o.p",
            "8",
        ),
        // A third read after the shadow is removed goes back down the chain.
        (
            "function F() {} F.prototype.p = 3; var o = new F(); o.p = 8;",
            200,
            "delete o.p;",
            "o.p",
            "3",
        ),
        // `get_field2` keeps the receiver for the call that follows, so the fast arm has to
        // leave the stack one element higher than `get_field` does.
        (
            "var o = { v: 5, m: function () { return this.v; } };",
            200,
            "",
            "o.m()",
            "5",
        ),
        // The receiver replaced *and* the value being an object, which the overwrite over
        // the top slot has to hand out with the right reference count.
        ("var o = { k: { inner: 1 } };", 200, "", "o.k.inner", "1"),
        // A string receiver, which is not an object at all and must fall to the slow arm.
        ("var o = { x: 1 };", 200, "", "'abc'.length", "3"),
        // Reading past the end of an array, which is a hole and then undefined.
        ("var a = [1, 2]; var o = a;", 200, "", "o[5]", "undefined"),
    ];
    for (setup, prime, mutate, read, expected) in cases {
        let got = probe_after(setup, prime, mutate, read);
        assert_eq!(
            got,
            format!("{expected}\n"),
            "case: {setup} {mutate} {read}"
        );
    }
}

#[test]
fn a_frozen_object_still_reads_through_the_cache() {
    // Sealing changes attributes, not the property table length or the values, so the entry
    // stays valid — but a read must come back with the value either way.
    let source = "var o = { x: 1 };\n\
         function probe() { return o.x; }\n\
         for (var i = 0; i < 200; i++) probe();\n\
         Object.freeze(o);\n\
         print(probe());";
    assert_eq!(eval(source), "1\n");
}

#[test]
fn the_global_variable_cache_is_keyed_by_name_not_just_slot() {
    // `Interp::get_plain_global` is keyed on `slot & (GLOBAL_CACHE_SLOTS - 1)`, and two
    // functions that read *different* globals can have the same slot number. The entry
    // records only the object and the index now — the name comparison is made against the
    // property table's entry, which is what catches the collision. Priming one and reading
    // the other through the same slot is the case that must not answer the wrong value.
    let source = "var A1 = 11, B1 = 22;\n\
         function f1() { return A1; }\n\
         function f2() { return B1; }\n\
         var seen = [];\n\
         for (var i = 0; i < 50; i++) { seen.push(f1(), f2()); }\n\
         print(seen[0], seen[1], seen[98], seen[99]);";
    assert_eq!(eval(source), "11 22 11 22\n");
}

#[test]
fn the_global_variable_cache_notices_every_way_a_global_can_change() {
    // Each case primes one `get_var` site in a loop and then changes the global that site
    // reads. Expected values are from `oracle/quickjs-master/qjs`.
    let cases = [
        // Redefined in place, same index, same length.
        (
            "var A = 11; function p() { return A; } for (var i = 0; i < 20; i++) p();",
            "Object.defineProperty(globalThis, 'A', { value: 99, writable: true });",
            "p()",
            "99",
        ),
        // An own data property turned into an accessor: the read must run the getter, so
        // the cached index may not be answered. The global has to be *implicit* (`B = 1`
        // with no declaration) — a `var` global is non-configurable, so redefining it
        // throws in the reference too, and the case would test nothing.
        (
            "B = 1; function p() { return B; } for (var i = 0; i < 20; i++) p();",
            "Object.defineProperty(globalThis, 'B', { get: function () { return 77; } });",
            "p()",
            "77",
        ),
        // Another global appears, which the entry's index would survive but must not
        // answer for.
        (
            "var C = 1; function p() { return C; } for (var i = 0; i < 20; i++) p();",
            "globalThis.ZZ = 9;",
            "p()",
            "1",
        ),
        // A plain write.
        (
            "var D = 1; function p() { return D; } for (var i = 0; i < 20; i++) p();",
            "D = 5;",
            "p()",
            "5",
        ),
        // A closure reading a global: `get_var` again, through the closure's own code.
        (
            "var E = 3; function outer() { return function () { return E; } } \
             var p = outer(); for (var i = 0; i < 20; i++) p();",
            "E = 4;",
            "p()",
            "4",
        ),
        // A `var` a direct `eval` added, read through a call site that had already been
        // primed reading something else on the same slot.
        (
            "var F = 1; function p() { return F; } for (var i = 0; i < 20; i++) p(); \
             eval('var added = 8;');",
            "",
            "p() + ',' + added",
            "1,8",
        ),
    ];
    for (setup, mutate, read, expected) in cases {
        let got = eval(&format!("{setup}\n{mutate}\nprint({read});"));
        assert_eq!(
            got,
            format!("{expected}\n"),
            "case: {setup} {mutate} {read}"
        );
    }
}

#[test]
fn a_lexical_global_never_goes_through_the_variable_cache() {
    // `let`/`const` live in a side table, not on the global object, so the cache — which
    // remembers an index into the object's property table — cannot describe them. The
    // presence test in `global_binding` is what keeps them off that path.
    let source = "let L = 3; const C = 4;\n\
         function p() { return L + C; }\n\
         for (var i = 0; i < 20; i++) p();\n\
         print(p());\n\
         try { L } catch (e) { print('no'); }\n\
         print(typeof globalThis.L);";
    assert_eq!(eval(source), "7\nundefined\n");
}

#[test]
fn a_scoped_read_never_answers_from_the_global_cache() {
    // `run_fast` answers a `get_var` only when `get_global`'s first branch applies: not
    // lexical, and no `eval` in scope. Expected values from
    // `oracle/quickjs-master/qjs`.
    //
    // Note what this does *not* cover. A `with (o) { x }` does not reach `get_var` at
    // all — the compiler turns it into a `in` test plus `get_array_el` — so a `with`
    // case would pass with the guard removed. Verified by deleting the
    // `scopes_are_plain` call from `fast_get_plain_global`: these tests still passed. The
    // guard stays because it is the condition `get_global` documents, but the tests below
    // cannot prove it, and saying so is more useful than a test that looks like it does.
    let source = "var x = 1;\n\
         function plain() { return x; }\n\
         for (var i = 0; i < 50; i++) plain();\n\
         print(plain());\n\
         function insideEval() { eval('var x = 42'); return x; }\n\
         print(insideEval());\n\
         function closure() { var v = 5; return function () { return x + v; }; }\n\
         var f = closure();\n\
         print(f());";
    assert_eq!(eval(source), "1\n42\n6\n");
}

#[test]
fn a_global_added_by_eval_is_seen_by_an_already_primed_site() {
    // The call site below is primed while `y` does not exist (so the cache slot holds
    // nothing and every read falls to the slow path), then `eval` creates it. The fast
    // arm must not have cached a miss.
    let source = "function read() { return y; }\n\
         try { read(); } catch (e) { print(e.name); }\n\
         eval('var y = 7;');\n\
         print(read());";
    assert_eq!(eval(source), "ReferenceError\n7\n");
}