Skip to main content

nsh_core/js/
ops.rs

1//! Operations JS records into flat lists (a canvas's drawing): a code, then
2//! its arguments. `#[derive(JsOps)]` on an enum of operations maps codes
3//! to variants and reads their fields in order ([`OpArg`]), and describes
4//! the methods and properties that record them as they are, which the
5//! native recorders (`nsh-js` `canvas.rs`) and their declarations
6//! (`canvas.gen.ts`) are made from. The
7//! lists are read through [`HostInput`], straight from QuickJS values.
8
9use std::{fmt, sync::Arc};
10
11pub use nsh_macros::JsOps;
12
13use super::host::{HostCx, HostInput, HostList, HostValue};
14use crate::ui::TsTypes;
15
16/// Why a recorded list could not be read.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum OpsError {
19    /// It ends inside an operation.
20    Truncated,
21    /// A code is not a number.
22    NotAnOperation,
23    /// A code no operation has.
24    Unknown(i32),
25    /// An operation where it cannot be (a path's list holds path
26    /// operations only).
27    Misplaced(i32),
28}
29
30impl fmt::Display for OpsError {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        match self {
33            OpsError::Truncated => f.write_str("truncated list of operations"),
34            OpsError::NotAnOperation => f.write_str("expected an operation"),
35            OpsError::Unknown(code) => write!(f, "unknown operation {code}"),
36            OpsError::Misplaced(code) => write!(f, "operation {code} does not belong here"),
37        }
38    }
39}
40
41impl std::error::Error for OpsError {}
42
43/// Reads items `start..end` of a recorded list, in order.
44pub struct OpReader<'a, L> {
45    list: &'a L,
46    pos: usize,
47    end: usize,
48}
49
50impl<'a, L: HostList<Item: HostInput>> OpReader<'a, L> {
51    /// Items `start..end` of `list`.
52    pub fn new(list: &'a L, start: usize, end: usize) -> Self {
53        Self {
54            list,
55            pos: start,
56            end,
57        }
58    }
59
60    /// The whole of `list`.
61    pub fn all(list: &'a L) -> Self {
62        Self::new(list, 0, list.len())
63    }
64
65    /// Whether items are left.
66    #[inline]
67    pub fn more(&self) -> bool {
68        self.pos < self.end
69    }
70
71    /// The next item (an argument).
72    #[inline]
73    pub fn arg(&mut self) -> Result<L::Item, OpsError> {
74        if self.pos >= self.end {
75            return Err(OpsError::Truncated);
76        }
77        let item = self.list.item(self.pos).ok_or(OpsError::Truncated)?;
78        self.pos += 1;
79        Ok(item)
80    }
81
82    /// The next item as an operation's code.
83    #[inline]
84    pub fn code(&mut self) -> Result<i32, OpsError> {
85        self.arg()?
86            .as_number()
87            .map(|n| n as i32)
88            .ok_or(OpsError::NotAnOperation)
89    }
90}
91
92/// An argument of a recorded operation: how it is read (with the list's
93/// context `Cx`, e.g. the drawing that numbers' animated values become slots
94/// of) and its TypeScript type.
95pub trait OpArg<Cx>: Sized {
96    /// How many items it takes (an `[f32; 4]` four, one parameter each).
97    const ARITY: usize = 1;
98    /// The argument; `None` drops the operation (an invalid color, as in
99    /// HTML Canvas). Values of another type are the type's default.
100    fn read<L: HostList<Item: HostInput>>(
101        r: &mut OpReader<'_, L>,
102        cx: &mut Cx,
103    ) -> Result<Option<Self>, OpsError>;
104    /// The TypeScript type of (each of) its parameters.
105    fn ts(types: &mut TsTypes) -> String;
106}
107
108/// A parameter of a recording method.
109#[derive(Debug, Clone)]
110pub struct OpParam {
111    /// Its JS name.
112    pub name: &'static str,
113    /// Its TypeScript type.
114    pub ts: String,
115    /// Its JS default (`None`: required).
116    pub default: Option<&'static str>,
117}
118
119/// A method that pushes its code and its arguments as they are.
120#[derive(Debug, Clone)]
121pub struct OpMethod {
122    /// Its JS name.
123    pub name: &'static str,
124    /// The operation's code.
125    pub code: i32,
126    /// Its parameters, pushed in order.
127    pub params: Vec<OpParam>,
128    /// Documentation.
129    pub doc: &'static str,
130}
131
132/// A state property: reading it gives the kept value, setting it keeps
133/// the value and pushes its code and the value.
134#[derive(Debug, Clone)]
135pub struct OpProperty {
136    /// Its JS name.
137    pub name: &'static str,
138    /// The operation's code.
139    pub code: i32,
140    /// Its TypeScript type.
141    pub ts: String,
142    /// Its initial value (JS).
143    pub initial: &'static str,
144    /// Documentation.
145    pub doc: &'static str,
146}
147
148/// An enum of recorded operations (`#[derive(JsOps)]`).
149pub trait JsOps: Sized {
150    /// What reading the arguments needs.
151    type Cx;
152    /// The operation with code `code`, its arguments read from `r`:
153    /// `None` for a code that is not one of these operations, `Some(None)`
154    /// for one that is dropped.
155    fn decode<L: HostList<Item: HostInput>>(
156        code: i32,
157        r: &mut OpReader<'_, L>,
158        cx: &mut Self::Cx,
159    ) -> Result<Option<Option<Self>>, OpsError>;
160    /// The methods recording these operations as they are (not those of
161    /// nested enums).
162    fn methods(types: &mut TsTypes, out: &mut Vec<OpMethod>);
163    /// The properties recording them.
164    fn properties(types: &mut TsTypes, out: &mut Vec<OpProperty>);
165}
166
167/// Values of another type are 0.
168impl<Cx> OpArg<Cx> for f32 {
169    fn read<L: HostList<Item: HostInput>>(
170        r: &mut OpReader<'_, L>,
171        _: &mut Cx,
172    ) -> Result<Option<Self>, OpsError> {
173        Ok(Some(r.arg()?.as_number().map_or(0.0, |n| n as f32)))
174    }
175
176    fn ts(_: &mut TsTypes) -> String {
177        "number".into()
178    }
179}
180
181/// A number, or nothing (`maxWidth`).
182impl<Cx> OpArg<Cx> for Option<f32> {
183    fn read<L: HostList<Item: HostInput>>(
184        r: &mut OpReader<'_, L>,
185        _: &mut Cx,
186    ) -> Result<Option<Self>, OpsError> {
187        Ok(Some(r.arg()?.as_number().map(|n| n as f32)))
188    }
189
190    fn ts(_: &mut TsTypes) -> String {
191        "number".into()
192    }
193}
194
195/// Values of another type are false.
196impl<Cx> OpArg<Cx> for bool {
197    fn read<L: HostList<Item: HostInput>>(
198        r: &mut OpReader<'_, L>,
199        _: &mut Cx,
200    ) -> Result<Option<Self>, OpsError> {
201        Ok(Some(r.arg()?.as_bool().unwrap_or(false)))
202    }
203
204    fn ts(_: &mut TsTypes) -> String {
205        "boolean".into()
206    }
207}
208
209/// Values of another type are the empty string.
210impl<Cx> OpArg<Cx> for Arc<str> {
211    fn read<L: HostList<Item: HostInput>>(
212        r: &mut OpReader<'_, L>,
213        _: &mut Cx,
214    ) -> Result<Option<Self>, OpsError> {
215        Ok(Some(r.arg()?.as_string().unwrap_or_default().into()))
216    }
217
218    fn ts(_: &mut TsTypes) -> String {
219        "string".into()
220    }
221}
222
223/// `N` arguments of type `T` (one parameter each).
224impl<Cx, T: OpArg<Cx> + Copy + Default, const N: usize> OpArg<Cx> for [T; N] {
225    const ARITY: usize = N * T::ARITY;
226
227    fn read<L: HostList<Item: HostInput>>(
228        r: &mut OpReader<'_, L>,
229        cx: &mut Cx,
230    ) -> Result<Option<Self>, OpsError> {
231        let mut out = [T::default(); N];
232        let mut kept = true;
233        for v in &mut out {
234            match T::read(r, cx)? {
235                Some(read) => *v = read,
236                None => kept = false,
237            }
238        }
239        Ok(kept.then_some(out))
240    }
241
242    fn ts(types: &mut TsTypes) -> String {
243        T::ts(types)
244    }
245}
246
247/// An argument read as a host value (one of a string union and the
248/// like); `None` when it does not take the value.
249pub(crate) fn host_value<T: HostValue, L: HostList<Item: HostInput>>(
250    r: &mut OpReader<'_, L>,
251) -> Result<Option<T>, OpsError> {
252    let item = r.arg()?;
253    Ok(T::decode(&item, &mut HostCx::default()))
254}