Skip to main content

datumesh_core/
object.rs

1//! Object keys (16.5, `spec-0.5.0`): the key encoding of an object, its decoded form, its
2//! object JSON, its object id and short ids. Pure functions; an object is never stored.
3
4use std::collections::BTreeMap;
5
6use crate::error::{err, ErrorCode, Result};
7use crate::json::Value;
8use crate::lexical;
9use crate::model::{self, Scalar, Type};
10
11/// The value of one key of an object: a typed scalar, or, for a class-typed key, the nested
12/// object (written unquoted in the encoding, 16.5).
13#[derive(Clone, Debug, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum KeyValue {
16    /// A scalar key: a string, number, boolean, date or instant.
17    Scalar(Scalar),
18    /// A class-typed key: the key of an object of another class.
19    Object(ObjectKey),
20}
21
22/// An object as its key encoding decodes: a class name and its key tuple, by key name. Which
23/// class the name denotes, and whether the keys are that class's, are not known here: the
24/// encoding is checked for form only (16.5), against a class by the caller.
25#[derive(Clone, Debug, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct ObjectKey {
28    /// The full class name, e.g. `rates.example.org/fx_pair`.
29    pub class: String,
30    /// The keys by name (ascending in the encoding, as a `BTreeMap` iterates).
31    pub keys: BTreeMap<String, KeyValue>,
32}
33
34/// Parses a key encoding (16.5): `class-name "(" [ key-pair *( "," key-pair ) ] ")"`, names
35/// strictly ascending, no space, strings quoted with `"` doubled, a class-typed key its own
36/// encoding unquoted. Anything that is not exactly the canonical encoding of what it decodes
37/// to (a bare class name, an unquoted string, a space, trailing text, unsorted or repeated
38/// names, a number not in canonical form) is `E_KEY_ENCODING`.
39///
40/// Since `spec-0.5.0` (16.5) an encoding is one string value: as a whole it is at most 1024
41/// bytes, holds no control character, is in NFC and is assigned in Unicode 15.1; that bounds
42/// each string inside it too. Every failure of these checks is `E_KEY_ENCODING` as well.
43pub fn parse_object_key(text: &str) -> Result<ObjectKey> {
44    if let Err(e) = lexical::check_string(text, "$") {
45        return err(ErrorCode::KeyEncoding, "$", format!("the encoding is not one string value: {}", e.detail()));
46    }
47    let mut p = Parser { s: text, i: 0 };
48    let key = p.object()?;
49    if p.i != text.len() {
50        return p.fail("trailing text after the encoding");
51    }
52    // The encoding of what it decodes to is the input itself (one spelling).
53    if format_object_key(&key) != text {
54        return p.fail("not the canonical encoding");
55    }
56    Ok(key)
57}
58
59/// A cursor over an encoding text.
60struct Parser<'a> {
61    s: &'a str,
62    i: usize,
63}
64
65impl Parser<'_> {
66    fn fail<T>(&self, why: &str) -> Result<T> {
67        err(ErrorCode::KeyEncoding, "$", format!("{why} (at byte {})", self.i))
68    }
69
70    fn peek(&self) -> Option<char> {
71        self.s[self.i..].chars().next()
72    }
73
74    /// `class-name "(" ... ")"`, with the class name checked as a full name (2.3).
75    fn object(&mut self) -> Result<ObjectKey> {
76        let rest = &self.s[self.i..];
77        let Some(open) = rest.find('(') else {
78            return self.fail("a key encoding has an opening parenthesis");
79        };
80        let class = &rest[..open];
81        if lexical::check_function_name(class, "$").is_err() {
82            return self.fail("the class name is not a full name");
83        }
84        self.i += open + 1;
85        let mut keys = BTreeMap::new();
86        let mut prev: Option<String> = None;
87        if self.peek() == Some(')') {
88            self.i += 1;
89            return Ok(ObjectKey { class: class.into(), keys });
90        }
91        loop {
92            let rest = &self.s[self.i..];
93            let Some(colon) = rest.find(':') else {
94                return self.fail("a key has a label");
95            };
96            let name = &rest[..colon];
97            if lexical::check_arg_name(name, "$").is_err() {
98                return self.fail("a key label is an argument name");
99            }
100            if prev.as_deref().is_some_and(|p| p >= name) {
101                return self.fail("key labels are strictly ascending");
102            }
103            self.i += colon + 1;
104            let value = self.value()?;
105            keys.insert(name.to_string(), value);
106            prev = Some(name.to_string());
107            match self.peek() {
108                Some(',') => self.i += 1,
109                Some(')') => {
110                    self.i += 1;
111                    break;
112                }
113                _ => return self.fail("a key is followed by a comma or the closing parenthesis"),
114            }
115        }
116        Ok(ObjectKey { class: class.into(), keys })
117    }
118
119    /// One key value: a string, a boolean, a number, date or instant in its lexical form, or a
120    /// nested key encoding (class-typed).
121    fn value(&mut self) -> Result<KeyValue> {
122        if self.peek() == Some('"') {
123            self.i += 1;
124            let mut out = String::new();
125            loop {
126                let Some(c) = self.peek() else {
127                    return self.fail("an unterminated string");
128                };
129                self.i += c.len_utf8();
130                if c == '"' {
131                    if self.peek() == Some('"') {
132                        self.i += 1;
133                        out.push('"');
134                    } else {
135                        break;
136                    }
137                } else {
138                    out.push(c);
139                }
140            }
141            if lexical::check_string(&out, "$").is_err() {
142                return self.fail("a string is not a valid string value");
143            }
144            return Ok(KeyValue::Scalar(Scalar::String(out)));
145        }
146        let rest = &self.s[self.i..];
147        let stop = rest.find([',', ')', '(']).unwrap_or(rest.len());
148        if rest[stop..].starts_with('(') {
149            return Ok(KeyValue::Object(self.object()?));
150        }
151        let token = &rest[..stop];
152        self.i += stop;
153        let scalar = if token == "true" {
154            Scalar::Boolean(true)
155        } else if token == "false" {
156            Scalar::Boolean(false)
157        } else if token.len() == 10 && lexical::check_date(token, "$").is_ok() {
158            Scalar::Date(token.into())
159        } else if lexical::check_instant(token, "$").is_ok() {
160            Scalar::Instant(token.into())
161        } else if lexical::check_number(token, "$").is_ok() {
162            Scalar::Number(token.into())
163        } else {
164            return self.fail("a key value is a string, boolean, number, date, instant or key encoding");
165        };
166        Ok(KeyValue::Scalar(scalar))
167    }
168}
169
170/// A string as a key encoding writes it: in double quotes, `"` doubled.
171fn quoted(s: &str) -> String {
172    let mut out = String::with_capacity(s.len() + 2);
173    out.push('"');
174    for c in s.chars() {
175        if c == '"' {
176            out.push('"');
177        }
178        out.push(c);
179    }
180    out.push('"');
181    out
182}
183
184/// The canonical key encoding of an object: the class name in full, the keys labelled in
185/// ascending order of name with no space, a string quoted with `"` doubled, numbers, dates and
186/// instants in their lexical forms, a class-typed key its own encoding unquoted.
187/// `parse_object_key(&format_object_key(k)) == Ok(k)` for every key `format_object_key` is
188/// given, and `format_object_key(&parse_object_key(s)?) == s` for every `s` that parses.
189pub fn format_object_key(key: &ObjectKey) -> String {
190    let mut out = String::with_capacity(key.class.len() + 2);
191    out.push_str(&key.class);
192    out.push('(');
193    for (i, (name, value)) in key.keys.iter().enumerate() {
194        if i > 0 {
195            out.push(',');
196        }
197        out.push_str(name);
198        out.push(':');
199        match value {
200            KeyValue::Scalar(Scalar::String(s)) => out.push_str(&quoted(s)),
201            KeyValue::Scalar(other) => out.push_str(other.lexical()),
202            KeyValue::Object(inner) => out.push_str(&format_object_key(inner)),
203        }
204    }
205    out.push(')');
206    out
207}
208
209impl ObjectKey {
210    /// An object of `class` with these keys (the pairs may come in any order: the encoding sorts
211    /// them). `E_CANON_NAME` for a class name that is not a full name (2.3), `E_CANON_ARG_NAME`
212    /// for a key name that is not an argument name (2.4), `E_CANON_TYPE` for a `blob` scalar (a
213    /// key is never a blob, 16.1), `E_CANON_ARG_DUPLICATE` for a key name given twice.
214    pub fn new(class: &str, keys: impl IntoIterator<Item = (String, KeyValue)>) -> Result<ObjectKey> {
215        lexical::check_function_name(class, "$.class")?;
216        let mut map = BTreeMap::new();
217        for (name, value) in keys {
218            lexical::check_arg_name(&name, "$.keys")?;
219            if let KeyValue::Scalar(scalar) = &value {
220                if scalar.ty() == Type::Blob {
221                    return err(ErrorCode::CanonType, &name, "a key is never a blob");
222                }
223                // The lexical form is checked, so that the encoding of the key parses back.
224                model::check_lexical(scalar.ty(), scalar.lexical(), &name)?;
225            }
226            if map.contains_key(&name) {
227                return err(ErrorCode::CanonArgDuplicate, &name, "a key is bound twice");
228            }
229            map.insert(name, value);
230        }
231        Ok(ObjectKey { class: class.into(), keys: map })
232    }
233
234    /// The decoded form the `key` vectors give: `{"class": name, "keys": {name: <typed scalar or
235    /// a nested decoded object>, ...}}`.
236    pub fn to_value(&self) -> Value {
237        Value::Object(vec![
238            ("class".into(), Value::String(self.class.clone())),
239            (
240                "keys".into(),
241                Value::Object(
242                    self.keys
243                        .iter()
244                        .map(|(k, v)| {
245                            let value = match v {
246                                KeyValue::Scalar(s) => s.to_value(),
247                                KeyValue::Object(o) => o.to_value(),
248                            };
249                            (k.clone(), value)
250                        })
251                        .collect(),
252                ),
253            ),
254        ])
255    }
256
257    /// The object JSON of 16.5, `{"class", "class_hash", "keys": {name: <typed scalar>, ...}}`,
258    /// every key bound. `class_hash` is 64 lowercase hex digits (`E_CANON_HEX` otherwise). A
259    /// class-typed key is the typed `string` scalar holding its key encoding (16.5: "the object
260    /// travels as one canonical string").
261    pub fn object_value(&self, class_hash: &str) -> Result<Value> {
262        lexical::check_hex(class_hash, 64, "$.class_hash")?;
263        let keys = self
264            .keys
265            .iter()
266            .map(|(k, v)| {
267                let scalar = match v {
268                    KeyValue::Scalar(s) => s.clone(),
269                    KeyValue::Object(o) => Scalar::String(format_object_key(o)),
270                };
271                (k.clone(), scalar.to_value())
272            })
273            .collect();
274        Ok(Value::Object(vec![
275            ("class".into(), Value::String(self.class.clone())),
276            ("class_hash".into(), Value::String(class_hash.into())),
277            ("keys".into(), Value::Object(keys)),
278        ]))
279    }
280
281    /// The object id: SHA-256 (lowercase hex) of the canonical bytes (6.2) of
282    /// [`object_value`](Self::object_value).
283    pub fn object_id(&self, class_hash: &str) -> Result<String> {
284        Ok(crate::crypto::sha256_hex(&self.object_value(class_hash)?.to_jcs()))
285    }
286
287    /// The object's canonical call form (16.8): the class name and every key labelled in
288    /// ascending order, `name: <literal>`, separated by `, `: strings quoted with `"` doubled,
289    /// numbers, dates, instants and booleans bare, and a class-typed key (a string holding its
290    /// key encoding) quoted like any string, `x: "b.example.org/m(y:1)"`. For example `scripture.example.org/verse(book: "Gen", chapter: 1,
291    /// corpus: "tanakh", verse: 1)`.
292    pub fn call_form(&self) -> String {
293        let mut out = String::with_capacity(self.class.len() + 2);
294        out.push_str(&self.class);
295        out.push('(');
296        for (i, (name, value)) in self.keys.iter().enumerate() {
297            if i > 0 {
298                out.push_str(", ");
299            }
300            out.push_str(name);
301            out.push_str(": ");
302            match value {
303                KeyValue::Scalar(Scalar::String(s)) => out.push_str(&quoted(s)),
304                KeyValue::Scalar(other) => out.push_str(other.lexical()),
305                KeyValue::Object(inner) => out.push_str(&quoted(&format_object_key(inner))),
306            }
307        }
308        out.push(')');
309        out
310    }
311}
312
313/// The short id of a cell id or an object id (16.8): its first 12 hex digits. `id` must be 64
314/// lowercase hex digits (`E_CANON_HEX` otherwise).
315pub fn short_id(id: &str) -> Result<String> {
316    lexical::check_hex(id, 64, "$.id")?;
317    Ok(id[..12].to_string())
318}