1use 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
29pub(crate) unsafe fn arg(value: JsValue) -> Option<Value> {
35 unsafe { value_of(value) }
37}
38
39fn 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#[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 unsafe { core::slice::from_raw_parts(str1.cast::<u8>(), len1) }
88 };
89 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#[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 let text = unsafe { c_text(str1) };
114 context.with_current_interp(|interp| jsvalue_of(interp.string(text)))
115}
116
117#[unsafe(no_mangle)]
119pub 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#[unsafe(no_mangle)]
134pub 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#[unsafe(no_mangle)]
153pub 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 let magnitude = (u128::from(high) << 64) | u128::from(low);
165 let negative = high >> 63 != 0;
166 let unsigned = if negative {
167 (!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#[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 Some(unsafe { c_text(description) })
207 };
208 context.with_current_interp(|interp| {
209 let value = match text {
210 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#[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#[unsafe(no_mangle)]
246pub 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#[unsafe(no_mangle)]
259pub 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#[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 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 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#[unsafe(no_mangle)]
320pub 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#[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#[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
367fn 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 unsafe { pres.write(convert(number)) };
386 }
387 0
388 }
389 Err(()) => -1,
390 }
391}
392
393#[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 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 unsafe { *pres = truncated as i64 };
424 }
425 0
426 }
427 Err(()) => -1,
428 }
429}
430
431#[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 unsafe { *pres = clamped };
455 }
456 0
457 }
458 Err(()) => -1,
459 }
460}
461
462#[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 let value = unsafe { *pres };
486 let adjusted = if value < 0 {
487 value.saturating_add(neg_offset)
488 } else {
489 value
490 };
491 unsafe { *pres = adjusted.clamp(min, max) };
494 0
495}
496
497#[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 let numeric = big.to_i64_wrapping();
514 if !pres.is_null() {
515 unsafe { *pres = numeric };
517 }
518 return 0;
519 }
520 unsafe { JS_ToInt64(ctx, pres, val) }
522}
523
524#[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 unsafe { *pres = big.to_i64_wrapping() };
543 }
544 0
545 }
546 _ => runtime::throw_error(context, "TypeError", "cannot convert to BigInt")
548 .to_int_or_minus_one(),
549 }
550}
551
552#[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 unsafe { to_bigint128(ctx, plow, phigh, val, false) }
566}
567
568#[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 unsafe { to_bigint128(ctx, plow, phigh, val, true) }
582}
583
584unsafe 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 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 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 magnitude.wrapping_neg() as u128
646 } else {
647 magnitude as u128
648 };
649 let _ = saturate;
653 if !plow.is_null() {
654 unsafe { *plow = bits as u64 };
656 }
657 if !phigh.is_null() {
658 unsafe { *phigh = (bits >> 64) as u64 };
660 }
661 0
662}
663
664#[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#[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 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#[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#[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#[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 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 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#[unsafe(no_mangle)]
819pub unsafe extern "C" fn JS_ToCStringNZ(ctx: *mut JsContext, val1: JsValue) -> *const c_char {
820 unsafe { crate::objects::JS_ToCStringLen2(ctx, std::ptr::null_mut(), val1, 0) }
822}
823
824pub(crate) unsafe fn c_text(pointer: *const c_char) -> String {
830 if pointer.is_null() {
831 return String::new();
832 }
833 unsafe { core::ffi::CStr::from_ptr(pointer) }
835 .to_string_lossy()
836 .into_owned()
837}
838
839trait IntOrMinusOne {
841 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 let _ = self;
850 -1
851 }
852}
853
854#[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}