Skip to main content

datumesh_core/
descriptor.rs

1//! Function descriptors (7), units (7.1, `units.md`) and unit resolution (`units.md` 3).
2
3use std::collections::BTreeMap;
4
5use crate::error::{err, index, member, Error, ErrorCode, Result};
6use crate::json::{self, jcs_sorted, Value};
7use crate::lexical::{self, limits};
8use crate::model::{self, Arg, Cell, Scalar, Type};
9use crate::normalisation::KeyNormalisation;
10use crate::schema;
11
12/// One side of a rate: a currency code or an argument reference. The `per` side may also be
13/// the literal `shares` (`units.md` 2.3, `spec-0.6.2`), held here as a `Currency` side: it is
14/// never a currency code, and only the `per` side of a rate holds it.
15#[derive(Clone, Debug, PartialEq, Eq, Hash)]
16pub enum RateSide {
17    /// A currency code from `units.md` 2.1, or `shares` on the `per` side.
18    Currency(String),
19    /// `{"arg": name}`: the value of a string argument.
20    Arg(String),
21}
22
23/// A unit in a signature (7.1).
24#[derive(Clone, Debug, PartialEq, Eq, Hash)]
25pub enum Unit {
26    /// A unit listed in `units.md`, or an index unit.
27    Literal(String),
28    /// `{"arg": name}`: the value of the named string argument.
29    Arg(String),
30    /// `{"of": X, "per": Y}`: units of X per one unit of Y.
31    Rate {
32        /// The numerator.
33        of: RateSide,
34        /// The denominator.
35        per: RateSide,
36    },
37}
38
39impl Unit {
40    /// The JSON form.
41    pub fn to_value(&self) -> Value {
42        fn arg(n: &str) -> Value {
43            Value::Object(vec![("arg".into(), Value::String(n.into()))])
44        }
45        fn side(s: &RateSide) -> Value {
46            match s {
47                RateSide::Currency(c) => Value::String(c.clone()),
48                RateSide::Arg(n) => arg(n),
49            }
50        }
51        match self {
52            Unit::Literal(s) => Value::String(s.clone()),
53            Unit::Arg(n) => arg(n),
54            Unit::Rate { of, per } => Value::Object(vec![("of".into(), side(of)), ("per".into(), side(per))]),
55        }
56    }
57}
58
59/// An argument declaration: `{"type", "valid"}`, plus `unit` for numbers.
60#[derive(Clone, Debug, PartialEq, Eq, Hash)]
61pub struct ArgDecl {
62    /// The argument's type.
63    pub ty: Type,
64    /// The unit; present exactly when the type is `number`.
65    pub unit: Option<Unit>,
66    /// Whether this is a valid-time argument.
67    pub valid: bool,
68}
69
70/// The declared return: a type, with a unit exactly when it is `number`.
71#[derive(Clone, Debug, PartialEq, Eq, Hash)]
72pub struct Returns {
73    /// The value type.
74    pub ty: Type,
75    /// The unit of a number return.
76    pub unit: Option<Unit>,
77}
78
79/// A function signature.
80#[derive(Clone, Debug, PartialEq, Eq, Hash)]
81pub struct Signature {
82    /// Argument declarations by name.
83    pub args: BTreeMap<String, ArgDecl>,
84    /// The return type.
85    pub returns: Returns,
86}
87
88impl Signature {
89    /// The JSON form, as it appears in a descriptor.
90    pub fn to_value(&self) -> Value {
91        let args = self
92            .args
93            .iter()
94            .map(|(k, d)| {
95                let mut m = vec![("type".to_string(), Value::String(d.ty.as_str().into()))];
96                if let Some(u) = &d.unit {
97                    m.push(("unit".into(), u.to_value()));
98                }
99                m.push(("valid".into(), Value::Bool(d.valid)));
100                (k.clone(), Value::Object(m))
101            })
102            .collect();
103        let returns = match &self.returns.unit {
104            Some(u) => Value::Object(vec![
105                ("type".into(), Value::String(self.returns.ty.as_str().into())),
106                ("unit".into(), u.to_value()),
107            ]),
108            None => Value::String(self.returns.ty.as_str().into()),
109        };
110        Value::Object(vec![("args".into(), Value::Object(args)), ("returns".into(), returns)])
111    }
112}
113
114/// The cells a slice over an argument enumerates (7, `spec-0.4.0`): the argument
115/// declaration's optional `extent`.
116#[derive(Clone, Debug, PartialEq, Eq, Hash)]
117#[non_exhaustive]
118pub enum Extent {
119    /// Lexical values of the argument's type, strictly ascending in the type's order
120    /// (numbers numerically, dates and instants chronologically, strings by code point); at
121    /// most 4096.
122    Values(Vec<String>),
123    /// For a `date` or `number` argument, every date (or every integer) from `lo` to `hi`,
124    /// inclusive; number ends are integers, and `lo <= hi`.
125    Range {
126        /// The first value.
127        lo: String,
128        /// The last value.
129        hi: String,
130    },
131}
132
133impl Extent {
134    /// The JSON form: an array of strings, or `{"hi", "lo"}`.
135    pub fn to_value(&self) -> Value {
136        match self {
137            Extent::Values(v) => Value::Array(v.iter().map(|s| Value::String(s.clone())).collect()),
138            Extent::Range { lo, hi } => {
139                Value::Object(vec![("hi".into(), Value::String(hi.clone())), ("lo".into(), Value::String(lo.clone()))])
140            }
141        }
142    }
143}
144
145/// A function descriptor (7) in its `spec-0.3.0` form: signature, code and declared inputs.
146///
147/// It has no place for the members `spec-0.4.0` adds, `signature.order` and argument
148/// `extent`, so [`from_json`](Self::from_json) and [`from_value`](Self::from_value) refuse a
149/// descriptor that has them with `E_SCHEMA`, as in 0.3.3, rather than return a value whose
150/// [`canonical`](Self::canonical) bytes and [`hash`](Self::hash) would drop them. Read any
151/// descriptor with [`FunctionDescriptor`], which has both; [`FunctionDescriptor::to_descriptor`]
152/// gives this form when neither is present.
153#[derive(Clone, Debug, PartialEq, Eq, Hash)]
154pub struct Descriptor {
155    /// `code.lang`, e.g. `stored`.
156    pub lang: String,
157    /// `code.body`, opaque to this crate.
158    pub body: String,
159    /// Fully qualified names of the functions this one may read, ascending.
160    pub inputs: Vec<String>,
161    /// The signature.
162    pub signature: Signature,
163}
164
165impl Descriptor {
166    /// Parses a descriptor from JSON text: strict JSON, structure, canonical form (7). A
167    /// descriptor with `signature.order` or an argument `extent` is `E_SCHEMA` here (see
168    /// [`Descriptor`]); use [`FunctionDescriptor::from_json`].
169    pub fn from_json(bytes: &[u8]) -> Result<Descriptor> {
170        Descriptor::from_value(&json::parse(bytes)?)
171    }
172
173    /// Checks a parsed JSON value as a descriptor; `E_SCHEMA` for `order` or `extent`, as
174    /// [`from_json`](Self::from_json).
175    pub fn from_value(v: &Value) -> Result<Descriptor> {
176        json::check_value_depth(v)?;
177        descriptor_structure(v, false)?;
178        let f = descriptor_canonical(v)?;
179        Ok(Descriptor { lang: f.lang, body: f.body, inputs: f.inputs, signature: f.signature })
180    }
181
182    /// The JSON form.
183    pub fn to_value(&self) -> Value {
184        descriptor_value(
185            &self.lang,
186            &self.body,
187            &self.inputs,
188            &self.signature,
189            None,
190            &BTreeMap::new(),
191            &BTreeMap::new(),
192            None,
193        )
194    }
195
196    /// The canonical bytes (6.2).
197    pub fn canonical(&self) -> Vec<u8> {
198        self.to_value().to_jcs()
199    }
200
201    /// The function hash: SHA-256 of the canonical bytes, lowercase hex.
202    pub fn hash(&self) -> String {
203        crate::crypto::sha256_hex(&self.canonical())
204    }
205}
206
207/// A function descriptor (7) with the optional members of `spec-0.4.0`: `signature.order`
208/// and argument `extent`. Absent, it is the [`Descriptor`] of `spec-0.3.0`, byte for byte and
209/// hash for hash ([`From<Descriptor>`], [`to_descriptor`](Self::to_descriptor)).
210///
211/// The fields are public to read; a value changed by hand is not checked again until it is
212/// parsed: `FunctionDescriptor::from_value(&d.to_value())` checks it.
213#[derive(Clone, Debug, PartialEq, Eq, Hash)]
214#[non_exhaustive]
215pub struct FunctionDescriptor {
216    /// `code.lang`, e.g. `stored` or `formula`.
217    pub lang: String,
218    /// `code.body`, opaque to this crate.
219    pub body: String,
220    /// Fully qualified names of the functions this one may read, ascending.
221    pub inputs: Vec<String>,
222    /// The signature's arguments and return; its `order` and the arguments' extents are
223    /// [`order`](Self::order) and [`extents`](Self::extents).
224    pub signature: Signature,
225    /// `signature.order`: every argument name exactly once, the order positional arguments
226    /// bind in (15.5); `None` when absent.
227    pub order: Option<Vec<String>>,
228    /// The arguments' `extent` members, by argument name; empty when none has one.
229    pub extents: BTreeMap<String, Extent>,
230    /// The optional members of `spec-0.5.0` of the `string` and `date`/`instant` argument
231    /// declarations (`classes`, `default`, `key_normalisation`), by argument name; an entry
232    /// exists only for an argument that has at least one of them. Absent, a descriptor is
233    /// byte for byte and hash for hash what it was (7).
234    pub arg_extras: BTreeMap<String, ArgExtras>,
235    /// `returns.classes` (7, `spec-0.5.0`): the function returns an object key of one of these
236    /// classes (ascending, unique, at least one); `None` when absent.
237    pub returns_classes: Option<Vec<String>>,
238}
239
240/// The `spec-0.5.0` members of one argument declaration (7), each absent by default.
241///
242/// [`ArgDecl`] has no field for them (it is not `#[non_exhaustive]`, so adding fields would
243/// break the 0.3.x API); they live in [`FunctionDescriptor::arg_extras`], as `extent` lives in
244/// [`FunctionDescriptor::extents`].
245#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
246#[non_exhaustive]
247pub struct ArgExtras {
248    /// `classes`: a `string` argument holding an object key of one of these classes (full class
249    /// names, ascending and unique, at least one; 16.6).
250    pub classes: Option<Vec<String>>,
251    /// `default`: `true` when the declaration says `"default": "asof"`, on a valid-time `date` or
252    /// `instant` argument (16.7).
253    pub default_asof: bool,
254    /// `default` as a literal (K13, the classes round): the lexical value of the argument's
255    /// type that the declaration gives (`"1"` for a number, `"main"` for a string, `"true"` for a
256    /// boolean), as written. `None` when there is no literal default. Never `"asof"`, which is
257    /// [`ArgExtras::default_asof`]. Hashed, as the rest of the descriptor (7).
258    pub default_literal: Option<String>,
259    /// `key_normalisation` of a `string` argument without `classes`: never
260    /// [`KeyNormalisation::NoRule`]. An absent member means `none`, so `"none"` written out is
261    /// `E_SCHEMA`.
262    pub key_normalisation: Option<KeyNormalisation>,
263}
264
265impl FunctionDescriptor {
266    /// Parses a descriptor from JSON text: strict JSON, structure, canonical form (7), with
267    /// `order` and `extent` and their checks (`E_SCHEMA` for their shapes, `E_CANON_SET`,
268    /// `E_CANON_TYPE`, `E_CANON_NUMBER`, `E_CANON_LIMIT` and the lexical codes otherwise).
269    pub fn from_json(bytes: &[u8]) -> Result<FunctionDescriptor> {
270        FunctionDescriptor::from_value(&json::parse(bytes)?)
271    }
272
273    /// Checks a parsed JSON value as a descriptor.
274    pub fn from_value(v: &Value) -> Result<FunctionDescriptor> {
275        json::check_value_depth(v)?;
276        descriptor_structure(v, true)?;
277        descriptor_canonical(v)
278    }
279
280    /// The JSON form.
281    pub fn to_value(&self) -> Value {
282        descriptor_value(
283            &self.lang,
284            &self.body,
285            &self.inputs,
286            &self.signature,
287            self.order.as_deref(),
288            &self.extents,
289            &self.arg_extras,
290            self.returns_classes.as_deref(),
291        )
292    }
293
294    /// The canonical bytes (6.2).
295    pub fn canonical(&self) -> Vec<u8> {
296        self.to_value().to_jcs()
297    }
298
299    /// The function hash: SHA-256 of the canonical bytes, lowercase hex.
300    pub fn hash(&self) -> String {
301        crate::crypto::sha256_hex(&self.canonical())
302    }
303
304    /// The `spec-0.3.0` form, when there is no `order` and no `extent`.
305    pub fn to_descriptor(&self) -> Option<Descriptor> {
306        (self.order.is_none() && self.extents.is_empty()).then(|| Descriptor {
307            lang: self.lang.clone(),
308            body: self.body.clone(),
309            inputs: self.inputs.clone(),
310            signature: self.signature.clone(),
311        })
312    }
313
314    /// The unit of `cell`'s value (7.1, `units.md` 3), as [`resolve_with`] does for a
315    /// [`Descriptor`]; `None` when the function does not return a number.
316    pub fn resolve_unit(&self, cell: &Cell) -> Result<Option<String>> {
317        resolve_returns(&self.signature.returns, cell)
318    }
319}
320
321impl From<Descriptor> for FunctionDescriptor {
322    fn from(d: Descriptor) -> FunctionDescriptor {
323        FunctionDescriptor {
324            lang: d.lang,
325            body: d.body,
326            inputs: d.inputs,
327            signature: d.signature,
328            order: None,
329            extents: BTreeMap::new(),
330            arg_extras: BTreeMap::new(),
331            returns_classes: None,
332        }
333    }
334}
335
336#[allow(clippy::too_many_arguments)]
337fn descriptor_value(
338    lang: &str,
339    body: &str,
340    inputs: &[String],
341    sig: &Signature,
342    order: Option<&[String]>,
343    extents: &BTreeMap<String, Extent>,
344    extras: &BTreeMap<String, ArgExtras>,
345    returns_classes: Option<&[String]>,
346) -> Value {
347    let strings = |v: &[String]| Value::Array(v.iter().map(|s| Value::String(s.clone())).collect());
348    let mut sig_v = sig.to_value();
349    if let Value::Object(m) = &mut sig_v {
350        if let Some((_, Value::Object(args))) = m.iter_mut().find(|(k, _)| k == "args") {
351            for (name, decl) in args.iter_mut() {
352                if let Value::Object(dm) = decl {
353                    if let Some(e) = extents.get(name) {
354                        dm.push(("extent".into(), e.to_value()));
355                    }
356                    if let Some(x) = extras.get(name) {
357                        if let Some(c) = &x.classes {
358                            dm.push(("classes".into(), strings(c)));
359                        }
360                        if x.default_asof {
361                            dm.push(("default".into(), Value::String("asof".into())));
362                        }
363                        if let Some(lit) = &x.default_literal {
364                            dm.push(("default".into(), Value::String(lit.clone())));
365                        }
366                        if let Some(r) = x.key_normalisation {
367                            dm.push(("key_normalisation".into(), Value::String(r.as_str().into())));
368                        }
369                    }
370                }
371            }
372        }
373        if let Some(c) = returns_classes {
374            let returns =
375                Value::Object(vec![("classes".into(), strings(c)), ("type".into(), Value::String("string".into()))]);
376            match m.iter_mut().find(|(k, _)| k == "returns") {
377                Some((_, slot)) => *slot = returns,
378                None => m.push(("returns".into(), returns)),
379            }
380        }
381        if let Some(o) = order {
382            m.push(("order".into(), Value::Array(o.iter().map(|s| Value::String(s.clone())).collect())));
383        }
384    }
385    Value::Object(vec![
386        (
387            "code".into(),
388            Value::Object(vec![
389                ("body".into(), Value::String(body.into())),
390                ("lang".into(), Value::String(lang.into())),
391            ]),
392        ),
393        ("inputs".into(), Value::Array(inputs.iter().map(|s| Value::String(s.clone())).collect())),
394        ("signature".into(), sig_v),
395    ])
396}
397
398pub(crate) fn unit_shape(v: &Value, path: &str) -> Result<()> {
399    let bad = || err(ErrorCode::Schema, path, "a unit is a string, {\"arg\": name} or {\"of\", \"per\"}");
400    match v {
401        Value::String(_) => Ok(()),
402        Value::Object(m) if m.len() == 1 && m[0].0 == "arg" => match m[0].1 {
403            Value::String(_) => Ok(()),
404            _ => bad(),
405        },
406        Value::Object(m) if m.len() == 2 && schema::opt(m, "of").is_some() && schema::opt(m, "per").is_some() => {
407            for side in ["of", "per"] {
408                let ok = match schema::get(m, side) {
409                    Value::String(_) => true,
410                    Value::Object(a) => a.len() == 1 && a[0].0 == "arg" && matches!(a[0].1, Value::String(_)),
411                    _ => false,
412                };
413                if !ok {
414                    return err(
415                        ErrorCode::Schema,
416                        &member(path, side),
417                        "a rate side is a currency code or {\"arg\": name}",
418                    );
419                }
420            }
421            Ok(())
422        }
423        _ => bad(),
424    }
425}
426
427/// The shape of an argument's `extent` (`E_SCHEMA`): an array of strings, or `{"hi", "lo"}`
428/// with string ends.
429fn extent_shape(v: &Value, path: &str) -> Result<()> {
430    match v {
431        Value::Array(items) => {
432            if !items.iter().all(|i| matches!(i, Value::String(_))) {
433                return err(ErrorCode::Schema, path, "an extent array holds lexical values as strings");
434            }
435            Ok(())
436        }
437        Value::Object(m) => {
438            schema::exact(m, &["hi", "lo"], &[], path, ErrorCode::Schema)?;
439            schema::string(m, "hi", path)?;
440            schema::string(m, "lo", path)?;
441            Ok(())
442        }
443        _ => err(ErrorCode::Schema, path, "an extent is an array of values or a range {\"hi\", \"lo\"}"),
444    }
445}
446
447/// The structure of a descriptor (`E_SCHEMA`), over the whole descriptor; with `extended`,
448/// the members of `spec-0.4.0` (`signature.order`, argument `extent`) are allowed.
449pub(crate) fn descriptor_structure(v: &Value, extended: bool) -> Result<()> {
450    let new_sig: &[&str] = if extended { &["order"] } else { &[] };
451    let new_arg: &[&str] =
452        if extended { &["extent", "unit", "classes", "default", "key_normalisation"] } else { &["unit"] };
453    let new_ret: &[&str] = if extended { &["unit", "classes"] } else { &["unit"] };
454    let m = schema::object(v, "$")?;
455    schema::exact(m, &["code", "inputs", "signature"], &[], "$", ErrorCode::Schema)?;
456    let code = schema::object(schema::get(m, "code"), "$.code")?;
457    schema::exact(code, &["body", "lang"], &[], "$.code", ErrorCode::Schema)?;
458    schema::string(code, "body", "$.code")?;
459    schema::string(code, "lang", "$.code")?;
460    match schema::get(m, "inputs") {
461        Value::Array(items) if items.iter().all(|i| matches!(i, Value::String(_))) => {}
462        _ => return err(ErrorCode::Schema, "$.inputs", "inputs must be an array of strings"),
463    }
464    let sig = schema::object(schema::get(m, "signature"), "$.signature")?;
465    schema::exact(sig, &["args", "returns"], new_sig, "$.signature", ErrorCode::Schema)?;
466    let args = schema::object(schema::get(sig, "args"), "$.signature.args")?;
467    for (k, d) in jcs_sorted(args) {
468        let p = member("$.signature.args", k);
469        let dm = schema::object(d, &p)?;
470        schema::exact(dm, &["type", "valid"], new_arg, &p, ErrorCode::Schema)?;
471        if let Some(e) = schema::opt(dm, "extent") {
472            extent_shape(e, &member(&p, "extent"))?;
473        }
474        if let Some(c) = schema::opt(dm, "classes") {
475            names_shape(c, &member(&p, "classes"))?;
476        }
477        if let Some(d) = schema::opt(dm, "default") {
478            match d.as_str() {
479                None => {
480                    return err(
481                        ErrorCode::Schema,
482                        &member(&p, "default"),
483                        "a default is a string: asof, or a lexical value",
484                    )
485                }
486                // K13: a literal default is a lexical value of the argument's type, E_SCHEMA over the whole
487                // descriptor first (7). An unknown type is found by the canonical form, as before.
488                Some(text) if text != "asof" => {
489                    if let Some(t) = schema::opt(dm, "type").and_then(Value::as_str).and_then(Type::from_name) {
490                        Scalar::from_lexical(t, text).map_err(|_| {
491                            Error::new(ErrorCode::Schema, member(&p, "default"), "a default is a value of the type")
492                        })?;
493                    }
494                }
495                Some(_) => {}
496            }
497        }
498        if let Some(k) = schema::opt(dm, "key_normalisation") {
499            match k.as_str().and_then(KeyNormalisation::from_name) {
500                Some(r) if r != KeyNormalisation::NoRule => {}
501                _ => {
502                    return err(
503                        ErrorCode::Schema,
504                        &member(&p, "key_normalisation"),
505                        "a rule of 16.4 other than none (an absent member means none)",
506                    )
507                }
508            }
509        }
510        schema::string(dm, "type", &p)?;
511        if !matches!(schema::get(dm, "valid"), Value::Bool(_)) {
512            return err(ErrorCode::Schema, &member(&p, "valid"), "valid must be a boolean");
513        }
514        if let Some(u) = schema::opt(dm, "unit") {
515            unit_shape(u, &member(&p, "unit"))?;
516        }
517    }
518    if let Some(o) = schema::opt(sig, "order") {
519        if !matches!(o, Value::Array(items) if items.iter().all(|i| matches!(i, Value::String(_)))) {
520            return err(ErrorCode::Schema, "$.signature.order", "order is an array of argument names");
521        }
522    }
523    let rp = "$.signature.returns";
524    match schema::get(sig, "returns") {
525        Value::String(_) => {}
526        Value::Object(rm) => {
527            schema::exact(rm, &["type"], new_ret, rp, ErrorCode::Schema)?;
528            schema::string(rm, "type", rp)?;
529            if let Some(c) = schema::opt(rm, "classes") {
530                names_shape(c, &member(rp, "classes"))?;
531            }
532            if let Some(u) = schema::opt(rm, "unit") {
533                unit_shape(u, &member(rp, "unit"))?;
534            }
535        }
536        _ => return err(ErrorCode::Schema, rp, "returns must be a type name or an object"),
537    }
538    Ok(())
539}
540
541/// The shape of a `classes` member (`E_SCHEMA`): an array of strings.
542fn names_shape(v: &Value, path: &str) -> Result<()> {
543    match v {
544        Value::Array(items) if items.iter().all(|i| matches!(i, Value::String(_))) => Ok(()),
545        _ => err(ErrorCode::Schema, path, "classes is an array of class names"),
546    }
547}
548
549/// The class names of a structurally valid `classes` member (16): each a full name
550/// (`E_CANON_NAME`), then ascending and unique, at least one (`E_CANON_SET`).
551fn class_names(v: &Value, path: &str) -> Result<Vec<String>> {
552    let names: Vec<&str> = match v {
553        Value::Array(items) => items.iter().filter_map(Value::as_str).collect(),
554        _ => Vec::new(),
555    };
556    for (i, n) in names.iter().enumerate() {
557        lexical::check_function_name(n, &index(path, i))?;
558    }
559    if names.is_empty() || names.windows(2).any(|w| w[0] >= w[1]) {
560        return err(ErrorCode::CanonSet, path, "classes is a non-empty array, ascending and unique");
561    }
562    Ok(names.iter().map(|n| n.to_string()).collect())
563}
564
565fn unit_arg_ref(name: &str, args: &[(String, Value)], path: &str) -> Result<()> {
566    let is_string = schema::opt(args, name)
567        .and_then(Value::as_object)
568        .map(|d| schema::get(d, "type").as_str() == Some("string"))
569        .unwrap_or(false);
570    if !is_string {
571        return err(ErrorCode::CanonUnit, path, format!("a unit names a string argument of the signature: {name:?}"));
572    }
573    Ok(())
574}
575
576fn side_value(v: &Value) -> RateSide {
577    match v {
578        Value::String(s) => RateSide::Currency(s.clone()),
579        other => RateSide::Arg(other.get("arg").and_then(Value::as_str).unwrap_or("").into()),
580    }
581}
582
583/// Whether `v` is the resolved form `<of>/<per>` of a rate (`units.md` 3, `spec-0.6.2`): exactly
584/// one `/`, a currency code before it, and a currency code or `shares` after it.
585fn is_rate_form(v: &str) -> bool {
586    match v.split_once('/') {
587        Some((of, per)) => lexical::is_currency(of) && (per == lexical::SHARES || lexical::is_currency(per)),
588        None => false,
589    }
590}
591
592/// Checks a structurally valid unit against 7.1 and returns it.
593pub(crate) fn unit_canonical(v: &Value, args: &[(String, Value)], path: &str) -> Result<Unit> {
594    match v {
595        Value::String(s) => {
596            if !lexical::is_literal_unit(s) {
597                return err(ErrorCode::CanonUnit, path, format!("not a unit listed in units.md: {s:?}"));
598            }
599            Ok(Unit::Literal(s.clone()))
600        }
601        Value::Object(m) if m.len() == 1 => {
602            let name = schema::get(m, "arg").as_str().unwrap_or("");
603            unit_arg_ref(name, args, path)?;
604            Ok(Unit::Arg(name.into()))
605        }
606        Value::Object(m) => {
607            for side in ["of", "per"] {
608                let sp = member(path, side);
609                match schema::get(m, side) {
610                    Value::String(s) => {
611                        // The per side may be shares (spec-0.6.2); the of side is a currency code.
612                        let ok = lexical::is_currency(s) || (side == "per" && s == lexical::SHARES);
613                        if !ok {
614                            return err(ErrorCode::CanonUnit, &sp, format!("a rate side is a currency code: {s:?}"));
615                        }
616                    }
617                    other => unit_arg_ref(other.get("arg").and_then(Value::as_str).unwrap_or(""), args, &sp)?,
618                }
619            }
620            Ok(Unit::Rate { of: side_value(schema::get(m, "of")), per: side_value(schema::get(m, "per")) })
621        }
622        _ => err(ErrorCode::Schema, path, "not a unit"),
623    }
624}
625
626/// Compares two lexical values of `ty` in the type's order (7): numbers numerically, dates
627/// and instants chronologically (their canonical text order), strings by code point (UTF-8
628/// byte order), `false` before `true`.
629pub(crate) fn cmp_lexical(ty: Type, a: &str, b: &str) -> core::cmp::Ordering {
630    match ty {
631        Type::Number => lexical::cmp_numbers(a, b),
632        Type::Boolean => (a == "true").cmp(&(b == "true")),
633        _ => a.cmp(b),
634    }
635}
636
637/// The canonical form of a structurally valid `extent` of an argument of type `ty` (7):
638/// the type, then each value's lexical form, their order, their count; for a range, `hi`
639/// then `lo` (lexical form, integer for numbers), then `lo <= hi`.
640fn extent_canonical(v: &Value, ty: Type, path: &str) -> Result<Extent> {
641    if matches!(ty, Type::Boolean | Type::Blob) {
642        return err(ErrorCode::CanonType, path, format!("a {} argument has no extent", ty.as_str()));
643    }
644    match v {
645        Value::Array(items) => {
646            let values: Vec<&str> = items.iter().filter_map(Value::as_str).collect();
647            for (i, x) in values.iter().enumerate() {
648                model::check_lexical(ty, x, &index(path, i))?;
649            }
650            if values.windows(2).any(|w| cmp_lexical(ty, w[0], w[1]) != core::cmp::Ordering::Less) {
651                return err(ErrorCode::CanonSet, path, "extent values are strictly ascending in their type's order");
652            }
653            if values.len() > limits::EXTENT {
654                return err(ErrorCode::CanonLimit, path, "more than 4096 extent values");
655            }
656            Ok(Extent::Values(values.iter().map(|x| x.to_string()).collect()))
657        }
658        Value::Object(m) => {
659            if !matches!(ty, Type::Date | Type::Number) {
660                return err(ErrorCode::CanonType, path, "an extent range is for date and number arguments");
661            }
662            for side in ["hi", "lo"] {
663                let sp = member(path, side);
664                let x = schema::string(m, side, path)?;
665                model::check_lexical(ty, x, &sp)?;
666                if ty == Type::Number && !lexical::is_integer(x) {
667                    return err(ErrorCode::CanonNumber, &sp, "an extent range over numbers has integer ends");
668                }
669            }
670            let (lo, hi) = (schema::string(m, "lo", path)?, schema::string(m, "hi", path)?);
671            if cmp_lexical(ty, lo, hi) == core::cmp::Ordering::Greater {
672                return err(ErrorCode::CanonSet, path, "an extent range has lo <= hi");
673            }
674            Ok(Extent::Range { lo: lo.into(), hi: hi.into() })
675        }
676        _ => err(ErrorCode::Schema, path, "not an extent"),
677    }
678}
679
680pub(crate) fn descriptor_canonical(v: &Value) -> Result<FunctionDescriptor> {
681    let m = schema::object(v, "$")?;
682    let code = schema::object(schema::get(m, "code"), "$.code")?;
683    let body = schema::string(code, "body", "$.code")?;
684    lexical::check_text(body, limits::BODY, true, "$.code.body")?;
685    let lang = schema::string(code, "lang", "$.code")?;
686    lexical::check_name(lang, "$.code.lang")?;
687
688    let items: Vec<&str> = match schema::get(m, "inputs") {
689        Value::Array(items) => items.iter().filter_map(Value::as_str).collect(),
690        _ => Vec::new(),
691    };
692    for (i, s) in items.iter().enumerate() {
693        lexical::check_function_name(s, &index("$.inputs", i))?;
694    }
695    if items.windows(2).any(|w| w[0] >= w[1]) {
696        return err(ErrorCode::CanonSet, "$.inputs", "entries must be strictly ascending");
697    }
698    if items.len() > limits::INPUTS {
699        return err(ErrorCode::CanonLimit, "$.inputs", "more than 4096 inputs");
700    }
701
702    let sig = schema::object(schema::get(m, "signature"), "$.signature")?;
703    let args = schema::object(schema::get(sig, "args"), "$.signature.args")?;
704    if args.len() > limits::ARGS {
705        return err(ErrorCode::CanonLimit, "$.signature.args", "more than 32 arguments");
706    }
707    let mut decls = BTreeMap::new();
708    let mut extents = BTreeMap::new();
709    let mut arg_extras = BTreeMap::new();
710    for (k, d) in jcs_sorted(args) {
711        let p = member("$.signature.args", k);
712        lexical::check_arg_name(k, &p)?;
713        let dm = schema::object(d, &p)?;
714        let ty = Type::parse(schema::string(dm, "type", &p)?, &member(&p, "type"))?;
715        let unit = match (ty, schema::opt(dm, "unit")) {
716            (Type::Number, None) => return err(ErrorCode::CanonUnit, &p, "a number argument declares its unit"),
717            (Type::Number, Some(u)) => Some(unit_canonical(u, args, &member(&p, "unit"))?),
718            (_, Some(_)) => return err(ErrorCode::CanonUnit, &member(&p, "unit"), "only number arguments have a unit"),
719            (_, None) => None,
720        };
721        let valid = matches!(schema::get(dm, "valid"), Value::Bool(true));
722        if valid && !ty.may_be_valid_time() {
723            return err(ErrorCode::CanonType, &p, "a valid-time argument must be a date, instant or string");
724        }
725        let mut extras = ArgExtras::default();
726        if let Some(c) = schema::opt(dm, "classes") {
727            if ty != Type::String {
728                return err(ErrorCode::CanonType, &member(&p, "classes"), "classes is on a string argument");
729            }
730            extras.classes = Some(class_names(c, &member(&p, "classes"))?);
731        }
732        if let Some(d) = schema::opt(dm, "default") {
733            let text = d.as_str().unwrap_or("");
734            if text == "asof" {
735                if !valid || !matches!(ty, Type::Date | Type::Instant) {
736                    return err(
737                        ErrorCode::CanonType,
738                        &member(&p, "default"),
739                        "default asof is on a valid-time date or instant",
740                    );
741                }
742                extras.default_asof = true;
743            } else {
744                // K13: a literal is a lexical value of the argument's type (3.1 to 3.4), else E_SCHEMA.
745                Scalar::from_lexical(ty, text).map_err(|e| {
746                    Error::new(
747                        ErrorCode::Schema,
748                        member(&p, "default"),
749                        format!("not a value of the type: {}", e.detail()),
750                    )
751                })?;
752                extras.default_literal = Some(text.into());
753            }
754        }
755        if let Some(k) = schema::opt(dm, "key_normalisation") {
756            if ty != Type::String || extras.classes.is_some() {
757                return err(
758                    ErrorCode::CanonType,
759                    &member(&p, "key_normalisation"),
760                    "key_normalisation is on a string argument without classes",
761                );
762            }
763            extras.key_normalisation = k.as_str().and_then(KeyNormalisation::from_name);
764        }
765        if extras != ArgExtras::default() {
766            arg_extras.insert(k.clone(), extras);
767        }
768        if let Some(e) = schema::opt(dm, "extent") {
769            extents.insert(k.clone(), extent_canonical(e, ty, &member(&p, "extent"))?);
770        }
771        decls.insert(k.clone(), ArgDecl { ty, unit, valid });
772    }
773    let order = match schema::opt(sig, "order") {
774        Some(Value::Array(items)) => {
775            let names: Vec<&str> = items.iter().filter_map(Value::as_str).collect();
776            let mut sorted = names.clone();
777            sorted.sort_unstable();
778            sorted.dedup();
779            if sorted.len() != names.len()
780                || names.len() != decls.len()
781                || !names.iter().all(|n| decls.contains_key(*n))
782            {
783                return err(ErrorCode::CanonSet, "$.signature.order", "order lists every argument exactly once");
784            }
785            Some(names.iter().map(|n| n.to_string()).collect())
786        }
787        _ => None,
788    };
789
790    let rp = "$.signature.returns";
791    let mut returns_classes = None;
792    if let Value::Object(rm) = schema::get(sig, "returns") {
793        if let Some(c) = schema::opt(rm, "classes") {
794            if Type::parse(schema::string(rm, "type", rp)?, &member(rp, "type"))? != Type::String {
795                return err(ErrorCode::CanonType, rp, "a returned key is a string");
796            }
797            if schema::opt(rm, "unit").is_some() {
798                return err(ErrorCode::CanonUnit, rp, "a returned key has no unit");
799            }
800            returns_classes = Some(class_names(c, &member(rp, "classes"))?);
801        }
802    }
803    let returns = match schema::get(sig, "returns") {
804        Value::Object(_) if returns_classes.is_some() => Returns { ty: Type::String, unit: None },
805        Value::String(name) => {
806            let ty = Type::parse(name, rp)?;
807            if ty == Type::Number {
808                return err(
809                    ErrorCode::CanonUnit,
810                    rp,
811                    "a number return is written {\"type\": \"number\", \"unit\": ...}",
812                );
813            }
814            Returns { ty, unit: None }
815        }
816        Value::Object(rm) => {
817            let ty = Type::parse(schema::string(rm, "type", rp)?, &member(rp, "type"))?;
818            if ty != Type::Number {
819                return err(ErrorCode::CanonUnit, rp, "only a number return is written as an object");
820            }
821            let Some(u) = schema::opt(rm, "unit") else {
822                return err(ErrorCode::CanonUnit, rp, "a number return declares its unit");
823            };
824            Returns { ty, unit: Some(unit_canonical(u, args, &member(rp, "unit"))?) }
825        }
826        _ => return err(ErrorCode::Schema, rp, "returns must be a type name or an object"),
827    };
828    Ok(FunctionDescriptor {
829        lang: lang.into(),
830        body: body.into(),
831        inputs: items.iter().map(|s| s.to_string()).collect(),
832        signature: Signature { args: decls, returns },
833        order,
834        extents,
835        arg_extras,
836        returns_classes,
837    })
838}
839
840/// The unit of a cell's value (7.1, `units.md` 3), from the descriptor and cell JSON texts.
841///
842/// Checks, in order: the cell (structure, canonical form; slices allowed), that the
843/// descriptor hashes to `cell.fn_hash` (`E_FN_HASH_MISMATCH`), the descriptor, then
844/// substitution. Returns `None` when the function does not return a number.
845pub fn resolved_unit(descriptor: &[u8], cell: &[u8]) -> Result<Option<String>> {
846    let cell_v = json::parse(cell)?;
847    let desc_v = json::parse(descriptor)?;
848    resolved_unit_value(&desc_v, &cell_v)
849}
850
851/// [`resolved_unit`] over parsed JSON values.
852pub fn resolved_unit_value(descriptor: &Value, cell: &Value) -> Result<Option<String>> {
853    json::check_value_depth(descriptor)?;
854    json::check_value_depth(cell)?;
855    let cell = Cell::from_value(cell)?;
856    let hash = crate::crypto::sha256_hex(&descriptor.to_jcs());
857    if hash != cell.fn_hash {
858        return err(ErrorCode::FnHashMismatch, "$.descriptor", "the descriptor does not hash to cell.fn_hash");
859    }
860    let d = FunctionDescriptor::from_value(descriptor)?;
861    d.resolve_unit(&cell)
862}
863
864/// Substitutes a checked cell's arguments into a checked descriptor's return unit.
865pub fn resolve_with(d: &Descriptor, cell: &Cell) -> Result<Option<String>> {
866    resolve_returns(&d.signature.returns, cell)
867}
868
869fn resolve_returns(returns: &Returns, cell: &Cell) -> Result<Option<String>> {
870    let Some(unit) = &returns.unit else { return Ok(None) };
871    let arg_value = |name: &str| -> Result<String> {
872        let p = member("$.cell.args", name);
873        match cell.args.get(name) {
874            None => err(
875                ErrorCode::ArgMissing,
876                &p,
877                format!("the unit refers to argument {name:?}, which the cell does not bind"),
878            ),
879            Some(Arg::Slice) => err(ErrorCode::Slice, &p, "a slice has no single unit"),
880            Some(Arg::Value(Scalar::String(s))) => Ok(s.clone()),
881            Some(Arg::Value(other)) => {
882                err(ErrorCode::ArgType, &p, format!("bound as {}, not string", other.ty().as_str()))
883            }
884        }
885    };
886    // A rate side: a currency code, and on the per side also `shares` (spec-0.6.2).
887    let side = |s: &RateSide, per: bool| -> Result<String> {
888        match s {
889            RateSide::Currency(c) => Ok(c.clone()),
890            RateSide::Arg(n) => {
891                let v = arg_value(n)?;
892                let ok = lexical::is_currency(&v) || (per && v == lexical::SHARES);
893                if !ok {
894                    return err(
895                        ErrorCode::CanonUnit,
896                        &member("$.cell.args", n),
897                        format!("a rate side must be a currency code{}: {v:?}", if per { " or shares" } else { "" }),
898                    );
899                }
900                Ok(v)
901            }
902        }
903    };
904    Ok(Some(match unit {
905        Unit::Literal(s) => s.clone(),
906        Unit::Arg(n) => {
907            // A listed literal (even one with a slash, such as m/s) is taken whole; otherwise
908            // the value is a rate's resolved form, split once at its single slash (spec-0.6.2).
909            let v = arg_value(n)?;
910            if !lexical::is_literal_unit(&v) && !is_rate_form(&v) {
911                return err(ErrorCode::CanonUnit, &member("$.cell.args", n), format!("not a unit: {v:?}"));
912            }
913            v
914        }
915        Unit::Rate { of, per } => {
916            let o = side(of, false)?;
917            let p = side(per, true)?;
918            format!("{o}/{p}")
919        }
920    }))
921}