Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions ffi/boa_ffi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
180 changes: 169 additions & 11 deletions ffi/boa_ffi/README.md
Original file line number Diff line number Diff line change
@@ -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, inspection and conversion. The API is experimental and may change.

## Build and test

Expand All @@ -20,17 +20,34 @@ 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/<host>/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.
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 and message encoding through
the generated headers and shared library. They check results explicitly, so
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.

Expand Down Expand Up @@ -69,10 +86,83 @@ 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.

## 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 <stdio.h>
#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.
- `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
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.

## Value handles

`boa_JsValue_from_number(double)`, `boa_JsValue_from_null()` and
Expand Down Expand Up @@ -114,8 +204,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
Expand Down Expand Up @@ -159,8 +250,75 @@ 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.

`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 <stdio.h>
#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 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`. 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
`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
Expand Down
5 changes: 5 additions & 0 deletions ffi/boa_ffi/bindings/c/BoaContext.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions ffi/boa_ffi/bindings/c/JsError.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions ffi/boa_ffi/bindings/c/JsTryNativeError.d.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions ffi/boa_ffi/bindings/c/JsTryNativeError.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading