Skip to main content

brrrty_js/
functions.rs

1//! Calling functions from JavaScript data while a page is built.
2//!
3//! A function in JavaScript data stays in the runtime that made it, and the
4//! data holds a [`Value::Function`] handle to it. The build sets a
5//! [`Caller`] on each thread that renders or places pages; a template that
6//! calls the function goes through it. A page that uses a function any
7//! other way (prints it, compares it, passes it to a filter) records a
8//! trap, as a read of a withheld key does, and the build refuses the page:
9//! 11ty's output there would be JavaScript's own text for the function.
10
11use std::cell::RefCell;
12use std::sync::Arc;
13
14use crate::Value;
15use crate::value::FnHandle;
16
17/// Prefix of a trap recorded for a function a page couldn't use: the rest
18/// is the reason, to show as it is.
19pub const FUNCTION_PREFIX: &str = "function.";
20
21/// What `this` is inside a call.
22#[derive(Debug, Clone, Copy)]
23pub enum This<'a> {
24    /// The object the function was read from (`fmt.money(1)`, and Liquid's
25    /// `{{ fmt.who }}`), as the page sees it.
26    Value(&'a Value),
27    /// An object as the page sees it, but reading any of these keys (`key`, and what it is in
28    /// 11ty) refuses the page: parts of 11ty's `this` Brrrty doesn't model.
29    Guarded(&'a Value, &'a [(&'a str, &'a str)]),
30    /// Something Brrrty doesn't model (Nunjucks's render context, 11ty's
31    /// filter collection): reading any property of it refuses the page.
32    Opaque(&'static str),
33}
34
35/// How a call's result is used.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Settle {
38    /// Await a promise, as Liquid and 11ty's computed data do.
39    Await,
40    /// Take the result as it is, as Nunjucks does: a promise can't cross.
41    AsIs,
42}
43
44/// The runtime that calls functions for the pages on this thread.
45pub trait Caller: Send + Sync {
46    /// Call `f` with `this` and `args`. `Err` is why the page can't use
47    /// the result: the function threw, kept state between calls, changed
48    /// its arguments, or returned something that can't cross.
49    fn call(
50        &self,
51        f: FnHandle,
52        this: This<'_>,
53        args: &[Value],
54        settle: Settle,
55    ) -> Result<Value, String>;
56}
57
58thread_local! {
59    static CALLER: RefCell<Option<Arc<dyn Caller>>> = const { RefCell::new(None) };
60    static UNIT: RefCell<Option<(u64, Arc<str>)>> = const { RefCell::new(None) };
61}
62
63thread_local! {
64    static OWN_PAGE: RefCell<Option<(crate::Value, Option<f64>)>> = const { RefCell::new(None) };
65}
66
67/// The page whose template is rendering on this thread: its `page`
68/// object and, on a paginated page, its number. A function the template
69/// calls is told, so that it finds the page's own data among the
70/// collections' items as the same objects it was handed (in 11ty they
71/// are: a collection item's `data` is the page's data).
72pub fn own_page() -> Option<(crate::Value, Option<f64>)> {
73    OWN_PAGE.with(|p| p.borrow().clone())
74}
75
76/// Marks the renders on this thread, until it drops, as the page's whose
77/// data is `data`.
78pub struct OwnPageGuard(Option<(crate::Value, Option<f64>)>);
79
80impl OwnPageGuard {
81    pub fn enter(data: &indexmap::IndexMap<String, crate::Value>) -> OwnPageGuard {
82        let own = match data.get("page") {
83            Some(page @ crate::Value::Object(_)) => {
84                let number = match data.get("pagination") {
85                    Some(crate::Value::Object(p)) => match p.get("pageNumber") {
86                        Some(crate::Value::Number(n)) => Some(*n),
87                        _ => None,
88                    },
89                    _ => None,
90                };
91                Some((page.clone(), number))
92            }
93            _ => None,
94        };
95        OwnPageGuard(OWN_PAGE.with(|p| std::mem::replace(&mut *p.borrow_mut(), own)))
96    }
97}
98
99impl Drop for OwnPageGuard {
100    fn drop(&mut self) {
101        let before = self.0.take();
102        OWN_PAGE.with(|p| *p.borrow_mut() = before);
103    }
104}
105
106static NEXT_UNIT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
107
108/// The render the calls on this thread belong to (a page's content, its
109/// layouts, the placing of a template's pages): its id, and a name that
110/// orders it among the build's renders the same way every build.
111pub fn unit() -> Option<(u64, Arc<str>)> {
112    UNIT.with(|u| u.borrow().clone())
113}
114
115/// Marks the calls made on this thread, until it drops, as one render
116/// named `label`.
117pub struct UnitGuard(Option<(u64, Arc<str>)>);
118
119impl UnitGuard {
120    pub fn enter(label: impl Into<Arc<str>>) -> UnitGuard {
121        let id = NEXT_UNIT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
122        let before = UNIT.with(|u| u.borrow_mut().replace((id, label.into())));
123        UnitGuard(before)
124    }
125}
126
127impl Drop for UnitGuard {
128    fn drop(&mut self) {
129        let before = self.0.take();
130        UNIT.with(|u| *u.borrow_mut() = before);
131    }
132}
133
134/// Make `caller` this thread's caller from now on (none with `None`).
135pub fn set(caller: Option<Arc<dyn Caller>>) {
136    let before = CALLER.with(|c| std::mem::replace(&mut *c.borrow_mut(), caller));
137    drop(before);
138}
139
140/// The caller installed on this thread, if any.
141pub fn installed() -> Option<Arc<dyn Caller>> {
142    CALLER.with(|c| c.borrow().clone())
143}
144
145/// Call `f`; when it can't be called or its result can't be used, record
146/// the reason as a trap and give `undefined` (the page will be refused).
147pub fn call(f: FnHandle, this: This<'_>, args: &[Value], settle: Settle) -> Value {
148    let Some(caller) = installed() else {
149        crate::traps::record(format!(
150            "{FUNCTION_PREFIX}this page calls a function from JavaScript data where Brrrty can't call it yet"
151        ));
152        return Value::Undefined;
153    };
154    match caller.call(f, this, args, settle) {
155        Ok(v) => v,
156        Err(why) => {
157            crate::traps::record(format!("{FUNCTION_PREFIX}{why}"));
158            Value::Undefined
159        }
160    }
161}
162
163/// Filters known to treat a function as 11ty's do: JSON leaves it out,
164/// `default` keeps it.
165const FILTERS_FOR_FUNCTIONS: &[&str] = &["dump", "json", "default", "d"];
166
167/// Record a trap when the filter `name` would get a function from
168/// JavaScript data as its input or an argument: each filter would need its
169/// own probe against 11ty to say what it does with one.
170pub fn check_filter_args<'a>(name: &str, values: impl IntoIterator<Item = &'a Value>) {
171    if FILTERS_FOR_FUNCTIONS.contains(&name) {
172        return;
173    }
174    if values.into_iter().any(|v| matches!(v, Value::Function(_))) {
175        crate::traps::record(format!(
176            "{FUNCTION_PREFIX}this page passes a function from JavaScript data to the `{name}` filter, which Brrrty can't follow"
177        ));
178    }
179}
180
181/// Record that a page used a function from JavaScript data as a value:
182/// `how` says how ("prints").
183pub fn used_as_value(how: &str) {
184    crate::traps::record(format!(
185        "{FUNCTION_PREFIX}this page {how} a function from JavaScript data as a value, which 11ty shows as JavaScript's own text for it"
186    ));
187}