@rust-js/builtins
v0.0.1
Published
JS's language, as rust-js compiles Rust to it: promises, errors, regular expressions, JSON
Readme
js: the JS language for rust-js
The js crate declares what JS has that Rust's std doesn't, as ReScript's
standard library does: its promises, errors and regular expressions, its byte
buffers, its JSON, and its global functions, its timers too, as ReScript's has
them. What the browser adds is the
webapi crate's; what std has, rust-js maps itself.
It holds declarations only, so it's never compiled to JS. See
ADR 0102.
use js::{decode_uri_component, encode_uri_component, settle, spawn};
let query = encode_uri_component("a b&c"); // encodeURIComponent("a b&c")
let text = decode_uri_component("%E0%A4%A"); // Err: a URIError
spawn(Box::new(async move { // runs, unawaited
match settle(webapi::window::fetch(webapi::window, &url)).await {
Ok(response) => { .. } // what fetch fulfils with
Err(error) => { .. } // a network error: not a throw
}
}));- A promise is a
Promise<T>, to.await(ADR 0029);settle(p)makes its.awaitaResult, and one a binding declares asPromise<Result<T, &JsError>>is one already (ADR 0035). JsErroris what JS threw;js_error::to_string(e)isString(e), andjs_error::is_error(e)andjs_error::message(e)are anError's.RegExpis there for what Rust would useregexfor:reg_exp::new(r"^\d+$", ""), andreg_exp::replace(text, pattern, "$1"). A replacer closure, andmatchAll, are a program's own bindings, typed for its pattern's groups.json::stringify(text)is a string's JSON, which is a JS string literal too. A Rust value's JSON is serde's (ADR 0077), and so is reading JSON: whatJSON.parsegives is whatever the text holds.object::from_entries(entries)is a JS object of keys and values, as an API taking a dictionary wants, andobject::is(a, b)isObject.is: whether two JS objects are one.set_timeout(f, ms)andset_interval(f, ms)run a closure later, or every so often, andclear_timeoutandclear_intervalof what they gave stop it: every JS runtime has them, browsers', workers' and Node's.number::to_fixed(x, digits)isx.toFixed(digits), JS's rounding: a tie away from zero,2.5to"3", whereformat!("{:.0}", 2.5)is"2".
builtins/build.sh -o "$PWD/target/libjs.rmeta"
./target/debug/rust-js app.rs -- --extern js=target/libjs.rmeta