quickjs-pure 0.17.19

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
//! `Math`.
//!
//! Two behaviours are easy to get wrong and both are covered by the reference's test
//! suite: `Math.round` rounds halves *up* rather than away from zero, so
//! `Math.round(-0.5)` is `-0` and not `-1`; and `Math.min`/`max` return `NaN` if any
//! argument is `NaN`, even though `Math.min(1, NaN)` could be read as `1`.

use crate::bigint::BigInt;
use crate::builtins::{arg, define_method, install_tag};
use crate::interp::{Interp, JsResult};
use crate::object::Property;
use crate::value::{Value, to_int32};

/// Install `Math`.
pub fn install(interp: &mut Interp<'_>) {
    let object_proto = interp.realm.object_proto.clone();
    let math = interp.new_object(Some(object_proto));
    // §21.3: `Object.prototype.toString.call(Math)` is `[object Math]`.
    install_tag(&math, "Math", interp);

    for (name, value) in [
        ("PI", std::f64::consts::PI),
        ("E", std::f64::consts::E),
        ("LN2", std::f64::consts::LN_2),
        ("LN10", std::f64::consts::LN_10),
        ("LOG2E", std::f64::consts::LOG2_E),
        ("LOG10E", std::f64::consts::LOG10_E),
        ("SQRT2", std::f64::consts::SQRT_2),
        ("SQRT1_2", std::f64::consts::FRAC_1_SQRT_2),
    ] {
        math.define(
            name,
            Property::with_attributes(Value::Float(value), false, false),
        );
    }
    for (name, length, func) in [
        ("abs", 1, abs as crate::object::NativeFn),
        ("floor", 1, floor),
        ("ceil", 1, ceil),
        ("round", 1, round),
        ("trunc", 1, trunc),
        ("sign", 1, sign),
        ("sqrt", 1, sqrt),
        ("cbrt", 1, cbrt),
        ("pow", 2, pow),
        ("exp", 1, exp),
        ("log", 1, log),
        ("log2", 1, log2),
        ("log10", 1, log10),
        ("sin", 1, sin),
        ("cos", 1, cos),
        ("tan", 1, tan),
        ("asin", 1, asin),
        ("acos", 1, acos),
        ("atan", 1, atan),
        ("atan2", 2, atan2),
        ("min", 2, min),
        ("max", 2, max),
        ("imul", 2, imul),
        ("hypot", 2, hypot),
        ("fround", 1, fround),
        ("f16round", 1, f16round),
        ("clz32", 1, clz32),
        ("random", 0, random),
        ("sumPrecise", 1, sum_precise),
    ] {
        define_method(&math, name, length, func, interp);
    }

    // The transcendental family. All eight are a straight `ToNumber` + one libm call, and
    // all eight were missing outright — `Math.acosh(1)` was `TypeError: undefined is not a
    // function`, which read like a caller bug and cost 42 test262 cases before
    // `scripts/builtin-surface.py` made it visible.
    //
    // Values, not just names: all eight are "implementation-approximated" in the spec
    // (§21.3.2), so a ULP here or there is conforming. Measured anyway — 200 probes
    // (8 functions x 25 inputs: ±0, ±1, ±Infinity, NaN, denormals, the overflow knee at
    // ±710) against the reference — and **one differs by 1 ULP**: `atanh(-0.5)` is
    // -0.5493061443340548 here and ...49 in the reference, because Rust computes it as
    // `0.5*ln((1+x)/(1-x))` while the reference calls the platform's `atanh`. Nothing in
    // test262 pins a transcendental to the last bit, and pinning it would tie this engine
    // to one libm; the deviation is recorded rather than chased
    // (`docs/test262-status.md` §4.42).
    for (name, func) in [
        ("acosh", acosh as crate::object::NativeFn),
        ("asinh", asinh),
        ("atanh", atanh),
        ("cosh", cosh),
        ("sinh", sinh),
        ("tanh", tanh),
        ("expm1", expm1),
        ("log1p", log1p),
    ] {
        define_method(&math, name, 1, func, interp);
    }

    let global = interp.realm.global.clone();
    global.define(
        "Math",
        Property::with_attributes(Value::Object(math), true, false),
    );
}

/// `ToNumber` for a `Math` argument.
///
/// `Value::to_number` is total and answers `NaN` for a BigInt, which left the engine
/// silently wrong here: `Math.max(1n)` is a `TypeError`, not `NaN`, because there is no
/// lossless number for a 2^70 integer. Every other `ToNumber` caller was moved onto
/// [`Interp::to_js_number`] when this was found; `Math` was missed because it does its own
/// coercion, so it kept answering `NaN` long after the rest of the engine refused.
/// `ToUint32`, which is `ToInt32` reinterpreted.
fn to_uint32(value: f64) -> u32 {
    to_int32(value) as u32
}

fn to_number(interp: &mut Interp<'_>, value: &Value) -> JsResult<f64> {
    interp.to_js_number(value)
}

/// [`to_number`] for the common case where the argument is already owned.
fn number_of(interp: &mut Interp<'_>, value: Value) -> JsResult<f64> {
    to_number(interp, &value)
}

fn unary(interp: &mut Interp<'_>, args: &[Value], f: impl Fn(f64) -> f64) -> JsResult<Value> {
    let value = number_of(interp, arg(args, 0))?;
    Ok(Value::Float(f(value)))
}

fn abs(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `abs(-0)` is `+0`, and `abs` of an integer stays an integer.
    Ok(match arg(args, 0) {
        Value::Int(value) => Value::Int(value.saturating_abs()),
        other => Value::Float(number_of(interp, other)?.abs()),
    })
}

fn floor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::floor)
}

fn ceil(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::ceil)
}

/// `Math.round`, which rounds halves toward `+∞`.
///
/// `(x + 0.5).floor()` would be wrong for negatives (`-0.5` would become `-1`), so
/// the half is added and the result clamped back for zero to keep `-0`.
fn round(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let value = number_of(interp, arg(args, 0))?;
    if !value.is_finite() {
        return Ok(Value::Float(value));
    }
    // §21.3.2.28 is "the integer closest to `x`, and the larger of the two when they are
    // equally close" — *not* `floor(x + 0.5)`. The two differ by a whole unit at the
    // boundary: `0.5 - 2^-54` rounds up, but `(0.5 - 2^-54) + 0.5` is not representable and
    // rounds to `1`, whose floor is also `1` (`S15.8.2.15_A7`).
    let floor = value.floor();
    let fraction = value - floor;
    let rounded = if fraction >= 0.5 { floor + 1.0 } else { floor };
    // A negative input that rounds to zero answers **-0**: the spec spells this out, and
    // the arithmetic gets it wrong — `-1 + 1` is `+0`.
    if rounded == 0.0 && value.is_sign_negative() {
        return Ok(Value::Float(-0.0));
    }
    Ok(Value::Float(rounded))
}

fn trunc(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::trunc)
}

fn sign(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let value = number_of(interp, arg(args, 0))?;
    Ok(Value::Float(if value.is_nan() {
        f64::NAN
    } else if value > 0.0 {
        1.0
    } else if value < 0.0 {
        -1.0
    } else {
        // `sign(-0)` is `-0`, `sign(0)` is `0`.
        value
    }))
}

fn sqrt(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::sqrt)
}

fn cbrt(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::cbrt)
}

fn pow(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let base = number_of(interp, arg(args, 0))?;
    let exponent = number_of(interp, arg(args, 1))?;
    // §21.3.2.26 says "the result of `base ** exponent`", and the exponentiation operator
    // follows IEEE 754-2019 rather than the old `pow`: `1 ** NaN` and `(-1) ** ±Infinity`
    // are **NaN**, where C's `powf` answers `1`.
    if exponent.is_nan() || (base.abs() == 1.0 && exponent.is_infinite()) {
        return Ok(Value::Float(f64::NAN));
    }
    Ok(Value::Float(base.powf(exponent)))
}

fn acosh(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::acosh)
}

fn asinh(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::asinh)
}

fn atanh(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::atanh)
}

fn cosh(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::cosh)
}

fn sinh(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::sinh)
}

fn tanh(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::tanh)
}

fn expm1(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::exp_m1)
}

fn log1p(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::ln_1p)
}

fn exp(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::exp)
}

fn log(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::ln)
}

fn log2(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::log2)
}

fn log10(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::log10)
}

fn sin(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::sin)
}

fn cos(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::cos)
}

fn tan(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::tan)
}

fn asin(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::asin)
}

fn acos(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::acos)
}

fn atan(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    unary(interp, args, f64::atan)
}

fn atan2(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let y = number_of(interp, arg(args, 0))?;
    let x = number_of(interp, arg(args, 1))?;
    let _ = interp;
    Ok(Value::Float(y.atan2(x)))
}

/// `Math.min`, which propagates `NaN` and normalises `-0`.
fn min(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    if args.is_empty() {
        return Ok(Value::Float(f64::INFINITY));
    }
    let mut best = f64::INFINITY;
    let mut saw_nan = false;
    for value in args {
        let number = to_number(interp, value)?;
        if number.is_nan() {
            saw_nan = true;
            continue;
        }
        if saw_nan {
            continue;
        }
        // `Math.min(0, -0)` is `-0`, so an equal comparison keeps the negative one.
        if number < best || (number == best && number.is_sign_negative()) {
            best = number;
        }
    }
    if saw_nan {
        return Ok(Value::Float(f64::NAN));
    }
    let _ = interp;
    Ok(Value::Float(best))
}

fn max(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    if args.is_empty() {
        return Ok(Value::Float(f64::NEG_INFINITY));
    }
    let mut best = f64::NEG_INFINITY;
    let mut saw_nan = false;
    for value in args {
        // Every argument is coerced, **even after a NaN**: §21.3.2.24 step 3 runs
        // `ToNumber(next)` for all of them and only then asks whether one was NaN.
        let number = to_number(interp, value)?;
        if number.is_nan() {
            saw_nan = true;
            continue;
        }
        if saw_nan {
            continue;
        }
        if number > best || (number == best && !number.is_sign_negative()) {
            best = number;
        }
    }
    if saw_nan {
        return Ok(Value::Float(f64::NAN));
    }
    let _ = interp;
    Ok(Value::Float(best))
}

/// `Math.imul`, the 32-bit wrapping multiply.
fn imul(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `ToInt32` runs `ToNumber` first, so a BigInt argument is refused here too.
    let a = to_int32(number_of(interp, arg(args, 0))?);
    let b = to_int32(number_of(interp, arg(args, 1))?);
    Ok(Value::Int(a.wrapping_mul(b)))
}

/// `Math.hypot`, which avoids intermediate overflow by scaling.
fn hypot(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let mut max = 0.0f64;
    let mut found_infinite = false;
    let mut found_nan = false;
    let numbers: Vec<f64> = {
        let mut numbers = Vec::with_capacity(args.len());
        for value in args {
            numbers.push(to_number(interp, value)?);
        }
        numbers
    };
    for number in &numbers {
        if number.is_infinite() {
            found_infinite = true;
        }
        if number.is_nan() {
            found_nan = true;
        }
        max = max.max(number.abs());
    }
    let _ = interp;
    if found_infinite {
        return Ok(Value::Float(f64::INFINITY));
    }
    if found_nan {
        return Ok(Value::Float(f64::NAN));
    }
    if max == 0.0 {
        return Ok(Value::Float(0.0));
    }
    let sum: f64 = numbers.iter().map(|value| (value / max).powi(2)).sum();
    Ok(Value::Float(max * sum.sqrt()))
}

/// `Math.fround`, rounding to the nearest `f32`.
fn fround(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let value = number_of(interp, arg(args, 0))?;
    let _ = interp;
    Ok(Value::Float(value as f32 as f64))
}

/// `Math.f16round`, rounding to the nearest `f16` (§21.3.2.16).
///
/// The spec's definition is `RoundHalfToEven` on the binary16 grid, which is exactly what
/// encoding to binary16 and decoding again does — so this calls the `Float16Array` pair
/// rather than growing a second rounding rule. That is not only shorter, it is the property
/// the test asserts: `Math.f16round(x)` has to equal what `new Float16Array([x])[0]`
/// stores, and two independent implementations of "nearest even on 11-bit significands"
/// can differ on the ties and the subnormal boundary.
///
/// Why it was missing at all is the interesting part: `Float16Array` shipped, `Math.f16round`
/// did not, so the companion function was absent while the thing it rounds *for* was
/// present. Five test262 cases, four of which only check the property's shape — the whole
/// failure was `Math.f16round is not a function`.
fn f16round(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let value = number_of(interp, arg(args, 0))?;
    let _ = interp;
    Ok(Value::Float(super::typedarray::f16_to_f64(
        super::typedarray::f64_to_f16(value),
    )))
}

/// `Math.clz32`, the count of leading zero bits.
fn clz32(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let value = to_uint32(number_of(interp, arg(args, 0))?);
    Ok(Value::Int(value.leading_zeros() as i32))
}

/// `Math.sumPrecise(values)`: the correctly rounded sum of an iterable.
///
/// Not a compensated accumulator. The defining property of this function is that the
/// result is the exact sum rounded *once*, so `[1, 2^-53, 2^-1074]` is
/// `1.0000000000000002`: the tiny terms break the tie that `2^-53` alone would lose,
/// while Kahan/Neumaier summation still rounds that final `1 + 2^-53` back to `1`.
///
/// The accumulator is an **exact expansion** — Shewchuk's algorithm, the one CPython's
/// `math.fsum` uses — not a fixed three-term one. A three-term expansion carries about
/// 159 bits, which is exact only while the sum's dynamic range fits in that; the moment a
/// `1e308` and a `1e-1` meet it has to give up, and
/// `[1e308, 1e308, 0.1, 0.1, 1e30, 0.1, -1e30, -1e308, -1e308]` came back `Infinity`
/// instead of `0.30000000000000004` (`sumPrecise/sum`).
fn sum_precise(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // §21.3.2.34 step 3 is `GetIterator(items, sync)`: any **iterable** works, so a
    // generator and an array with an overridden `@@iterator` both count.
    let iterable = arg(args, 0);
    if iterable.as_object().is_none() {
        return Err(interp.type_error("Math.sumPrecise argument is not iterable"));
    }
    let iterator = interp.get_iterator(&iterable)?;
    let mut expansion = Expansion::default();
    let mut seen = false;
    loop {
        let (element, done) = interp.iterator_step(&iterator)?;
        if done {
            break;
        }
        if !matches!(element, Value::Int(_) | Value::Float(_)) {
            let _ = interp.close_iterator(&iterator);
            return Err(interp.type_error("Math.sumPrecise element is not a number"));
        }
        seen = true;
        expansion.add(number_of(interp, element)?);
    }
    // The empty sum is `-0`, which is the addition identity this operation is defined with
    // and what the reference returns (`sum-is-minus-zero`).
    if !seen {
        return Ok(Value::Float(-0.0));
    }
    Ok(Value::Float(expansion.finish()))
}

/// An exact accumulator: the running sum as a fixed-point integer in units of `2^-1074`.
///
/// Every finite `double` is `mantissa × 2^exponent` with `exponent >= -1074` — the smallest
/// subnormal — so their sum is too, and a `BigInt` holds it with no loss at all. Cancellation
/// and dynamic range therefore cost nothing, which no floating-point accumulator can manage:
/// a three-term expansion carries ~159 bits and had to give up the moment a `1e308` and a
/// `1e-1` met, and even the exact `f64`-only Shewchuk expansion overflows *intermediately* on
/// `[1e308, 1e308, …, -1e308, -1e308]` even though the sum is `0.30000000000000004`
/// (`sumPrecise/sum`).
struct Expansion {
    /// The running sum in units of `2^-1074`.
    total: BigInt,
    positive_infinity: bool,
    negative_infinity: bool,
    nan: bool,
    /// The sign a **zero** result takes: `-0` only while every value so far has been `-0`,
    /// which is IEEE addition's rule and what `sum-is-minus-zero` checks
    /// (`[-0, -0]` is `-0`, `[-0, 0]` is `0`).
    zero_is_minus: bool,
}

impl Default for Expansion {
    fn default() -> Expansion {
        Expansion {
            total: BigInt::zero(),
            positive_infinity: false,
            negative_infinity: false,
            nan: false,
            // An empty list sums to `-0`.
            zero_is_minus: true,
        }
    }
}

impl Expansion {
    fn add(&mut self, value: f64) {
        if value.is_nan() {
            self.nan = true;
            return;
        }
        if value.is_infinite() {
            if value > 0.0 {
                self.positive_infinity = true;
            } else {
                self.negative_infinity = true;
            }
            return;
        }
        let bits = value.to_bits();
        let negative = bits >> 63 == 1;
        let biased = ((bits >> 52) & 0x7ff) as i64;
        let fraction = bits & ((1u64 << 52) - 1);
        // A subnormal has an implied zero leading bit and the smallest exponent, which is
        // exactly what a zero exponent field encodes; a normal one has the implicit bit.
        let (mantissa, exponent) = if biased == 0 {
            (fraction, -1074)
        } else {
            (fraction | (1u64 << 52), biased - 1075)
        };
        if mantissa == 0 {
            self.zero_is_minus &= negative;
            return;
        }
        self.zero_is_minus = false;
        let term = BigInt::from_u64(mantissa).shl((exponent + 1074) as u64);
        self.total = if negative {
            self.total.sub(&term)
        } else {
            self.total.add(&term)
        };
    }

    /// The exact sum rounded to a `double` once, ties to even.
    fn finish(&self) -> f64 {
        // `+∞` and `-∞` together have no sum, and one `NaN` anywhere poisons the whole thing.
        if self.nan || (self.positive_infinity && self.negative_infinity) {
            return f64::NAN;
        }
        if self.positive_infinity {
            return f64::INFINITY;
        }
        if self.negative_infinity {
            return f64::NEG_INFINITY;
        }
        if self.total.is_zero() {
            return if self.zero_is_minus { -0.0 } else { 0.0 };
        }
        let negative = self.total.is_negative();
        let magnitude = self.total.abs();
        let bits = magnitude.bit_length();
        // The leading bit of the *value*, since the integer counts units of `2^-1074`.
        let leading = bits as i64 - 1 - 1074;
        if leading > 1023 {
            return if negative {
                f64::NEG_INFINITY
            } else {
                f64::INFINITY
            };
        }
        // 53 bits for a normal result, fewer once the exponent is below the subnormal
        // threshold — the value becomes a subnormal with that many bits of precision, and
        // rounding it to 53 first would round twice.
        let precision = if leading >= -1022 { 53 } else { leading + 1075 };
        let drop = (bits as i64 - precision).max(0) as u64;
        let mut significand = magnitude.shr(drop);
        if drop > 0 {
            // Round to nearest, ties to even: compare what was dropped with half.
            let dropped = magnitude.sub(&significand.shl(drop));
            let half = BigInt::one().shl(drop - 1);
            let up = match dropped.cmp(&half) {
                std::cmp::Ordering::Greater => true,
                std::cmp::Ordering::Equal => significand.to_u64_wrapping() % 2 == 1,
                std::cmp::Ordering::Less => false,
            };
            if up {
                significand = significand.add(&BigInt::one());
            }
        }
        // At most 2^53, so the conversion is exact and only the scale is left.
        let value = scale_by_power_of_two(significand.to_u64_wrapping() as f64, drop as i64 - 1074);
        if negative { -value } else { value }
    }
}

/// `mantissa × 2^exponent`, exactly.
///
/// In two steps when the exponent is below the normal range: the scale factors themselves
/// have to be representable, and `2^-1074` is not (it is the smallest *subnormal*). Splitting
/// at `-537` keeps every intermediate normal, and the caller has already rounded `mantissa`
/// to what the result can hold, so each multiplication is exact.
fn scale_by_power_of_two(mut mantissa: f64, mut exponent: i64) -> f64 {
    const SPLIT: i64 = 537;
    while exponent < -1022 {
        mantissa *= f64::from_bits(((-SPLIT + 1023) as u64) << 52);
        exponent += SPLIT;
    }
    mantissa * f64::from_bits(((exponent + 1023) as u64) << 52)
}

/// `Math.random`.
///
/// A xorshift generator seeded from the clock, matching neither the reference's
/// algorithm nor its sequence — no test can compare random numbers, so the only
/// requirement is that successive calls differ.
fn random(interp: &mut Interp<'_>, _this: Value, _args: &[Value]) -> JsResult<Value> {
    // An `AtomicU64` rather than a `static mut`: the interpreter is single-threaded, so
    // `Relaxed` costs nothing here, and it keeps this out of the `unsafe` the engine
    // confines to its low-level modules.
    static STATE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    use std::sync::atomic::Ordering;
    let mut state = STATE.load(Ordering::Relaxed);
    if state == 0 {
        state = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|elapsed| elapsed.as_nanos() as u64)
            .unwrap_or(0x2545_F491_4F6C_DD1D)
            | 1;
    }
    state ^= state << 13;
    state ^= state >> 7;
    state ^= state << 17;
    STATE.store(state, Ordering::Relaxed);
    let state = state;
    let _ = interp;
    Ok(Value::Float((state >> 11) as f64 / (1u64 << 53) as f64))
}