katex/
js_engine.rs

1//! Abstraction of the JS Engine.
2
3use crate::error::Result;
4use cfg_if::cfg_if;
5
6/// A trait to represent a JS engine.
7pub(crate) trait JsEngine: Sized {
8    /// The type of the JS value.
9    type JsValue<'a>: JsValue<'a>
10    where
11        Self: 'a;
12
13    /// Create a JS engine.
14    fn new() -> Result<Self>;
15
16    /// Evaluate arbitrary code in the JS engine.
17    fn eval<'a>(&'a self, code: &str) -> Result<Self::JsValue<'a>>;
18
19    /// Call a JS function in the JS engine.
20    fn call_function<'a>(
21        &'a self,
22        func_name: &str,
23        args: impl Iterator<Item = Self::JsValue<'a>>,
24    ) -> Result<Self::JsValue<'a>>;
25
26    /// Create a JS value from [`bool`].
27    fn create_bool_value(&self, input: bool) -> Result<Self::JsValue<'_>>;
28
29    /// Create a JS value from [`i32`].
30    fn create_int_value(&self, input: i32) -> Result<Self::JsValue<'_>>;
31
32    /// Create a JS value from [`f64`].
33    fn create_float_value(&self, input: f64) -> Result<Self::JsValue<'_>>;
34
35    /// Create a JS value from [`String`].
36    fn create_string_value(&self, input: String) -> Result<Self::JsValue<'_>>;
37
38    /// Create a JS object value from an iterator for `(String, Self::JsValue)`.
39    fn create_object_value<'a>(
40        &'a self,
41        input: impl Iterator<Item = (String, Self::JsValue<'a>)>,
42    ) -> Result<Self::JsValue<'a>>;
43}
44
45/// A trait to represent a JS value.
46pub(crate) trait JsValue<'a>: Sized {
47    /// Convert the JS Value to a [`String`].
48    fn into_string(self) -> Result<String>;
49}
50
51cfg_if! {
52    if #[cfg(feature = "quick-js")] {
53        cfg_if! {
54            if #[cfg(any(unix, all(windows, target_env = "gnu")))] {
55                mod quick_js;
56
57                pub(crate) type Engine = self::quick_js::Engine;
58            } else {
59                compile_error!("quick-js backend is not support in the current build target.");
60            }
61        }
62    } else if #[cfg(feature = "duktape")] {
63        cfg_if! {
64            if #[cfg(any(unix, windows))] {
65                mod duktape;
66
67                pub(crate) type Engine = self::duktape::Engine;
68            } else {
69                compile_error!("duktape backend is not support in the current build target.");
70            }
71        }
72    } else if #[cfg(feature = "wasm-js")] {
73        cfg_if! {
74            if #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] {
75                mod wasm_js;
76
77                pub(crate) type Engine = self::wasm_js::Engine;
78            } else {
79                compile_error!("wasm-js backend is not support in the current build target.");
80            }
81        }
82    } else {
83        compile_error!("Must enable one of the JS engines.");
84    }
85}