1use core::ffi::{c_char, c_int};
17
18use engine::interp::JsResult;
19use engine::object::Property;
20use engine::{ClassId, Value};
21
22use crate::cdefs::{self, CFunctionEnum, JSCFunctionListEntry, JSCFunctionType, JSClassDef, prop};
23use crate::jsvalue::{self, JsValue};
24use crate::runtime::{self, JsContext, JsRuntime};
25use crate::value_helpers::jsvalue_of;
26
27pub(crate) unsafe fn arg(value: JsValue) -> Option<Value> {
33 unsafe { runtime::argument(value) }
35}
36
37#[unsafe(no_mangle)]
47pub unsafe extern "C" fn JS_NewObject(ctx: *mut JsContext) -> JsValue {
48 let Some(context) = (unsafe { ctx.as_ref() }) else {
49 return jsvalue::EXCEPTION;
50 };
51 context.with_current_interp(|interp| {
52 let proto = interp.realm.object_proto.clone();
53 jsvalue_of(Value::Object(interp.new_object(Some(proto))))
54 })
55}
56
57#[unsafe(no_mangle)]
63pub unsafe extern "C" fn JS_GetGlobalObject(ctx: *mut JsContext) -> JsValue {
64 let Some(context) = (unsafe { ctx.as_ref() }) else {
65 return jsvalue::EXCEPTION;
66 };
67 context.with_current_interp(|interp| {
68 let global = interp.realm.global.clone();
69 jsvalue_of(Value::Object(global))
70 })
71}
72
73#[unsafe(no_mangle)]
79pub unsafe extern "C" fn JS_NewObjectProtoClass(
80 ctx: *mut JsContext,
81 proto: JsValue,
82 class_id: cdefs::ClassId,
83) -> JsValue {
84 let Some(context) = (unsafe { ctx.as_ref() }) else {
85 return jsvalue::EXCEPTION;
86 };
87 let Some(proto) = (unsafe { arg(proto) }) else {
88 return runtime::throw_error(context, "TypeError", "prototype is not an object");
89 };
90 let Some(prototype) = proto.as_object().cloned() else {
91 return runtime::throw_error(context, "TypeError", "prototype is not an object");
92 };
93 context.with_current_interp(|interp| {
94 match interp.new_host_object(Some(prototype), ClassId::from_raw(class_id)) {
95 Some(object) => jsvalue_of(Value::Object(object)),
96 None => runtime::throw_error(
99 context,
100 "TypeError",
101 &format!("invalid class id {class_id}"),
102 ),
103 }
104 })
105}
106
107#[unsafe(no_mangle)]
113pub unsafe extern "C" fn JS_NewObjectClass(ctx: *mut JsContext, class_id: c_int) -> JsValue {
114 let Some(context) = (unsafe { ctx.as_ref() }) else {
115 return jsvalue::EXCEPTION;
116 };
117 context.with_current_interp(|interp| {
118 match interp.new_host_object(None, ClassId::from_raw(class_id as u32)) {
119 Some(object) => jsvalue_of(Value::Object(object)),
120 None => runtime::throw_error(
121 context,
122 "TypeError",
123 &format!("invalid class id {class_id}"),
124 ),
125 }
126 })
127}
128
129#[unsafe(no_mangle)]
136pub unsafe extern "C" fn JS_GetPropertyStr(
137 ctx: *mut JsContext,
138 this_obj: JsValue,
139 name: *const c_char,
140) -> JsValue {
141 let Some(context) = (unsafe { ctx.as_ref() }) else {
142 return jsvalue::EXCEPTION;
143 };
144 let Some(target) = (unsafe { arg(this_obj) }) else {
145 return runtime::throw_error(context, "TypeError", "not an object");
146 };
147 let name = unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy();
149 let result = context.with_current_interp(|interp| interp.read_field(&target, &name));
152 runtime::result_value(context, result)
153}
154
155#[unsafe(no_mangle)]
162pub unsafe extern "C" fn JS_SetPropertyStr(
163 ctx: *mut JsContext,
164 this_obj: JsValue,
165 name: *const c_char,
166 value: JsValue,
167) -> c_int {
168 let Some(context) = (unsafe { ctx.as_ref() }) else {
169 return -1;
170 };
171 let Some(target) = (unsafe { arg(this_obj) }) else {
172 runtime::throw_error(context, "TypeError", "not an object");
173 return -1;
174 };
175 let Some(new_value) = (unsafe { arg(value) }) else {
176 runtime::throw_error(context, "TypeError", "not a value");
177 return -1;
178 };
179 let name = unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy();
181 let result = context.with_current_interp(|interp| match target.as_object() {
182 Some(object) => interp.set_property(object, &name, new_value),
183 None => Err(engine::Signal::Throw(interp.make_error(
184 "TypeError",
185 &format!("cannot set property '{name}' of a primitive"),
186 ))),
187 });
188 unsafe { runtime::release(value) };
192 match result {
193 Ok(()) => 0,
194 Err(signal) => {
195 let _ = runtime::result_value(context, Err(signal));
196 -1
197 }
198 }
199}
200
201#[unsafe(no_mangle)]
207pub unsafe extern "C" fn JS_ToBool(ctx: *mut JsContext, val: JsValue) -> c_int {
208 let Some(context) = (unsafe { ctx.as_ref() }) else {
209 return -1;
210 };
211 match unsafe { arg(val) } {
212 Some(value) => c_int::from(value.to_boolean()),
213 None => {
214 runtime::throw_error(context, "TypeError", "not a value");
215 -1
216 }
217 }
218}
219
220#[unsafe(no_mangle)]
226pub unsafe extern "C" fn JS_ToIndex(ctx: *mut JsContext, plen: *mut u64, val: JsValue) -> c_int {
227 let Some(context) = (unsafe { ctx.as_ref() }) else {
228 return -1;
229 };
230 let Some(value) = (unsafe { arg(val) }) else {
231 runtime::throw_error(context, "TypeError", "not a value");
232 return -1;
233 };
234 let number = match context.with_current_interp(|interp| interp.to_js_number(&value)) {
235 Ok(number) => number,
236 Err(signal) => {
237 let _ = runtime::result_value(context, Err(signal));
238 return -1;
239 }
240 };
241 let index = number.trunc();
243 if number.is_nan() || index != number || index < 0.0 || index > 9_007_199_254_740_991.0 {
244 runtime::throw_error(context, "RangeError", "invalid array index");
245 return -1;
246 }
247 if !plen.is_null() {
248 unsafe { *plen = index as u64 };
250 }
251 0
252}
253
254pub type RawFunction = *const core::ffi::c_void;
264
265#[unsafe(no_mangle)]
272pub unsafe extern "C" fn JS_NewCFunction2(
273 ctx: *mut JsContext,
274 func: RawFunction,
275 name: *const c_char,
276 length: c_int,
277 cproto: c_int,
278 magic: c_int,
279) -> JsValue {
280 let Some(context) = (unsafe { ctx.as_ref() }) else {
281 return jsvalue::EXCEPTION;
282 };
283 let name = unsafe { std::ffi::CStr::from_ptr(name) }
285 .to_string_lossy()
286 .into_owned();
287 let Some(kind) = u8::try_from(cproto).ok().and_then(CFunctionEnum::from_raw) else {
288 return runtime::throw_error(
289 context,
290 "TypeError",
291 &format!("unsupported JSCFunctionEnum {cproto}"),
292 );
293 };
294 context.with_current_interp(|interp| {
295 let function = make_c_function(interp, func, kind, name, length, magic);
296 jsvalue_of(Value::Object(function))
297 })
298}
299
300pub(crate) fn make_c_function(
302 interp: &mut engine::Interp<'static>,
303 func: RawFunction,
304 kind: CFunctionEnum,
305 name: String,
306 length: c_int,
307 magic: c_int,
308) -> engine::Gc<engine::JsObject> {
309 let arity = u32::try_from(length).unwrap_or(0);
310 let body: engine::object::HostFn = Box::new(move |interp, this, args| {
311 let context = current_context_or_null();
312 call_c_function(context, interp, func, kind, magic, this, args)
313 });
314 if kind.is_constructor() {
318 interp.new_host_ctor(name, arity, body)
319 } else {
320 interp.new_host_function(name, arity, body)
321 }
322}
323
324fn current_context_or_null() -> *mut JsContext {
330 runtime::current_context()
331 .map(|context| context as *const JsContext as *mut JsContext)
332 .unwrap_or(std::ptr::null_mut())
333}
334
335fn call_c_function<'i>(
341 ctx: *mut JsContext,
342 interp: &mut engine::Interp<'i>,
343 func: RawFunction,
344 kind: CFunctionEnum,
345 magic: c_int,
346 this: Value,
347 args: &[Value],
348) -> JsResult<Value> {
349 let this = if kind.is_constructor() {
352 interp.current_new_target()
353 } else {
354 this
355 };
356 let this_value = crate::convert::encode(&this);
357 let arguments: Vec<JsValue> = args.iter().map(crate::convert::encode).collect();
358 let pointer = arguments.as_ptr();
359 let argc = c_int::try_from(arguments.len()).unwrap_or(c_int::MAX);
360 let context = current_context_or_null();
363 let _ = ctx;
364
365 let answer = unsafe {
369 match kind {
370 CFunctionEnum::Generic => {
371 let f: unsafe extern "C" fn(
372 *mut JsContext,
373 JsValue,
374 c_int,
375 *const JsValue,
376 ) -> JsValue = core::mem::transmute(func);
377 f(context, this_value, argc, pointer)
378 }
379 CFunctionEnum::GenericMagic => {
380 let f: unsafe extern "C" fn(
381 *mut JsContext,
382 JsValue,
383 c_int,
384 *const JsValue,
385 c_int,
386 ) -> JsValue = core::mem::transmute(func);
387 f(context, this_value, argc, pointer, magic)
388 }
389 CFunctionEnum::Constructor | CFunctionEnum::ConstructorOrFunc => {
390 let f: unsafe extern "C" fn(
391 *mut JsContext,
392 JsValue,
393 c_int,
394 *const JsValue,
395 ) -> JsValue = core::mem::transmute(func);
396 f(context, this_value, argc, pointer)
397 }
398 CFunctionEnum::ConstructorMagic | CFunctionEnum::ConstructorOrFuncMagic => {
399 let f: unsafe extern "C" fn(
400 *mut JsContext,
401 JsValue,
402 c_int,
403 *const JsValue,
404 c_int,
405 ) -> JsValue = core::mem::transmute(func);
406 f(context, this_value, argc, pointer, magic)
407 }
408 CFunctionEnum::ConstructorOrFuncFlags => {
409 let flags = if this_value.is_undefined() {
412 0
413 } else {
414 cdefs::JS_CALL_FLAG_CONSTRUCTOR
415 };
416 let f: unsafe extern "C" fn(
417 *mut JsContext,
418 JsValue,
419 JsValue,
420 c_int,
421 *const JsValue,
422 c_int,
423 ) -> JsValue = core::mem::transmute(func);
424 f(context, this_value, this_value, argc, pointer, flags)
425 }
426 CFunctionEnum::Getter => {
427 let f: unsafe extern "C" fn(*mut JsContext, JsValue) -> JsValue =
428 core::mem::transmute(func);
429 f(context, this_value)
430 }
431 CFunctionEnum::GetterMagic => {
432 let f: unsafe extern "C" fn(*mut JsContext, JsValue, c_int) -> JsValue =
433 core::mem::transmute(func);
434 f(context, this_value, magic)
435 }
436 CFunctionEnum::Setter => {
437 let f: unsafe extern "C" fn(*mut JsContext, JsValue, JsValue) -> JsValue =
438 core::mem::transmute(func);
439 let value = args.first().cloned().unwrap_or(Value::Undefined);
440 let encoded = crate::convert::encode(&value);
441 let answer = f(context, this_value, encoded);
442 runtime::release(encoded);
443 answer
444 }
445 CFunctionEnum::SetterMagic => {
446 let f: unsafe extern "C" fn(*mut JsContext, JsValue, JsValue, c_int) -> JsValue =
447 core::mem::transmute(func);
448 let value = args.first().cloned().unwrap_or(Value::Undefined);
449 let encoded = crate::convert::encode(&value);
450 let answer = f(context, this_value, encoded, magic);
451 runtime::release(encoded);
452 answer
453 }
454 CFunctionEnum::FF | CFunctionEnum::FFF | CFunctionEnum::IteratorNext => {
458 return Err(engine::Signal::Throw(
459 interp.make_error("TypeError", "unsupported C function convention"),
460 ));
461 }
462 }
463 };
464
465 for value in arguments {
468 unsafe { runtime::release(value) };
470 }
471 let answer_is_this = answer.has_ref_count() && answer.payload() == this_value.payload();
472 let result = finish_call(context, interp, answer);
473 if !answer_is_this {
479 unsafe { runtime::release(this_value) };
481 }
482 result
483}
484
485fn finish_call(
495 context: *mut JsContext,
496 interp: &mut engine::Interp<'_>,
497 answer: JsValue,
498) -> JsResult<Value> {
499 if answer.is_exception() {
500 let pending = unsafe { context.as_ref() }.and_then(|context| context.take_pending());
503 return Err(match pending {
504 Some(value) => engine::Signal::Throw(value),
505 None => engine::Signal::Throw(interp.make_error(
506 "InternalError",
507 "C function returned JS_EXCEPTION without raising",
508 )),
509 });
510 }
511 let decoded = if answer.is_undefined() {
512 Some(Value::Undefined)
513 } else {
514 unsafe { runtime::argument(answer) }
516 };
517 unsafe { runtime::release(answer) };
519 Ok(decoded.unwrap_or(Value::Undefined))
520}
521
522#[unsafe(no_mangle)]
529pub unsafe extern "C" fn JS_SetConstructor(
530 ctx: *mut JsContext,
531 func_obj: JsValue,
532 proto: JsValue,
533) -> c_int {
534 let Some(context) = (unsafe { ctx.as_ref() }) else {
535 return -1;
536 };
537 let (Some(function), Some(prototype)) = (unsafe { arg(func_obj) }, unsafe { arg(proto) })
538 else {
539 runtime::throw_error(context, "TypeError", "not an object");
540 return -1;
541 };
542 let (Some(function), Some(prototype)) = (function.as_object(), prototype.as_object()) else {
543 runtime::throw_error(context, "TypeError", "not an object");
544 return -1;
545 };
546 function.define(
550 "prototype",
551 Property {
552 value: Some(Value::Object(prototype.clone())),
553 writable: true,
554 enumerable: false,
555 configurable: false,
556 ..Property::default()
557 },
558 );
559 prototype.define(
560 "constructor",
561 Property::with_attributes(Value::Object(function.clone()), true, false),
562 );
563 0
564}
565
566#[unsafe(no_mangle)]
577pub unsafe extern "C" fn JS_SetPropertyFunctionList(
578 ctx: *mut JsContext,
579 obj: JsValue,
580 tab: *const JSCFunctionListEntry,
581 len: c_int,
582) -> c_int {
583 let Some(context) = (unsafe { ctx.as_ref() }) else {
584 return -1;
585 };
586 let Some(object) = (unsafe { arg(obj) }).and_then(|value| value.as_object().cloned()) else {
587 runtime::throw_error(context, "TypeError", "not an object");
588 return -1;
589 };
590 if tab.is_null() || len <= 0 {
591 return 0;
592 }
593 context.with_current_interp(|interp| {
594 for index in 0..len as usize {
595 let entry = unsafe { &*tab.add(index) };
597 if let Err(signal) = install_entry(interp, &object, entry) {
598 let _ = runtime::result_value(context, Err(signal));
599 return -1;
600 }
601 }
602 0
603 })
604}
605
606fn install_entry(
608 interp: &mut engine::Interp<'static>,
609 object: &engine::Gc<engine::JsObject>,
610 entry: &JSCFunctionListEntry,
611) -> JsResult<()> {
612 if entry.name.is_null() {
613 return Ok(());
614 }
615 let name = unsafe { std::ffi::CStr::from_ptr(entry.name) }
617 .to_string_lossy()
618 .into_owned();
619 let writable = entry.prop_flags & prop::WRITABLE != 0;
623 let enumerable = entry.prop_flags & prop::ENUMERABLE != 0;
624 let configurable = entry.prop_flags & prop::CONFIGURABLE != 0;
625
626 let data_property = |value: Value| Property {
627 value: Some(value),
628 writable,
629 enumerable,
630 configurable,
631 ..Property::default()
632 };
633 let accessor_property = |getter: Option<Value>, setter: Option<Value>| Property {
634 getter,
635 setter,
636 writable: false,
637 enumerable,
638 configurable,
639 ..Property::default()
640 };
641
642 match entry.def_type {
643 cdefs::JS_DEF_CFUNC => {
644 let func = unsafe { &entry.u.func };
646 let Some(kind) = CFunctionEnum::from_raw(func.cproto) else {
647 return Err(engine::Signal::Throw(interp.make_error(
648 "TypeError",
649 &format!("unsupported JSCFunctionEnum {}", func.cproto),
650 )));
651 };
652 let pointer = func.cfunc.as_ptr();
654 let value = make_c_function(
657 interp,
658 pointer,
659 kind,
660 name.clone(),
661 c_int::from(func.length),
662 entry.magic as c_int,
663 );
664 object.define(&name, data_property(Value::Object(value)));
665 }
666 cdefs::JS_DEF_CGETSET | cdefs::JS_DEF_CGETSET_MAGIC => {
667 let magic = entry.magic as c_int;
668 let (getter_kind, setter_kind) = if entry.def_type == cdefs::JS_DEF_CGETSET_MAGIC {
673 (CFunctionEnum::GetterMagic, CFunctionEnum::SetterMagic)
674 } else {
675 (CFunctionEnum::Getter, CFunctionEnum::Setter)
676 };
677 let pair = unsafe { &entry.u.getset };
679 let getter = wrap_accessor(interp, pair.get, getter_kind, magic, "get");
680 let setter = wrap_accessor(interp, pair.set, setter_kind, magic, "set");
681 object.define(&entry_name(entry), accessor_property(getter, setter));
682 }
683 cdefs::JS_DEF_PROP_STRING => {
684 let text = unsafe { entry.u.str_ };
686 let value = if text.is_null() {
687 Value::Undefined
688 } else {
689 let text = unsafe { std::ffi::CStr::from_ptr(text) };
691 interp.string(text.to_string_lossy().into_owned())
692 };
693 object.define(&entry_name(entry), data_property(value));
694 }
695 cdefs::JS_DEF_PROP_INT32 => {
696 let number = unsafe { entry.u.i32 };
698 object.define(&entry_name(entry), data_property(Value::Int(number)));
699 }
700 cdefs::JS_DEF_PROP_INT64 => {
701 let number = unsafe { entry.u.i64 };
703 object.define(
704 &entry_name(entry),
705 data_property(Value::Float(number as f64)),
706 );
707 }
708 cdefs::JS_DEF_PROP_DOUBLE => {
709 let number = unsafe { entry.u.f64 };
711 object.define(&entry_name(entry), data_property(Value::Float(number)));
712 }
713 cdefs::JS_DEF_PROP_UNDEFINED => {
714 object.define(&entry_name(entry), data_property(Value::Undefined));
715 }
716 cdefs::JS_DEF_PROP_BOOL => {
717 let flag = unsafe { entry.u.i32 } != 0;
719 object.define(&entry_name(entry), data_property(Value::Bool(flag)));
720 }
721 other => {
722 return Err(engine::Signal::Throw(interp.make_error(
723 "TypeError",
724 &format!("unsupported JS_DEF_* {other} in a function list"),
725 )));
726 }
727 }
728 Ok(())
729}
730
731fn entry_name(entry: &JSCFunctionListEntry) -> String {
733 if entry.name.is_null() {
734 return String::new();
735 }
736 unsafe { std::ffi::CStr::from_ptr(entry.name) }
738 .to_string_lossy()
739 .into_owned()
740}
741
742fn wrap_accessor(
748 interp: &mut engine::Interp<'static>,
749 function: JSCFunctionType,
750 kind: CFunctionEnum,
751 magic: c_int,
752 which: &str,
753) -> Option<Value> {
754 if function.is_null() {
755 return None;
756 }
757 let pointer = function.as_ptr();
758 let body: engine::object::HostFn = Box::new(move |interp, this, args| {
759 let context = current_context_or_null();
760 call_c_function(context, interp, pointer, kind, magic, this, args)
761 });
762 Some(Value::Object(interp.new_host_function(which, 0, body)))
763}
764
765#[unsafe(no_mangle)]
778pub unsafe extern "C" fn JS_NewClassID(pclass_id: *mut cdefs::ClassId) -> cdefs::ClassId {
779 let Some(slot) = (unsafe { pclass_id.as_mut() }) else {
780 return 0;
781 };
782 if *slot != 0 {
783 return *slot;
784 }
785 *slot = runtime::allocate_class_id();
789 *slot
790}
791
792#[unsafe(no_mangle)]
799pub unsafe extern "C" fn JS_NewClass(
800 rt: *mut JsRuntime,
801 class_id: cdefs::ClassId,
802 class_def: *const JSClassDef,
803) -> c_int {
804 let (Some(runtime), Some(definition)) = (unsafe { rt.as_ref() }, unsafe { class_def.as_ref() })
805 else {
806 return -1;
807 };
808 let declaration = runtime::ClassDecl {
809 finalizer: definition.finalizer,
810 gc_mark: definition.gc_mark,
811 exotic: definition.exotic,
812 name: definition.class_name,
813 };
814 -c_int::from(!runtime.define_class(class_id, declaration))
815}
816
817#[unsafe(no_mangle)]
823pub unsafe extern "C" fn JS_IsRegisteredClass(
824 rt: *mut JsRuntime,
825 class_id: cdefs::ClassId,
826) -> c_int {
827 match unsafe { rt.as_ref() } {
828 Some(runtime) => c_int::from(runtime.has_class(class_id)),
829 None => 0,
830 }
831}
832
833#[unsafe(no_mangle)]
839pub unsafe extern "C" fn JS_GetClassID(value: JsValue) -> cdefs::ClassId {
840 let Some(value) = (unsafe { arg(value) }) else {
841 return 0;
842 };
843 value
844 .as_object()
845 .and_then(|object| object.host_class_id())
846 .map_or(0, |id| id.get())
847}
848
849#[unsafe(no_mangle)]
856pub unsafe extern "C" fn JS_SetClassProto(
857 ctx: *mut JsContext,
858 class_id: cdefs::ClassId,
859 obj: JsValue,
860) {
861 let Some(context) = (unsafe { ctx.as_ref() }) else {
862 return;
863 };
864 let Some(prototype) = (unsafe { arg(obj) }).and_then(|value| value.as_object().cloned()) else {
865 return;
866 };
867 unsafe { runtime::release(obj) };
869 context.with_current_interp(|interp| {
870 interp.set_host_class_proto(ClassId::from_raw(class_id), prototype);
871 });
872}
873
874#[unsafe(no_mangle)]
880pub unsafe extern "C" fn JS_GetClassProto(
881 ctx: *mut JsContext,
882 class_id: cdefs::ClassId,
883) -> JsValue {
884 let Some(context) = (unsafe { ctx.as_ref() }) else {
885 return jsvalue::EXCEPTION;
886 };
887 context.with_interp(
888 |interp| match interp.host_class_proto(ClassId::from_raw(class_id)) {
889 Some(proto) => jsvalue_of(Value::Object(proto)),
890 None => jsvalue::UNDEFINED,
891 },
892 )
893}
894
895#[unsafe(no_mangle)]
901pub unsafe extern "C" fn JS_SetOpaque(obj: JsValue, opaque: *mut core::ffi::c_void) {
902 let Some(value) = (unsafe { arg(obj) }) else {
903 return;
904 };
905 let Some(object) = value.as_object() else {
906 return;
907 };
908 object.set_host_opaque(engine::Opaque::new(opaque.cast()));
909}
910
911#[unsafe(no_mangle)]
921pub unsafe extern "C" fn JS_GetOpaque(
922 obj: JsValue,
923 class_id: cdefs::ClassId,
924) -> *mut core::ffi::c_void {
925 if runtime::is_finalizer_sentinel(obj) {
926 return runtime::finalizer_opaque(class_id)
927 .map(|opaque| opaque.cast())
928 .unwrap_or(std::ptr::null_mut());
929 }
930 let Some(value) = (unsafe { arg(obj) }) else {
931 return std::ptr::null_mut();
932 };
933 let Some(object) = value.as_object() else {
934 return std::ptr::null_mut();
935 };
936 if object.host_class_id().is_none_or(|id| id.get() != class_id) {
937 return std::ptr::null_mut();
938 }
939 object
940 .host_opaque()
941 .map_or(std::ptr::null_mut(), |opaque| opaque.as_ptr().cast())
942}
943
944#[unsafe(no_mangle)]
950pub unsafe extern "C" fn JS_GetOpaque2(
951 ctx: *mut JsContext,
952 obj: JsValue,
953 class_id: cdefs::ClassId,
954) -> *mut core::ffi::c_void {
955 let opaque = unsafe { JS_GetOpaque(obj, class_id) };
957 if !opaque.is_null() {
958 return opaque;
959 }
960 if let Some(context) = unsafe { ctx.as_ref() } {
961 let runtime = unsafe { context.runtime().as_ref() };
965 let name = runtime
966 .and_then(|runtime| runtime.class(class_id))
967 .map(|decl| class_name(decl.name))
968 .unwrap_or_else(|| format!("class {class_id}"));
969 runtime::throw_error(context, "TypeError", &format!("not a {name}"));
970 }
971 std::ptr::null_mut()
972}
973
974fn class_name(name: *const c_char) -> String {
976 if name.is_null() {
977 return "<anonymous>".to_string();
978 }
979 unsafe { std::ffi::CStr::from_ptr(name) }
981 .to_string_lossy()
982 .into_owned()
983}
984
985#[unsafe(no_mangle)]
991pub unsafe extern "C" fn JS_GetRuntime(ctx: *mut JsContext) -> *mut JsRuntime {
992 match unsafe { ctx.as_ref() } {
993 Some(context) => context.runtime(),
994 None => std::ptr::null_mut(),
995 }
996}
997
998#[unsafe(no_mangle)]
1010pub unsafe extern "C" fn JS_ThrowRangeError(
1011 ctx: *mut JsContext,
1012 message: *const c_char,
1013) -> JsValue {
1014 let Some(context) = (unsafe { ctx.as_ref() }) else {
1015 return jsvalue::EXCEPTION;
1016 };
1017 let message = if message.is_null() {
1018 String::new()
1019 } else {
1020 unsafe { std::ffi::CStr::from_ptr(message) }
1022 .to_string_lossy()
1023 .into_owned()
1024 };
1025 runtime::throw_error(context, "RangeError", &message)
1026}
1027
1028#[unsafe(no_mangle)]
1038pub unsafe extern "C" fn JS_ToFloat64(ctx: *mut JsContext, pres: *mut f64, val: JsValue) -> c_int {
1039 let Some(context) = (unsafe { ctx.as_ref() }) else {
1040 return -1;
1041 };
1042 let Some(value) = (unsafe { arg(val) }) else {
1043 runtime::throw_error(context, "TypeError", "not a value");
1044 return -1;
1045 };
1046 match context.with_current_interp(|interp| interp.to_js_number(&value)) {
1047 Ok(number) => {
1048 if !pres.is_null() {
1049 unsafe { *pres = number };
1051 }
1052 0
1053 }
1054 Err(signal) => {
1055 let _ = runtime::result_value(context, Err(signal));
1056 -1
1057 }
1058 }
1059}
1060
1061#[unsafe(no_mangle)]
1071pub unsafe extern "C" fn JS_ToCStringLen2(
1072 ctx: *mut JsContext,
1073 plen: *mut usize,
1074 val: JsValue,
1075 _cesu8: c_int,
1076) -> *mut c_char {
1077 let Some(context) = (unsafe { ctx.as_ref() }) else {
1078 return std::ptr::null_mut();
1079 };
1080 let Some(value) = (unsafe { arg(val) }) else {
1081 runtime::throw_error(context, "TypeError", "not a value");
1082 return std::ptr::null_mut();
1083 };
1084 let text = match context.with_current_interp(|interp| interp.to_js_string(&value)) {
1085 Ok(text) => text,
1086 Err(signal) => {
1087 let _ = runtime::result_value(context, Err(signal));
1088 return std::ptr::null_mut();
1089 }
1090 };
1091 let bytes = text.as_bytes();
1092 let buffer = unsafe { crate::alloc::alloc_raw_zeroed(bytes.len() + 1) };
1096 if buffer.is_null() {
1097 runtime::throw_error(context, "InternalError", "out of memory");
1098 return std::ptr::null_mut();
1099 }
1100 unsafe {
1102 std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, bytes.len());
1103 }
1104 if !plen.is_null() {
1105 unsafe { *plen = bytes.len() };
1107 }
1108 buffer.cast()
1109}
1110
1111#[unsafe(no_mangle)]
1117pub unsafe extern "C" fn JS_FreeCString(_ctx: *mut JsContext, ptr: *const c_char) {
1118 unsafe { crate::alloc::free_raw(ptr.cast_mut().cast()) }
1120}