Skip to main content

taba/
lib.rs

1//! Taba's runtime
2#![no_std]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4
5extern crate alloc;
6extern crate self as taba; // our own types also use derives, which call ::taba
7#[cfg(feature = "std")]
8extern crate std;
9
10mod error;
11mod procedure;
12#[cfg(feature = "rpc")]
13pub mod rpc;
14mod typescript;
15
16use alloc::string::{String, ToString as _};
17use core::fmt::{self, Display, Write};
18
19use serde_core::Serialize;
20#[cfg(feature = "derive")]
21pub use taba_derive::{Input, Output};
22
23pub use crate::{
24    error::Error,
25    procedure::{IntoReply, Never, Once, Procedure, Procedures, Strand},
26    typescript::{Input, Key, Output},
27};
28
29/// Alias for a `Result` with the error type `taba::Error`.
30pub type Result<T, E = Error> = core::result::Result<T, E>;
31
32/// What generated code names through taba.
33#[doc(hidden)]
34pub mod __private {
35    /// A std crate has no `alloc` without [`extern crate`](https://doc.rust-lang.org/reference/names/preludes.html#extern-prelude).
36    pub use alloc::string::String;
37
38    #[cfg(feature = "rpc")]
39    pub use crate::rpc::__private as rpc;
40    pub use crate::{procedure::__private as procedure, typescript::__private as typescript};
41}
42
43/// Include `taba-build` output as the named module.
44///
45/// ```ignore
46/// taba::include_scripts!(mod scripts);
47/// let js = scripts::core(&input)?;
48/// ```
49///
50/// Attributes and documentation work fine:
51///
52/// ```ignore
53/// taba::include_scripts!(
54///     /// Some explicit documentation we want to add to the binding's root.
55///     #[forbid(unsafe_code)]
56///     mod scripts;
57/// );
58/// ```
59#[macro_export]
60macro_rules! include_scripts {
61    ($(#[$attribute:meta])* $visibility:vis mod $name:ident $(;)?) => {
62        $(#[$attribute])*
63        $visibility mod $name {
64            ::core::include!(::core::concat!(::core::env!("OUT_DIR"), "/taba/mod.rs"));
65        }
66    };
67}
68
69/// The unresolved ("global") block-scoped variable scripts read input from.
70const BLOCK_SCOPED_GLOBAL: &str = "_taba";
71
72/// A script that runs the bundle with input.
73///
74/// The bundle reads `input` from the global `_taba`.
75pub fn script<T>(bundle: &str, input: &T) -> Result<String, Error>
76where
77    T: ?Sized + Serialize,
78{
79    let input = Json::serialize(input)?.declare_constant();
80    Ok(block(format_args!("{input}\n{bundle}")).to_string())
81}
82
83/// A [block statement] to scope our input, preventing any global naming collisions.
84///
85/// [block statement]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block
86fn block(body: impl Display) -> impl Display {
87    fmt::from_fn(move |f| write!(f, "{{\n{body}\n}}"))
88}
89
90/// The ability to safely escape JSON into a JSON.parse('{json}') relies entirely on 2 things.
91///
92/// 1. `serde_json`'s ability to correctly escape and format JSON into a [`String`].
93/// 2. JavaScript engines not accepting anything except another unescaped, literal single quote
94///    character to end a string that was opened with it.
95struct Json(String);
96
97impl Json {
98    fn serialize<T: ?Sized + Serialize>(input: &T) -> Result<Self, Error> {
99        serde_json::to_string(input).map(Self).map_err(Error)
100    }
101
102    fn declare_constant(self) -> impl Display {
103        fmt::from_fn(move |f| write!(f, "const {BLOCK_SCOPED_GLOBAL} = {};", self.json_parse()))
104    }
105
106    fn json_parse(&self) -> impl Display {
107        fmt::from_fn(move |f| write!(f, "JSON.parse({})", self.string_literal()))
108    }
109
110    /// A single-quoted JavaScript string literal, for use inside `JSON.parse()`.
111    ///
112    /// Single quotes chosen because double quotes are already used in JSON. With single quotes, we
113    /// only need to escape strings that include backslashes or single quotes. If we used double
114    /// quotes, then there would be no cases that a string doesn't need escaping.
115    fn string_literal(&self) -> impl Display {
116        const BACKSLASH: char = '\\';
117        const SINGLE_QUOTE: char = '\'';
118        fmt::from_fn(move |f| {
119            f.write_char(SINGLE_QUOTE)?;
120
121            let mut last = 0;
122            for (idx, _) in self.0.match_indices([BACKSLASH, SINGLE_QUOTE]) {
123                f.write_str(&self.0[last..idx])?;
124                f.write_char(BACKSLASH)?;
125                last = idx;
126            }
127
128            f.write_str(&self.0[last..])?;
129            f.write_char(SINGLE_QUOTE)
130        })
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    #[test]
137    fn every_json_type() {
138        let input = serde_json::json!({ "input": [null, true, 42, r"it's C:\"] });
139        let bundle = "run(_taba);\n//# sourceMappingURL=run.js.map";
140
141        insta::assert_snapshot!(super::script(bundle, &input).unwrap(), @r#"
142        {
143        const _taba = JSON.parse('{"input":[null,true,42,"it\'s C:\\\\"]}');
144        run(_taba);
145        //# sourceMappingURL=run.js.map
146        }
147        "#);
148    }
149}