Skip to main content

quickjs/
conversions.rs

1//! Conversions: the `JS_To*` family, and the constructors that make a `JSValue` out of a
2//! Rust primitive.
3//!
4//! # The rule every function here follows
5//!
6//! A conversion that can run script — `ToNumber` calls `valueOf`, `ToString` calls
7//! `toString`, `ToPrimitive` calls either — can throw, and the C API says so by answering
8//! `-1` (a `c_int`) or [`jsvalue::EXCEPTION`] (a `JSValue`) with the reason left in the
9//! context's pending slot. Nothing here answers "a best guess": `JS_ToInt32` on a `Symbol` is
10//! `-1`, not `0`, which is what makes `new Point(Symbol(), 0)` a `TypeError` rather than a
11//! point at the origin.
12//!
13//! # Saturating and wrapping are different functions
14//!
15//! `JS_ToInt32` *wraps* (`ToInt32`: modulo 2³²), `JS_ToInt32Sat` *clamps*, `JS_ToInt64`
16//! refuses a value that does not fit and `JS_ToInt64Sat` clamps. The reference keeps them
17//! apart and so does this file: a `Number.MAX_VALUE` argument is `-1` from one and
18//! `2147483647` from the other, and the difference is observable from a script.
19
20use core::ffi::{c_char, c_int, c_void};
21
22use engine::Value;
23
24use crate::cdefs::Bool;
25use crate::jsvalue::{self, JsValue};
26use crate::runtime::{self, JsContext};
27use crate::value_helpers::{jsvalue_of, value_of};
28
29/// Read a `JSValue` argument.
30///
31/// # Safety
32///
33/// `value` must be a `JSValue` this crate produced, or a primitive.
34pub(crate) unsafe fn arg(value: JsValue) -> Option<Value> {
35    // SAFETY: the caller's contract.
36    unsafe { value_of(value) }
37}
38
39/// Run `f` with the interpreter, turning a throw into a pending exception and `-1`.
40///
41/// Every `JS_To*` below is this shape, which is why it is one function rather than a
42/// repeated match: the failure path is the part that is easy to get subtly wrong (leaving
43/// the reason unconverted, or answering `0`), and it lives here once.
44fn with_number<T>(
45    context: &JsContext,
46    value: Value,
47    f: impl FnOnce(&mut engine::Interp<'static>, &Value) -> engine::interp::JsResult<T>,
48) -> Result<T, ()> {
49    match context.with_current_interp(|interp| f(interp, &value)) {
50        Ok(answer) => Ok(answer),
51        Err(signal) => {
52            let _ = runtime::result_value(context, Err(signal));
53            Err(())
54        }
55    }
56}
57
58// ---------------------------------------------------------------------------
59// Constructors
60// ---------------------------------------------------------------------------
61
62/// `JS_NewStringLen`: a string from `len1` bytes.
63///
64/// The bytes are WTF-8, not UTF-8, which is what lets a lone surrogate survive a round trip
65/// through C: `JS_ToCStringLen2` emits the same three-byte form, and a host that stores a
66/// QuickJS string as bytes gets its characters back.
67///
68/// # Safety
69///
70/// `str1` must point at `len1` readable bytes.
71#[unsafe(no_mangle)]
72pub unsafe extern "C" fn JS_NewStringLen(
73    ctx: *mut JsContext,
74    str1: *const c_char,
75    len1: usize,
76) -> JsValue {
77    let Some(context) = (unsafe { ctx.as_ref() }) else {
78        return jsvalue::EXCEPTION;
79    };
80    if str1.is_null() && len1 != 0 {
81        return runtime::throw_error(context, "TypeError", "null string");
82    }
83    let bytes: &[u8] = if len1 == 0 {
84        &[]
85    } else {
86        // SAFETY: the caller guarantees `len1` readable bytes.
87        unsafe { core::slice::from_raw_parts(str1.cast::<u8>(), len1) }
88    };
89    // A string that is not valid WTF-8 cannot have come from this engine, and inventing one
90    // would be worse than refusing: the reference would store the bytes and produce a string
91    // whose `length` is a guess.
92    let Some(text) = engine::value::Wtf8::from_wtf8_bytes(bytes) else {
93        return runtime::throw_error(context, "TypeError", "invalid string bytes");
94    };
95    context.with_current_interp(|interp| jsvalue_of(interp.string_wtf8(text)))
96}
97
98/// `JS_NewAtomString`: a string, interning it on the way.
99///
100/// The reference's version keeps the atom's identity, which is observable only through the
101/// atom API; here the string is what matters and the atom is interned for
102/// `JS_ValueToAtom`'s benefit.
103///
104/// # Safety
105///
106/// `str1` must be null or a NUL-terminated string.
107#[unsafe(no_mangle)]
108pub unsafe extern "C" fn JS_NewAtomString(ctx: *mut JsContext, str1: *const c_char) -> JsValue {
109    let Some(context) = (unsafe { ctx.as_ref() }) else {
110        return jsvalue::EXCEPTION;
111    };
112    // SAFETY: the caller guarantees a NUL-terminated string.
113    let text = unsafe { c_text(str1) };
114    context.with_current_interp(|interp| jsvalue_of(interp.string(text)))
115}
116
117/// `JS_NewBigInt64`: a `BigInt` from an `i64`.
118#[unsafe(no_mangle)]
119///
120/// # Safety
121///
122/// `ctx` must be a live context.
123pub unsafe extern "C" fn JS_NewBigInt64(ctx: *mut JsContext, value: i64) -> JsValue {
124    let Some(context) = (unsafe { ctx.as_ref() }) else {
125        return jsvalue::EXCEPTION;
126    };
127    context.with_current_interp(|interp| {
128        jsvalue_of(interp.bigint(engine::bigint::BigInt::from_i64(value)))
129    })
130}
131
132/// `JS_NewBigUint64`: a `BigInt` from a `u64`.
133#[unsafe(no_mangle)]
134///
135/// # Safety
136///
137/// `ctx` must be a live context.
138pub unsafe extern "C" fn JS_NewBigUint64(ctx: *mut JsContext, value: u64) -> JsValue {
139    let Some(context) = (unsafe { ctx.as_ref() }) else {
140        return jsvalue::EXCEPTION;
141    };
142    context.with_current_interp(|interp| {
143        jsvalue_of(interp.bigint(engine::bigint::BigInt::from_u64(value)))
144    })
145}
146
147/// `JS_NewBigInt128`: a `BigInt` from a 128-bit two's-complement pair.
148///
149/// Built the way the reference builds it: the low and high halves are combined into limbs,
150/// then the sign is applied. `low` is unsigned in the header, so a negative value arrives as
151/// a high half whose top bit is set.
152#[unsafe(no_mangle)]
153///
154/// # Safety
155///
156/// `ctx` must be a live context.
157pub unsafe extern "C" fn JS_NewBigInt128(ctx: *mut JsContext, low: u64, high: u64) -> JsValue {
158    let Some(context) = (unsafe { ctx.as_ref() }) else {
159        return jsvalue::EXCEPTION;
160    };
161    // Step through the decimal representation rather than a limb layout: `from_string` is the
162    // one constructor this engine's `BigInt` exposes that is not width-limited, so the value
163    // is assembled arithmetically.
164    let magnitude = (u128::from(high) << 64) | u128::from(low);
165    let negative = high >> 63 != 0;
166    let unsigned = if negative {
167        // Two's complement: negate in 128 bits, which is exact because the modulus is 2^128.
168        (!magnitude).wrapping_add(1)
169    } else {
170        magnitude
171    };
172    let mut big = engine::bigint::BigInt::zero();
173    let mut remaining = unsigned;
174    let mut power = engine::bigint::BigInt::one();
175    let ten = engine::bigint::BigInt::from_i64(10);
176    while remaining != 0 {
177        let digit = engine::bigint::BigInt::from_i64((remaining % 10) as i64);
178        big = big.add(&digit.mul(&power));
179        power = power.mul(&ten);
180        remaining /= 10;
181    }
182    if negative {
183        big = big.negate();
184    }
185    context.with_current_interp(|interp| jsvalue_of(interp.bigint(big)))
186}
187
188/// `JS_NewSymbol`: a symbol with `description`, optionally from the global registry.
189///
190/// # Safety
191///
192/// `description` must be null or a NUL-terminated string.
193#[unsafe(no_mangle)]
194pub unsafe extern "C" fn JS_NewSymbol(
195    ctx: *mut JsContext,
196    description: *const c_char,
197    is_global: Bool,
198) -> JsValue {
199    let Some(context) = (unsafe { ctx.as_ref() }) else {
200        return jsvalue::EXCEPTION;
201    };
202    let text = if description.is_null() {
203        None
204    } else {
205        // SAFETY: the caller guarantees a NUL-terminated string.
206        Some(unsafe { c_text(description) })
207    };
208    context.with_current_interp(|interp| {
209        let value = match text {
210            // `Symbol.for(k)` consults the realm's registry, which is what makes two calls
211            // with the same key the same symbol. The C API's `is_global` means exactly that.
212            Some(key) if is_global != 0 => interp.symbol_for(&key),
213            other => {
214                engine::builtins::symbol::symbol_value(interp, engine::value::JsSymbol::new(other))
215            }
216        };
217        jsvalue_of(value)
218    })
219}
220
221/// `JS_NewObjectProto`: an ordinary object with `proto`.
222///
223/// # Safety
224///
225/// `proto` must be null or a live `JSValue`.
226#[unsafe(no_mangle)]
227pub unsafe extern "C" fn JS_NewObjectProto(ctx: *mut JsContext, proto: JsValue) -> JsValue {
228    let Some(context) = (unsafe { ctx.as_ref() }) else {
229        return jsvalue::EXCEPTION;
230    };
231    let proto = if proto.is_null() {
232        None
233    } else {
234        match unsafe { arg(proto) } {
235            Some(Value::Object(object)) => Some(object),
236            Some(Value::Null) => None,
237            Some(_) => return runtime::throw_error(context, "TypeError", "not an object"),
238            None => return runtime::throw_error(context, "TypeError", "not a value"),
239        }
240    };
241    context.with_current_interp(|interp| jsvalue_of(Value::Object(interp.new_object(proto))))
242}
243
244/// `JS_NewArray`: an empty array.
245#[unsafe(no_mangle)]
246///
247/// # Safety
248///
249/// `ctx` must be a live context.
250pub unsafe extern "C" fn JS_NewArray(ctx: *mut JsContext) -> JsValue {
251    let Some(context) = (unsafe { ctx.as_ref() }) else {
252        return jsvalue::EXCEPTION;
253    };
254    context.with_current_interp(|interp| jsvalue_of(Value::Object(interp.new_array(Vec::new()))))
255}
256
257/// `JS_NewDate`: a `Date` for `epoch_ms`.
258#[unsafe(no_mangle)]
259///
260/// # Safety
261///
262/// `ctx` must be a live context.
263pub unsafe extern "C" fn JS_NewDate(ctx: *mut JsContext, epoch_ms: f64) -> JsValue {
264    let Some(context) = (unsafe { ctx.as_ref() }) else {
265        return jsvalue::EXCEPTION;
266    };
267    context.with_current_interp(|interp| {
268        let proto = interp.realm.date_proto.clone();
269        let object = interp.new_object(Some(proto));
270        interp.internal_set(&object, "_class", interp.string("Date"));
271        interp.internal_set(&object, "_date_value", Value::Float(epoch_ms));
272        jsvalue_of(Value::Object(object))
273    })
274}
275
276/// `JS_ThisDateValue`: `this`'s `[[DateValue]]`, or `-1` when it is not a `Date`.
277///
278/// # Safety
279///
280/// `valp` must be null or writable, and `this_val` a live `JSValue`.
281#[unsafe(no_mangle)]
282pub unsafe extern "C" fn JS_ThisDateValue(
283    ctx: *mut JsContext,
284    valp: *mut f64,
285    this_val: JsValue,
286) -> c_int {
287    let Some(context) = (unsafe { ctx.as_ref() }) else {
288        return -1;
289    };
290    let Some(Value::Object(object)) = (unsafe { arg(this_val) }) else {
291        return runtime::throw_error(context, "TypeError", "not a Date").to_int_or_minus_one();
292    };
293    let value = context.with_current_interp(|interp| {
294        // The class tag is what makes it a `Date`; a plain object with a `_date_value`-shaped
295        // symbol is not one, which is the check `Date.prototype.getTime` makes too.
296        if !interp
297            .internal_get(&object, "_class")
298            .is_some_and(|tag| tag.to_js_string() == "Date")
299        {
300            return None;
301        }
302        interp
303            .internal_get(&object, "_date_value")
304            .map(|v| v.to_number())
305    });
306    match value {
307        Some(number) => {
308            if !valp.is_null() {
309                // SAFETY: the caller guarantees a writable pointer.
310                unsafe { *valp = number };
311            }
312            0
313        }
314        None => runtime::throw_error(context, "TypeError", "not a Date").to_int_or_minus_one(),
315    }
316}
317
318/// `JS_NewError`: a plain `Error`.
319#[unsafe(no_mangle)]
320///
321/// # Safety
322///
323/// `ctx` must be a live context.
324pub unsafe extern "C" fn JS_NewError(ctx: *mut JsContext) -> JsValue {
325    let Some(context) = (unsafe { ctx.as_ref() }) else {
326        return jsvalue::EXCEPTION;
327    };
328    context.with_current_interp(|interp| jsvalue_of(interp.make_error("Error", "")))
329}
330
331// ---------------------------------------------------------------------------
332// ToNumber and its siblings
333// ---------------------------------------------------------------------------
334
335/// `JS_ToInt32`: `ToInt32` (wrapping), or `-1` with a pending exception.
336///
337/// # Safety
338///
339/// `pres` must be null or writable, `val` a live `JSValue`.
340#[unsafe(no_mangle)]
341pub unsafe extern "C" fn JS_ToInt32(ctx: *mut JsContext, pres: *mut i32, val: JsValue) -> c_int {
342    to_int32_like(ctx, pres.cast(), val, engine::value::to_int32)
343}
344
345/// `JS_ToInt32Sat`: `ToInt32` clamped to the `int` range instead of wrapped.
346///
347/// The reference's `-2^31 ..= 2^31-1` clamp, which a `DataView` offset check relies on: a
348/// wrapped offset would land inside the view.
349///
350/// # Safety
351///
352/// `pres` must be null or writable, `val` a live `JSValue`.
353#[unsafe(no_mangle)]
354pub unsafe extern "C" fn JS_ToInt32Sat(
355    ctx: *mut JsContext,
356    pres: *mut c_int,
357    val: JsValue,
358) -> c_int {
359    to_int32_like(ctx, pres, val, |number| {
360        if number.is_nan() {
361            return 0;
362        }
363        number.trunc().clamp(i32::MIN as f64, i32::MAX as f64) as i32
364    })
365}
366
367/// The shared body of `JS_ToInt32` and `JS_ToInt32Sat`: convert, then store.
368fn to_int32_like(
369    ctx: *mut JsContext,
370    pres: *mut c_int,
371    val: JsValue,
372    convert: impl Fn(f64) -> i32 + Copy,
373) -> c_int {
374    let Some(context) = (unsafe { ctx.as_ref() }) else {
375        return -1;
376    };
377    let Some(value) = (unsafe { arg(val) }) else {
378        runtime::throw_error(context, "TypeError", "not a value");
379        return -1;
380    };
381    match with_number(context, value, |interp, value| interp.to_js_number(value)) {
382        Ok(number) => {
383            if !pres.is_null() {
384                // SAFETY: the caller guarantees a writable `int`; `c_int` is `i32`.
385                unsafe { pres.write(convert(number)) };
386            }
387            0
388        }
389        Err(()) => -1,
390    }
391}
392
393/// `JS_ToInt64`: `ToInt64`, refusing a value outside the `i64` range.
394///
395/// # Safety
396///
397/// `pres` must be null or writable, `val` a live `JSValue`.
398#[unsafe(no_mangle)]
399pub unsafe extern "C" fn JS_ToInt64(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
400    let Some(context) = (unsafe { ctx.as_ref() }) else {
401        return -1;
402    };
403    let Some(value) = (unsafe { arg(val) }) else {
404        runtime::throw_error(context, "TypeError", "not a value");
405        return -1;
406    };
407    match with_number(context, value, |interp, value| interp.to_js_number(value)) {
408        Ok(number) => {
409            // `ToInt64` is "the value if it is an integer in range, otherwise fail" — it
410            // truncates first (so `1.5` is `1`) and then refuses anything that does not fit.
411            let truncated = if number.is_nan() || number.is_infinite() {
412                return runtime::throw_error(context, "TypeError", "not an integer")
413                    .to_int_or_minus_one();
414            } else {
415                number.trunc()
416            };
417            if truncated < i64::MIN as f64 || truncated >= -(i64::MIN as f64) {
418                return runtime::throw_error(context, "TypeError", "not an integer")
419                    .to_int_or_minus_one();
420            }
421            if !pres.is_null() {
422                // SAFETY: the caller guarantees a writable pointer.
423                unsafe { *pres = truncated as i64 };
424            }
425            0
426        }
427        Err(()) => -1,
428    }
429}
430
431/// `JS_ToInt64Sat`: `ToInt64` clamped to the `i64` range.
432///
433/// # Safety
434///
435/// `pres` must be null or writable, `val` a live `JSValue`.
436#[unsafe(no_mangle)]
437pub unsafe extern "C" fn JS_ToInt64Sat(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
438    let Some(context) = (unsafe { ctx.as_ref() }) else {
439        return -1;
440    };
441    let Some(value) = (unsafe { arg(val) }) else {
442        runtime::throw_error(context, "TypeError", "not a value");
443        return -1;
444    };
445    match with_number(context, value, |interp, value| interp.to_js_number(value)) {
446        Ok(number) => {
447            let clamped = if number.is_nan() {
448                0
449            } else {
450                number.trunc().clamp(i64::MIN as f64, i64::MAX as f64) as i64
451            };
452            if !pres.is_null() {
453                // SAFETY: the caller guarantees a writable pointer.
454                unsafe { *pres = clamped };
455            }
456            0
457        }
458        Err(()) => -1,
459    }
460}
461
462/// `JS_ToInt64Clamp`: `JS_ToInt64Sat` and then an affine shift, which is how the reference
463/// reads a `Date`'s time value with a timezone correction.
464///
465/// # Safety
466///
467/// `pres` must be null or writable, `val` a live `JSValue`.
468#[unsafe(no_mangle)]
469pub unsafe extern "C" fn JS_ToInt64Clamp(
470    ctx: *mut JsContext,
471    pres: *mut i64,
472    val: JsValue,
473    min: i64,
474    max: i64,
475    neg_offset: i64,
476) -> c_int {
477    let status = unsafe { JS_ToInt64Sat(ctx, pres, val) };
478    if status != 0 {
479        return status;
480    }
481    if pres.is_null() {
482        return 0;
483    }
484    // SAFETY: `JS_ToInt64Sat` just wrote it, so the pointer is live.
485    let value = unsafe { *pres };
486    let adjusted = if value < 0 {
487        value.saturating_add(neg_offset)
488    } else {
489        value
490    };
491    // A clamped result is the answer, not an error: the reference's callers use this to bound
492    // a time value and expect the bound rather than a `RangeError`.
493    unsafe { *pres = adjusted.clamp(min, max) };
494    0
495}
496
497/// `JS_ToInt64Ext`: `ToInt64`, but a `BigInt` is accepted too.
498///
499/// # Safety
500///
501/// `pres` must be null or writable, `val` a live `JSValue`.
502#[unsafe(no_mangle)]
503pub unsafe extern "C" fn JS_ToInt64Ext(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
504    let Some(context) = (unsafe { ctx.as_ref() }) else {
505        return -1;
506    };
507    let Some(value) = (unsafe { arg(val) }) else {
508        runtime::throw_error(context, "TypeError", "not a value");
509        return -1;
510    };
511    if let Value::BigInt(big) = &value {
512        // `ToBigInt64`: modulo 2^64, which is what a `BigInt64Array` store does.
513        let numeric = big.to_i64_wrapping();
514        if !pres.is_null() {
515            // SAFETY: the caller guarantees a writable pointer.
516            unsafe { *pres = numeric };
517        }
518        return 0;
519    }
520    // SAFETY: the pointer and value contracts are `JS_ToInt64`'s.
521    unsafe { JS_ToInt64(ctx, pres, val) }
522}
523
524/// `JS_ToBigInt64`: a `BigInt` (or a number) as an `i64`, modulo 2^64.
525///
526/// # Safety
527///
528/// `pres` must be null or writable, `val` a live `JSValue`.
529#[unsafe(no_mangle)]
530pub unsafe extern "C" fn JS_ToBigInt64(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
531    let Some(context) = (unsafe { ctx.as_ref() }) else {
532        return -1;
533    };
534    let Some(value) = (unsafe { arg(val) }) else {
535        runtime::throw_error(context, "TypeError", "not a value");
536        return -1;
537    };
538    match value {
539        Value::BigInt(big) => {
540            if !pres.is_null() {
541                // SAFETY: the caller guarantees a writable pointer.
542                unsafe { *pres = big.to_i64_wrapping() };
543            }
544            0
545        }
546        // A Number is a `TypeError`, exactly as `ToBigInt` says: `1n + 1` throws.
547        _ => runtime::throw_error(context, "TypeError", "cannot convert to BigInt")
548            .to_int_or_minus_one(),
549    }
550}
551
552/// `JS_ToBigInt128`: a `BigInt` as a 128-bit two's-complement pair.
553///
554/// # Safety
555///
556/// `plow`/`phigh` must be null or writable, `val` a live `JSValue`.
557#[unsafe(no_mangle)]
558pub unsafe extern "C" fn JS_ToBigInt128(
559    ctx: *mut JsContext,
560    plow: *mut u64,
561    phigh: *mut u64,
562    val: JsValue,
563) -> c_int {
564    // SAFETY: the caller's contract is `to_bigint128`'s.
565    unsafe { to_bigint128(ctx, plow, phigh, val, false) }
566}
567
568/// `JS_ToBigInt128Sat`: [`JS_ToBigInt128`] clamped to the 128-bit range.
569///
570/// # Safety
571///
572/// As [`JS_ToBigInt128`].
573#[unsafe(no_mangle)]
574pub unsafe extern "C" fn JS_ToBigInt128Sat(
575    ctx: *mut JsContext,
576    plow: *mut u64,
577    phigh: *mut u64,
578    val: JsValue,
579) -> c_int {
580    // SAFETY: as above.
581    unsafe { to_bigint128(ctx, plow, phigh, val, true) }
582}
583
584/// The shared body of the two 128-bit conversions.
585///
586/// The value is read through its decimal text, which is the only width-free view this
587/// engine's `BigInt` offers. That is slower than reading limbs, and it is exact — which
588/// matters more for an API whose whole job is to be the same number the script has.
589unsafe fn to_bigint128(
590    ctx: *mut JsContext,
591    plow: *mut u64,
592    phigh: *mut u64,
593    val: JsValue,
594    saturate: bool,
595) -> c_int {
596    let Some(context) = (unsafe { ctx.as_ref() }) else {
597        return -1;
598    };
599    let Some(value) = (unsafe { arg(val) }) else {
600        runtime::throw_error(context, "TypeError", "not a value");
601        return -1;
602    };
603    let Value::BigInt(big) = &value else {
604        return runtime::throw_error(context, "TypeError", "cannot convert to BigInt")
605            .to_int_or_minus_one();
606    };
607    let negative = big.is_negative();
608    let text = big.abs().to_decimal_string();
609    // Accumulate in `i128` so an out-of-range value is visible rather than wrapped: the whole
610    // difference between `JS_ToBigInt128` and its `Sat` sibling is what happens here.
611    let mut magnitude: Option<i128> = Some(0);
612    for byte in text.bytes() {
613        if !byte.is_ascii_digit() {
614            return runtime::throw_error(context, "TypeError", "not an integer")
615                .to_int_or_minus_one();
616        }
617        magnitude = magnitude.and_then(|current| {
618            current
619                .checked_mul(10)?
620                .checked_add(i128::from(byte - b'0'))
621        });
622    }
623    let Some(magnitude) = magnitude else {
624        // Too wide for 128 bits. Saturating answers the extreme value, which is what a
625        // `DataView` bounds check wants; the exact one refuses.
626        if !saturate {
627            return runtime::throw_error(context, "TypeError", "BigInt out of range")
628                .to_int_or_minus_one();
629        }
630        let (low, high) = if negative {
631            (0u64, u64::MAX)
632        } else {
633            (u64::MAX, i64::MAX as u64)
634        };
635        if !plow.is_null() {
636            unsafe { *plow = low };
637        }
638        if !phigh.is_null() {
639            unsafe { *phigh = high };
640        }
641        return 0;
642    };
643    let bits = if negative {
644        // Two's complement in 128 bits, sign-extended into a `u128` by the cast.
645        magnitude.wrapping_neg() as u128
646    } else {
647        magnitude as u128
648    };
649    // No range check is needed here: `magnitude` is already an `i128`, and the accumulation
650    // above refused anything that would not fit. The `saturate` flag only decides what an
651    // *overflow* answers, which is the branch above.
652    let _ = saturate;
653    if !plow.is_null() {
654        // SAFETY: the caller guarantees a writable pointer.
655        unsafe { *plow = bits as u64 };
656    }
657    if !phigh.is_null() {
658        // SAFETY: as above.
659        unsafe { *phigh = (bits >> 64) as u64 };
660    }
661    0
662}
663
664/// `JS_ToObject`: `ToObject`, boxing a primitive and refusing `null`/`undefined`.
665///
666/// # Safety
667///
668/// `val` must be a live `JSValue`.
669#[unsafe(no_mangle)]
670pub unsafe extern "C" fn JS_ToObject(ctx: *mut JsContext, val: JsValue) -> JsValue {
671    let Some(context) = (unsafe { ctx.as_ref() }) else {
672        return jsvalue::EXCEPTION;
673    };
674    let Some(value) = (unsafe { arg(val) }) else {
675        return runtime::throw_error(context, "TypeError", "not a value");
676    };
677    match context.with_current_interp(|interp| interp.object_from(&value)) {
678        Ok(object) => context.with_current_interp(|interp| {
679            let _ = interp;
680            jsvalue_of(Value::Object(object))
681        }),
682        Err(signal) => runtime::result_value(context, Err(signal)),
683    }
684}
685
686/// `JS_ToPrimitive`: `ToPrimitive` with a `hint` (`0` default, `1` number, `2` string).
687///
688/// # Safety
689///
690/// `val` must be a live `JSValue`.
691#[unsafe(no_mangle)]
692pub unsafe extern "C" fn JS_ToPrimitive(ctx: *mut JsContext, val: JsValue, hint: c_int) -> JsValue {
693    let Some(context) = (unsafe { ctx.as_ref() }) else {
694        return jsvalue::EXCEPTION;
695    };
696    let Some(value) = (unsafe { arg(val) }) else {
697        return runtime::throw_error(context, "TypeError", "not a value");
698    };
699    let hint = match hint {
700        // `JS_HINT_NUMBER` / `JS_HINT_STRING` / `JS_HINT_DEFAULT`, in the header's order.
701        0 => engine::interp::Hint::Number,
702        1 => engine::interp::Hint::String,
703        _ => engine::interp::Hint::Default,
704    };
705    let result = context.with_current_interp(|interp| interp.to_primitive(value, hint));
706    runtime::result_value(context, result)
707}
708
709/// `JS_ToString`: `ToString`, which calls `toString`/`valueOf` and so can throw.
710///
711/// # Safety
712///
713/// `val` must be a live `JSValue`.
714#[unsafe(no_mangle)]
715pub unsafe extern "C" fn JS_ToString(ctx: *mut JsContext, val: JsValue) -> JsValue {
716    let Some(context) = (unsafe { ctx.as_ref() }) else {
717        return jsvalue::EXCEPTION;
718    };
719    let Some(value) = (unsafe { arg(val) }) else {
720        return runtime::throw_error(context, "TypeError", "not a value");
721    };
722    let result = context.with_current_interp(|interp| {
723        let text = interp.checked_to_string(&value)?;
724        Ok(interp.string(text))
725    });
726    runtime::result_value(context, result)
727}
728
729/// `JS_ToPropertyKey`: `ToPropertyKey`, which keeps a symbol as a symbol.
730///
731/// # Safety
732///
733/// `val` must be a live `JSValue`.
734#[unsafe(no_mangle)]
735pub unsafe extern "C" fn JS_ToPropertyKey(ctx: *mut JsContext, val: JsValue) -> JsValue {
736    let Some(context) = (unsafe { ctx.as_ref() }) else {
737        return jsvalue::EXCEPTION;
738    };
739    let Some(value) = (unsafe { arg(val) }) else {
740        return runtime::throw_error(context, "TypeError", "not a value");
741    };
742    let converted = context
743        .with_current_interp(|interp| interp.to_primitive(value, engine::interp::Hint::String));
744    match converted {
745        Ok(Value::Symbol(_)) => {
746            let value = converted.expect("just matched");
747            context.with_current_interp(|interp| {
748                let _ = interp;
749                jsvalue_of(value)
750            })
751        }
752        Ok(value) => {
753            let result = context.with_current_interp(|interp| {
754                let text = interp.checked_to_string(&value)?;
755                Ok(interp.string(text))
756            });
757            runtime::result_value(context, result)
758        }
759        Err(signal) => runtime::result_value(context, Err(signal)),
760    }
761}
762
763/// `JS_ToUTF32String`: the code points of a string, as a `js_malloc` block.
764///
765/// # Safety
766///
767/// `pbuf` must be null or writable, `val` a live `JSValue`.
768#[unsafe(no_mangle)]
769pub unsafe extern "C" fn JS_ToUTF32String(
770    ctx: *mut JsContext,
771    pbuf: *mut *mut u32,
772    val: JsValue,
773) -> c_int {
774    let Some(context) = (unsafe { ctx.as_ref() }) else {
775        return -1;
776    };
777    let Some(value) = (unsafe { arg(val) }) else {
778        runtime::throw_error(context, "TypeError", "not a value");
779        return -1;
780    };
781    let text = match context.with_current_interp(|interp| interp.checked_to_wtf8(&value)) {
782        Ok(text) => text,
783        Err(signal) => {
784            let _ = runtime::result_value(context, Err(signal));
785            return -1;
786        }
787    };
788    let points: Vec<u32> = text.code_point_values();
789    if pbuf.is_null() {
790        return 0;
791    }
792    // The block is `js_malloc`'s because the caller frees it with `js_free`, and a `Vec`'s
793    // pointer is not something that function understands. One extra element holds the NUL
794    // terminator the reference writes, which is not part of the returned count.
795    // SAFETY: `alloc_raw` has no preconditions beyond a size.
796    let block = unsafe { crate::alloc::alloc_raw((points.len() + 1) * 4) };
797    if block.is_null() {
798        runtime::throw_error(context, "InternalError", "out of memory");
799        return -1;
800    }
801    // SAFETY: the block is `(len + 1) * 4` writable bytes, and `points` is `len` elements.
802    unsafe {
803        let out = block.cast::<u32>();
804        for (index, point) in points.iter().enumerate() {
805            out.add(index).write(*point);
806        }
807        out.add(points.len()).write(0);
808        pbuf.write(out);
809    }
810    0
811}
812
813/// `JS_ToCStringNZ`: [`crate::objects::JS_ToCStringLen2`] without the length.
814///
815/// # Safety
816///
817/// `val1` must be a live `JSValue`.
818#[unsafe(no_mangle)]
819pub unsafe extern "C" fn JS_ToCStringNZ(ctx: *mut JsContext, val1: JsValue) -> *const c_char {
820    // SAFETY: the caller's contract is `JS_ToCStringLen2`'s with a null length pointer.
821    unsafe { crate::objects::JS_ToCStringLen2(ctx, std::ptr::null_mut(), val1, 0) }
822}
823
824/// The text of a NUL-terminated string argument, or the empty string for null.
825///
826/// # Safety
827///
828/// `pointer` must be null or NUL-terminated.
829pub(crate) unsafe fn c_text(pointer: *const c_char) -> String {
830    if pointer.is_null() {
831        return String::new();
832    }
833    // SAFETY: the caller guarantees a NUL-terminated string.
834    unsafe { core::ffi::CStr::from_ptr(pointer) }
835        .to_string_lossy()
836        .into_owned()
837}
838
839/// A `JSValue`'s payload as `c_int`, for the "`-1` on failure" convention.
840trait IntOrMinusOne {
841    /// `-1` when the value is not an integer, which every failure path here is.
842    fn to_int_or_minus_one(self) -> c_int;
843}
844
845impl IntOrMinusOne for JsValue {
846    fn to_int_or_minus_one(self) -> c_int {
847        // The failure paths above all answer `EXCEPTION`, whose payload is not a number; the
848        // convention is that the caller only ever sees `-1`.
849        let _ = self;
850        -1
851    }
852}
853
854/// `JS_MarkValue`: stop the collector from reclaiming `val`.
855///
856/// The reference's mark phase is explicit; this engine's is reference-counting plus a cycle
857/// collector, so a live `JSValue` box already keeps its payload alive and there is nothing to
858/// mark. The function exists because a `JSClassDef::gc_mark` implementation calls it, and a
859/// missing symbol would stop such a module from loading at all.
860///
861/// # Safety
862///
863/// The arguments are ignored; the reference's contract is on `val` only.
864#[unsafe(no_mangle)]
865pub unsafe extern "C" fn JS_MarkValue(
866    _rt: *mut runtime::JsRuntime,
867    _val: JsValue,
868    _mark_func: *mut c_void,
869) {
870}