From c935b61e018cb193bebd75f2c74f406d3809f858 Mon Sep 17 00:00:00 2001 From: Roger Chen Date: Fri, 20 Nov 2026 15:42:38 -0500 Subject: [PATCH 1/9] Add eval to the C API --- ffi/boa_ffi/bindings/c/BoaContext.h | 5 +++++ ffi/boa_ffi/src/lib.rs | 33 +++++++++++++++++++++++++---- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/ffi/boa_ffi/bindings/c/BoaContext.h b/ffi/boa_ffi/bindings/c/BoaContext.h index 17c3e785646..84d1b872589 100644 --- a/ffi/boa_ffi/bindings/c/BoaContext.h +++ b/ffi/boa_ffi/bindings/c/BoaContext.h @@ -7,6 +7,8 @@ #include #include "diplomat_runtime.h" +#include "JsError.d.h" +#include "JsValue.d.h" #include "BoaContext.d.h" @@ -17,6 +19,9 @@ BoaContext* boa_BoaContext_new(void); +typedef struct boa_BoaContext_eval_result {union {JsValue* ok; JsError* err;}; bool is_ok;} boa_BoaContext_eval_result; +boa_BoaContext_eval_result boa_BoaContext_eval(BoaContext* self, DiplomatStringView source); + void boa_BoaContext_destroy(BoaContext* self); diff --git a/ffi/boa_ffi/src/lib.rs b/ffi/boa_ffi/src/lib.rs index 3a738b815b3..363e326fd36 100644 --- a/ffi/boa_ffi/src/lib.rs +++ b/ffi/boa_ffi/src/lib.rs @@ -17,8 +17,8 @@ pub mod ffi { use boa_engine::{ Context, JsError as BoaJsError, JsNativeError as BoaJsNativeError, - JsNativeErrorKind as BoaJsNativeErrorKind, JsValue as BoaJsValue, context::ContextBuilder, - value::Type, + JsNativeErrorKind as BoaJsNativeErrorKind, JsValue as BoaJsValue, Source, + context::ContextBuilder, value::Type, }; use diplomat_runtime::{DiplomatOption, DiplomatStr, DiplomatUtf8StrSlice}; @@ -30,7 +30,7 @@ pub mod ffi { #[derive(Debug)] #[diplomat::opaque_mut] pub struct BoaContext { - _context: Context, + context: Context, } impl BoaContext { @@ -48,7 +48,32 @@ pub mod ffi { builder .build() .ok() - .map(|context| Box::new(Self { _context: context })) + .map(|context| Box::new(Self { context })) + } + + /// Evaluates UTF-8 source text as a script and returns its completion value. + /// + /// Empty source evaluates to undefined. The source is borrowed only for + /// this call. Promise jobs are not run, and there is no time limit: a + /// script that never finishes never returns. + /// + /// In C, check `is_ok`, then destroy the handle that was returned with + /// `boa_JsValue_destroy` or `boa_JsError_destroy`. It is never null. + /// + /// # Errors + /// + /// Returns the engine's error unchanged if the source does not parse or + /// the script throws. Source that is not valid UTF-8 returns a native + /// type error, and nothing is evaluated. + pub fn eval(&mut self, source: &DiplomatStr) -> Result, Box> { + let Ok(source) = std::str::from_utf8(source) else { + let error = BoaJsNativeError::typ().with_message("source text is not valid UTF-8"); + return Err(Box::new(JsError(error.into()))); + }; + match self.context.eval(Source::from_bytes(source)) { + Ok(value) => Ok(Box::new(JsValue(value))), + Err(error) => Err(Box::new(JsError(error))), + } } } From 6d9a17586cf45c1ac66ca2218a48f59a867deef2 Mon Sep 17 00:00:00 2001 From: Roger Chen Date: Mon, 23 Nov 2026 13:28:15 -0500 Subject: [PATCH 2/9] Add Rust eval tests --- ffi/boa_ffi/src/lib.rs | 169 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) diff --git a/ffi/boa_ffi/src/lib.rs b/ffi/boa_ffi/src/lib.rs index 363e326fd36..4c82a100df3 100644 --- a/ffi/boa_ffi/src/lib.rs +++ b/ffi/boa_ffi/src/lib.rs @@ -560,6 +560,175 @@ pub mod ffi { assert_eq!(error.0.as_engine(), Some(&original)); } } + + /// Evaluates source that should succeed and reads the result as a number. + fn eval_number(context: &mut BoaContext, source: &str) -> Option { + context + .eval(source.as_bytes()) + .expect("source should evaluate") + .as_number() + .into_option() + } + + #[test] + fn eval_returns_values_and_keeps_each_error_representation() { + let mut context = BoaContext::new().expect("context should initialize"); + + assert_eq!(eval_number(&mut context, "1 + 2"), Some(3.0)); + for source in ["undefined", "", "var a = 4;"] { + let value = context + .eval(source.as_bytes()) + .expect("source should evaluate"); + assert_eq!(value.get_type(), JsValueType::Undefined, "{source:?}"); + } + + for (source, payload_type) in [ + ("throw 7", JsValueType::Number), + ("throw null", JsValueType::Null), + ("throw undefined", JsValueType::Undefined), + ("throw new Error('boom')", JsValueType::Object), + ] { + let error = context + .eval(source.as_bytes()) + .expect_err("source should throw"); + assert_eq!( + error.get_representation(), + JsErrorRepresentation::Opaque, + "{source}" + ); + assert!(error.as_native().is_none(), "{source}"); + let payload = error.as_opaque().expect("opaque payload"); + assert_eq!(payload.get_type(), payload_type, "{source}"); + } + + for (source, kind) in [ + ("1 +", JsNativeErrorKind::Syntax), + ("setTimeout", JsNativeErrorKind::Reference), + ] { + let error = context + .eval(source.as_bytes()) + .expect_err("source should fail"); + assert_eq!( + error.get_representation(), + JsErrorRepresentation::Native, + "{source}" + ); + let info = error.as_native().expect("native details"); + assert_eq!(info.kind, kind, "{source}"); + assert!(error.as_opaque().is_none(), "{source}"); + } + } + + #[test] + fn eval_error_carries_the_thrown_object() { + let mut context = BoaContext::new().expect("context should initialize"); + let error = context + .eval(b"globalThis.thrown = { payload: 7 }; throw thrown") + .expect_err("source should throw"); + let payload = error.as_opaque().expect("opaque payload"); + let thrown = context.eval(b"thrown").expect("global should be readable"); + assert!(BoaJsValue::same_value(&payload.0, &thrown.0)); + } + + #[test] + fn eval_state_persists_across_calls_and_throws() { + let mut context = BoaContext::new().expect("context should initialize"); + context + .eval(b"var count = 1;") + .expect("declaration should evaluate"); + assert_eq!(eval_number(&mut context, "count + 1"), Some(2.0)); + + // Effects that happened before a throw are kept. + let error = context + .eval(b"count = 9; throw 7") + .expect_err("source should throw"); + let payload = error.as_opaque().expect("opaque payload"); + assert_eq!(payload.as_number().into_option(), Some(7.0)); + assert_eq!(eval_number(&mut context, "count"), Some(9.0)); + } + + #[test] + fn eval_rejects_invalid_utf8_before_running_anything() { + let mut context = BoaContext::new().expect("context should initialize"); + context + .eval(b"var ran = 0;") + .expect("declaration should evaluate"); + for invalid in [ + &b"ran++; \xff"[..], + b"ran++; '\xf0\x9f\xa6'", + b"ran++; '\xed\xa0\x80'", + ] { + let error = context + .eval(invalid) + .expect_err("invalid UTF-8 should be rejected"); + assert_eq!(error.get_representation(), JsErrorRepresentation::Native); + let info = error.as_native().expect("native details"); + assert_eq!(info.kind, JsNativeErrorKind::Type); + assert_eq!(info.message.as_bytes(), b"source text is not valid UTF-8"); + } + assert_eq!(eval_number(&mut context, "ran"), Some(0.0)); + } + + #[test] + fn eval_source_may_contain_nul() { + let mut context = BoaContext::new().expect("context should initialize"); + assert_eq!(eval_number(&mut context, "'a\0b'.length"), Some(3.0)); + } + + #[test] + fn eval_reports_engine_errors_and_the_context_stays_usable() { + let mut context = BoaContext::new().expect("context should initialize"); + let error = context + .eval(b"function recurse() { recurse(); } recurse()") + .expect_err("endless recursion should fail"); + assert_eq!(error.get_representation(), JsErrorRepresentation::Engine); + assert!(error.as_native().is_none()); + assert!(error.as_opaque().is_none()); + assert_eq!( + error.0.as_engine(), + Some(&EngineError::from(RuntimeLimitError::Recursion)) + ); + + assert_eq!(eval_number(&mut context, "1 + 2"), Some(3.0)); + } + + #[test] + fn eval_results_can_outlive_their_context() { + let mut context = BoaContext::new().expect("context should initialize"); + let object = context + .eval(b"({ payload: 7 })") + .expect("object should be created"); + let function = context + .eval(b"(function named() { return 7; })") + .expect("function should be created"); + let error = context + .eval(b"throw new Error('boom')") + .expect_err("source should throw"); + let payload = error.as_opaque().expect("opaque payload"); + drop(context); + gc::force_collect(); + + assert_eq!(object.get_type(), JsValueType::Object); + assert_eq!(function.get_type(), JsValueType::Object); + assert_eq!(error.get_representation(), JsErrorRepresentation::Opaque); + assert_eq!(payload.get_type(), JsValueType::Object); + drop((object, function, error, payload)); + gc::force_collect(); + } + + #[test] + fn eval_does_not_run_promise_jobs() { + let mut context = BoaContext::new().expect("context should initialize"); + let promise = context + .eval( + b"var ran = 0; + Promise.resolve().then(() => { ran = 1; }); + Promise.reject(new Error('boom'))", + ) + .expect("a rejected promise is a value, not a thrown error"); + assert_eq!(promise.get_type(), JsValueType::Object); + assert_eq!(eval_number(&mut context, "ran"), Some(0.0)); + } } } From e14e3ec12a380d1d3229e4ec0c2ff72e0881f90c Mon Sep 17 00:00:00 2001 From: Roger Chen Date: Mon, 23 Nov 2026 14:27:48 -0500 Subject: [PATCH 3/9] Add C eval tests and docs --- ffi/boa_ffi/README.md | 88 +++++++++++++-- ffi/boa_ffi/tests/c/eval.c | 223 +++++++++++++++++++++++++++++++++++++ ffi/boa_ffi/tests/c/run.sh | 2 +- 3 files changed, 303 insertions(+), 10 deletions(-) create mode 100644 ffi/boa_ffi/tests/c/eval.c diff --git a/ffi/boa_ffi/README.md b/ffi/boa_ffi/README.md index bbc55feb6f2..369eb1db756 100644 --- a/ffi/boa_ffi/README.md +++ b/ffi/boa_ffi/README.md @@ -1,9 +1,9 @@ # Boa C bindings `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. +API supports context lifecycle, evaluating JavaScript source, value handles with +type inspection and number/null/undefined construction, and structured error +construction and inspection. The API is experimental and may change. ## Build and test @@ -27,10 +27,11 @@ 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. -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 +round trips, retained error data, inspection without JavaScript execution and +each kind of evaluation result. Object retention is checked across garbage +collection. The C tests exercise context/value/error lifecycle, numeric edge +cases, message encoding and evaluation (`tests/c/eval.c`) 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. @@ -73,6 +74,75 @@ int main(void) { - `NULL` does not represent recovery from arbitrary Rust panics or allocation failure. These failures may abort the process; this API does not catch panics. +## Evaluating JavaScript + +`boa_BoaContext_eval()` runs source text as a script in a context. It returns +either the script's completion value or the error that stopped it. + +```c +#include +#include "BoaContext.h" +#include "JsError.h" +#include "JsValue.h" + +int main(void) { + BoaContext *context = boa_BoaContext_new(); + if (context == NULL) { + return 1; + } + const char source[] = "6 * 7"; + boa_BoaContext_eval_result result = boa_BoaContext_eval(context, + (DiplomatStringView){.data = source, .len = sizeof(source) - 1}); + if (result.is_ok) { + boa_JsValue_as_number_result number = boa_JsValue_as_number(result.ok); + if (number.is_ok) { + printf("%g\n", number.ok); + } + boa_JsValue_destroy(result.ok); + } else { + /* A thrown value, such as the 7 in `throw 7`, is the error's payload. + The payload is its own handle, so it can outlive the error. */ + JsValue *thrown = boa_JsError_as_opaque(result.err); + boa_JsError_destroy(result.err); + if (thrown != NULL) { + boa_JsValue_as_number_result number = boa_JsValue_as_number(thrown); + if (number.is_ok) { + printf("threw %g\n", number.ok); + } + boa_JsValue_destroy(thrown); + } + } + boa_BoaContext_destroy(context); + return 0; +} +``` + +- The source is a pointer and a byte length, not a NUL-terminated string, so it + may contain NUL. It must be UTF-8. The bytes are borrowed only for the call; + the caller may change or free the buffer once it returns. Empty source may + use a `NULL` pointer with length 0. +- Check `is_ok` before reading the result. Success carries `ok`, an owned value + handle that is never `NULL`: empty source and source that only declares + evaluate to undefined. Failure carries `err`, an owned error handle. Destroy + whichever handle was returned, exactly once. +- The error is Boa's own, unchanged, so the functions under [Errors](#errors) + apply. A value the script throws is `Opaque`, including Error objects: + `throw 7` holds the number 7 and `throw new Error('boom')` holds the object. + An error the engine raises that the script does not catch, such as a syntax + error or an undefined name, is `Native`; if the script catches and rethrows + it, it is `Opaque`. Exceeding an engine limit, such as the recursion limit, + is `Engine`, and the context remains usable afterward. +- Source that is not valid UTF-8 fails with a `Native` type error, and nothing + is evaluated. +- Calls on one context share its global state: a later call sees what an + earlier one defined, and a throw does not undo what ran before it. Separate + contexts share nothing. +- Promise jobs are not run. `then` callbacks do not execute, and a rejected + promise is returned as a value, not reported as an error. +- There is no time limit. A script that never finishes never returns. +- Returned handles do not borrow from the context. Each one may be inspected + and destroyed before or after the context is destroyed. + ## Value handles `boa_JsValue_from_number(double)`, `boa_JsValue_from_null()` and @@ -159,8 +229,8 @@ input handle and may destroy it independently. `boa_JsError_as_opaque()` returns new owned value handle for the stored payload, or `NULL` for native/engine errors. Null and undefined payloads return present handles with their respective types. Each returned payload must be destroyed with `boa_JsValue_destroy()`, independently -of the error. Object identity is preserved. Keep a context alive while using -resources that depend on it, including retained objects. +of the error. Object identity is preserved. A payload may outlive both the +error and the context it came from. Use and destroy errors on their creating thread. Getters require live, non-null handles. Destroy each owned error exactly once with `boa_JsError_destroy()`; pointer diff --git a/ffi/boa_ffi/tests/c/eval.c b/ffi/boa_ffi/tests/c/eval.c new file mode 100644 index 00000000000..90492af33a9 --- /dev/null +++ b/ffi/boa_ffi/tests/c/eval.c @@ -0,0 +1,223 @@ +#include +#include +#include +#include + +#include "BoaContext.h" +#include "JsError.h" +#include "JsValue.h" + +static DiplomatStringView view(const char *source) { + return (DiplomatStringView){.data = source, .len = strlen(source)}; +} + +static JsValue *eval_value(BoaContext *context, DiplomatStringView source) { + boa_BoaContext_eval_result result = boa_BoaContext_eval(context, source); + if (result.is_ok) { + return result.ok; + } + boa_JsError_destroy(result.err); + return NULL; +} + +static JsError *eval_error(BoaContext *context, DiplomatStringView source) { + boa_BoaContext_eval_result result = boa_BoaContext_eval(context, source); + if (!result.is_ok) { + return result.err; + } + if (result.ok != NULL) { + boa_JsValue_destroy(result.ok); + } + return NULL; +} + +static bool has_type(BoaContext *context, DiplomatStringView source, JsValueType type) { + JsValue *value = eval_value(context, source); + if (value == NULL) { + return false; + } + bool valid = boa_JsValue_get_type(value) == type; + boa_JsValue_destroy(value); + return valid; +} + +static bool has_number(BoaContext *context, const char *source, double expected) { + JsValue *value = eval_value(context, view(source)); + if (value == NULL) { + return false; + } + boa_JsValue_as_number_result number = boa_JsValue_as_number(value); + boa_JsValue_destroy(value); + return number.is_ok && number.ok == expected; +} + +static bool throws(BoaContext *context, const char *source, JsValueType type) { + JsError *error = eval_error(context, view(source)); + if (error == NULL) { + return false; + } + JsValue *payload = boa_JsError_as_opaque(error); + bool valid = boa_JsError_get_representation(error) == JsErrorRepresentation_Opaque && + !boa_JsError_as_native(error).is_ok && + payload != NULL && boa_JsValue_get_type(payload) == type; + if (valid && type == JsValueType_Number) { + boa_JsValue_as_number_result number = boa_JsValue_as_number(payload); + valid = number.is_ok && number.ok == 7.0; + } + if (payload != NULL) { + boa_JsValue_destroy(payload); + } + boa_JsError_destroy(error); + return valid; +} + +// `kind` is checked only for native errors. +static bool fails(BoaContext *context, const char *source, + JsErrorRepresentation representation, JsNativeErrorKind kind) { + JsError *error = eval_error(context, view(source)); + if (error == NULL) { + return false; + } + boa_JsError_as_native_result info = boa_JsError_as_native(error); + JsValue *payload = boa_JsError_as_opaque(error); + bool valid = boa_JsError_get_representation(error) == representation && payload == NULL && + (representation == JsErrorRepresentation_Native + ? info.is_ok && info.ok.kind == kind + : !info.is_ok); + if (payload != NULL) { + boa_JsValue_destroy(payload); + } + boa_JsError_destroy(error); + return valid; +} + +static bool results(BoaContext *context) { + return has_type(context, view("undefined"), JsValueType_Undefined) && + throws(context, "throw 7", JsValueType_Number) && + throws(context, "throw new Error('boom')", JsValueType_Object) && + throws(context, "throw undefined", JsValueType_Undefined) && + throws(context, "throw null", JsValueType_Null) && + has_number(context, "1 + 2", 3.0) && + has_type(context, (DiplomatStringView){.data = NULL, .len = 0}, JsValueType_Undefined) && + fails(context, "1 +", JsErrorRepresentation_Native, JsNativeErrorKind_Syntax) && + fails(context, "missing", JsErrorRepresentation_Native, JsNativeErrorKind_Reference) && + fails(context, "null.x", JsErrorRepresentation_Native, JsNativeErrorKind_Type) && + throws(context, "try { null.x } catch (error) { throw error; }", JsValueType_Object); +} + +static bool invalid_utf8(BoaContext *context) { + const char *const sources[] = { + "ran++; \xFF", "ran++; '\xF0\x9F\xA6'", "ran++; '\xED\xA0\x80'", + }; + if (!has_type(context, view("var ran = 0;"), JsValueType_Undefined)) { + return false; + } + for (size_t i = 0; i < sizeof(sources) / sizeof(sources[0]); ++i) { + if (!fails(context, sources[i], JsErrorRepresentation_Native, JsNativeErrorKind_Type)) { + return false; + } + } + return has_number(context, "ran", 0.0); +} + +static bool source_is_only_borrowed(BoaContext *context) { + char source[] = "function seven() { return 3 + 4; } seven"; + JsValue *function = eval_value(context, view(source)); + memset(source, 'x', sizeof(source) - 1); + if (function == NULL) { + return false; + } + bool valid = boa_JsValue_get_type(function) == JsValueType_Object && + has_number(context, "seven()", 7.0); + boa_JsValue_destroy(function); + return valid; +} + +static bool state_and_limits(BoaContext *context) { + return has_type(context, view("var count = 1;"), JsValueType_Undefined) && + has_number(context, "count + 1", 2.0) && + throws(context, "count = 9; throw 7", JsValueType_Number) && + has_number(context, "count", 9.0) && + fails(context, "function recurse() { recurse(); } recurse()", + JsErrorRepresentation_Engine, JsNativeErrorKind_Other) && + has_number(context, "1 + 2", 3.0); +} + +static bool contexts_are_isolated(void) { + BoaContext *first = boa_BoaContext_new(); + BoaContext *second = boa_BoaContext_new(); + bool valid = first != NULL && second != NULL && + has_type(first, view("var only_first = 1;"), JsValueType_Undefined) && + fails(second, "only_first", JsErrorRepresentation_Native, JsNativeErrorKind_Reference) && + has_number(first, "only_first", 1.0); + if (first != NULL) { + boa_BoaContext_destroy(first); + } + if (second != NULL) { + boa_BoaContext_destroy(second); + } + return valid; +} + +static bool destruction_order(bool context_first) { + BoaContext *context = boa_BoaContext_new(); + if (context == NULL) { + return false; + } + JsValue *value = eval_value(context, view("({ payload: 7 })")); + JsError *error = eval_error(context, view("throw new Error('boom')")); + JsValue *payload = error == NULL ? NULL : boa_JsError_as_opaque(error); + if (context_first) { + boa_BoaContext_destroy(context); + } + + bool valid = value != NULL && error != NULL && payload != NULL && + boa_JsValue_get_type(value) == JsValueType_Object && + boa_JsError_get_representation(error) == JsErrorRepresentation_Opaque && + boa_JsValue_get_type(payload) == JsValueType_Object; + if (value != NULL) { + boa_JsValue_destroy(value); + } + if (error != NULL) { + boa_JsError_destroy(error); + } + if (payload != NULL) { + boa_JsValue_destroy(payload); + } + if (!context_first) { + boa_BoaContext_destroy(context); + } + return valid; +} + +int main(void) { + BoaContext *context = boa_BoaContext_new(); + if (context == NULL) { + fputs("context failed to initialize\n", stderr); + return EXIT_FAILURE; + } + const char *failure = NULL; + if (!results(context)) { + failure = "eval results were not distinguished"; + } else if (!invalid_utf8(context)) { + failure = "invalid UTF-8 source was not rejected before running"; + } else if (!source_is_only_borrowed(context)) { + failure = "eval results depended on the source buffer"; + } else if (!state_and_limits(context)) { + failure = "eval state or engine limit handling failed"; + } + boa_BoaContext_destroy(context); + + if (failure == NULL && !contexts_are_isolated()) { + failure = "contexts shared globals"; + } + if (failure == NULL && (!destruction_order(true) || !destruction_order(false))) { + failure = "handles did not survive either destruction order"; + } + if (failure != NULL) { + fprintf(stderr, "%s\n", failure); + return EXIT_FAILURE; + } + puts("C eval tests passed."); + return EXIT_SUCCESS; +} diff --git a/ffi/boa_ffi/tests/c/run.sh b/ffi/boa_ffi/tests/c/run.sh index 3c6f315bea6..e3ed06ebace 100755 --- a/ffi/boa_ffi/tests/c/run.sh +++ b/ffi/boa_ffi/tests/c/run.sh @@ -38,7 +38,7 @@ esac test_dir=$(mktemp -d "${TMPDIR:-/tmp}/boa-ffi-c.XXXXXX") trap 'rm -rf "$test_dir"' EXIT HUP INT TERM -for test_name in context value error; do +for test_name in context value error eval; do "${CC:-cc}" -std=c11 -Wall -Wextra -Werror -pedantic \ -I "$script_dir/../../bindings/c" "$script_dir/$test_name.c" \ "$library_dir/$library_name" "-Wl,-rpath,$library_dir" -lm \ From 4667aa50e7ec64e848424d6950335db0676e4ffe Mon Sep 17 00:00:00 2001 From: Roger Chen Date: Mon, 23 Nov 2026 16:27:38 -0500 Subject: [PATCH 4/9] Add try_native to JsError --- ffi/boa_ffi/bindings/c/JsError.h | 5 ++ ffi/boa_ffi/bindings/c/JsTryNativeError.d.h | 29 ++++++++++ ffi/boa_ffi/bindings/c/JsTryNativeError.h | 22 +++++++ ffi/boa_ffi/src/lib.rs | 64 ++++++++++++++++++++- 4 files changed, 119 insertions(+), 1 deletion(-) create mode 100644 ffi/boa_ffi/bindings/c/JsTryNativeError.d.h create mode 100644 ffi/boa_ffi/bindings/c/JsTryNativeError.h diff --git a/ffi/boa_ffi/bindings/c/JsError.h b/ffi/boa_ffi/bindings/c/JsError.h index bf386bc0227..70b3ebc6604 100644 --- a/ffi/boa_ffi/bindings/c/JsError.h +++ b/ffi/boa_ffi/bindings/c/JsError.h @@ -7,9 +7,11 @@ #include #include "diplomat_runtime.h" +#include "BoaContext.d.h" #include "JsErrorRepresentation.d.h" #include "JsNativeErrorInfo.d.h" #include "JsNativeErrorKind.d.h" +#include "JsTryNativeError.d.h" #include "JsValue.d.h" #include "JsError.d.h" @@ -30,6 +32,9 @@ boa_JsError_as_native_result boa_JsError_as_native(const JsError* self); JsValue* boa_JsError_as_opaque(const JsError* self); +typedef struct boa_JsError_try_native_result {union {JsError* ok; JsTryNativeError err;}; bool is_ok;} boa_JsError_try_native_result; +boa_JsError_try_native_result boa_JsError_try_native(const JsError* self, BoaContext* context); + void boa_JsError_destroy(JsError* self); diff --git a/ffi/boa_ffi/bindings/c/JsTryNativeError.d.h b/ffi/boa_ffi/bindings/c/JsTryNativeError.d.h new file mode 100644 index 00000000000..72414fcb822 --- /dev/null +++ b/ffi/boa_ffi/bindings/c/JsTryNativeError.d.h @@ -0,0 +1,29 @@ +#ifndef JsTryNativeError_D_H +#define JsTryNativeError_D_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + + + + +typedef enum JsTryNativeError { + JsTryNativeError_NotAnErrorObject = 0, + JsTryNativeError_InvalidPropertyType = 1, + JsTryNativeError_InvalidMessageEncoding = 2, + JsTryNativeError_InvalidConstructor = 3, + JsTryNativeError_InaccessibleProperty = 4, + JsTryNativeError_InvalidErrorsIndex = 5, + JsTryNativeError_InaccessibleRealm = 6, + JsTryNativeError_EngineError = 7, +} JsTryNativeError; + +typedef struct JsTryNativeError_option {union { JsTryNativeError ok; }; bool is_ok; } JsTryNativeError_option; + + + +#endif // JsTryNativeError_D_H diff --git a/ffi/boa_ffi/bindings/c/JsTryNativeError.h b/ffi/boa_ffi/bindings/c/JsTryNativeError.h new file mode 100644 index 00000000000..f0409994d6d --- /dev/null +++ b/ffi/boa_ffi/bindings/c/JsTryNativeError.h @@ -0,0 +1,22 @@ +#ifndef JsTryNativeError_H +#define JsTryNativeError_H + +#include +#include +#include +#include +#include "diplomat_runtime.h" + + +#include "JsTryNativeError.d.h" + + + + +// No Content + + + + + +#endif // JsTryNativeError_H diff --git a/ffi/boa_ffi/src/lib.rs b/ffi/boa_ffi/src/lib.rs index 4c82a100df3..b22d4cf2956 100644 --- a/ffi/boa_ffi/src/lib.rs +++ b/ffi/boa_ffi/src/lib.rs @@ -18,7 +18,7 @@ pub mod ffi { use boa_engine::{ Context, JsError as BoaJsError, JsNativeError as BoaJsNativeError, JsNativeErrorKind as BoaJsNativeErrorKind, JsValue as BoaJsValue, Source, - context::ContextBuilder, value::Type, + context::ContextBuilder, error::TryNativeError, value::Type, }; use diplomat_runtime::{DiplomatOption, DiplomatStr, DiplomatUtf8StrSlice}; @@ -180,6 +180,27 @@ pub mod ffi { Other, } + /// The reason an error could not be converted into a native error. + #[derive(Debug, PartialEq, Eq)] + pub enum JsTryNativeError { + /// The error holds a thrown value that is not an Error object. + NotAnErrorObject, + /// The `message` is not a string, or an aggregate's `errors` is not an array. + InvalidPropertyType, + /// The `message` contains an unpaired surrogate, so it has no UTF-8 form. + InvalidMessageEncoding, + /// The `constructor` property is missing or is not a constructor. + InvalidConstructor, + /// Reading a property of the Error object threw, for example in a getter. + InaccessibleProperty, + /// Reading a member of an aggregate's `errors` threw. + InvalidErrorsIndex, + /// The realm of the Error object's constructor could not be found. + InaccessibleRealm, + /// The error is an engine failure, which has no native form. + EngineError, + } + /// Native error details borrowed from a live error handle. pub struct JsNativeErrorInfo<'a> { /// The native category. @@ -276,6 +297,47 @@ pub mod ffi { .as_opaque() .map(|value| Box::new(JsValue(value.clone()))) } + + /// Converts this error into a new owned native error. + /// + /// A native error converts to an equal copy. An opaque error converts if + /// its payload is an Error object: the category comes from the object's + /// internal type, and the message, cause and aggregate members are read + /// from its properties. Unlike the other error functions, this can run + /// JavaScript, because those properties may be getters. + /// + /// This error is left unchanged. Pass the context it came from. In C, + /// check `is_ok`, and destroy a returned error with `boa_JsError_destroy`, + /// independently of this one. + /// + /// # Errors + /// + /// Returns the reason the conversion failed. An exception thrown while + /// reading a property is discarded. + pub fn try_native( + &self, + context: &mut BoaContext, + ) -> Result, JsTryNativeError> { + match self.0.try_native(&mut context.context) { + Ok(native) => Ok(Box::new(JsError(native.into()))), + Err(error) => Err(match error { + TryNativeError::NotAnErrorObject(_) => JsTryNativeError::NotAnErrorObject, + TryNativeError::InvalidPropertyType(_) => JsTryNativeError::InvalidPropertyType, + TryNativeError::InvalidMessageEncoding => { + JsTryNativeError::InvalidMessageEncoding + } + TryNativeError::InvalidConstructor => JsTryNativeError::InvalidConstructor, + TryNativeError::InaccessibleProperty { .. } => { + JsTryNativeError::InaccessibleProperty + } + TryNativeError::InvalidErrorsIndex { .. } => { + JsTryNativeError::InvalidErrorsIndex + } + TryNativeError::InaccessibleRealm { .. } => JsTryNativeError::InaccessibleRealm, + TryNativeError::EngineError { .. } => JsTryNativeError::EngineError, + }), + } + } } #[cfg(test)] From 1e0eb81af2190f2ca29a15f5e11b36b938d2b298 Mon Sep 17 00:00:00 2001 From: Jason Milad Date: Mon, 23 Nov 2026 18:05:23 -0500 Subject: [PATCH 5/9] Add Rust try_native tests --- ffi/boa_ffi/src/lib.rs | 195 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 194 insertions(+), 1 deletion(-) diff --git a/ffi/boa_ffi/src/lib.rs b/ffi/boa_ffi/src/lib.rs index b22d4cf2956..10fadc6811a 100644 --- a/ffi/boa_ffi/src/lib.rs +++ b/ffi/boa_ffi/src/lib.rs @@ -344,7 +344,8 @@ pub mod ffi { mod tests { use super::{ BoaContext, BoaJsError, BoaJsNativeError, BoaJsNativeErrorKind, BoaJsValue, Context, - JsError, JsErrorRepresentation, JsNativeErrorKind, JsValue, JsValueType, + JsError, JsErrorRepresentation, JsNativeErrorKind, JsTryNativeError, JsValue, + JsValueType, }; use boa_engine::{ Source, @@ -791,6 +792,198 @@ pub mod ffi { assert_eq!(promise.get_type(), JsValueType::Object); assert_eq!(eval_number(&mut context, "ran"), Some(0.0)); } + + /// Evaluates source that should fail and returns its error. + fn eval_error(context: &mut BoaContext, source: &str) -> Box { + context + .eval(source.as_bytes()) + .expect_err("source should fail") + } + + #[test] + fn try_native_reads_the_category_and_message_of_error_objects() { + let mut context = BoaContext::new().expect("context should initialize"); + for (source, kind, message) in [ + ("throw new Error('boom')", JsNativeErrorKind::Error, "boom"), + ( + "throw new TypeError('bad type')", + JsNativeErrorKind::Type, + "bad type", + ), + ("throw new RangeError()", JsNativeErrorKind::Range, ""), + // The category is the object's internal type, not its class. + ( + "class Sub extends Error {} throw new Sub('sub')", + JsNativeErrorKind::Error, + "sub", + ), + ] { + let error = eval_error(&mut context, source); + let native = error + .try_native(&mut context) + .expect("Error object should convert"); + assert_eq!( + native.get_representation(), + JsErrorRepresentation::Native, + "{source}" + ); + let info = native.as_native().expect("native details"); + assert_eq!(info.kind, kind, "{source}"); + assert_eq!(info.message.as_bytes(), message.as_bytes(), "{source}"); + } + } + + #[test] + fn try_native_leaves_the_original_error_unchanged() { + let mut context = BoaContext::new().expect("context should initialize"); + let error = eval_error( + &mut context, + "globalThis.thrown = new Error('boom'); throw thrown", + ); + let native = error + .try_native(&mut context) + .expect("Error object should convert"); + + assert_eq!(error.get_representation(), JsErrorRepresentation::Opaque); + assert!(error.as_native().is_none()); + let payload = error.as_opaque().expect("opaque payload"); + let thrown = context.eval(b"thrown").expect("global should be readable"); + assert!(BoaJsValue::same_value(&payload.0, &thrown.0)); + + // The converted error does not depend on the original. + drop((error, payload, thrown)); + gc::force_collect(); + let info = native.as_native().expect("native details"); + assert_eq!(info.message.as_bytes(), b"boom"); + } + + #[test] + fn try_native_copies_an_error_that_is_already_native() { + let mut context = BoaContext::new().expect("context should initialize"); + for error in [ + eval_error(&mut context, "1 +"), + JsError::from_native(JsNativeErrorKind::Range, b"out of range") + .expect("known category"), + ] { + let copy = error + .try_native(&mut context) + .expect("native error should convert"); + assert_eq!(copy.get_representation(), JsErrorRepresentation::Native); + assert_eq!(copy.0, error.0); + } + } + + #[test] + fn try_native_runs_getters_that_inspection_does_not() { + let mut context = BoaContext::new().expect("context should initialize"); + let error = eval_error( + &mut context, + "var reads = 0; + var thrown = new Error(); + Object.defineProperty(thrown, 'message', { + get() { reads++; return 'boom'; } + }); + throw thrown", + ); + assert_eq!(error.get_representation(), JsErrorRepresentation::Opaque); + assert!(error.as_native().is_none()); + assert!(error.as_opaque().is_some()); + assert_eq!(eval_number(&mut context, "reads"), Some(0.0)); + + let native = error + .try_native(&mut context) + .expect("Error object should convert"); + let info = native.as_native().expect("native details"); + assert_eq!(info.message.as_bytes(), b"boom"); + assert_eq!(eval_number(&mut context, "reads"), Some(1.0)); + } + + #[test] + fn try_native_keeps_aggregate_members_and_causes() { + let mut context = BoaContext::new().expect("context should initialize"); + let error = eval_error( + &mut context, + "throw new AggregateError([new Error('first'), 7], 'all failed', { cause: 9 })", + ); + let native = error + .try_native(&mut context) + .expect("aggregate error should convert"); + let info = native.as_native().expect("native details"); + assert_eq!(info.kind, JsNativeErrorKind::Aggregate); + assert_eq!(info.message.as_bytes(), b"all failed"); + + // C cannot reach members or causes yet, so check Boa's own data. + let native = native.0.as_native().expect("native error"); + let BoaJsNativeErrorKind::Aggregate(members) = native.kind() else { + panic!("aggregate members should be retained"); + }; + assert_eq!(members.len(), 2); + let first = members[0].as_opaque().expect("opaque member"); + assert!(first.is_object()); + let second = members[1].as_opaque().expect("opaque member"); + assert_eq!(second.as_number(), Some(7.0)); + let cause = native.cause().expect("cause should be retained"); + let cause = cause.as_opaque().expect("opaque cause"); + assert_eq!(cause.as_number(), Some(9.0)); + } + + #[test] + fn try_native_reports_why_conversion_failed() { + let mut context = BoaContext::new().expect("context should initialize"); + for (source, reason) in [ + ("throw 7", JsTryNativeError::NotAnErrorObject), + ("throw { message: 'x' }", JsTryNativeError::NotAnErrorObject), + ( + "var e = new Error(); e.message = 7; throw e", + JsTryNativeError::InvalidPropertyType, + ), + ( + "var e = new AggregateError([]); e.errors = 7; throw e", + JsTryNativeError::InvalidPropertyType, + ), + ( + "throw new Error('\\ud800')", + JsTryNativeError::InvalidMessageEncoding, + ), + ( + "var e = new Error(); e.constructor = 7; throw e", + JsTryNativeError::InvalidConstructor, + ), + ( + "var e = new Error(); + Object.defineProperty(e, 'message', { get() { throw 1; } }); + throw e", + JsTryNativeError::InaccessibleProperty, + ), + ( + "var e = new AggregateError([1]); + Object.defineProperty(e.errors, 0, { get() { throw 1; } }); + throw e", + JsTryNativeError::InvalidErrorsIndex, + ), + ( + "var revocable = Proxy.revocable(function () {}, {}); + var e = new Error(); + e.constructor = revocable.proxy; + revocable.revoke(); + throw e", + JsTryNativeError::InaccessibleRealm, + ), + ( + "function recurse() { recurse(); } recurse()", + JsTryNativeError::EngineError, + ), + ] { + let error = eval_error(&mut context, source); + let representation = error.get_representation(); + let failure = error + .try_native(&mut context) + .expect_err("conversion should fail"); + assert_eq!(failure, reason, "{source}"); + // A failed conversion leaves the error as it was too. + assert_eq!(error.get_representation(), representation, "{source}"); + } + } } } From 4537135a6b9eec48bf30601b3a9647ab96a2009f Mon Sep 17 00:00:00 2001 From: Jason Milad Date: Mon, 23 Nov 2026 22:13:11 -0500 Subject: [PATCH 6/9] Add C try_native tests and docs --- ffi/boa_ffi/README.md | 81 ++++++++++++++++++++++++--- ffi/boa_ffi/tests/c/eval.c | 110 ++++++++++++++++++++++++++++++++++++- 2 files changed, 182 insertions(+), 9 deletions(-) diff --git a/ffi/boa_ffi/README.md b/ffi/boa_ffi/README.md index 369eb1db756..05f9a5db972 100644 --- a/ffi/boa_ffi/README.md +++ b/ffi/boa_ffi/README.md @@ -3,7 +3,7 @@ `boa_ffi` exposes Boa through opaque C handles generated by Diplomat. The current API supports context lifecycle, evaluating JavaScript source, value handles with type inspection and number/null/undefined construction, and structured error -construction and inspection. The API is experimental and may change. +construction, inspection and conversion. The API is experimental and may change. ## Build and test @@ -27,10 +27,11 @@ 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, inspection without JavaScript execution and -each kind of evaluation result. Object retention is checked across garbage -collection. The C tests exercise context/value/error lifecycle, numeric edge -cases, message encoding and evaluation (`tests/c/eval.c`) through the generated +round trips, retained error data, inspection without JavaScript execution, +each kind of evaluation result and error conversion with every failure reason. +Object retention is checked across garbage collection. The C tests exercise +context/value/error lifecycle, numeric edge cases, message encoding, and +evaluation and error conversion (`tests/c/eval.c`) 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. @@ -184,8 +185,9 @@ afterward. `boa_JsValue_destroy(NULL)` and C's `free()` are invalid for these ha `boa_JsError_get_representation()` and the getters inspect stored data without running JavaScript. They do not read object properties or normalize opaque Error objects -into native errors. Engine details, cause/aggregate traversal and normalization -are not exposed yet; their underlying data remains in the error handle. +into native errors; `boa_JsError_try_native()`, described below, does that as a +separate call. Engine details and cause/aggregate traversal are not exposed +yet; their underlying data remains in the error handle. `boa_JsError_from_native()` copies the supplied UTF-8 message, using its explicit byte length, including any embedded NUL. It requires no context and returns an owned @@ -232,6 +234,71 @@ Each returned payload must be destroyed with `boa_JsValue_destroy()`, independen of the error. Object identity is preserved. A payload may outlive both the error and the context it came from. +`boa_JsError_try_native()` converts an error into a new owned `Native` error, so +that C can read the category and message of a thrown Error object. A script's +`throw new Error('boom')` arrives as `Opaque`; converting it gives the category +`Error` and the message `boom`: + +```c +#include +#include "BoaContext.h" +#include "JsError.h" +#include "JsValue.h" + +int main(void) { + BoaContext *context = boa_BoaContext_new(); + if (context == NULL) { + return 1; + } + const char source[] = "throw new Error('boom')"; + boa_BoaContext_eval_result result = boa_BoaContext_eval(context, + (DiplomatStringView){.data = source, .len = sizeof(source) - 1}); + if (result.is_ok) { + boa_JsValue_destroy(result.ok); + } else { + boa_JsError_try_native_result converted = + boa_JsError_try_native(result.err, context); + if (converted.is_ok) { + boa_JsError_as_native_result info = boa_JsError_as_native(converted.ok); + if (info.is_ok) { + fwrite(info.ok.message.data, 1, info.ok.message.len, stdout); + fputc('\n', stdout); + } + boa_JsError_destroy(converted.ok); + } + boa_JsError_destroy(result.err); + } + boa_BoaContext_destroy(context); + return 0; +} +``` + +- Unlike the other error functions, it can run JavaScript. It reads properties + of the Error object, such as `message` and `cause`, and a property may be a + getter. +- Pass the context the error came from. The context must still be alive. +- The original error is not consumed or changed: it keeps its representation + and payload. The converted error is a separate handle. Destroy both, in + either order. +- The category comes from the object's internal type, so an instance of a class + that extends `Error` reports `Error`. An error that is already `Native` + converts to an equal copy. +- Check `is_ok` before reading the result. On failure nothing is returned to + destroy, and `err` is a `JsTryNativeError` reason: + - `NotAnErrorObject`: the thrown value is not an Error object, as with + `throw 7`. + - `InvalidPropertyType`: `message` is not a string, or the `errors` of an + aggregate error is not an array. + - `InvalidMessageEncoding`: `message` contains an unpaired surrogate. + - `InvalidConstructor`: `constructor` is missing or is not a constructor. + - `InaccessibleProperty`: reading a property threw. + - `InvalidErrorsIndex`: reading a member of an aggregate error's `errors` + threw. + - `InaccessibleRealm`: the realm of the constructor could not be found. + - `EngineError`: the error is an `Engine` error, which has no native form. +- An exception thrown while reading a property is discarded; only the reason + is reported. + Use and destroy errors on their creating thread. Getters require live, non-null handles. Destroy each owned error exactly once with `boa_JsError_destroy()`; pointer aliases then become invalid. `boa_JsError_destroy(NULL)` and C's `free()` are invalid. diff --git a/ffi/boa_ffi/tests/c/eval.c b/ffi/boa_ffi/tests/c/eval.c index 90492af33a9..3e6542be715 100644 --- a/ffi/boa_ffi/tests/c/eval.c +++ b/ffi/boa_ffi/tests/c/eval.c @@ -159,6 +159,99 @@ static bool contexts_are_isolated(void) { return valid; } +static bool converts(BoaContext *context, const char *source, JsNativeErrorKind kind, + const char *message, bool original_first) { + JsError *error = eval_error(context, view(source)); + if (error == NULL) { + return false; + } + boa_JsError_try_native_result converted = boa_JsError_try_native(error, context); + if (!converted.is_ok || converted.ok == NULL) { + boa_JsError_destroy(error); + return false; + } + bool valid = boa_JsError_get_representation(error) == JsErrorRepresentation_Opaque; + if (original_first) { + boa_JsError_destroy(error); + } + + boa_JsError_as_native_result info = boa_JsError_as_native(converted.ok); + valid = valid && + boa_JsError_get_representation(converted.ok) == JsErrorRepresentation_Native && + info.is_ok && info.ok.kind == kind && info.ok.message.len == strlen(message) && + (info.ok.message.len == 0 || + memcmp(info.ok.message.data, message, info.ok.message.len) == 0); + boa_JsError_destroy(converted.ok); + if (!original_first) { + valid = valid && boa_JsError_get_representation(error) == JsErrorRepresentation_Opaque; + boa_JsError_destroy(error); + } + return valid; +} + +static bool conversions(BoaContext *context) { + return converts(context, "throw new Error('boom')", JsNativeErrorKind_Error, "boom", true) && + converts(context, "throw new Error('boom')", JsNativeErrorKind_Error, "boom", false) && + converts(context, "throw new TypeError('bad type')", + JsNativeErrorKind_Type, "bad type", false) && + converts(context, "class Sub extends Error {} throw new Sub('sub')", + JsNativeErrorKind_Error, "sub", false); +} + +// A failed conversion must leave the error with its representation and payload. +static bool conversion_fails(BoaContext *context, const char *source, + JsErrorRepresentation representation, JsTryNativeError reason) { + JsError *error = eval_error(context, view(source)); + if (error == NULL) { + return false; + } + boa_JsError_try_native_result converted = boa_JsError_try_native(error, context); + JsValue *payload = boa_JsError_as_opaque(error); + bool valid = !converted.is_ok && converted.err == reason && + boa_JsError_get_representation(error) == representation && + (payload != NULL) == (representation == JsErrorRepresentation_Opaque); + if (converted.is_ok && converted.ok != NULL) { + boa_JsError_destroy(converted.ok); + } + if (payload != NULL) { + boa_JsValue_destroy(payload); + } + boa_JsError_destroy(error); + return valid; +} + +static bool failed_conversions(BoaContext *context) { + const JsErrorRepresentation opaque = JsErrorRepresentation_Opaque; + return conversion_fails(context, "throw 7", opaque, JsTryNativeError_NotAnErrorObject) && + conversion_fails(context, "throw { message: 'x' }", + opaque, JsTryNativeError_NotAnErrorObject) && + conversion_fails(context, "var e = new Error(); e.message = 7; throw e", + opaque, JsTryNativeError_InvalidPropertyType) && + conversion_fails(context, "throw new Error('\\ud800')", + opaque, JsTryNativeError_InvalidMessageEncoding) && + conversion_fails(context, "var e = new Error(); e.constructor = 7; throw e", + opaque, JsTryNativeError_InvalidConstructor) && + conversion_fails(context, + "var e = new Error();" + "Object.defineProperty(e, 'message', { get() { throw 1; } });" + "throw e", + opaque, JsTryNativeError_InaccessibleProperty) && + conversion_fails(context, + "var e = new AggregateError([1]);" + "Object.defineProperty(e.errors, 0, { get() { throw 1; } });" + "throw e", + opaque, JsTryNativeError_InvalidErrorsIndex) && + conversion_fails(context, + "var revocable = Proxy.revocable(function () {}, {});" + "var e = new Error();" + "e.constructor = revocable.proxy;" + "revocable.revoke();" + "throw e", + opaque, JsTryNativeError_InaccessibleRealm) && + conversion_fails(context, "function recurse() { recurse(); } recurse()", + JsErrorRepresentation_Engine, JsTryNativeError_EngineError); +} + static bool destruction_order(bool context_first) { BoaContext *context = boa_BoaContext_new(); if (context == NULL) { @@ -167,14 +260,23 @@ static bool destruction_order(bool context_first) { JsValue *value = eval_value(context, view("({ payload: 7 })")); JsError *error = eval_error(context, view("throw new Error('boom')")); JsValue *payload = error == NULL ? NULL : boa_JsError_as_opaque(error); + JsError *converted = NULL; + if (error != NULL) { + boa_JsError_try_native_result result = boa_JsError_try_native(error, context); + converted = result.is_ok ? result.ok : NULL; + } if (context_first) { boa_BoaContext_destroy(context); } - bool valid = value != NULL && error != NULL && payload != NULL && + bool valid = value != NULL && error != NULL && payload != NULL && converted != NULL && boa_JsValue_get_type(value) == JsValueType_Object && boa_JsError_get_representation(error) == JsErrorRepresentation_Opaque && - boa_JsValue_get_type(payload) == JsValueType_Object; + boa_JsValue_get_type(payload) == JsValueType_Object && + boa_JsError_get_representation(converted) == JsErrorRepresentation_Native; + if (converted != NULL) { + boa_JsError_destroy(converted); + } if (value != NULL) { boa_JsValue_destroy(value); } @@ -205,6 +307,10 @@ int main(void) { failure = "eval results depended on the source buffer"; } else if (!state_and_limits(context)) { failure = "eval state or engine limit handling failed"; + } else if (!conversions(context)) { + failure = "thrown Error objects were not converted to native errors"; + } else if (!failed_conversions(context)) { + failure = "failed conversions did not report their reason"; } boa_BoaContext_destroy(context); From 25796488a066469a097a936c0715f03c03d2a857 Mon Sep 17 00:00:00 2001 From: Roger Chen Date: Tue, 24 Nov 2026 09:40:36 -0500 Subject: [PATCH 7/9] Enable engine features in boa_ffi --- ffi/boa_ffi/Cargo.toml | 10 ++++++++++ ffi/boa_ffi/README.md | 15 +++++++++++++++ ffi/boa_ffi/src/lib.rs | 16 ++++++++++++++++ ffi/boa_ffi/tests/c/eval.c | 11 +++++++++++ 4 files changed, 52 insertions(+) diff --git a/ffi/boa_ffi/Cargo.toml b/ffi/boa_ffi/Cargo.toml index 34d9603ee3e..6cfddcb3767 100644 --- a/ffi/boa_ffi/Cargo.toml +++ b/ffi/boa_ffi/Cargo.toml @@ -17,5 +17,15 @@ boa_engine.workspace = true diplomat.workspace = true diplomat-runtime.workspace = true +[features] +default = [ + "boa_engine/annex-b", + "boa_engine/experimental", + "boa_engine/float16", + "boa_engine/intl_bundled", + "boa_engine/temporal", + "boa_engine/xsum", +] + [lints] workspace = true diff --git a/ffi/boa_ffi/README.md b/ffi/boa_ffi/README.md index 05f9a5db972..c63c3228c5e 100644 --- a/ffi/boa_ffi/README.md +++ b/ffi/boa_ffi/README.md @@ -20,6 +20,21 @@ The library is `target/debug/libboa_ffi.dylib` on macOS or `bindings/c/BoaContext.h`, `bindings/c/JsValue.h` and `bindings/c/JsError.h` as needed in C programs and link against this library. +The default build enables the same engine features as Boa's WebAssembly +bindings: `annex-b`, `experimental`, `float16`, `intl_bundled`, `temporal` and +`xsum`. Scripts can therefore use `Intl`, `Temporal`, `Float16Array`, +`Math.sumPrecise` and the Annex B additions. `intl_bundled` embeds ICU data, +which makes a release library roughly three times larger. For a small build +without these features, add `--no-default-features`: + +```sh +cargo build --locked -p boa_ffi --no-default-features +``` + +A single feature can be added back with, for example, +`--features boa_engine/temporal`. The C test runner builds the default +features and its tests expect them. + The C test runner requires a native macOS or Linux environment and a C11 compiler (`cc`, or an executable specified by `CC`). By default it builds for the Rust host explicitly in `target//debug/`, honors `CARGO_TARGET_DIR`, and runs diff --git a/ffi/boa_ffi/src/lib.rs b/ffi/boa_ffi/src/lib.rs index 10fadc6811a..9f5b678b756 100644 --- a/ffi/boa_ffi/src/lib.rs +++ b/ffi/boa_ffi/src/lib.rs @@ -984,6 +984,22 @@ pub mod ffi { assert_eq!(error.get_representation(), representation, "{source}"); } } + + #[test] + #[cfg(feature = "default")] + fn default_features_enable_optional_builtins() { + let mut context = BoaContext::new().expect("context should initialize"); + for (name, expected) in [ + ("Temporal", "object"), + ("Intl", "object"), + ("Float16Array", "function"), + ("Math.sumPrecise", "function"), + ("escape", "function"), + ] { + let source = format!("typeof {name} === '{expected}' ? 1 : 0"); + assert_eq!(eval_number(&mut context, &source), Some(1.0), "{name}"); + } + } } } diff --git a/ffi/boa_ffi/tests/c/eval.c b/ffi/boa_ffi/tests/c/eval.c index 3e6542be715..98027e27c77 100644 --- a/ffi/boa_ffi/tests/c/eval.c +++ b/ffi/boa_ffi/tests/c/eval.c @@ -252,6 +252,15 @@ static bool failed_conversions(BoaContext *context) { JsErrorRepresentation_Engine, JsTryNativeError_EngineError); } +// The runner builds the library with its default features. +static bool default_features(BoaContext *context) { + return has_number(context, "typeof Temporal === 'object' ? 1 : 0", 1.0) && + has_number(context, "typeof Intl === 'object' ? 1 : 0", 1.0) && + has_number(context, "typeof Float16Array === 'function' ? 1 : 0", 1.0) && + has_number(context, "typeof Math.sumPrecise === 'function' ? 1 : 0", 1.0) && + has_number(context, "typeof escape === 'function' ? 1 : 0", 1.0); +} + static bool destruction_order(bool context_first) { BoaContext *context = boa_BoaContext_new(); if (context == NULL) { @@ -311,6 +320,8 @@ int main(void) { failure = "thrown Error objects were not converted to native errors"; } else if (!failed_conversions(context)) { failure = "failed conversions did not report their reason"; + } else if (!default_features(context)) { + failure = "default engine features were missing"; } boa_BoaContext_destroy(context); From e4b66a8b4eff915afaca3eaab4710e89e29f52e1 Mon Sep 17 00:00:00 2001 From: Jason Milad Date: Tue, 24 Nov 2026 11:23:54 -0500 Subject: [PATCH 8/9] Fix C FFI cleanup and preserve native error backtraces --- ffi/boa_ffi/README.md | 29 ++++++----- ffi/boa_ffi/src/lib.rs | 107 ++++++++++++++++++++++++++++++++++------- 2 files changed, 106 insertions(+), 30 deletions(-) diff --git a/ffi/boa_ffi/README.md b/ffi/boa_ffi/README.md index c63c3228c5e..e451481e34d 100644 --- a/ffi/boa_ffi/README.md +++ b/ffi/boa_ffi/README.md @@ -86,7 +86,8 @@ int main(void) { - Copying a pointer creates an alias, not another owned handle. After destruction, every alias is invalid. - Use and destroy a context on the thread that created it. Calls on the same - handle must not overlap. Multiple independent contexts can coexist on one thread. + handle must not overlap. Contexts on the same thread share Boa's runtime, + and each has its own globals. - `NULL` does not represent recovery from arbitrary Rust panics or allocation failure. These failures may abort the process; this API does not catch panics. @@ -150,11 +151,13 @@ int main(void) { is `Engine`, and the context remains usable afterward. - Source that is not valid UTF-8 fails with a `Native` type error, and nothing is evaluated. -- Calls on one context share its global state: a later call sees what an - earlier one defined, and a throw does not undo what ran before it. Separate - contexts share nothing. -- Promise jobs are not run. `then` callbacks do not execute, and a rejected - promise is returned as a value, not reported as an error. +- Calls on one context see globals defined by earlier calls, including changes + made before a script threw. +- The context discards promise jobs as they are scheduled. A `then` callback + never runs. Evaluating a rejected promise returns the promise as a value. +- When `eval` or `try_native` finishes running JavaScript, it releases the + temporary references Boa keeps for `WeakRef`. An owned value handle still + keeps its object alive until the caller destroys the handle. - There is no time limit. A script that never finishes never returns. - Returned handles do not borrow from the context. Each one may be inspected and destroyed before or after the context is destroyed. @@ -291,13 +294,15 @@ int main(void) { - Unlike the other error functions, it can run JavaScript. It reads properties of the Error object, such as `message` and `cause`, and a property may be a getter. -- Pass the context the error came from. The context must still be alive. -- The original error is not consumed or changed: it keeps its representation - and payload. The converted error is a separate handle. Destroy both, in - either order. +- Pass a live context on the error's creating thread. For a thrown Error + object, use the object's original context to run its getters. A native error, + including one created with `boa_JsError_from_native()`, can be copied with + any live context on that thread. +- The original handle keeps its representation and payload. The converted + error is a separate handle. Destroy both in either order. - The category comes from the object's internal type, so an instance of a class - that extends `Error` reports `Error`. An error that is already `Native` - converts to an equal copy. + that extends `Error` reports `Error`. Copying an already-native error + preserves its captured JavaScript backtrace. - Check `is_ok` before reading the result. On failure nothing is returned to destroy, and `err` is a `JsTryNativeError` reason: - `NotAnErrorObject`: the thrown value is not an Error object, as with diff --git a/ffi/boa_ffi/src/lib.rs b/ffi/boa_ffi/src/lib.rs index 9f5b678b756..4bc6be36bad 100644 --- a/ffi/boa_ffi/src/lib.rs +++ b/ffi/boa_ffi/src/lib.rs @@ -15,10 +15,12 @@ reason = "Diplomat transfers opaque handle ownership to C through boxed pointers" )] pub mod ffi { + use std::rc::Rc; + use boa_engine::{ Context, JsError as BoaJsError, JsNativeError as BoaJsNativeError, JsNativeErrorKind as BoaJsNativeErrorKind, JsValue as BoaJsValue, Source, - context::ContextBuilder, error::TryNativeError, value::Type, + context::ContextBuilder, error::TryNativeError, job::IdleJobExecutor, value::Type, }; use diplomat_runtime::{DiplomatOption, DiplomatStr, DiplomatUtf8StrSlice}; @@ -41,7 +43,7 @@ pub mod ffi { /// failures may abort the process rather than return null. #[must_use] pub fn new() -> Option> { - Self::from_builder(Context::builder()) + Self::from_builder(Context::builder().job_executor(Rc::new(IdleJobExecutor))) } fn from_builder(builder: ContextBuilder) -> Option> { @@ -54,8 +56,8 @@ pub mod ffi { /// Evaluates UTF-8 source text as a script and returns its completion value. /// /// Empty source evaluates to undefined. The source is borrowed only for - /// this call. Promise jobs are not run, and there is no time limit: a - /// script that never finishes never returns. + /// this call. The context discards promise jobs as they are scheduled. + /// Evaluation has no time limit. /// /// In C, check `is_ok`, then destroy the handle that was returned with /// `boa_JsValue_destroy` or `boa_JsError_destroy`. It is never null. @@ -70,7 +72,10 @@ pub mod ffi { let error = BoaJsNativeError::typ().with_message("source text is not valid UTF-8"); return Err(Box::new(JsError(error.into()))); }; - match self.context.eval(Source::from_bytes(source)) { + let result = self.context.eval(Source::from_bytes(source)); + // Release the temporary WeakRef roots even if the script threw. + self.context.clear_kept_objects(); + match result { Ok(value) => Ok(Box::new(JsValue(value))), Err(error) => Err(Box::new(JsError(error))), } @@ -300,15 +305,14 @@ pub mod ffi { /// Converts this error into a new owned native error. /// - /// A native error converts to an equal copy. An opaque error converts if - /// its payload is an Error object: the category comes from the object's - /// internal type, and the message, cause and aggregate members are read - /// from its properties. Unlike the other error functions, this can run - /// JavaScript, because those properties may be getters. + /// A native error is copied with its captured backtrace. For an opaque + /// Error object, the category comes from its internal type. Reading its + /// message, cause and aggregate members can run JavaScript getters. /// - /// This error is left unchanged. Pass the context it came from. In C, - /// check `is_ok`, and destroy a returned error with `boa_JsError_destroy`, - /// independently of this one. + /// Pass the object's original context when reading an Error object. + /// A native error can be copied with any live context on its creating + /// thread. In C, check `is_ok` and destroy the returned handle with + /// `boa_JsError_destroy` independently of the original. /// /// # Errors /// @@ -318,7 +322,13 @@ pub mod ffi { &self, context: &mut BoaContext, ) -> Result, JsTryNativeError> { - match self.0.try_native(&mut context.context) { + // Rebuilding a native error from its inner value drops the outer backtrace. + if self.0.as_native().is_some() { + return Ok(Box::new(Self(self.0.clone()))); + } + let result = self.0.try_native(&mut context.context); + context.context.clear_kept_objects(); + match result { Ok(native) => Ok(Box::new(JsError(native.into()))), Err(error) => Err(match error { TryNativeError::NotAnErrorObject(_) => JsTryNativeError::NotAnErrorObject, @@ -779,8 +789,37 @@ pub mod ffi { gc::force_collect(); } + fn eval_after_gc(context: &mut BoaContext, source: &str) -> Box { + gc::force_collect(); + context + .eval(source.as_bytes()) + .expect("source should evaluate") + } + #[test] - fn eval_does_not_run_promise_jobs() { + fn eval_releases_weak_ref_targets_on_return_and_throw() { + let mut context = BoaContext::new().expect("context should initialize"); + let owned = context + .eval(b"var weak = new WeakRef({}); weak.deref()") + .expect("target should be returned"); + let deref = "weak.deref()"; + let target = eval_after_gc(&mut context, deref); + assert!(BoaJsValue::same_value(&owned.0, &target.0)); + drop((owned, target)); + assert_eq!( + eval_after_gc(&mut context, deref).get_type(), + JsValueType::Undefined + ); + + eval_error(&mut context, "weak = new WeakRef({}); throw 7"); + assert_eq!( + eval_after_gc(&mut context, deref).get_type(), + JsValueType::Undefined + ); + } + + #[test] + fn eval_discards_promise_jobs() { let mut context = BoaContext::new().expect("context should initialize"); let promise = context .eval( @@ -790,6 +829,8 @@ pub mod ffi { ) .expect("a rejected promise is a value, not a thrown error"); assert_eq!(promise.get_type(), JsValueType::Object); + // A deferred callback would run when the executor is drained. + context.context.run_jobs().expect("executor should finish"); assert_eq!(eval_number(&mut context, "ran"), Some(0.0)); } @@ -860,16 +901,27 @@ pub mod ffi { #[test] fn try_native_copies_an_error_that_is_already_native() { let mut context = BoaContext::new().expect("context should initialize"); - for error in [ + let runtime_error = eval_error( + &mut context, + "function readConfig() { return missingOption; } readConfig()", + ); + assert!(runtime_error.0.to_string().contains("readConfig")); + let errors = [ + runtime_error, eval_error(&mut context, "1 +"), JsError::from_native(JsNativeErrorKind::Range, b"out of range") .expect("known category"), - ] { + ]; + drop(context); + let mut other_context = BoaContext::new().expect("context should initialize"); + for error in errors { let copy = error - .try_native(&mut context) + .try_native(&mut other_context) .expect("native error should convert"); assert_eq!(copy.get_representation(), JsErrorRepresentation::Native); assert_eq!(copy.0, error.0); + // Boa ignores backtraces when comparing errors for equality. + assert_eq!(copy.0.to_string(), error.0.to_string()); } } @@ -898,6 +950,25 @@ pub mod ffi { assert_eq!(eval_number(&mut context, "reads"), Some(1.0)); } + #[test] + fn try_native_releases_weak_ref_targets_after_getters() { + let mut context = BoaContext::new().expect("context should initialize"); + let error = eval_error( + &mut context, + "var weak, reads = 0; + throw Object.defineProperty(new Error(), 'message', { get() { + weak = new WeakRef({}); + if (++reads === 2) throw 7; + return 'boom'; + } });", + ); + for failure in [None, Some(JsTryNativeError::InaccessibleProperty)] { + assert_eq!(error.try_native(&mut context).err(), failure); + let target = eval_after_gc(&mut context, "weak.deref()"); + assert_eq!(target.get_type(), JsValueType::Undefined); + } + } + #[test] fn try_native_keeps_aggregate_members_and_causes() { let mut context = BoaContext::new().expect("context should initialize"); From c543422fda05f7ddcc885028502c87f41848f10e Mon Sep 17 00:00:00 2001 From: Roger Chen Date: Tue, 24 Nov 2026 12:02:15 -0500 Subject: [PATCH 9/9] Cleanup README --- ffi/boa_ffi/README.md | 15 ++++++++------- ffi/boa_ffi/tests/c/eval.c | 11 +++++++++++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/ffi/boa_ffi/README.md b/ffi/boa_ffi/README.md index e451481e34d..c0467905716 100644 --- a/ffi/boa_ffi/README.md +++ b/ffi/boa_ffi/README.md @@ -142,13 +142,14 @@ int main(void) { handle that is never `NULL`: empty source and source that only declares evaluate to undefined. Failure carries `err`, an owned error handle. Destroy whichever handle was returned, exactly once. -- The error is Boa's own, unchanged, so the functions under [Errors](#errors) - apply. A value the script throws is `Opaque`, including Error objects: - `throw 7` holds the number 7 and `throw new Error('boom')` holds the object. - An error the engine raises that the script does not catch, such as a syntax - error or an undefined name, is `Native`; if the script catches and rethrows - it, it is `Opaque`. Exceeding an engine limit, such as the recursion limit, - is `Engine`, and the context remains usable afterward. +- `eval` preserves Boa's error representation, which you can check with + `boa_JsError_get_representation()`. + `throw 7` and `throw new Error('boom')` both return `Opaque` errors holding + the thrown value. A syntax error such as `1 +` is `Native`. In a fresh + context, `missingName` produces a `Native` reference error. The same lookup + in `try { missingName } finally {}` can reach C as an `Opaque` error holding a + `ReferenceError` object. Exceeding the recursion limit returns an `Engine` + error, and the context remains usable afterward. See [Errors](#errors). - Source that is not valid UTF-8 fails with a `Native` type error, and nothing is evaluated. - Calls on one context see globals defined by earlier calls, including changes diff --git a/ffi/boa_ffi/tests/c/eval.c b/ffi/boa_ffi/tests/c/eval.c index 98027e27c77..45ab79dc0e7 100644 --- a/ffi/boa_ffi/tests/c/eval.c +++ b/ffi/boa_ffi/tests/c/eval.c @@ -120,6 +120,15 @@ static bool invalid_utf8(BoaContext *context) { return has_number(context, "ran", 0.0); } +static bool source_uses_byte_length(BoaContext *context) { + const char buffer[] = "var textFromView = '\xC3\xA9\0b'!"; + // The view includes the NUL in the string literal and ends before the '!'. + DiplomatStringView source = {.data = buffer, .len = sizeof(buffer) - 2}; + return has_type(context, source, JsValueType_Undefined) && + has_number(context, "textFromView.length", 3.0) && + has_number(context, "textFromView.charCodeAt(1)", 0.0); +} + static bool source_is_only_borrowed(BoaContext *context) { char source[] = "function seven() { return 3 + 4; } seven"; JsValue *function = eval_value(context, view(source)); @@ -312,6 +321,8 @@ int main(void) { failure = "eval results were not distinguished"; } else if (!invalid_utf8(context)) { failure = "invalid UTF-8 source was not rejected before running"; + } else if (!source_uses_byte_length(context)) { + failure = "eval did not respect the source byte length"; } else if (!source_is_only_borrowed(context)) { failure = "eval results depended on the source buffer"; } else if (!state_and_limits(context)) {