quickjs/convert.rs
1//! The bridge: engine [`Value`] ⇄ C [`JsValue`].
2//!
3//! Two directions, both total for the values that can cross the boundary:
4//!
5//! * [`encode`] never fails. Primitives become their bit pattern; anything with a
6//! reference count is boxed (see [`crate::alloc`]), because C will eventually decrement
7//! the count through a pointer it only knows because we allocated one.
8//! * [`decode`] answers `None` for a tag the engine has no value for — an internal tag the
9//! reference uses for its own containers (`JS_TAG_FUNCTION_BYTECODE`, `JS_TAG_MODULE`)
10//! or a `JS_TAG_SHORT_BIG_INT`, which this engine does not produce because a `BigInt`
11//! here is always a heap allocation.
12//!
13//! # What is deliberately not here
14//!
15//! The engine's internal markers (`CatchOffset`, `ReturnAddress`, `Hole`, `Uninitialized`)
16//! never cross this boundary in either direction: they live on the operand stack and in
17//! object slots, and a host never sees one. [`encode`] maps the two that have a spelling in
18//! C (`Uninitialized` is `JS_UNINITIALIZED`) and treats the rest as a programming error
19//! rather than inventing a tag.
20
21use engine::Value;
22
23use crate::alloc;
24use crate::jsvalue::{self, JsValue};
25
26/// Engine value → C value.
27///
28/// # The box, and who owns it
29///
30/// A reference-counted value is boxed with a count of one. That count *is* the answer's
31/// ownership: the caller owns the single reference, `JS_DupValue` makes more of them, and
32/// the last `JS_FreeValue` drops the box and with it the engine's handle. Boxes are not
33/// shared between calls — two `encode`s of the same object give two boxes — which is
34/// invisible to C for values, and observable only through `JS_VALUE_GET_PTR` equality,
35/// which the C API uses for object identity. That identity is S3's interning table; until
36/// then two encodings of one object are two pointers.
37pub fn encode(value: &Value) -> JsValue {
38 match value {
39 Value::Undefined => jsvalue::UNDEFINED,
40 Value::Null => jsvalue::NULL,
41 Value::Bool(flag) => jsvalue::new_bool(*flag),
42 Value::Int(number) => jsvalue::new_int32(*number),
43 Value::Float(number) => jsvalue::new_float64(*number),
44 Value::Uninitialized => jsvalue::UNINITIALIZED,
45 // Everything below owns a heap allocation, so it needs a reference count C can
46 // write through. `Hole` is an array's hole marker: it never comes out of a
47 // property read (`undefined` does), and boxing it would hand C a value with no
48 // meaning in the C API.
49 Value::String(_) | Value::Object(_) | Value::Symbol(_) | Value::BigInt(_) => {
50 alloc::box_value(value.clone())
51 }
52 // Operand-stack markers. A value that reaches here is a bug in the caller, and a
53 // debug assertion is the loudest available answer: the alternative is inventing a
54 // tag for something no C program can interpret.
55 Value::CatchOffset(_) | Value::ReturnAddress(_) | Value::Hole => {
56 debug_assert!(false, "an engine-internal marker cannot cross the C ABI");
57 jsvalue::UNDEFINED
58 }
59 }
60}
61
62/// C value → engine value.
63///
64/// `None` means the tag names nothing this engine can produce. It is not an error path for
65/// well-behaved callers: a `JSValue` from a host is always one of ours.
66///
67/// # Safety
68///
69/// A reference-counted `value` must be a live box from this crate whose count is at least
70/// one — the returned [`Value`] is a *clone* whose handle keeps the payload alive on its
71/// own, but reading the box at all requires it to exist.
72pub unsafe fn decode(value: JsValue) -> Option<Value> {
73 match value.norm_tag() {
74 jsvalue::TAG_UNDEFINED => Some(Value::Undefined),
75 jsvalue::TAG_NULL => Some(Value::Null),
76 jsvalue::TAG_BOOL => Some(Value::Bool(value.to_bool())),
77 jsvalue::TAG_INT => Some(Value::Int(value.to_int())),
78 jsvalue::TAG_FLOAT64 => Some(Value::Float(value.to_float())),
79 jsvalue::TAG_UNINITIALIZED => Some(Value::Uninitialized),
80 // `TAG_EXCEPTION` is not a value: it is the marker `JS_IsException` tests, and
81 // decoding it into anything would let a caller store it in an object.
82 tag if jsvalue::is_engine_tag(tag) => {
83 let payload = value.as_ptr()?;
84 // SAFETY: the caller guarantees the payload is a live box.
85 Some(unsafe { alloc::value_of(payload) })
86 }
87 _ => None,
88 }
89}
90
91/// Whether a C value is one this layer produced.
92///
93/// Cheap enough to call on every incoming argument, and the answer to "is this a
94/// `JSValue` from a foreign implementation", which mixing two `libquickjs`s would produce.
95pub fn is_ours(value: JsValue) -> bool {
96 match value.norm_tag() {
97 jsvalue::TAG_UNDEFINED
98 | jsvalue::TAG_NULL
99 | jsvalue::TAG_BOOL
100 | jsvalue::TAG_INT
101 | jsvalue::TAG_FLOAT64
102 | jsvalue::TAG_UNINITIALIZED
103 | jsvalue::TAG_EXCEPTION => true,
104 tag => jsvalue::is_engine_tag(tag),
105 }
106}
107
108#[cfg(test)]
109mod tests {
110 use super::*;
111
112 #[test]
113 fn primitives_round_trip_without_a_box() {
114 for value in [
115 Value::Undefined,
116 Value::Null,
117 Value::Bool(true),
118 Value::Bool(false),
119 Value::Int(0),
120 Value::Int(-7),
121 Value::Float(1.5),
122 Value::Float(-0.0),
123 ] {
124 let encoded = encode(&value);
125 assert!(!encoded.has_ref_count(), "{value:?} needed a box");
126 // SAFETY: no reference count means no box to read.
127 let decoded = unsafe { decode(encoded) }.expect("a primitive decodes");
128 // `Value` has no `PartialEq` on purpose (a `Gc` handle compares by identity,
129 // not by contents); `same_value` is the language's own equality.
130 assert!(decoded.same_value(&value), "{value:?} round-tripped wrong");
131 }
132 }
133
134 #[test]
135 fn uninitiailised_has_a_tag_of_its_own() {
136 let encoded = encode(&Value::Uninitialized);
137 assert_eq!(encoded.norm_tag(), jsvalue::TAG_UNINITIALIZED);
138 // SAFETY: no reference count.
139 assert!(matches!(
140 unsafe { decode(encoded) },
141 Some(Value::Uninitialized)
142 ));
143 }
144
145 #[test]
146 fn a_boxed_string_round_trips() {
147 let runtime = engine::Runtime::new();
148 let mut ctx = engine::Context::new(&runtime);
149 let string = ctx.new_string("boxed");
150 let encoded = encode(&string);
151 assert!(encoded.has_ref_count(), "a string needs a count for C");
152 assert_eq!(
153 encoded.norm_tag(),
154 jsvalue::TAG_STRING,
155 "JS_IsString reads the tag"
156 );
157 // SAFETY: `encoded` is a live box with a count of one.
158 let decoded = unsafe { decode(encoded) }.expect("a box decodes");
159 assert!(decoded.same_value(&string), "the string survived the box");
160 // SAFETY: the count is still one, so this is the only reference.
161 unsafe { crate::alloc::free_value(encoded.as_ptr().unwrap()) };
162 }
163
164 #[test]
165 fn a_boxed_object_round_trips_and_keeps_the_engine_handle() {
166 let runtime = engine::Runtime::new();
167 let mut ctx = engine::Context::new(&runtime);
168 let object = ctx.new_object();
169 let engine::Value::Object(handle) = &object else {
170 panic!("new_object must answer an object");
171 };
172 let before = handle.strong_count();
173
174 let encoded = encode(&object);
175 assert_eq!(encoded.norm_tag(), jsvalue::TAG_OBJECT);
176 assert_eq!(
177 handle.strong_count(),
178 before + 1,
179 "the box holds a reference"
180 );
181
182 // SAFETY: the box is live and this is its only reference.
183 unsafe { crate::alloc::free_value(encoded.as_ptr().unwrap()) };
184 assert_eq!(handle.strong_count(), before, "freeing the box released it");
185 }
186
187 #[test]
188 fn an_exception_is_not_a_decodable_value() {
189 // `JS_EXCEPTION` is a marker, not a value: `JS_IsException` tests the bits, and
190 // nothing may store it in an object.
191 // SAFETY: no reference count.
192 assert!(unsafe { decode(jsvalue::EXCEPTION) }.is_none());
193 assert!(is_ours(jsvalue::EXCEPTION));
194 }
195
196 #[test]
197 fn foreign_tags_are_not_ours() {
198 // The reference's own containers: a string rope and a bytecode object. Neither has
199 // a spelling in this engine, so a value carrying one did not come from here.
200 assert!(!is_ours(jsvalue::JsValue::mkval(
201 jsvalue::TAG_STRING_ROPE,
202 0
203 )));
204 assert!(!is_ours(jsvalue::JsValue::mkval(
205 jsvalue::TAG_FUNCTION_BYTECODE,
206 0
207 )));
208 assert!(!is_ours(jsvalue::JsValue::mkval(jsvalue::TAG_MODULE, 0)));
209 }
210
211 #[test]
212 fn a_nan_is_a_double_like_any_other() {
213 // `JS_NAN` is not a foreign tag: it is the canonical NaN, and `JS_IsNumber` is
214 // true for it. `is_ours` has to agree, or every `NaN` a script passes back would
215 // look like another implementation's value.
216 let nan = JsValue::new(jsvalue::NAN);
217 assert!(is_ours(nan));
218 assert!(nan.is_number());
219 // SAFETY: no reference count.
220 let decoded = unsafe { decode(nan) }.expect("NaN decodes");
221 assert!(matches!(decoded, Value::Float(number) if number.is_nan()));
222 }
223}