use core::ffi::{c_char, c_int, c_void};
use engine::Value;
use crate::cdefs::Bool;
use crate::jsvalue::{self, JsValue};
use crate::runtime::{self, JsContext};
use crate::value_helpers::{jsvalue_of, value_of};
pub(crate) unsafe fn arg(value: JsValue) -> Option<Value> {
unsafe { value_of(value) }
}
fn with_number<T>(
context: &JsContext,
value: Value,
f: impl FnOnce(&mut engine::Interp<'static>, &Value) -> engine::interp::JsResult<T>,
) -> Result<T, ()> {
match context.with_current_interp(|interp| f(interp, &value)) {
Ok(answer) => Ok(answer),
Err(signal) => {
let _ = runtime::result_value(context, Err(signal));
Err(())
}
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewStringLen(
ctx: *mut JsContext,
str1: *const c_char,
len1: usize,
) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
if str1.is_null() && len1 != 0 {
return runtime::throw_error(context, "TypeError", "null string");
}
let bytes: &[u8] = if len1 == 0 {
&[]
} else {
unsafe { core::slice::from_raw_parts(str1.cast::<u8>(), len1) }
};
let Some(text) = engine::value::Wtf8::from_wtf8_bytes(bytes) else {
return runtime::throw_error(context, "TypeError", "invalid string bytes");
};
context.with_current_interp(|interp| jsvalue_of(interp.string_wtf8(text)))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewAtomString(ctx: *mut JsContext, str1: *const c_char) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let text = unsafe { c_text(str1) };
context.with_current_interp(|interp| jsvalue_of(interp.string(text)))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewBigInt64(ctx: *mut JsContext, value: i64) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
context.with_current_interp(|interp| {
jsvalue_of(interp.bigint(engine::bigint::BigInt::from_i64(value)))
})
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewBigUint64(ctx: *mut JsContext, value: u64) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
context.with_current_interp(|interp| {
jsvalue_of(interp.bigint(engine::bigint::BigInt::from_u64(value)))
})
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewBigInt128(ctx: *mut JsContext, low: u64, high: u64) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let magnitude = (u128::from(high) << 64) | u128::from(low);
let negative = high >> 63 != 0;
let unsigned = if negative {
(!magnitude).wrapping_add(1)
} else {
magnitude
};
let mut big = engine::bigint::BigInt::zero();
let mut remaining = unsigned;
let mut power = engine::bigint::BigInt::one();
let ten = engine::bigint::BigInt::from_i64(10);
while remaining != 0 {
let digit = engine::bigint::BigInt::from_i64((remaining % 10) as i64);
big = big.add(&digit.mul(&power));
power = power.mul(&ten);
remaining /= 10;
}
if negative {
big = big.negate();
}
context.with_current_interp(|interp| jsvalue_of(interp.bigint(big)))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewSymbol(
ctx: *mut JsContext,
description: *const c_char,
is_global: Bool,
) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let text = if description.is_null() {
None
} else {
Some(unsafe { c_text(description) })
};
context.with_current_interp(|interp| {
let value = match text {
Some(key) if is_global != 0 => interp.symbol_for(&key),
other => {
engine::builtins::symbol::symbol_value(interp, engine::value::JsSymbol::new(other))
}
};
jsvalue_of(value)
})
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewObjectProto(ctx: *mut JsContext, proto: JsValue) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let proto = if proto.is_null() {
None
} else {
match unsafe { arg(proto) } {
Some(Value::Object(object)) => Some(object),
Some(Value::Null) => None,
Some(_) => return runtime::throw_error(context, "TypeError", "not an object"),
None => return runtime::throw_error(context, "TypeError", "not a value"),
}
};
context.with_current_interp(|interp| jsvalue_of(Value::Object(interp.new_object(proto))))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewArray(ctx: *mut JsContext) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
context.with_current_interp(|interp| jsvalue_of(Value::Object(interp.new_array(Vec::new()))))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewDate(ctx: *mut JsContext, epoch_ms: f64) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
context.with_current_interp(|interp| {
let proto = interp.realm.date_proto.clone();
let object = interp.new_object(Some(proto));
interp.internal_set(&object, "_class", interp.string("Date"));
interp.internal_set(&object, "_date_value", Value::Float(epoch_ms));
jsvalue_of(Value::Object(object))
})
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThisDateValue(
ctx: *mut JsContext,
valp: *mut f64,
this_val: JsValue,
) -> c_int {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return -1;
};
let Some(Value::Object(object)) = (unsafe { arg(this_val) }) else {
return runtime::throw_error(context, "TypeError", "not a Date").to_int_or_minus_one();
};
let value = context.with_current_interp(|interp| {
if !interp
.internal_get(&object, "_class")
.is_some_and(|tag| tag.to_js_string() == "Date")
{
return None;
}
interp
.internal_get(&object, "_date_value")
.map(|v| v.to_number())
});
match value {
Some(number) => {
if !valp.is_null() {
unsafe { *valp = number };
}
0
}
None => runtime::throw_error(context, "TypeError", "not a Date").to_int_or_minus_one(),
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewError(ctx: *mut JsContext) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
context.with_current_interp(|interp| jsvalue_of(interp.make_error("Error", "")))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt32(ctx: *mut JsContext, pres: *mut i32, val: JsValue) -> c_int {
to_int32_like(ctx, pres.cast(), val, engine::value::to_int32)
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt32Sat(
ctx: *mut JsContext,
pres: *mut c_int,
val: JsValue,
) -> c_int {
to_int32_like(ctx, pres, val, |number| {
if number.is_nan() {
return 0;
}
number.trunc().clamp(i32::MIN as f64, i32::MAX as f64) as i32
})
}
fn to_int32_like(
ctx: *mut JsContext,
pres: *mut c_int,
val: JsValue,
convert: impl Fn(f64) -> i32 + Copy,
) -> c_int {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return -1;
};
let Some(value) = (unsafe { arg(val) }) else {
runtime::throw_error(context, "TypeError", "not a value");
return -1;
};
match with_number(context, value, |interp, value| interp.to_js_number(value)) {
Ok(number) => {
if !pres.is_null() {
unsafe { pres.write(convert(number)) };
}
0
}
Err(()) => -1,
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt64(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return -1;
};
let Some(value) = (unsafe { arg(val) }) else {
runtime::throw_error(context, "TypeError", "not a value");
return -1;
};
match with_number(context, value, |interp, value| interp.to_js_number(value)) {
Ok(number) => {
let truncated = if number.is_nan() || number.is_infinite() {
return runtime::throw_error(context, "TypeError", "not an integer")
.to_int_or_minus_one();
} else {
number.trunc()
};
if truncated < i64::MIN as f64 || truncated >= -(i64::MIN as f64) {
return runtime::throw_error(context, "TypeError", "not an integer")
.to_int_or_minus_one();
}
if !pres.is_null() {
unsafe { *pres = truncated as i64 };
}
0
}
Err(()) => -1,
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt64Sat(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return -1;
};
let Some(value) = (unsafe { arg(val) }) else {
runtime::throw_error(context, "TypeError", "not a value");
return -1;
};
match with_number(context, value, |interp, value| interp.to_js_number(value)) {
Ok(number) => {
let clamped = if number.is_nan() {
0
} else {
number.trunc().clamp(i64::MIN as f64, i64::MAX as f64) as i64
};
if !pres.is_null() {
unsafe { *pres = clamped };
}
0
}
Err(()) => -1,
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt64Clamp(
ctx: *mut JsContext,
pres: *mut i64,
val: JsValue,
min: i64,
max: i64,
neg_offset: i64,
) -> c_int {
let status = unsafe { JS_ToInt64Sat(ctx, pres, val) };
if status != 0 {
return status;
}
if pres.is_null() {
return 0;
}
let value = unsafe { *pres };
let adjusted = if value < 0 {
value.saturating_add(neg_offset)
} else {
value
};
unsafe { *pres = adjusted.clamp(min, max) };
0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt64Ext(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return -1;
};
let Some(value) = (unsafe { arg(val) }) else {
runtime::throw_error(context, "TypeError", "not a value");
return -1;
};
if let Value::BigInt(big) = &value {
let numeric = big.to_i64_wrapping();
if !pres.is_null() {
unsafe { *pres = numeric };
}
return 0;
}
unsafe { JS_ToInt64(ctx, pres, val) }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToBigInt64(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return -1;
};
let Some(value) = (unsafe { arg(val) }) else {
runtime::throw_error(context, "TypeError", "not a value");
return -1;
};
match value {
Value::BigInt(big) => {
if !pres.is_null() {
unsafe { *pres = big.to_i64_wrapping() };
}
0
}
_ => runtime::throw_error(context, "TypeError", "cannot convert to BigInt")
.to_int_or_minus_one(),
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToBigInt128(
ctx: *mut JsContext,
plow: *mut u64,
phigh: *mut u64,
val: JsValue,
) -> c_int {
unsafe { to_bigint128(ctx, plow, phigh, val, false) }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToBigInt128Sat(
ctx: *mut JsContext,
plow: *mut u64,
phigh: *mut u64,
val: JsValue,
) -> c_int {
unsafe { to_bigint128(ctx, plow, phigh, val, true) }
}
unsafe fn to_bigint128(
ctx: *mut JsContext,
plow: *mut u64,
phigh: *mut u64,
val: JsValue,
saturate: bool,
) -> c_int {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return -1;
};
let Some(value) = (unsafe { arg(val) }) else {
runtime::throw_error(context, "TypeError", "not a value");
return -1;
};
let Value::BigInt(big) = &value else {
return runtime::throw_error(context, "TypeError", "cannot convert to BigInt")
.to_int_or_minus_one();
};
let negative = big.is_negative();
let text = big.abs().to_decimal_string();
let mut magnitude: Option<i128> = Some(0);
for byte in text.bytes() {
if !byte.is_ascii_digit() {
return runtime::throw_error(context, "TypeError", "not an integer")
.to_int_or_minus_one();
}
magnitude = magnitude.and_then(|current| {
current
.checked_mul(10)?
.checked_add(i128::from(byte - b'0'))
});
}
let Some(magnitude) = magnitude else {
if !saturate {
return runtime::throw_error(context, "TypeError", "BigInt out of range")
.to_int_or_minus_one();
}
let (low, high) = if negative {
(0u64, u64::MAX)
} else {
(u64::MAX, i64::MAX as u64)
};
if !plow.is_null() {
unsafe { *plow = low };
}
if !phigh.is_null() {
unsafe { *phigh = high };
}
return 0;
};
let bits = if negative {
magnitude.wrapping_neg() as u128
} else {
magnitude as u128
};
let _ = saturate;
if !plow.is_null() {
unsafe { *plow = bits as u64 };
}
if !phigh.is_null() {
unsafe { *phigh = (bits >> 64) as u64 };
}
0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToObject(ctx: *mut JsContext, val: JsValue) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let Some(value) = (unsafe { arg(val) }) else {
return runtime::throw_error(context, "TypeError", "not a value");
};
match context.with_current_interp(|interp| interp.object_from(&value)) {
Ok(object) => context.with_current_interp(|interp| {
let _ = interp;
jsvalue_of(Value::Object(object))
}),
Err(signal) => runtime::result_value(context, Err(signal)),
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToPrimitive(ctx: *mut JsContext, val: JsValue, hint: c_int) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let Some(value) = (unsafe { arg(val) }) else {
return runtime::throw_error(context, "TypeError", "not a value");
};
let hint = match hint {
0 => engine::interp::Hint::Number,
1 => engine::interp::Hint::String,
_ => engine::interp::Hint::Default,
};
let result = context.with_current_interp(|interp| interp.to_primitive(value, hint));
runtime::result_value(context, result)
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToString(ctx: *mut JsContext, val: JsValue) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let Some(value) = (unsafe { arg(val) }) else {
return runtime::throw_error(context, "TypeError", "not a value");
};
let result = context.with_current_interp(|interp| {
let text = interp.checked_to_string(&value)?;
Ok(interp.string(text))
});
runtime::result_value(context, result)
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToPropertyKey(ctx: *mut JsContext, val: JsValue) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let Some(value) = (unsafe { arg(val) }) else {
return runtime::throw_error(context, "TypeError", "not a value");
};
let converted = context
.with_current_interp(|interp| interp.to_primitive(value, engine::interp::Hint::String));
match converted {
Ok(Value::Symbol(_)) => {
let value = converted.expect("just matched");
context.with_current_interp(|interp| {
let _ = interp;
jsvalue_of(value)
})
}
Ok(value) => {
let result = context.with_current_interp(|interp| {
let text = interp.checked_to_string(&value)?;
Ok(interp.string(text))
});
runtime::result_value(context, result)
}
Err(signal) => runtime::result_value(context, Err(signal)),
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToUTF32String(
ctx: *mut JsContext,
pbuf: *mut *mut u32,
val: JsValue,
) -> c_int {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return -1;
};
let Some(value) = (unsafe { arg(val) }) else {
runtime::throw_error(context, "TypeError", "not a value");
return -1;
};
let text = match context.with_current_interp(|interp| interp.checked_to_wtf8(&value)) {
Ok(text) => text,
Err(signal) => {
let _ = runtime::result_value(context, Err(signal));
return -1;
}
};
let points: Vec<u32> = text.code_point_values();
if pbuf.is_null() {
return 0;
}
let block = unsafe { crate::alloc::alloc_raw((points.len() + 1) * 4) };
if block.is_null() {
runtime::throw_error(context, "InternalError", "out of memory");
return -1;
}
unsafe {
let out = block.cast::<u32>();
for (index, point) in points.iter().enumerate() {
out.add(index).write(*point);
}
out.add(points.len()).write(0);
pbuf.write(out);
}
0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToCStringNZ(ctx: *mut JsContext, val1: JsValue) -> *const c_char {
unsafe { crate::objects::JS_ToCStringLen2(ctx, std::ptr::null_mut(), val1, 0) }
}
pub(crate) unsafe fn c_text(pointer: *const c_char) -> String {
if pointer.is_null() {
return String::new();
}
unsafe { core::ffi::CStr::from_ptr(pointer) }
.to_string_lossy()
.into_owned()
}
trait IntOrMinusOne {
fn to_int_or_minus_one(self) -> c_int;
}
impl IntOrMinusOne for JsValue {
fn to_int_or_minus_one(self) -> c_int {
let _ = self;
-1
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_MarkValue(
_rt: *mut runtime::JsRuntime,
_val: JsValue,
_mark_func: *mut c_void,
) {
}