quickjs-pure 0.17.29

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
//! `Number`, `Boolean`, `parseInt`/`parseFloat`/`isNaN`/`isFinite`, `eval` and the
//! remaining global functions.

use crate::bignum::Big;
use crate::builtins::{arg, define_method};
use crate::interp::{Interp, JsResult};
use crate::object::{JsObject, Property};
use crate::value::{Value, number_to_string, string_to_number};
use js_gc::Gc;
use std::cmp::Ordering;

/// Install `Number` and `Number.prototype`.
pub fn install(interp: &mut Interp<'_>, number_proto: &Gc<JsObject>) {
    define_method(number_proto, "toString", 1, to_string, interp);
    define_method(number_proto, "toFixed", 1, to_fixed, interp);
    define_method(number_proto, "toExponential", 1, to_exponential, interp);
    define_method(number_proto, "toPrecision", 1, to_precision, interp);
    define_method(number_proto, "valueOf", 0, value_of, interp);
    // Without this, `Number.prototype.toLocaleString` was `Object.prototype`'s, which runs
    // `this.toString()` on the *wrapper* and answers `"[object Number]"`.
    define_method(number_proto, "toLocaleString", 0, to_locale_string, interp);

    let constructor = interp.new_native_constructor("Number", 1, constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(number_proto.clone()), false, false),
    );
    number_proto.define(
        "constructor",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );
    for (name, value) in [
        ("MAX_VALUE", f64::MAX),
        ("MIN_VALUE", 5e-324),
        ("MAX_SAFE_INTEGER", 9007199254740991.0),
        ("MIN_SAFE_INTEGER", -9007199254740991.0),
        ("EPSILON", f64::EPSILON),
        ("POSITIVE_INFINITY", f64::INFINITY),
        ("NEGATIVE_INFINITY", f64::NEG_INFINITY),
        ("NaN", f64::NAN),
    ] {
        constructor.define(
            name,
            Property::with_attributes(Value::Float(value), false, false),
        );
    }
    for (name, length, func) in [
        ("isNaN", 1, is_nan as crate::object::NativeFn),
        ("isFinite", 1, is_finite),
        ("isInteger", 1, is_integer),
        ("isSafeInteger", 1, is_safe_integer),
        // §21.1.2.13/§21.1.2.12: the *same function objects* as the globals — `Number.parseInt
        // === parseInt` is required, not merely equivalent behaviour. The bodies live in this
        // module already, so the globals call them too; only the wiring was missing, which
        // left `Number.parseInt` `undefined` while `parseInt` worked.
        ("parseInt", 2, parse_int),
        ("parseFloat", 1, parse_float),
    ] {
        define_method(&constructor, name, length, func, interp);
    }
    let global = interp.realm.global.clone();
    global.define(
        "Number",
        Property::with_attributes(Value::Object(constructor), true, false),
    );
}

fn constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let number = match args.first() {
        None => Value::Int(0),
        // The one place a BigInt is accepted: `Number(1n)` is `1`, unlike `Math.max(1n)`
        // which is a `TypeError`. §21.1.1.1 says so explicitly, so it cannot share the
        // `ToNumber` refusal below.
        Some(Value::BigInt(big)) => Value::Float(big.to_f64()),
        // Everything else is `ToNumber`, which refuses a Symbol and unwraps an object
        // through `ToPrimitive` first — so `Number(Symbol())` is a `TypeError` rather
        // than `NaN`, and `Number(Object(Symbol()))` is too.
        Some(value) => Value::Float(interp.to_js_number(value)?),
    };
    // `new Number(1)` is a wrapper object, so the number has to be stored on the
    // receiver: without it `Number.prototype.valueOf` finds no `_value` and every
    // `ToPrimitive` step on a wrapper throws. Called as a plain function there is no
    // receiver and the primitive is the answer.
    if let Value::Object(object) = &this {
        interp.internal_set(object, "_value", number);
        return Ok(this);
    }
    let _ = interp;
    Ok(number)
}

/// The receiver as a number, unboxing a wrapper object.
fn number_of(interp: &Interp<'_>, this: &Value) -> Result<f64, crate::interp::Signal> {
    match this {
        Value::Int(_) | Value::Float(_) => Ok(this.to_number()),
        // The slot has to hold a *number*: `to_number()` would happily convert a string
        // or a boolean box, so `Number.prototype.valueOf.call(new String("x"))` answered
        // `NaN` instead of throwing. `thisNumberValue` is a brand check, not a coercion.
        Value::Object(object) => match interp.internal_get(object, "_value") {
            Some(value @ (Value::Int(_) | Value::Float(_))) => Ok(value.to_number()),
            _ => Err(interp.type_error("Number method on a non-number")),
        },
        _ => Err(interp.type_error("Number method on a non-number")),
    }
}

/// `Number.prototype.toLocaleString`, which is `toString` when there is no `Intl`.
fn to_locale_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let value = number_of(interp, &this)?;
    Ok(interp.string(number_to_string(value)))
}

fn to_string(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let value = number_of(interp, &this)?;
    let radix = match args.first() {
        None | Some(Value::Undefined) => return Ok(interp.string(number_to_string(value))),
        // `ToNumber`, so a Symbol or a BigInt raises `TypeError` rather than quietly
        // becoming radix 0.
        Some(other) => interp.to_js_number(other)? as u32,
    };
    if radix == 10 {
        return Ok(interp.string(number_to_string(value)));
    }
    if !(2..=36).contains(&radix) {
        return Err(interp.range_error("toString radix must be between 2 and 36"));
    }
    if !value.is_finite() {
        return Ok(interp.string(number_to_string(value)));
    }
    Ok(interp.string(radix_string(value, radix)))
}

/// `number.toString(radix)` for a radix other than ten.
///
/// The answer is the shortest digit string that reads back as the same double, decided
/// the way the reference decides it: in exact integer arithmetic. The value is held as
/// `mantissa * 2^exponent`, a candidate of `digits` significant digits is obtained by
/// rounding `value / radix^place` to nearest-even with [`Big`], and the candidate is
/// accepted when `candidate * radix^place` lands inside the interval that rounds back
/// to the original double. Searching `digits` upwards finds the shortest such candidate;
/// the search bound is `1 + ceil(53 / log2(radix))`, which is the reference's
/// `dtoa_max_digits_table`.
///
/// The previous version grew a float `delta` alongside the fraction and stopped when the
/// remainder dropped below it. That is the right idea and the wrong arithmetic: for
/// `(1.3).toString(7)` the error accumulated over the multiply-and-subtract loop and it
/// stopped one digit early with the last digit misrounded, printing
/// `1.204620462046204621` where the reference prints `1.2046204620462046205`.
fn radix_string(value: f64, radix: u32) -> String {
    if value == 0.0 {
        return "0".to_string();
    }
    let negative = value < 0.0;
    let magnitude = value.abs();
    let bits = magnitude.to_bits();
    let biased_exponent = ((bits >> 52) & 0x7ff) as i32;
    let fraction = bits & ((1u64 << 52) - 1);
    // `magnitude == mantissa * 2^exponent`, exactly. A subnormal keeps its 52 mantissa
    // bits and shares the minimum exponent, which is also the spacing between doubles
    // there, so the interval below needs no special case.
    let (mantissa, exponent) = if biased_exponent == 0 {
        (fraction, -1074)
    } else {
        (fraction | (1u64 << 52), biased_exponent - 1075)
    };

    // The number of significant digits that always suffices for this radix.
    let max_digits = 1 + (53.0 / (radix as f64).log2()).ceil() as u32;
    // Where the radix point falls: the smallest `point` with `radix^(point-1) <= value`.
    let point = radix_point(magnitude, mantissa, exponent, radix);

    let mut candidate = (Big::zero(), 0);
    for digits in 1..=max_digits {
        // `value ≈ scaled * radix^place`, with `scaled` the `digits`-digit mantissa.
        let mut place = point - digits as i32;
        let mut scaled = scaled_round(mantissa, exponent, radix, place);
        // Rounding can carry into one more digit (`1/3` in radix 3 rounds to `3`, which
        // is two digits). The reference bumps its exponent in that case and tries again;
        // at most one bump is possible, because the carry adds at most one digit.
        if scaled.to_radix_string(radix).len() > digits as usize {
            place += 1;
            scaled = scaled_round(mantissa, exponent, radix, place);
        }
        if scaled.is_zero() {
            continue;
        }
        candidate = (scaled, place);
        if round_trips(&candidate.0, place, radix, mantissa, exponent) {
            break;
        }
    }
    // The shortest candidate wins; the widest one is guaranteed to work, so the loop
    // always leaves something usable here even if no early acceptance happened.
    let (scaled, place) = candidate;
    let mut out = String::new();
    if negative {
        out.push('-');
    }
    out.push_str(&place_radix_point(&scaled, place, radix));
    out
}

/// Lay `value = scaled * radix^place` out with the radix point in place.
fn place_radix_point(scaled: &Big, place: i32, radix: u32) -> String {
    let digits = scaled.to_radix_string(radix);
    let length = digits.len() as i32;
    let point = length + place;
    if point <= 0 {
        // Purely fractional: `0.` then the zeros the value needs, then the digits.
        let mut out = String::from("0.");
        out.extend(std::iter::repeat_n('0', (-point) as usize));
        out.push_str(&digits);
        out
    } else if point >= length {
        // Integral: the digits, then the zeros the value needs to reach the point.
        let mut out = digits;
        out.extend(std::iter::repeat_n('0', (point - length) as usize));
        out
    } else {
        let (whole, rest) = digits.split_at(point as usize);
        format!("{whole}.{rest}")
    }
}

/// The smallest `point` with `radix^(point-1) <= value < radix^point`.
///
/// The logarithm gives the answer almost always; the correction loops make it exact,
/// because `f64::log2` is not trustworthy at the boundaries and a wrong `point` would
/// shift every digit of the output by one place.
///
/// `magnitude` is passed in rather than rebuilt from the mantissa: `mantissa *
/// 2^exponent` underflows to zero for the smallest subnormals, and a zero magnitude
/// sends `log2` to negative infinity and the correction loop off the end of `i32`.
fn radix_point(magnitude: f64, mantissa: u64, exponent: i32, radix: u32) -> i32 {
    let mut point = (magnitude.log2() / (radix as f64).log2()).floor() as i32 + 1;
    while compare_power(mantissa, exponent, point - 1, radix) == Ordering::Less {
        point -= 1;
    }
    while compare_power(mantissa, exponent, point, radix) != Ordering::Less {
        point += 1;
    }
    point
}

/// Compare `mantissa * 2^exponent` with `radix^power`.
fn compare_power(mantissa: u64, exponent: i32, power: i32, radix: u32) -> Ordering {
    let (value_num, value_den) = scaled_exact(&Big::from_u64(mantissa), exponent, radix, 0);
    let (power_num, power_den) = scaled_exact(&Big::one(), 0, radix, power);
    value_num.mul(&power_den).cmp(&power_num.mul(&value_den))
}

/// `base * 2^exponent * radix^place` as an exact fraction.
fn scaled_exact(base: &Big, exponent: i32, radix: u32, place: i32) -> (Big, Big) {
    let mut num = base.clone();
    let mut den = Big::one();
    if exponent >= 0 {
        num.shl(exponent as u32);
    } else {
        den.shl((-exponent) as u32);
    }
    if place >= 0 {
        num.mul_pow(radix, place as u32);
    } else {
        den.mul_pow(radix, (-place) as u32);
    }
    (num, den)
}

/// `round(value / radix^place)`, ties to even — the reference's `JS_RNDN`.
fn scaled_round(mantissa: u64, exponent: i32, radix: u32, place: i32) -> Big {
    // Dividing by `radix^place` is multiplying by `radix^-place`.
    let (num, den) = scaled_exact(&Big::from_u64(mantissa), exponent, radix, -place);
    let (mut quotient, remainder) = num.div_rem_radix(&den, radix);
    let mut twice = remainder;
    twice.mul_small(2);
    match twice.cmp(&den) {
        Ordering::Greater => quotient.add_one(),
        // A tie goes to the even neighbour, matching round-to-nearest-even.
        Ordering::Equal if quotient.is_odd() => quotient.add_one(),
        _ => {}
    }
    quotient
}

/// Whether `scaled * radix^place` rounds back to the original double.
///
/// The doubles that round to `mantissa * 2^exponent` are the ones inside
/// `value ± half an ulp`. The ulp is `2^exponent`, except just above a power of two,
/// where the spacing below is half that — hence the `1 << 52` test. A candidate exactly
/// on a boundary rounds to whichever neighbour is even, so the endpoints are included
/// only when the mantissa is even.
fn round_trips(scaled: &Big, place: i32, radix: u32, mantissa: u64, exponent: i32) -> bool {
    let (value_num, value_den) = scaled_exact(scaled, 0, radix, place);
    let inclusive = mantissa % 2 == 0;
    // Upper: `(mantissa * 2 + 1) * 2^(exponent - 1)`; lower, past a power of two:
    // `(mantissa * 4 - 1) * 2^(exponent - 2)`.
    let lower_half_bits = if mantissa == 1 << 52 { 2 } else { 1 };
    let upper = compare_bound(&value_num, &value_den, mantissa, exponent, 1, 1);
    let lower = compare_bound(
        &value_num,
        &value_den,
        mantissa,
        exponent,
        lower_half_bits,
        -1,
    );
    let below_upper = match upper {
        Ordering::Equal => inclusive,
        other => other == Ordering::Less,
    };
    let above_lower = match lower {
        Ordering::Equal => inclusive,
        other => other == Ordering::Greater,
    };
    below_upper && above_lower
}

/// Compare `value_num / value_den` with `(mantissa * 2^half_bits + sign) * 2^(exponent - half_bits)`.
fn compare_bound(
    value_num: &Big,
    value_den: &Big,
    mantissa: u64,
    exponent: i32,
    half_bits: u32,
    sign: i64,
) -> Ordering {
    // `mantissa * 2^half_bits` fits comfortably: the mantissa uses at most 53 bits.
    let mut bound_num = Big::from_u64(mantissa << half_bits);
    if sign < 0 {
        bound_num.sub_one();
    } else {
        bound_num.add_one();
    }
    let mut bound_den = Big::one();
    let shift = exponent - half_bits as i32;
    if shift >= 0 {
        bound_num.shl(shift as u32);
    } else {
        bound_den.shl((-shift) as u32);
    }
    value_num.mul(&bound_den).cmp(&bound_num.mul(value_den))
}

/// `ToIntegerOrInfinity`, saturated to `i64`.
///
/// Every caller range-checks the answer, and every legal range is far inside `i64`, so
/// saturating keeps `Infinity` and `1e300` in one out-of-range bucket without a separate
/// flag. `NaN` is `+0`, which is what `ToIntegerOrInfinity` asks for.
fn to_integer(interp: &mut Interp<'_>, value: &Value) -> JsResult<i64> {
    let number = interp.to_js_number(value)?;
    // `as` on `f64` saturates, so no explicit infinity check is needed.
    Ok(if number.is_nan() {
        0
    } else {
        number.trunc() as i64
    })
}

/// The exact decimal expansion of a finite, positive `value`, as `(digits, exponent)`
/// meaning `value = 0.<digits> × 10^(exponent + 1)`. Trailing zeros are stripped.
///
/// The three `toFixed`/`toExponential`/`toPrecision` conversions all have to round the
/// *exact* decimal value of the `double`, half away from zero. Doing the arithmetic in
/// `f64` gets the wrong answer as soon as the digit asked for is past the ~16 that `f64`
/// itself carries: `(123.456).toExponential(17)` is `1.23456000000000003e+2`, because the
/// `double` is `123.456000000000003069…`.
///
/// Rust's float formatting expands the value exactly for any precision — it falls back to
/// a bignum expansion rather than rounding — so asking for more digits than a `double` can
/// possibly need yields the exact value padded with zeros. 767 digits is the worst case (a
/// subnormal); 780 leaves headroom.
fn exact_decimal(value: f64) -> (String, i32) {
    debug_assert!(value.is_finite() && value > 0.0);
    let text = format!("{value:.780e}");
    let (mantissa, exponent) = text.split_once('e').expect("`LowerExp` writes an `e`");
    let exponent: i32 = exponent
        .parse()
        .expect("a `double`'s exponent fits in `i32`");
    let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
    let trimmed = digits.trim_end_matches('0');
    // `value > 0`, so at least the leading digit survives.
    (trimmed.to_string(), exponent)
}

/// Round `digits` from [`exact_decimal`] to `keep` significant digits, half away from
/// zero — the rule all three conversions use, and one that only makes sense on the exact
/// decimal: the discard is a tie exactly when its first digit is `5` and everything after
/// it is zero, and rounding a tie up is the same as rounding up anything `>= 5`.
///
/// Answers the new digits, padded to `keep` — or `keep + 1` long when rounding carried out
/// of the leading digit (`999 → 1000`), in which case the exponent rises by one and the
/// caller's own padding restores the length.
fn round_significant(digits: &str, exponent: i32, keep: usize) -> (String, i32) {
    debug_assert!(keep >= 1);
    let mut kept: Vec<u8> = digits.bytes().take(keep).collect();
    let round_up = digits
        .as_bytes()
        .get(keep)
        .is_some_and(|next| *next >= b'5');
    kept.resize(keep, b'0');
    if round_up {
        let mut index = kept.len();
        loop {
            if index == 0 {
                // Every digit carried, so the significand becomes `10…0` one order up.
                let mut carried = vec![b'1'];
                carried.resize(kept.len(), b'0');
                let carried = String::from_utf8(carried).expect("ASCII digits");
                return (carried, exponent + 1);
            }
            index -= 1;
            if kept[index] == b'9' {
                kept[index] = b'0';
            } else {
                kept[index] += 1;
                break;
            }
        }
    }
    (String::from_utf8(kept).expect("ASCII digits"), exponent)
}

/// `digits`/`exponent` (i.e. `0.<digits> × 10^(exponent + 1)`) spelled positionally with
/// exactly `decimals` fraction digits, padding on either side as needed.
fn positional(digits: &str, exponent: i32, decimals: usize) -> String {
    let mut text = digits.to_string();
    // One digit per place from `10^exponent` down to `10^-decimals`.
    let total = (exponent + 1 + decimals as i32).max(0) as usize;
    text.truncate(total);
    while text.len() < total {
        text.push('0');
    }
    if decimals == 0 {
        return text;
    }
    // A value below the first fraction place needs its digits pushed right, and a `0` in
    // front so the result is `0.00…` and never `.00…`.
    while text.len() <= decimals {
        text.insert(0, '0');
    }
    let split = text.len() - decimals;
    format!("{}.{}", &text[..split], &text[split..])
}

fn to_fixed(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let value = number_of(interp, &this)?;
    // §21.1.3.3 step 2: `ToIntegerOrInfinity` runs first, so a Symbol argument is a
    // `TypeError` rather than a `RangeError` about a fractional count, and `-0` is
    // accepted as `0` — `(3).toFixed(-0)` is `"3"`.
    let digits = to_integer(interp, &arg(args, 0))?;
    // Step 3 is checked before the value is looked at, which is why `NaN.toFixed(101)` is
    // a `RangeError` and not `"NaN"`.
    if !(0..=100).contains(&digits) {
        return Err(interp.range_error("toFixed argument out of range"));
    }
    let digits = digits as usize;
    if !value.is_finite() {
        return Ok(interp.string(number_to_string(value)));
    }
    // Step 6: at `10^21` and above the fixed notation is abandoned for `ToString(x)`, so
    // `(1e21).toFixed()` is `"1e+21"` and not 22 digits. `-0` keeps no sign, since `x < 0`
    // is false for it.
    if value.abs() >= 1e21 {
        return Ok(interp.string(number_to_string(value)));
    }
    let sign = if value < 0.0 { "-" } else { "" };
    let magnitude = value.abs();
    if magnitude == 0.0 {
        return Ok(interp.string(format!("{sign}{}", positional("0", 0, digits))));
    }
    let (exact, exponent) = exact_decimal(magnitude);
    // Significant digits that survive the rounding: everything down to `10^-digits`.
    let keep = exponent + 1 + digits as i32;
    let text = if keep < 0 {
        // Entirely below the last place asked for: `(0.0004).toFixed(2)` is `"0.00"`.
        positional("0", 0, digits)
    } else if keep == 0 {
        // The leading digit *is* the rounding digit: `(0.009).toFixed(2)` is `"0.01"`.
        let lead = if exact.as_bytes()[0] >= b'5' {
            "1"
        } else {
            "0"
        };
        // That digit sits in the last fraction place, i.e. at `10^-digits`.
        positional(lead, -(digits as i32), digits)
    } else {
        let (rounded, exponent) = round_significant(&exact, exponent, keep as usize);
        positional(&rounded, exponent, digits)
    };
    Ok(interp.string(format!("{sign}{text}")))
}

fn to_exponential(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let value = number_of(interp, &this)?;
    // §21.1.3.2 step 2 comes before step 4: the argument is converted even when the value
    // is `NaN` or infinite, so `NaN.toExponential(Symbol())` is a `TypeError`.
    let omitted = matches!(args.first(), None | Some(Value::Undefined));
    let digits = to_integer(interp, &arg(args, 0))?;
    if !value.is_finite() {
        return Ok(interp.string(number_to_string(value)));
    }
    // Step 5, again before the value is looked at.
    if !(0..=100).contains(&digits) {
        return Err(interp.range_error("toExponential argument out of range"));
    }
    let digits = digits as usize;
    if omitted {
        // Step 10.a: with no argument, as many digits as the value needs.
        return Ok(interp.string(normalise(&format!("{value:e}"))));
    }
    let sign = if value < 0.0 { "-" } else { "" };
    let magnitude = value.abs();
    if magnitude == 0.0 {
        // Step 9: `0` spelled with `digits` fraction places and exponent `+0`.
        let mantissa = match digits {
            0 => "0".to_string(),
            count => format!("0.{}", "0".repeat(count)),
        };
        return Ok(interp.string(format!("{sign}{mantissa}e+0")));
    }
    let (exact, exponent) = exact_decimal(magnitude);
    let (rounded, exponent) = round_significant(&exact, exponent, digits + 1);
    let mantissa = match digits {
        0 => rounded.clone(),
        count => format!("{}.{}", &rounded[..1], &rounded[1..count + 1]),
    };
    Ok(interp.string(format!("{sign}{mantissa}e{exponent:+}")))
}

fn to_precision(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let value = number_of(interp, &this)?;
    // Step 2: no argument at all means `ToString(x)`, with no conversion and no rounding.
    if matches!(args.first(), None | Some(Value::Undefined)) {
        return Ok(interp.string(number_to_string(value)));
    }
    // Step 3: the precision is converted first, which both `nan` and `infinity` check —
    // `NaN.toPrecision(Symbol())` is a `TypeError`, and the `valueOf` runs exactly once.
    let precision = to_integer(interp, &arg(args, 0))?;
    // Steps 4 and 7: a non-finite value is answered before the range check, so
    // `(Infinity).toPrecision(1000)` is `"Infinity"` rather than a `RangeError`.
    if !value.is_finite() {
        return Ok(interp.string(number_to_string(value)));
    }
    if !(1..=100).contains(&precision) {
        return Err(interp.range_error("toPrecision argument out of range"));
    }
    let precision = precision as usize;
    let sign = if value < 0.0 { "-" } else { "" };
    let magnitude = value.abs();
    if magnitude == 0.0 {
        let text = match precision {
            1 => "0".to_string(),
            count => format!("0.{}", "0".repeat(count - 1)),
        };
        return Ok(interp.string(format!("{sign}{text}")));
    }
    let (exact, exponent) = exact_decimal(magnitude);
    let (rounded, exponent) = round_significant(&exact, exponent, precision);
    // Step 10.b.iii: exponential notation when the exponent leaves `[-7, p)`. The test is
    // on the exponent *after* rounding, which is why `0.9999` — stored just under one —
    // prints as `1e+0` at one significant digit but as `9.999e-1` at four.
    let text = if exponent < -7 || exponent >= precision as i32 {
        let mantissa = match precision {
            1 => rounded.clone(),
            count => format!("{}.{}", &rounded[..1], &rounded[1..count]),
        };
        format!("{mantissa}e{exponent:+}")
    } else {
        let decimals = (precision as i32 - 1 - exponent).max(0) as usize;
        positional(&rounded, exponent, decimals)
    };
    Ok(interp.string(format!("{sign}{text}")))
}

/// Rewrite Rust's `1e5` as JavaScript's `1e+5`.
fn normalise(text: &str) -> String {
    match text.split_once('e') {
        Some((mantissa, exponent)) if !exponent.starts_with('-') => {
            format!("{mantissa}e+{}", exponent.trim_start_matches('+'))
        }
        _ => text.to_string(),
    }
}

fn value_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(Value::Float(number_of(interp, &this)?))
}

fn is_nan(_interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // Unlike the global `isNaN`, this one does not coerce: `Number.isNaN("x")` is
    // `false` because a string is not the number NaN.
    Ok(Value::Bool(match arg(args, 0) {
        Value::Int(_) | Value::Float(_) => arg(args, 0).to_number().is_nan(),
        _ => false,
    }))
}

fn is_finite(_interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let value = arg(args, 0);
    Ok(Value::Bool(match value {
        Value::Int(_) | Value::Float(_) => value.to_number().is_finite(),
        _ => false,
    }))
}

fn is_integer(_interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let value = arg(args, 0);
    Ok(Value::Bool(match value {
        Value::Int(_) | Value::Float(_) => {
            let number = value.to_number();
            number.is_finite() && number == number.trunc()
        }
        _ => false,
    }))
}

fn is_safe_integer(_interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let value = arg(args, 0);
    Ok(Value::Bool(match value {
        Value::Int(_) | Value::Float(_) => {
            let number = value.to_number();
            number.is_finite() && number == number.trunc() && number.abs() <= 9007199254740991.0
        }
        _ => false,
    }))
}

/// Install `Boolean`.
pub fn install_boolean(interp: &mut Interp<'_>, boolean_proto: &Gc<JsObject>) {
    define_method(boolean_proto, "toString", 0, boolean_to_string, interp);
    // **No** `Boolean.prototype.toLocaleString`: §20.4.3 names only `toString` and
    // `valueOf`, so `true.toLocaleString()` has to reach `Object.prototype`'s — which runs
    // `this.toString()` and therefore lets a test that overrides `Boolean.prototype.toString`
    // observe its own override. Defining a second copy here shadowed that, and
    // `Object/prototype/toLocaleString/primitive_this_value` caught it as
    // `true.toLocaleString() === "true"` instead of the override's answer.
    define_method(boolean_proto, "valueOf", 0, boolean_value_of, interp);
    let constructor = interp.new_native_constructor("Boolean", 1, boolean_constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(boolean_proto.clone()), false, false),
    );
    boolean_proto.define(
        "constructor",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );
    let global = interp.realm.global.clone();
    global.define(
        "Boolean",
        Property::with_attributes(Value::Object(constructor), true, false),
    );
}

fn boolean_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let flag = Value::Bool(arg(args, 0).to_boolean());
    // Same wrapper rule as `Number`: `new Boolean(true)` stores the primitive.
    if let Value::Object(object) = &this {
        interp.internal_set(object, "_value", flag);
        return Ok(this);
    }
    let _ = interp;
    Ok(flag)
}

fn boolean_receiver(interp: &Interp<'_>, this: &Value) -> Result<bool, crate::interp::Signal> {
    match this {
        Value::Bool(value) => Ok(*value),
        // A brand check, not a coercion: `to_boolean()` accepts anything, so a String
        // box passed the test and `Boolean.prototype.valueOf.call(new String())` answered
        // `false` instead of throwing.
        Value::Object(object) => match interp.internal_get(object, "_value") {
            Some(Value::Bool(value)) => Ok(value),
            _ => Err(interp.type_error("Boolean method on a non-boolean")),
        },
        _ => Err(interp.type_error("Boolean method on a non-boolean")),
    }
}

fn boolean_to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let value = boolean_receiver(interp, &this)?;
    Ok(interp.string(if value { "true" } else { "false" }))
}

fn boolean_value_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(Value::Bool(boolean_receiver(interp, &this)?))
}

/// `parseInt(text, radix)`.
///
/// The rules that surprise people and are therefore worth stating: leading
/// whitespace is skipped, an optional sign is allowed, a `0x` prefix implies radix
/// 16, and parsing stops at the first invalid digit rather than failing.
pub fn parse_int(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `ToString(string)`, so an object runs `ToPrimitive` — `parseInt(new Number(-1))` is
    // `-1`, not `NaN` from the `"[object Number]"` the total conversion renders. `trim_start`
    // is the spec's `StrWhiteSpace` trim, which is what makes `parseInt(" -1 ")` work.
    let text = interp.to_js_string(&arg(args, 0))?;
    let text = text.trim_start();
    let (sign, rest) = match text.strip_prefix('-') {
        Some(rest) => (-1.0, rest),
        None => (1.0, text.strip_prefix('+').unwrap_or(text)),
    };
    let explicit = match args.get(1) {
        None | Some(Value::Undefined) => 0,
        // `ToInt32(radix)`, so `parseInt("11", new Number(2))` is radix 2 and
        // `parseInt("11", new Boolean(true))` is radix 1 — out of range, hence `NaN`.
        Some(value) => Value::Float(interp.to_js_number(value)?).to_int32() as u32,
    };
    let (radix, rest) = if explicit == 0 {
        match rest.strip_prefix("0x").or_else(|| rest.strip_prefix("0X")) {
            Some(rest) => (16, rest),
            None => (10, rest),
        }
    } else {
        if !(2..=36).contains(&explicit) {
            return Ok(Value::Float(f64::NAN));
        }
        let rest = if explicit == 16 {
            rest.strip_prefix("0x")
                .or_else(|| rest.strip_prefix("0X"))
                .unwrap_or(rest)
        } else {
            rest
        };
        (explicit, rest)
    };
    let digits: String = rest.chars().take_while(|c| c.is_digit(radix)).collect();
    if digits.is_empty() {
        return Ok(Value::Float(f64::NAN));
    }
    let magnitude = i64::from_str_radix(&digits, radix)
        .map(|value| value as f64)
        .unwrap_or_else(|_| {
            digits.chars().fold(0.0, |acc, c| {
                acc * radix as f64 + c.to_digit(radix).unwrap_or(0) as f64
            })
        });
    let _ = interp;
    Ok(Value::Float(sign * magnitude))
}

/// `parseFloat(text)`, which also stops at the first invalid character.
pub fn parse_float(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `ToString`, so an object runs `ToPrimitive`: `parseFloat(new Number(-1.1))` is `-1.1`.
    let text = interp.to_js_string(&arg(args, 0))?;
    let trimmed = text.trim_start();
    // The longest prefix the number grammar accepts; `string_to_number` handles the
    // validation, so this only has to find where the prefix ends.
    let mut end = 0usize;
    let bytes = trimmed.as_bytes();
    let mut index = 0;
    if matches!(bytes.first(), Some(b'+' | b'-')) {
        index += 1;
    }
    if trimmed[index..].starts_with("Infinity") {
        end = index + "Infinity".len();
    } else {
        let mut digits = 0;
        while index < bytes.len() && bytes[index].is_ascii_digit() {
            index += 1;
            digits += 1;
        }
        if index < bytes.len() && bytes[index] == b'.' {
            index += 1;
            while index < bytes.len() && bytes[index].is_ascii_digit() {
                index += 1;
                digits += 1;
            }
        }
        if digits > 0 {
            if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
                let mut probe = index + 1;
                if probe < bytes.len() && (bytes[probe] == b'+' || bytes[probe] == b'-') {
                    probe += 1;
                }
                let start = probe;
                while probe < bytes.len() && bytes[probe].is_ascii_digit() {
                    probe += 1;
                }
                if probe > start {
                    index = probe;
                }
            }
            end = index;
        }
    }
    let _ = interp;
    Ok(Value::Float(if end == 0 {
        f64::NAN
    } else {
        string_to_number(&trimmed[..end])
    }))
}

/// The global `isNaN`, which coerces first.
/// §19.2.2 `isNaN(number)`.
///
/// `ToNumber`, which is `ToPrimitive` + a numeric conversion — **not**
/// `Value::to_number`, the engine's total no-script conversion. The difference is every
/// case in `isNaN/toprimitive-*`: an object argument has to run its `valueOf`, a symbol is a
/// `TypeError`, and a `@@toPrimitive` that answers an object is a `TypeError` too. With the
/// total conversion all nine of those answered `false` without complaining.
pub fn global_is_nan(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let number = interp.to_js_number(&arg(args, 0))?;
    Ok(Value::Bool(number.is_nan()))
}

/// §19.2.3 `isFinite(number)`: `ToNumber` first, for the same reason.
pub fn global_is_finite(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let number = interp.to_js_number(&arg(args, 0))?;
    Ok(Value::Bool(number.is_finite()))
}