Skip to main content

drawland_graph/
arg.rs

1//! The values the library takes and gives, whatever language calls it: the
2//! plain data a script writes (numbers, strings, lists, objects) and the
3//! handles the library returns (features, areas, lines, and the lazy parts
4//! of a module). JavaScript, Python and Rust each turn their own values into
5//! these and back.
6
7use serde_json::Value;
8
9/// A value passed to or returned by the library.
10#[derive(Clone, Debug, PartialEq)]
11pub enum Arg {
12    Null,
13    Bool(bool),
14    Num(f64),
15    Str(String),
16    List(Vec<Arg>),
17    Map(Obj),
18    /// A set of map features (`features.*`).
19    Features(String),
20    /// An area (`areas.*`, `page.frame`, a module's `.area`). `mask` is what
21    /// `compose.mask` hides with: the area itself, or the module's own.
22    Area { r: String, mask: String },
23    /// Lines (`lines.*`, `fills.fill`, a module's output). A module's output
24    /// can be drawn, not transformed.
25    Lines { r: String, module: Option<String> },
26    /// A module's part made only when it is asked for (`graticule.keys`,
27    /// `labels.area`, a label rule's bucket): read it with `Graph::get`.
28    Lazy(Lazy),
29    /// A function, where the library takes none (it says so).
30    Func,
31}
32
33/// An object: keys in the order they were written.
34#[derive(Clone, Debug, Default, PartialEq)]
35pub struct Obj(pub Vec<(String, Arg)>);
36
37impl Obj {
38    pub fn new() -> Obj {
39        Obj(Vec::new())
40    }
41
42    /// The value at `key`; `None` when the key is not there.
43    pub fn get(&self, key: &str) -> Option<&Arg> {
44        self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v)
45    }
46
47    pub fn has(&self, key: &str) -> bool {
48        self.get(key).is_some()
49    }
50
51    pub fn keys(&self) -> impl Iterator<Item = &str> {
52        self.0.iter().map(|(k, _)| k.as_str())
53    }
54
55    pub fn len(&self) -> usize {
56        self.0.len()
57    }
58
59    pub fn is_empty(&self) -> bool {
60        self.0.is_empty()
61    }
62
63    /// Set `key`, in place if it is there, at the end if not.
64    pub fn set(&mut self, key: &str, value: Arg) {
65        match self.0.iter_mut().find(|(k, _)| k == key) {
66            Some((_, v)) => *v = value,
67            None => self.0.push((key.to_string(), value)),
68        }
69    }
70
71    pub fn remove(&mut self, key: &str) -> Option<Arg> {
72        let i = self.0.iter().position(|(k, _)| k == key)?;
73        Some(self.0.remove(i).1)
74    }
75
76    /// Everything but `keys`, in order.
77    pub fn without(&self, keys: &[&str]) -> Obj {
78        Obj(self.0.iter().filter(|(k, _)| !keys.contains(&k.as_str())).cloned().collect())
79    }
80}
81
82/// Which part of a module a [`Lazy`] is, and what it was made from.
83#[derive(Clone, Debug, PartialEq)]
84pub enum Lazy {
85    /// `modules.graticule(…)`: its look, as the graph writes it.
86    Graticule(Value),
87    /// `modules.labels(…)`: the labels' node, and the rule ids it has.
88    Labels { r: String, rules: Vec<String> },
89    /// One rule's bucket of `modules.labels`.
90    LabelRule { r: String, rule: String },
91}
92
93impl Arg {
94    pub fn str(s: &str) -> Arg {
95        Arg::Str(s.to_string())
96    }
97
98    pub fn as_str(&self) -> Option<&str> {
99        match self {
100            Arg::Str(s) => Some(s),
101            _ => None,
102        }
103    }
104
105    pub fn as_num(&self) -> Option<f64> {
106        match self {
107            Arg::Num(n) => Some(*n),
108            _ => None,
109        }
110    }
111
112    /// A finite number.
113    pub fn as_finite(&self) -> Option<f64> {
114        self.as_num().filter(|n| n.is_finite())
115    }
116
117    pub fn as_map(&self) -> Option<&Obj> {
118        match self {
119            Arg::Map(o) => Some(o),
120            _ => None,
121        }
122    }
123
124    pub fn as_list(&self) -> Option<&[Arg]> {
125        match self {
126            Arg::List(l) => Some(l),
127            _ => None,
128        }
129    }
130
131    /// JavaScript's truthiness, for the flags a script may write as anything.
132    pub fn truthy(&self) -> bool {
133        match self {
134            Arg::Null => false,
135            Arg::Bool(b) => *b,
136            Arg::Num(n) => *n != 0.0 && !n.is_nan(),
137            Arg::Str(s) => !s.is_empty(),
138            _ => true,
139        }
140    }
141
142    /// The value as the graph's JSON writes it. A handle becomes its
143    /// reference (an area its own, not its mask).
144    pub fn to_json(&self) -> Value {
145        match self {
146            Arg::Null | Arg::Func => Value::Null,
147            Arg::Bool(b) => Value::Bool(*b),
148            Arg::Num(n) => number(*n),
149            Arg::Str(s) => Value::String(s.clone()),
150            Arg::List(l) => Value::Array(l.iter().map(Arg::to_json).collect()),
151            Arg::Map(o) => Value::Object(o.0.iter().map(|(k, v)| (k.clone(), v.to_json())).collect()),
152            Arg::Features(r) | Arg::Area { r, .. } | Arg::Lines { r, .. } => Value::String(r.clone()),
153            Arg::Lazy(_) => Value::Null,
154        }
155    }
156
157    /// Plain JSON as a value: no handles in it.
158    pub fn from_json(v: &Value) -> Arg {
159        match v {
160            Value::Null => Arg::Null,
161            Value::Bool(b) => Arg::Bool(*b),
162            Value::Number(n) => Arg::Num(n.as_f64().unwrap_or(f64::NAN)),
163            Value::String(s) => Arg::Str(s.clone()),
164            Value::Array(a) => Arg::List(a.iter().map(Arg::from_json).collect()),
165            Value::Object(o) => Arg::Map(Obj(o.iter().map(|(k, v)| (k.clone(), Arg::from_json(v))).collect())),
166        }
167    }
168}
169
170/// A number as JSON: a whole number as an integer, as a script writes it.
171pub fn number(n: f64) -> Value {
172    if n.fract() == 0.0 && n.abs() < 9_007_199_254_740_992.0 {
173        Value::from(n as i64)
174    } else {
175        serde_json::Number::from_f64(n).map(Value::Number).unwrap_or(Value::Null)
176    }
177}
178
179/// A number as JavaScript prints it: `3`, `0.5`, `-2.25`.
180pub fn show_number(n: f64) -> String {
181    if n.is_nan() {
182        "NaN".into()
183    } else if n.is_infinite() {
184        if n > 0.0 { "Infinity".into() } else { "-Infinity".into() }
185    } else if n.fract() == 0.0 && n.abs() < 1e21 {
186        format!("{}", n as i64)
187    } else {
188        format!("{n}")
189    }
190}
191
192/// How an error names what it got: `an area`, `the string "x"`, `nothing`.
193pub fn describe(v: Option<&Arg>) -> String {
194    match v {
195        None => "nothing".into(),
196        Some(Arg::Null) => "null".into(),
197        Some(Arg::Features(_)) => "features".into(),
198        Some(Arg::Area { .. }) => "an area".into(),
199        Some(Arg::Lines { .. }) => "lines".into(),
200        Some(Arg::List(_)) => "a list".into(),
201        Some(Arg::Map(_)) | Some(Arg::Lazy(_)) => "an object".into(),
202        Some(Arg::Func) => "a function".into(),
203        Some(Arg::Bool(b)) => format!("the boolean {b}"),
204        Some(Arg::Num(n)) => format!("the number {}", show_number(*n)),
205        Some(Arg::Str(s)) => format!("the string {}", Value::String(s.clone())),
206    }
207}
208
209/// `Arg` from the values a Rust caller has at hand.
210impl From<&str> for Arg {
211    fn from(s: &str) -> Arg {
212        Arg::Str(s.to_string())
213    }
214}
215impl From<String> for Arg {
216    fn from(s: String) -> Arg {
217        Arg::Str(s)
218    }
219}
220impl From<f64> for Arg {
221    fn from(n: f64) -> Arg {
222        Arg::Num(n)
223    }
224}
225impl From<i32> for Arg {
226    fn from(n: i32) -> Arg {
227        Arg::Num(n as f64)
228    }
229}
230impl From<u32> for Arg {
231    fn from(n: u32) -> Arg {
232        Arg::Num(n as f64)
233    }
234}
235impl From<bool> for Arg {
236    fn from(b: bool) -> Arg {
237        Arg::Bool(b)
238    }
239}
240impl<T: Into<Arg>> From<Vec<T>> for Arg {
241    fn from(v: Vec<T>) -> Arg {
242        Arg::List(v.into_iter().map(Into::into).collect())
243    }
244}
245impl<T: Into<Arg> + Clone, const N: usize> From<[T; N]> for Arg {
246    fn from(v: [T; N]) -> Arg {
247        Arg::List(v.into_iter().map(Into::into).collect())
248    }
249}
250impl From<Obj> for Arg {
251    fn from(o: Obj) -> Arg {
252        Arg::Map(o)
253    }
254}
255impl From<&Arg> for Arg {
256    fn from(a: &Arg) -> Arg {
257        a.clone()
258    }
259}
260impl From<Value> for Arg {
261    fn from(v: Value) -> Arg {
262        Arg::from_json(&v)
263    }
264}
265
266/// An object written in Rust: `obj! { "pattern" => "dots", "spacing" => "0.45mm", "in" => &parks }`.
267#[macro_export]
268macro_rules! obj {
269    () => { $crate::Obj::new() };
270    ($($k:expr => $v:expr),+ $(,)?) => {{
271        let mut o = $crate::Obj::new();
272        $( o.set($k, $crate::Arg::from($v)); )+
273        o
274    }};
275}
276
277impl Arg {
278    /// The value as JSON with its handles marked (`{ "$area": "$areas.x",
279    /// "mask": … }`), for a binding to hand its own language and take back
280    /// with [`Arg::decode`]. A lazy part lists the parts it has.
281    pub fn encode(&self) -> Value {
282        match self {
283            Arg::Features(r) => serde_json::json!({ "$features": r }),
284            Arg::Area { r, mask } => serde_json::json!({ "$area": r, "mask": mask }),
285            Arg::Lines { r, module } => serde_json::json!({ "$lines": r, "module": module }),
286            Arg::Func => serde_json::json!({ "$function": true }),
287            Arg::Lazy(l) => {
288                let tag = match l {
289                    Lazy::Graticule(look) => serde_json::json!({ "graticule": look }),
290                    Lazy::Labels { r, rules } => serde_json::json!({ "labels": { "r": r, "rules": rules } }),
291                    Lazy::LabelRule { r, rule } => serde_json::json!({ "rule": { "r": r, "rule": rule } }),
292                };
293                serde_json::json!({ "$lazy": tag, "parts": crate::Graph::parts(l) })
294            }
295            Arg::List(l) => Value::Array(l.iter().map(Arg::encode).collect()),
296            Arg::Map(o) => Value::Object(o.0.iter().map(|(k, v)| (k.clone(), v.encode())).collect()),
297            other => other.to_json(),
298        }
299    }
300
301    /// A value from [`Arg::encode`]'s JSON: marked handles become handles.
302    pub fn decode(v: &Value) -> Arg {
303        match v {
304            Value::Array(a) => Arg::List(a.iter().map(Arg::decode).collect()),
305            Value::Object(o) => {
306                let s = |k: &str| o.get(k).and_then(Value::as_str).map(str::to_string);
307                if let Some(r) = s("$features") {
308                    return Arg::Features(r);
309                }
310                if let Some(r) = s("$area") {
311                    return Arg::Area { mask: s("mask").unwrap_or_else(|| r.clone()), r };
312                }
313                if let Some(r) = s("$lines") {
314                    return Arg::Lines { r, module: s("module") };
315                }
316                if o.contains_key("$function") {
317                    return Arg::Func;
318                }
319                if let Some(tag) = o.get("$lazy") {
320                    let str_of = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
321                    if let Some(look) = tag.get("graticule") {
322                        return Arg::Lazy(Lazy::Graticule(look.clone()));
323                    }
324                    if let Some(l) = tag.get("labels") {
325                        let rules = l.get("rules").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();
326                        return Arg::Lazy(Lazy::Labels { r: str_of(l, "r"), rules });
327                    }
328                    if let Some(l) = tag.get("rule") {
329                        return Arg::Lazy(Lazy::LabelRule { r: str_of(l, "r"), rule: str_of(l, "rule") });
330                    }
331                }
332                Arg::Map(Obj(o.iter().map(|(k, v)| (k.clone(), Arg::decode(v))).collect()))
333            }
334            other => Arg::from_json(other),
335        }
336    }
337}