From 636a15f70374143db1da5289a35a3b11b6a66fbe Mon Sep 17 00:00:00 2001 From: Jason Milad Date: Wed, 25 Nov 2026 16:37:51 -0500 Subject: [PATCH 1/2] Add boolean and string support to JsValue in C FFI --- ffi/boa_ffi/README.md | 94 ++++++--- ffi/boa_ffi/bindings/c/JsStringError.d.h | 23 +++ ffi/boa_ffi/bindings/c/JsStringError.h | 22 +++ ffi/boa_ffi/bindings/c/JsValue.h | 14 ++ ffi/boa_ffi/src/lib.rs | 241 ++++++++++++++++++++++- ffi/boa_ffi/tests/c/error.c | 21 +- ffi/boa_ffi/tests/c/value.c | 189 +++++++++++++++++- 7 files changed, 562 insertions(+), 42 deletions(-) create mode 100644 ffi/boa_ffi/bindings/c/JsStringError.d.h create mode 100644 ffi/boa_ffi/bindings/c/JsStringError.h diff --git a/ffi/boa_ffi/README.md b/ffi/boa_ffi/README.md index bbc55feb6f2..da30178fc7a 100644 --- a/ffi/boa_ffi/README.md +++ b/ffi/boa_ffi/README.md @@ -2,8 +2,9 @@ `boa_ffi` exposes Boa through opaque C handles generated by Diplomat. The current API supports context lifecycle and value handles with type inspection and -number/null/undefined construction, plus structured error construction and -inspection. It does not yet execute JavaScript. The API is experimental and may change. +boolean/number/string/null/undefined construction and inspection, plus structured +error construction and inspection. It does not yet execute JavaScript. The API is +experimental and may change. ## Build and test @@ -26,13 +27,14 @@ host explicitly in `target//debug/`, honors `CARGO_TARGET_DIR`, and runs against that build's library; `--ci` reuses Cargo's `ci` profile build. Windows support is not covered by this runner. -Rust tests cover initialization failure, context cleanup, value types, numeric -round trips, retained error data and inspection without JavaScript execution. +Rust tests cover initialization failure, context cleanup, value types, boolean, +numeric and string round trips (including unpaired UTF-16 surrogates), retained +error data and inspection without JavaScript execution. Object retention is checked across garbage collection. The C tests exercise -context/value/error lifecycle, numeric edge cases and message encoding through -the generated headers and shared library. They check results explicitly, so -defining `NDEBUG` does not disable the tests. A dedicated CI job runs header -regeneration and the C tests across macOS and Linux. +context/value/error lifecycle, boolean/numeric/string edge cases and message +encoding through the generated headers and shared library. They check results +explicitly, so defining `NDEBUG` does not disable the tests. A dedicated CI job +runs header regeneration and the C tests across macOS and Linux. ## Regenerate headers @@ -75,35 +77,63 @@ int main(void) { ## Value handles -`boa_JsValue_from_number(double)`, `boa_JsValue_from_null()` and -`boa_JsValue_from_undefined()` each return one owned, non-null value handle. They -require no context, and these primitive values remain usable after a context -is destroyed. Allocation failures and unexpected Rust panics may abort the process. +Primitive constructors (`boa_JsValue_from_boolean`, `boa_JsValue_from_number`, +`boa_JsValue_from_string`, `boa_JsValue_from_null`, `boa_JsValue_from_undefined`) +require no context and return an owned `JsValue *` handle. All getters borrow a +live, non-null handle without coercing types, and return a tagged result whose +`is_ok` field must be checked before reading `ok` or `err`. + +- **Type inspection (`boa_JsValue_get_type`):** Returns the ECMAScript language + type (`JsValueType`). Unlike JS `typeof`, `null` and `undefined` are distinct + and functions have type `Object`. Object identity is preserved. +- **Booleans (`from_boolean` / `as_boolean`):** Only boolean values return + `is_ok == true`; truthy and falsy non-booleans return `is_ok == false`. +- **Numbers (`from_number` / `as_number`):** Only number values return + `is_ok == true`, including `NaN`, infinities, and signed zeros (`NaN` payload + bits are not guaranteed). +- **Strings (`from_string` / `as_string` / `as_string_lossy`):** + - `from_string` copies a UTF-8 `DiplomatStringView` using its explicit byte + length (including any `'\0'` bytes) and returns `NULL` on invalid UTF-8. + Empty strings may pass `{.data = NULL, .len = 0}`. + - `as_string` and `as_string_lossy` encode the string as UTF-8 into a + `DiplomatWrite` buffer (from `diplomat_runtime.h`). On failure, nothing is + written. `as_string` reports `JsStringError_NotAString` or + `JsStringError_InvalidEncoding` (unpaired UTF-16 surrogates); + `as_string_lossy` replaces unpaired surrogates with `U+FFFD` and only fails + on non-strings. + - Growable buffers (`diplomat_buffer_write_create`) are not NUL-terminated + and JS strings may contain `'\0'`, so use `diplomat_buffer_write_len()`. + Fixed stack buffers (`diplomat_simple_write`) append a trailing `'\0'` and + set `write.grow_failed` on overflow. +- **Ownership & lifetime:** Keep handles on their creating thread. Primitive + values remain valid after a `BoaContext` is destroyed. Destroy each owned + handle once with `boa_JsValue_destroy()` (never `NULL` or `free()`). + Allocation failures and unexpected Rust panics may abort the program. ```c -JsValue *value = boa_JsValue_from_number(7.0); -boa_JsValue_as_number_result number = boa_JsValue_as_number(value); -if (number.is_ok) { - printf("%g\n", number.ok); +JsValue *num = boa_JsValue_from_number(7.0); +boa_JsValue_as_number_result n = boa_JsValue_as_number(num); +if (n.is_ok) { + printf("%g\n", n.ok); +} +boa_JsValue_destroy(num); + +const char text[] = "hello"; +JsValue *str = boa_JsValue_from_string( + (DiplomatStringView){.data = text, .len = sizeof(text) - 1}); +if (str != NULL) { + DiplomatWrite *write = diplomat_buffer_write_create(0); + boa_JsValue_as_string_result res = boa_JsValue_as_string(str, write); + if (res.is_ok) { + fwrite(diplomat_buffer_write_get_bytes(write), 1, + diplomat_buffer_write_len(write), stdout); + fputc('\n', stdout); + } + diplomat_buffer_write_destroy(write); + boa_JsValue_destroy(str); } -boa_JsValue_destroy(value); ``` -`boa_JsValue_get_type()` borrows the handle and returns its `JsValueType`. It reports -the ECMAScript language type: null and undefined are distinct, and functions -have the object type. This differs from JavaScript's `typeof` operator. -The underlying handle retains the original Boa value, including object identity. - -`boa_JsValue_as_number()` borrows the handle and returns a tagged optional double. -Check `is_ok` before reading `ok`; only number values have a numeric payload. -Null and undefined produce an absent result without coercion. NaN is a present -number, as are infinities and signed zeros. NaN payload bits are not guaranteed. - -All value calls, including destruction, must stay on the creating thread. Getters -require a live, non-null value handle and do not consume it. Destroy each owned -handle exactly once with `boa_JsValue_destroy()`, and invalidate every pointer alias -afterward. `boa_JsValue_destroy(NULL)` and C's `free()` are invalid for these handles. - ## Errors `JsError` retains Boa's original error and its stored representation: diff --git a/ffi/boa_ffi/bindings/c/JsStringError.d.h b/ffi/boa_ffi/bindings/c/JsStringError.d.h new file mode 100644 index 00000000000..f4afe5fe4fb --- /dev/null +++ b/ffi/boa_ffi/bindings/c/JsStringError.d.h @@ -0,0 +1,23 @@ +#ifndef JsStringError_D_H +#define JsStringError_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum JsStringError { + JsStringError_NotAString = 0, + JsStringError_InvalidEncoding = 1, +} JsStringError; + +typedef struct JsStringError_option {union { JsStringError ok; }; bool is_ok; } JsStringError_option; + + + +#endif // JsStringError_D_H diff --git a/ffi/boa_ffi/bindings/c/JsStringError.h b/ffi/boa_ffi/bindings/c/JsStringError.h new file mode 100644 index 00000000000..94efa77efa9 --- /dev/null +++ b/ffi/boa_ffi/bindings/c/JsStringError.h @@ -0,0 +1,22 @@ +#ifndef JsStringError_H +#define JsStringError_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "JsStringError.d.h" + + + + +// No Content + + + + + +#endif // JsStringError_H diff --git a/ffi/boa_ffi/bindings/c/JsValue.h b/ffi/boa_ffi/bindings/c/JsValue.h index df1963cc4cf..a18a0492dc6 100644 --- a/ffi/boa_ffi/bindings/c/JsValue.h +++ b/ffi/boa_ffi/bindings/c/JsValue.h @@ -7,6 +7,7 @@ #include #include "diplomat_runtime.h" +#include "JsStringError.d.h" #include "JsValueType.d.h" #include "JsValue.d.h" @@ -16,17 +17,30 @@ +JsValue* boa_JsValue_from_boolean(bool value); + JsValue* boa_JsValue_from_number(double number); +JsValue* boa_JsValue_from_string(DiplomatStringView value); + JsValue* boa_JsValue_from_null(void); JsValue* boa_JsValue_from_undefined(void); JsValueType boa_JsValue_get_type(const JsValue* self); +typedef struct boa_JsValue_as_boolean_result {union {bool ok; }; bool is_ok;} boa_JsValue_as_boolean_result; +boa_JsValue_as_boolean_result boa_JsValue_as_boolean(const JsValue* self); + typedef struct boa_JsValue_as_number_result {union {double ok; }; bool is_ok;} boa_JsValue_as_number_result; boa_JsValue_as_number_result boa_JsValue_as_number(const JsValue* self); +typedef struct boa_JsValue_as_string_result {union { JsStringError err;}; bool is_ok;} boa_JsValue_as_string_result; +boa_JsValue_as_string_result boa_JsValue_as_string(const JsValue* self, DiplomatWrite* write); + +typedef struct boa_JsValue_as_string_lossy_result { bool is_ok;} boa_JsValue_as_string_lossy_result; +boa_JsValue_as_string_lossy_result boa_JsValue_as_string_lossy(const JsValue* self, DiplomatWrite* write); + void boa_JsValue_destroy(JsValue* self); diff --git a/ffi/boa_ffi/src/lib.rs b/ffi/boa_ffi/src/lib.rs index 3a738b815b3..053485bc5e1 100644 --- a/ffi/boa_ffi/src/lib.rs +++ b/ffi/boa_ffi/src/lib.rs @@ -15,12 +15,14 @@ reason = "Diplomat transfers opaque handle ownership to C through boxed pointers" )] pub mod ffi { + use std::fmt::Write as _; + use boa_engine::{ Context, JsError as BoaJsError, JsNativeError as BoaJsNativeError, - JsNativeErrorKind as BoaJsNativeErrorKind, JsValue as BoaJsValue, context::ContextBuilder, - value::Type, + JsNativeErrorKind as BoaJsNativeErrorKind, JsString as BoaJsString, JsValue as BoaJsValue, + context::ContextBuilder, value::Type, }; - use diplomat_runtime::{DiplomatOption, DiplomatStr, DiplomatUtf8StrSlice}; + use diplomat_runtime::{DiplomatOption, DiplomatStr, DiplomatUtf8StrSlice, DiplomatWrite}; /// An owned Boa context, exposed as an opaque C handle. /// @@ -77,6 +79,15 @@ pub mod ffi { Object, } + /// The reason a value could not be read as a UTF-8 string. + #[derive(Debug, PartialEq, Eq)] + pub enum JsStringError { + /// The value is not a string. + NotAString, + /// The string contains an unpaired UTF-16 surrogate, so it has no UTF-8 form. + InvalidEncoding, + } + /// An owned JavaScript value, exposed as an opaque C handle. /// /// Keep it on its creating thread and destroy it exactly once with @@ -87,12 +98,29 @@ pub mod ffi { pub struct JsValue(BoaJsValue); impl JsValue { + /// Creates an owned boolean value without requiring a context. + #[must_use] + pub fn from_boolean(value: bool) -> Box { + Box::new(Self(BoaJsValue::from(value))) + } + /// Creates an owned number value without requiring a context. #[must_use] pub fn from_number(number: f64) -> Box { Box::new(Self(BoaJsValue::from(number))) } + /// Creates an owned string value by copying UTF-8 bytes, including any NULs. + /// + /// Returns null in C if the input is not valid UTF-8. Empty input may + /// pass a null pointer with length 0. No context is required. Allocation + /// failures and unexpected panics may abort. + #[must_use] + pub fn from_string(value: &DiplomatStr) -> Option> { + let text = std::str::from_utf8(value).ok()?; + Some(Box::new(Self(BoaJsValue::from(BoaJsString::from(text))))) + } + /// Creates an owned null value without requiring a context. #[must_use] pub fn from_null() -> Box { @@ -111,6 +139,15 @@ pub mod ffi { self.0.get_type().into() } + /// Returns the boolean, or an absent result for any other type. + /// + /// No conversion is performed; truthy and falsy non-boolean values return + /// an absent result. In C, check `is_ok` before reading `ok`. + #[must_use] + pub fn as_boolean(&self) -> DiplomatOption { + self.0.as_boolean().into() + } + /// Returns the number, or an absent result for any other type. /// /// No conversion is performed. In C, check `is_ok` before reading `ok`. @@ -119,6 +156,43 @@ pub mod ffi { pub fn as_number(&self) -> DiplomatOption { self.0.as_number().into() } + + /// Writes this string as UTF-8 into `write`, without coercion. + /// + /// Embedded NULs are preserved. In C, check `is_ok` before reading from + /// `write`. On error, nothing is written to `write`. + /// + /// # Errors + /// + /// Returns `NotAString` for any non-string value, or `InvalidEncoding` + /// if the string contains an unpaired UTF-16 surrogate. + pub fn as_string(&self, write: &mut DiplomatWrite) -> Result<(), JsStringError> { + let Some(string) = self.0.as_string() else { + return Err(JsStringError::NotAString); + }; + let Ok(utf8) = string.to_std_string() else { + return Err(JsStringError::InvalidEncoding); + }; + // Write the entire string in one call so fixed buffers fail + // atomically and `diplomat_buffer_write_create` grows at most once. + let _ = write.write_str(&utf8); + Ok(()) + } + + /// Writes this string as UTF-8 into `write`, replacing unpaired UTF-16 + /// surrogates with `U+FFFD`, or returns an absent result for any other type. + /// + /// No conversion is performed and embedded NULs are preserved. In C, + /// check `is_ok` before reading from `write`. + #[must_use] + pub fn as_string_lossy(&self, write: &mut DiplomatWrite) -> Option<()> { + let string = self.0.as_string()?; + let utf8 = string.to_std_string_lossy(); + // Write the entire string in one call so fixed buffers fail + // atomically and `diplomat_buffer_write_create` grows at most once. + let _ = write.write_str(&utf8); + Some(()) + } } /// The stored representation of an error, without normalization. @@ -256,14 +330,44 @@ pub mod ffi { #[cfg(test)] mod tests { use super::{ - BoaContext, BoaJsError, BoaJsNativeError, BoaJsNativeErrorKind, BoaJsValue, Context, - JsError, JsErrorRepresentation, JsNativeErrorKind, JsValue, JsValueType, + BoaContext, BoaJsError, BoaJsNativeError, BoaJsNativeErrorKind, BoaJsString, + BoaJsValue, Context, JsError, JsErrorRepresentation, JsNativeErrorKind, JsStringError, + JsValue, JsValueType, }; use boa_engine::{ Source, error::{EngineError, PanicError, RuntimeLimitError}, gc, js_string, }; + use diplomat_runtime::rust_interop::RustWriteVec; + + fn read_string(value: &JsValue) -> Result, JsStringError> { + let mut buffer = RustWriteVec::with_capacity(0); + // SAFETY: this is the only `DiplomatWrite` in scope, so it cannot be swapped. + let result = value.as_string(unsafe { buffer.borrow_mut() }); + let bytes = buffer.borrow().as_bytes().to_vec(); + match result { + Ok(()) => Ok(bytes), + Err(error) => { + assert!(bytes.is_empty(), "failed as_string should not write bytes"); + Err(error) + } + } + } + + fn read_string_lossy(value: &JsValue) -> Option> { + let mut buffer = RustWriteVec::with_capacity(0); + // SAFETY: this is the only `DiplomatWrite` in scope, so it cannot be swapped. + let result = value.as_string_lossy(unsafe { buffer.borrow_mut() }); + let bytes = buffer.borrow().as_bytes().to_vec(); + if result.is_none() { + assert!( + bytes.is_empty(), + "failed as_string_lossy should not write bytes" + ); + } + result.map(|()| bytes) + } #[test] fn initialization_failure_returns_none() { @@ -327,6 +431,115 @@ pub mod ffi { } } + #[test] + fn booleans_round_trip_without_coercion() { + for expected in [false, true] { + let value = JsValue::from_boolean(expected); + assert_eq!(value.get_type(), JsValueType::Boolean); + assert_eq!(value.as_boolean().into_option(), Some(expected)); + assert!(value.as_number().into_option().is_none()); + assert_eq!(read_string(&value), Err(JsStringError::NotAString)); + assert!(read_string_lossy(&value).is_none()); + } + + // Truthy and falsy non-boolean values must not coerce. + for value in [ + JsValue::from_number(0.0), + JsValue::from_number(1.0), + JsValue::from_number(1.5), + JsValue::from_string(b"").expect("valid UTF-8"), + JsValue::from_string(b"true").expect("valid UTF-8"), + ] { + assert!(value.as_boolean().into_option().is_none()); + } + } + + #[test] + fn strings_round_trip_and_reject_invalid_utf8() { + for text in [ + "", + "hello", + "latin1 \u{00e9}", + "crab \u{1f980}", + "before\0after", + ] { + let value = JsValue::from_string(text.as_bytes()).expect("valid UTF-8"); + assert_eq!(value.get_type(), JsValueType::String, "{text:?}"); + assert!(value.as_boolean().into_option().is_none()); + assert!(value.as_number().into_option().is_none()); + assert_eq!( + read_string(&value), + Ok(text.as_bytes().to_vec()), + "{text:?}" + ); + assert_eq!( + read_string_lossy(&value), + Some(text.as_bytes().to_vec()), + "{text:?}" + ); + } + + for invalid in [&b"\xff"[..], b"\xed\xa0\x80"] { + assert!(JsValue::from_string(invalid).is_none(), "{invalid:?}"); + } + } + + #[test] + fn unpaired_surrogates_fail_strict_and_replace_in_lossy() { + for (units, expected_lossy) in [ + (&[0xD800u16][..], "\u{fffd}"), + (&[0xDC00u16][..], "\u{fffd}"), + ( + &[u16::from(b'a'), 0xD800, u16::from(b'b')][..], + "a\u{fffd}b", + ), + ] { + let value = JsValue(BoaJsValue::from(BoaJsString::from(units))); + assert_eq!(value.get_type(), JsValueType::String, "{units:x?}"); + assert_eq!( + read_string(&value), + Err(JsStringError::InvalidEncoding), + "{units:x?}" + ); + assert_eq!( + read_string_lossy(&value), + Some(expected_lossy.as_bytes().to_vec()), + "{units:x?}" + ); + } + } + + #[test] + fn engine_produced_strings_read_across_representations() { + let mut context = Context::builder() + .build() + .expect("context should initialize"); + for (source, expected) in [ + ("'hello world'.slice(6)", Ok(b"world".as_slice())), + ("'a' + '\\0' + '\\u{1F980}'", Ok("a\0\u{1f980}".as_bytes())), + ("'\\ud800'", Err(JsStringError::InvalidEncoding)), + ] { + let value = JsValue( + context + .eval(Source::from_bytes(source)) + .expect("valid source"), + ); + assert_eq!(value.get_type(), JsValueType::String, "{source}"); + assert_eq!( + read_string(&value), + expected.map(<[u8]>::to_vec), + "{source}" + ); + if expected.is_err() { + assert_eq!( + read_string_lossy(&value), + Some("\u{fffd}".as_bytes().to_vec()), + "{source}" + ); + } + } + } + #[test] fn null_and_undefined_are_distinct_non_numbers() { for (value, expected_type) in [ @@ -334,7 +547,10 @@ pub mod ffi { (JsValue::from_undefined(), JsValueType::Undefined), ] { assert_eq!(value.get_type(), expected_type); + assert!(value.as_boolean().into_option().is_none()); assert!(value.as_number().into_option().is_none()); + assert_eq!(read_string(&value), Err(JsStringError::NotAString)); + assert!(read_string_lossy(&value).is_none()); } } @@ -360,11 +576,26 @@ pub mod ffi { .expect("valid source"), ); assert_eq!(value.get_type(), expected_type, "{source}"); + assert_eq!( + value.as_boolean().into_option().is_some(), + expected_type == JsValueType::Boolean, + "{source}" + ); assert_eq!( value.as_number().into_option().is_some(), expected_type == JsValueType::Number, "{source}" ); + assert_eq!( + read_string(&value).is_ok(), + expected_type == JsValueType::String, + "{source}" + ); + assert_eq!( + read_string_lossy(&value).is_some(), + expected_type == JsValueType::String, + "{source}" + ); } } diff --git a/ffi/boa_ffi/tests/c/error.c b/ffi/boa_ffi/tests/c/error.c index 259a85d09df..bd8fa2fab33 100644 --- a/ffi/boa_ffi/tests/c/error.c +++ b/ffi/boa_ffi/tests/c/error.c @@ -85,10 +85,24 @@ static bool payload_matches(JsValue *value, JsValueType kind) { if (value == NULL || boa_JsValue_get_type(value) != kind) { return false; } + boa_JsValue_as_boolean_result boolean = boa_JsValue_as_boolean(value); boa_JsValue_as_number_result number = boa_JsValue_as_number(value); - return kind == JsValueType_Number + DiplomatWrite *write = diplomat_buffer_write_create(0); + boa_JsValue_as_string_result string = boa_JsValue_as_string(value, write); + const char *bytes = diplomat_buffer_write_get_bytes(write); + size_t len = diplomat_buffer_write_len(write); + bool string_ok = kind == JsValueType_String + ? string.is_ok && len == 4 && bytes != NULL && memcmp(bytes, "boom", 4) == 0 + : !string.is_ok && string.err == JsStringError_NotAString && len == 0; + diplomat_buffer_write_destroy(write); + + bool bool_ok = kind == JsValueType_Boolean + ? boolean.is_ok && boolean.ok + : !boolean.is_ok; + bool number_ok = kind == JsValueType_Number ? number.is_ok && number.ok == 7.0 : !number.is_ok; + return bool_ok && number_ok && string_ok; } static bool opaque_error(JsValue *input, JsValueType kind, bool error_first) { @@ -125,7 +139,10 @@ int main(void) { } for (size_t order = 0; order < 2; ++order) { bool error_first = order == 0; - if (!opaque_error(boa_JsValue_from_number(7.0), JsValueType_Number, error_first) || + if (!opaque_error(boa_JsValue_from_boolean(true), JsValueType_Boolean, error_first) || + !opaque_error(boa_JsValue_from_number(7.0), JsValueType_Number, error_first) || + !opaque_error(boa_JsValue_from_string((DiplomatStringView){.data = "boom", .len = 4}), + JsValueType_String, error_first) || !opaque_error(boa_JsValue_from_null(), JsValueType_Null, error_first) || !opaque_error(boa_JsValue_from_undefined(), JsValueType_Undefined, error_first)) { fputs("opaque error payload ownership failed\n", stderr); diff --git a/ffi/boa_ffi/tests/c/value.c b/ffi/boa_ffi/tests/c/value.c index c049ecdedbc..8d5880ecfc2 100644 --- a/ffi/boa_ffi/tests/c/value.c +++ b/ffi/boa_ffi/tests/c/value.c @@ -3,6 +3,7 @@ #include #include #include +#include #include "BoaContext.h" #include "JsValue.h" @@ -17,6 +18,162 @@ static bool same_number(double actual, double expected) { return expected != 0.0 || (signbit(actual) != 0) == (signbit(expected) != 0); } +static bool string_matches(const JsValue *value, const char *expected, size_t expected_len) { + DiplomatWrite *strict = diplomat_buffer_write_create(0); + boa_JsValue_as_string_result strict_result = boa_JsValue_as_string(value, strict); + const char *strict_bytes = diplomat_buffer_write_get_bytes(strict); + size_t strict_len = diplomat_buffer_write_len(strict); + bool strict_ok = strict_result.is_ok && strict_len == expected_len && + (expected_len == 0 || + (strict_bytes != NULL && memcmp(strict_bytes, expected, expected_len) == 0)); + diplomat_buffer_write_destroy(strict); + + DiplomatWrite *lossy = diplomat_buffer_write_create(0); + boa_JsValue_as_string_lossy_result lossy_result = boa_JsValue_as_string_lossy(value, lossy); + const char *lossy_bytes = diplomat_buffer_write_get_bytes(lossy); + size_t lossy_len = diplomat_buffer_write_len(lossy); + bool lossy_ok = lossy_result.is_ok && lossy_len == expected_len && + (expected_len == 0 || + (lossy_bytes != NULL && memcmp(lossy_bytes, expected, expected_len) == 0)); + diplomat_buffer_write_destroy(lossy); + + return strict_ok && lossy_ok; +} + +static bool not_a_string(const JsValue *value) { + DiplomatWrite *strict = diplomat_buffer_write_create(0); + boa_JsValue_as_string_result strict_result = boa_JsValue_as_string(value, strict); + bool strict_ok = !strict_result.is_ok && + strict_result.err == JsStringError_NotAString && + diplomat_buffer_write_len(strict) == 0; + diplomat_buffer_write_destroy(strict); + + DiplomatWrite *lossy = diplomat_buffer_write_create(0); + boa_JsValue_as_string_lossy_result lossy_result = boa_JsValue_as_string_lossy(value, lossy); + bool lossy_ok = !lossy_result.is_ok && diplomat_buffer_write_len(lossy) == 0; + diplomat_buffer_write_destroy(lossy); + + return strict_ok && lossy_ok; +} + +static bool booleans(void) { + const bool values[] = {false, true}; + for (size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i) { + JsValue *value = boa_JsValue_from_boolean(values[i]); + for (size_t read = 0; read < 2; ++read) { + boa_JsValue_as_boolean_result result = boa_JsValue_as_boolean(value); + if (boa_JsValue_get_type(value) != JsValueType_Boolean || + !result.is_ok || result.ok != values[i] || + boa_JsValue_as_number(value).is_ok || !not_a_string(value)) { + boa_JsValue_destroy(value); + return false; + } + } + boa_JsValue_destroy(value); + } + + JsValue *non_booleans[] = { + boa_JsValue_from_number(0.0), + boa_JsValue_from_number(1.0), + boa_JsValue_from_string((DiplomatStringView){.data = "", .len = 0}), + boa_JsValue_from_string((DiplomatStringView){.data = "true", .len = 4}), + }; + bool valid = true; + for (size_t i = 0; i < sizeof(non_booleans) / sizeof(non_booleans[0]); ++i) { + if (non_booleans[i] == NULL || boa_JsValue_as_boolean(non_booleans[i]).is_ok) { + valid = false; + } + if (non_booleans[i] != NULL) { + boa_JsValue_destroy(non_booleans[i]); + } + } + return valid; +} + +static bool strings(void) { + const char nul_sample[] = "before\0after"; + const DiplomatStringView samples[] = { + {.data = "", .len = 0}, + {.data = "hello", .len = 5}, + {.data = "latin1 \xC3\xA9", .len = 9}, + {.data = "crab \xF0\x9F\xA6\x80", .len = 9}, + {.data = nul_sample, .len = sizeof(nul_sample) - 1}, + }; + + for (size_t i = 0; i < sizeof(samples) / sizeof(samples[0]); ++i) { + char copy[32]; + if (samples[i].len > 0) { + memcpy(copy, samples[i].data, samples[i].len); + } + JsValue *value = boa_JsValue_from_string( + (DiplomatStringView){.data = copy, .len = samples[i].len}); + if (value == NULL) { + return false; + } + memset(copy, 'x', sizeof(copy)); + + for (size_t read = 0; read < 2; ++read) { + if (boa_JsValue_get_type(value) != JsValueType_String || + boa_JsValue_as_boolean(value).is_ok || + boa_JsValue_as_number(value).is_ok || + !string_matches(value, samples[i].data, samples[i].len)) { + boa_JsValue_destroy(value); + return false; + } + } + boa_JsValue_destroy(value); + } + + // Empty string with a NULL data pointer. + JsValue *empty = boa_JsValue_from_string((DiplomatStringView){.data = NULL, .len = 0}); + if (empty == NULL) { + return false; + } + bool empty_ok = boa_JsValue_get_type(empty) == JsValueType_String && + string_matches(empty, "", 0); + boa_JsValue_destroy(empty); + if (!empty_ok) { + return false; + } + + // Fixed stack buffer: exact fit and overflow handling, plus a shorter view. + const char slice_buf[] = "hello!"; + JsValue *hello = boa_JsValue_from_string((DiplomatStringView){.data = slice_buf, .len = 5}); + if (hello == NULL) { + return false; + } + char exact_buf[6]; + DiplomatWrite exact_write = diplomat_simple_write(exact_buf, sizeof(exact_buf)); + boa_JsValue_as_string_result exact_res = boa_JsValue_as_string(hello, &exact_write); + + char small_buf[4] = {'a', 'b', 'c', 'd'}; + DiplomatWrite small_write = diplomat_simple_write(small_buf, sizeof(small_buf)); + boa_JsValue_as_string_result small_res = boa_JsValue_as_string(hello, &small_write); + + bool simple_ok = exact_res.is_ok && !exact_write.grow_failed && exact_write.len == 5 && + memcmp(exact_buf, "hello\0", 6) == 0 && + small_res.is_ok && small_write.grow_failed && small_write.len == 0 && + small_buf[0] == '\0'; + boa_JsValue_destroy(hello); + if (!simple_ok) { + return false; + } + + // Invalid UTF-8 must be rejected with NULL. + const DiplomatStringView invalid[] = { + {.data = "\xFF", .len = 1}, + {.data = "\xED\xA0\x80", .len = 3}, + }; + for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { + JsValue *bad = boa_JsValue_from_string(invalid[i]); + if (bad != NULL) { + boa_JsValue_destroy(bad); + return false; + } + } + return true; +} + int main(void) { const double numbers[] = { 0.0, -0.0, 1.5, -2.75, @@ -30,7 +187,8 @@ int main(void) { for (size_t read = 0; read < 2; ++read) { boa_JsValue_as_number_result result = boa_JsValue_as_number(value); if (boa_JsValue_get_type(value) != JsValueType_Number || - !result.is_ok || !same_number(result.ok, numbers[i])) { + !result.is_ok || !same_number(result.ok, numbers[i]) || + boa_JsValue_as_boolean(value).is_ok || !not_a_string(value)) { boa_JsValue_destroy(value); fprintf(stderr, "number round trip failed at index %zu\n", i); return EXIT_FAILURE; @@ -39,26 +197,51 @@ int main(void) { boa_JsValue_destroy(value); } + if (!booleans()) { + fputs("boolean round trip or non-coercion check failed\n", stderr); + return EXIT_FAILURE; + } + if (!strings()) { + fputs("string round trip or UTF-8 validation failed\n", stderr); + return EXIT_FAILURE; + } + BoaContext *context = boa_BoaContext_new(); if (context == NULL) { fputs("context failed to initialize\n", stderr); return EXIT_FAILURE; } + const char kept[] = "kept\0value"; JsValue *null_value = boa_JsValue_from_null(); JsValue *undefined_value = boa_JsValue_from_undefined(); + JsValue *boolean = boa_JsValue_from_boolean(true); JsValue *number = boa_JsValue_from_number(42.5); + JsValue *string = boa_JsValue_from_string( + (DiplomatStringView){.data = kept, .len = sizeof(kept) - 1}); boa_BoaContext_destroy(context); - boa_JsValue_as_number_result result = boa_JsValue_as_number(number); + boa_JsValue_as_boolean_result bool_result = boa_JsValue_as_boolean(boolean); + boa_JsValue_as_number_result num_result = boa_JsValue_as_number(number); bool valid = boa_JsValue_get_type(null_value) == JsValueType_Null && boa_JsValue_get_type(undefined_value) == JsValueType_Undefined && + !boa_JsValue_as_boolean(null_value).is_ok && + !boa_JsValue_as_boolean(undefined_value).is_ok && !boa_JsValue_as_number(null_value).is_ok && !boa_JsValue_as_number(undefined_value).is_ok && + not_a_string(null_value) && not_a_string(undefined_value) && + boa_JsValue_get_type(boolean) == JsValueType_Boolean && + bool_result.is_ok && bool_result.ok && boa_JsValue_get_type(number) == JsValueType_Number && - result.is_ok && same_number(result.ok, 42.5); + num_result.is_ok && same_number(num_result.ok, 42.5) && + string != NULL && boa_JsValue_get_type(string) == JsValueType_String && + string_matches(string, kept, sizeof(kept) - 1); boa_JsValue_destroy(null_value); boa_JsValue_destroy(undefined_value); + boa_JsValue_destroy(boolean); boa_JsValue_destroy(number); + if (string != NULL) { + boa_JsValue_destroy(string); + } if (!valid) { fputs("primitive values failed after context destruction\n", stderr); return EXIT_FAILURE; From 0e3c3b63e5e4168bae371d8a50b04086f8d599c6 Mon Sep 17 00:00:00 2001 From: Jason Milad Date: Thu, 26 Nov 2026 09:30:19 -0500 Subject: [PATCH 2/2] Document write.grow_failed in as_string doc comments --- ffi/boa_ffi/src/lib.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/ffi/boa_ffi/src/lib.rs b/ffi/boa_ffi/src/lib.rs index 053485bc5e1..c3cc7c5dcf6 100644 --- a/ffi/boa_ffi/src/lib.rs +++ b/ffi/boa_ffi/src/lib.rs @@ -160,7 +160,9 @@ pub mod ffi { /// Writes this string as UTF-8 into `write`, without coercion. /// /// Embedded NULs are preserved. In C, check `is_ok` before reading from - /// `write`. On error, nothing is written to `write`. + /// `write`, and check `write.grow_failed` for overflow when using a + /// fixed stack buffer (`diplomat_simple_write`). On error, nothing is + /// written to `write`. /// /// # Errors /// @@ -183,7 +185,9 @@ pub mod ffi { /// surrogates with `U+FFFD`, or returns an absent result for any other type. /// /// No conversion is performed and embedded NULs are preserved. In C, - /// check `is_ok` before reading from `write`. + /// check `is_ok` before reading from `write`, and check + /// `write.grow_failed` for overflow when using a fixed stack buffer + /// (`diplomat_simple_write`). #[must_use] pub fn as_string_lossy(&self, write: &mut DiplomatWrite) -> Option<()> { let string = self.0.as_string()?;