Skip to main content

datumesh_core/
class.rs

1//! Classes (16, `spec-0.5.0`): the class descriptor and its check (16.1), define with
2//! flattening (16.2), and the class hash.
3//!
4//! A class is a third hashed object next to the function descriptor and the receipt. Define is
5//! a pure function of the descriptor as written and of what the definer knows ([`ClassEnv`]):
6//! the descriptors of the method functions, and the flattened descriptors of known classes.
7
8use std::collections::{BTreeMap, BTreeSet};
9
10use crate::descriptor::{self, ArgDecl, FunctionDescriptor, Returns, Unit};
11use crate::error::{err, ErrorCode, Result};
12use crate::json::{self, jcs_sorted, Value};
13use crate::lexical;
14use crate::model::Type;
15use crate::normalisation::KeyNormalisation;
16use crate::schema;
17
18/// The declaration of one class key (16.1).
19#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum ClassKey {
22    /// `{"type", ...}`: a scalar key. The type is any of section 3 but `blob`; `unit` is present
23    /// exactly for a `number`, `key_normalisation` exactly for a `string` (and then it is
24    /// written even when it is `none`).
25    Scalar {
26        /// The key's type.
27        ty: Type,
28        /// The unit of a `number` key (7.1).
29        unit: Option<Unit>,
30        /// The rule of a `string` key.
31        key_normalisation: Option<KeyNormalisation>,
32    },
33    /// `{"class": <full class name>}`: a class-typed key, whose value is the key encoding of an
34    /// object of that class (16.5).
35    Class(String),
36}
37
38/// The steward of a class (16.1): the namespace that keeps it and its change process.
39#[derive(Clone, Debug, PartialEq, Eq)]
40#[non_exhaustive]
41pub struct Steward {
42    /// The namespace (2.3).
43    pub namespace: String,
44    /// An `https` URL by the licence URL rule of 8.1.
45    pub process: String,
46}
47
48/// The `extent` functions of a class (16.1): function hashes, each optional, at least one.
49#[derive(Clone, Debug, Default, PartialEq, Eq)]
50#[non_exhaustive]
51pub struct ClassExtent {
52    /// `exists`: whether an object exists.
53    pub exists: Option<String>,
54    /// `keys`: a stored function whose recorded cells are the class's objects.
55    pub keys: Option<String>,
56}
57
58/// A class descriptor (16.1): as an author writes it ([`ClassDescriptor::from_json`], which
59/// checks it) or flattened ([`define_class`]); the flattened descriptor is the class
60/// descriptor, and its [`hash`](ClassDescriptor::hash) the class hash.
61///
62/// Optional members are absent rather than empty: an empty `Vec` here means the member is
63/// absent, and `false` for `is_final`.
64#[derive(Clone, Debug, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct ClassDescriptor {
67    /// `keys`: the key declarations by name (at most 32).
68    pub keys: BTreeMap<String, ClassKey>,
69    /// `order`: every key name exactly once.
70    pub order: Vec<String>,
71    /// `methods`: method name to function hash.
72    pub methods: BTreeMap<String, String>,
73    /// `steward`.
74    pub steward: Steward,
75    /// `parent`: the class hash of the parent class.
76    pub parent: Option<String>,
77    /// `final`: `true` when written (`"final": true`).
78    pub is_final: bool,
79    /// `open`: method names overridable in a subclass of a final class; ascending, unique.
80    pub open: Vec<String>,
81    /// `maps`: ontology URIs; ascending, unique.
82    pub maps: Vec<String>,
83    /// `inverse`: attribute names, each with a method `by_<attribute>`; ascending, unique.
84    pub inverse: Vec<String>,
85    /// `lookup`: the name of the lookup method (D93).
86    pub lookup: Option<String>,
87    /// `extent`.
88    pub extent: Option<ClassExtent>,
89    /// `implements`: class hashes of interfaces; ascending, unique.
90    pub implements: Vec<String>,
91}
92
93impl ClassDescriptor {
94    /// Parses and checks a class descriptor given as JSON text: strict JSON, then 16.1 in its
95    /// check order, for what the descriptor alone decides. The structure over the whole
96    /// descriptor first (`E_SCHEMA`: a missing required member, an unknown member, an empty
97    /// array, an empty `extent`, `final` other than `true`), then `keys` (the count, then each
98    /// key in JCS order of names: its name, then its declaration), `order`, `methods` (in JCS
99    /// order of names), `steward`, `parent`, `open`, `maps`, `inverse`, `lookup`, `extent`,
100    /// `implements`, with the codes of 16.1.
101    ///
102    /// Checks that need the method functions (that a lookup method takes one `label`, that an
103    /// extent function has the right signature) are [`define_class`]'s. A flattened descriptor
104    /// (one with `parent`) passes as well: this is the check define makes at steps 2 and 5.
105    pub fn from_json(bytes: &[u8]) -> Result<ClassDescriptor> {
106        ClassDescriptor::from_value(&json::parse(bytes)?)
107    }
108
109    /// As [`from_json`](Self::from_json), for a parsed value.
110    pub fn from_value(v: &Value) -> Result<ClassDescriptor> {
111        json::check_value_depth(v)?;
112        class_structure(v)?;
113        class_canonical(v)
114    }
115
116    /// The JSON form (members absent when empty).
117    pub fn to_value(&self) -> Value {
118        let keys = self
119            .keys
120            .iter()
121            .map(|(name, key)| {
122                let decl = match key {
123                    ClassKey::Class(c) => Value::Object(vec![("class".into(), Value::String(c.clone()))]),
124                    ClassKey::Scalar { ty, unit, key_normalisation } => {
125                        let mut m = vec![("type".to_string(), Value::String(ty.as_str().into()))];
126                        if let Some(u) = unit {
127                            m.push(("unit".into(), u.to_value()));
128                        }
129                        if let Some(r) = key_normalisation {
130                            m.push(("key_normalisation".into(), Value::String(r.as_str().into())));
131                        }
132                        Value::Object(m)
133                    }
134                };
135                (name.clone(), decl)
136            })
137            .collect();
138        let strings = |v: &[String]| Value::Array(v.iter().map(|s| Value::String(s.clone())).collect());
139        let mut m: Vec<(String, Value)> = vec![
140            ("keys".into(), Value::Object(keys)),
141            ("order".into(), strings(&self.order)),
142            (
143                "methods".into(),
144                Value::Object(self.methods.iter().map(|(k, h)| (k.clone(), Value::String(h.clone()))).collect()),
145            ),
146            (
147                "steward".into(),
148                Value::Object(vec![
149                    ("namespace".into(), Value::String(self.steward.namespace.clone())),
150                    ("process".into(), Value::String(self.steward.process.clone())),
151                ]),
152            ),
153        ];
154        if let Some(p) = &self.parent {
155            m.push(("parent".into(), Value::String(p.clone())));
156        }
157        if self.is_final {
158            m.push(("final".into(), Value::Bool(true)));
159        }
160        if !self.open.is_empty() {
161            m.push(("open".into(), strings(&self.open)));
162        }
163        if !self.maps.is_empty() {
164            m.push(("maps".into(), strings(&self.maps)));
165        }
166        if !self.inverse.is_empty() {
167            m.push(("inverse".into(), strings(&self.inverse)));
168        }
169        if let Some(l) = &self.lookup {
170            m.push(("lookup".into(), Value::String(l.clone())));
171        }
172        if let Some(e) = &self.extent {
173            let mut em = Vec::new();
174            if let Some(x) = &e.exists {
175                em.push(("exists".to_string(), Value::String(x.clone())));
176            }
177            if let Some(x) = &e.keys {
178                em.push(("keys".to_string(), Value::String(x.clone())));
179            }
180            m.push(("extent".into(), Value::Object(em)));
181        }
182        if !self.implements.is_empty() {
183            m.push(("implements".into(), strings(&self.implements)));
184        }
185        Value::Object(m)
186    }
187
188    /// The canonical bytes (6.2). Of a flattened descriptor, they are what the class hash
189    /// hashes.
190    pub fn canonical(&self) -> Vec<u8> {
191        self.to_value().to_jcs()
192    }
193
194    /// The class hash: SHA-256 of the canonical bytes, lowercase hex. The class name is not
195    /// part of it. Meant for a flattened descriptor ([`define_class`]'s result, or one read
196    /// back with [`from_json`](Self::from_json)).
197    pub fn hash(&self) -> String {
198        crate::crypto::sha256_hex(&self.canonical())
199    }
200}
201
202/// At most 32 keys in a class (16.1).
203const MAX_KEYS: usize = 32;
204
205/// The members a class descriptor may have (16.1); the first four are required.
206const CLASS_REQUIRED: &[&str] = &["keys", "order", "methods", "steward"];
207const CLASS_OPTIONAL: &[&str] = &["parent", "final", "open", "maps", "inverse", "lookup", "extent", "implements"];
208
209/// The structure of a class descriptor over the whole descriptor (`E_SCHEMA`).
210fn class_structure(v: &Value) -> Result<()> {
211    let m = schema::object(v, "$")?;
212    schema::exact(m, CLASS_REQUIRED, CLASS_OPTIONAL, "$", ErrorCode::Schema)?;
213    let keys = schema::object(schema::get(m, "keys"), "$.keys")?;
214    for (k, d) in keys {
215        let p = format!("$.keys.{k}");
216        let dm = schema::object(d, &p)?;
217        if schema::opt(dm, "class").is_some() {
218            schema::exact(dm, &["class"], &[], &p, ErrorCode::Schema)?;
219            schema::string(dm, "class", &p)?;
220        } else {
221            schema::exact(dm, &["type"], &["unit", "key_normalisation"], &p, ErrorCode::Schema)?;
222            schema::string(dm, "type", &p)?;
223            if let Some(u) = schema::opt(dm, "unit") {
224                descriptor::unit_shape(u, &format!("{p}.unit"))?;
225            }
226            if schema::opt(dm, "key_normalisation").is_some() {
227                schema::string(dm, "key_normalisation", &p)?;
228            }
229        }
230    }
231    string_array(schema::get(m, "order"), "$.order")?;
232    let methods = schema::object(schema::get(m, "methods"), "$.methods")?;
233    for (k, h) in methods {
234        if !matches!(h, Value::String(_)) {
235            return err(ErrorCode::Schema, &format!("$.methods.{k}"), "a method is a function hash");
236        }
237    }
238    let st = schema::object(schema::get(m, "steward"), "$.steward")?;
239    schema::exact(st, &["namespace", "process"], &[], "$.steward", ErrorCode::Schema)?;
240    schema::string(st, "namespace", "$.steward")?;
241    schema::string(st, "process", "$.steward")?;
242    if let Some(p) = schema::opt(m, "parent") {
243        if !matches!(p, Value::String(_)) {
244            return err(ErrorCode::Schema, "$.parent", "parent is a class hash");
245        }
246    }
247    if let Some(f) = schema::opt(m, "final") {
248        if !matches!(f, Value::Bool(true)) {
249            return err(ErrorCode::Schema, "$.final", "final is true when written");
250        }
251    }
252    for name in ["open", "maps", "inverse", "implements"] {
253        if let Some(a) = schema::opt(m, name) {
254            let items = string_array(a, &format!("$.{name}"))?;
255            if items.is_empty() {
256                return err(ErrorCode::Schema, &format!("$.{name}"), "an optional member is absent, not empty");
257            }
258        }
259    }
260    if let Some(l) = schema::opt(m, "lookup") {
261        if !matches!(l, Value::String(_)) {
262            return err(ErrorCode::Schema, "$.lookup", "lookup is a method name");
263        }
264    }
265    if let Some(e) = schema::opt(m, "extent") {
266        let em = schema::object(e, "$.extent")?;
267        if em.is_empty() {
268            return err(ErrorCode::Schema, "$.extent", "an optional member is absent, not empty");
269        }
270        schema::exact(em, &[], &["exists", "keys"], "$.extent", ErrorCode::Schema)?;
271        for (k, x) in em {
272            if !matches!(x, Value::String(_)) {
273                return err(ErrorCode::Schema, &format!("$.extent.{k}"), "an extent function is a hash");
274            }
275        }
276    }
277    Ok(())
278}
279
280/// An array of strings, or `E_SCHEMA`; an absent array is empty.
281fn string_array<'a>(v: &'a Value, path: &str) -> Result<Vec<&'a str>> {
282    match v {
283        Value::Array(items) => items
284            .iter()
285            .map(|i| match i {
286                Value::String(s) => Ok(s.as_str()),
287                _ => err(ErrorCode::Schema, path, "an array of strings"),
288            })
289            .collect(),
290        _ => err(ErrorCode::Schema, path, "an array of strings"),
291    }
292}
293
294/// Strictly ascending and unique (`E_CANON_SET`).
295fn ascending_unique(items: &[&str], path: &str) -> Result<()> {
296    if items.windows(2).any(|w| w[0] >= w[1]) {
297        return err(ErrorCode::CanonSet, path, "entries are strictly ascending");
298    }
299    Ok(())
300}
301
302/// A URL by the licence URL rule of 8.1: `https://` then printable ASCII, at most 512
303/// characters in all.
304fn https_url(s: &str) -> bool {
305    s.len() <= 512
306        && s.strip_prefix("https://").is_some_and(|rest| !rest.is_empty())
307        && s.bytes().all(|c| (0x21..=0x7E).contains(&c))
308}
309
310/// A URI (9.6 style for `maps`): a scheme, `:`, then printable ASCII, at most 512 characters.
311fn uri(s: &str) -> bool {
312    let Some((scheme, rest)) = s.split_once(':') else { return false };
313    let mut sb = scheme.bytes();
314    let scheme_ok = matches!(sb.next(), Some(c) if c.is_ascii_alphabetic())
315        && sb.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'+' | b'-' | b'.'));
316    scheme_ok && !rest.is_empty() && s.len() <= 512 && s.bytes().all(|c| (0x21..=0x7E).contains(&c))
317}
318
319/// The canonical form of a structurally valid class descriptor, in the order of 16.1.
320fn class_canonical(v: &Value) -> Result<ClassDescriptor> {
321    let m = schema::object(v, "$")?;
322
323    // keys
324    let kobj = schema::object(schema::get(m, "keys"), "$.keys")?;
325    if kobj.len() > MAX_KEYS {
326        return err(ErrorCode::CanonLimit, "$.keys", "more than 32 keys");
327    }
328    let mut keys = BTreeMap::new();
329    for (name, d) in jcs_sorted(kobj) {
330        let p = format!("$.keys.{name}");
331        lexical::check_arg_name(name, &p)?;
332        let dm = schema::object(d, &p)?;
333        let key = if schema::opt(dm, "class").is_some() {
334            let c = schema::string(dm, "class", &p)?;
335            lexical::check_function_name(c, &p)?;
336            ClassKey::Class(c.into())
337        } else {
338            let ty = Type::parse(schema::string(dm, "type", &p)?, &format!("{p}.type"))?;
339            if ty == Type::Blob {
340                return err(ErrorCode::CanonType, &format!("{p}.type"), "a key is never a blob");
341            }
342            let unit = match (ty, schema::opt(dm, "unit")) {
343                (Type::Number, None) => return err(ErrorCode::CanonUnit, &p, "a number key declares its unit"),
344                (Type::Number, Some(u)) => Some(descriptor::unit_canonical(u, &[], &format!("{p}.unit"))?),
345                (_, Some(_)) => return err(ErrorCode::CanonUnit, &format!("{p}.unit"), "only a number key has a unit"),
346                (_, None) => None,
347            };
348            let kn = match (ty == Type::String, schema::opt(dm, "key_normalisation")) {
349                (true, None) => return err(ErrorCode::ClassMember, &p, "a string key declares key_normalisation"),
350                // K8: label_fold is a label's rule; keys stay strict, so a key may not declare it.
351                (true, Some(Value::String(r))) => match KeyNormalisation::from_name(r) {
352                    Some(KeyNormalisation::LabelFold) => {
353                        return err(ErrorCode::ClassMember, &p, "label_fold is a label's rule, not a key's")
354                    }
355                    Some(rule) => Some(rule),
356                    None => return err(ErrorCode::ClassMember, &p, format!("not a rule of 16.4: {r:?}")),
357                },
358                (false, Some(_)) => return err(ErrorCode::ClassMember, &p, "only a string key has key_normalisation"),
359                _ => None,
360            };
361            ClassKey::Scalar { ty, unit, key_normalisation: kn }
362        };
363        keys.insert(name.clone(), key);
364    }
365
366    // order
367    let order: Vec<String> = string_array(schema::get(m, "order"), "$.order")?.iter().map(|s| s.to_string()).collect();
368    let mut seen = BTreeSet::new();
369    if order.len() != keys.len() || !order.iter().all(|n| keys.contains_key(n) && seen.insert(n.as_str())) {
370        return err(ErrorCode::CanonSet, "$.order", "order lists every key exactly once");
371    }
372
373    // methods
374    let mut methods = BTreeMap::new();
375    for (name, h) in jcs_sorted(schema::object(schema::get(m, "methods"), "$.methods")?) {
376        let p = format!("$.methods.{name}");
377        lexical::check_name(name, &p)?;
378        let Value::String(h) = h else { return err(ErrorCode::Schema, &p, "a method is a function hash") };
379        lexical::check_hex(h, 64, &p)?;
380        methods.insert(name.clone(), h.clone());
381    }
382
383    // steward
384    let st = schema::object(schema::get(m, "steward"), "$.steward")?;
385    let namespace = schema::string(st, "namespace", "$.steward")?;
386    lexical::check_namespace(namespace, "$.steward.namespace")?;
387    let process = schema::string(st, "process", "$.steward")?;
388    if !https_url(process) {
389        return err(ErrorCode::ClassMember, "$.steward.process", "the change process is an https URL");
390    }
391    let steward = Steward { namespace: namespace.into(), process: process.into() };
392
393    // parent
394    let parent = match schema::opt(m, "parent") {
395        Some(Value::String(p)) => {
396            lexical::check_hex(p, 64, "$.parent")?;
397            Some(p.clone())
398        }
399        _ => None,
400    };
401    let is_final = matches!(schema::opt(m, "final"), Some(Value::Bool(true)));
402
403    // open: only with final, naming methods of the class
404    let open: Vec<String> = match schema::opt(m, "open") {
405        Some(a) => {
406            let items = string_array(a, "$.open")?;
407            if !is_final {
408                return err(ErrorCode::ClassMember, "$.open", "open is only with final");
409            }
410            ascending_unique(&items, "$.open")?;
411            if items.iter().any(|n| !methods.contains_key(*n)) {
412                return err(ErrorCode::ClassMember, "$.open", "open names methods of the class");
413            }
414            items.iter().map(|s| s.to_string()).collect()
415        }
416        None => Vec::new(),
417    };
418
419    // maps
420    let maps: Vec<String> = match schema::opt(m, "maps") {
421        Some(a) => {
422            let items = string_array(a, "$.maps")?;
423            ascending_unique(&items, "$.maps")?;
424            if items.iter().any(|s| !uri(s)) {
425                return err(ErrorCode::ClassMember, "$.maps", "each map is a URI");
426            }
427            items.iter().map(|s| s.to_string()).collect()
428        }
429        None => Vec::new(),
430    };
431
432    // inverse: each attribute has a method by_<attribute>
433    let inverse: Vec<String> = match schema::opt(m, "inverse") {
434        Some(a) => {
435            let items = string_array(a, "$.inverse")?;
436            ascending_unique(&items, "$.inverse")?;
437            for attr in &items {
438                lexical::check_arg_name(attr, "$.inverse")?;
439                if !methods.contains_key(&format!("by_{attr}")) {
440                    return err(ErrorCode::ClassMember, "$.inverse", format!("no method by_{attr}"));
441                }
442            }
443            items.iter().map(|s| s.to_string()).collect()
444        }
445        None => Vec::new(),
446    };
447
448    // lookup: a method of the class
449    let lookup = match schema::opt(m, "lookup") {
450        Some(Value::String(l)) => {
451            if !methods.contains_key(l) {
452                return err(ErrorCode::ClassMember, "$.lookup", "lookup names a method of the class");
453            }
454            Some(l.clone())
455        }
456        _ => None,
457    };
458
459    // extent
460    let extent = match schema::opt(m, "extent") {
461        Some(e) => {
462            let em = schema::object(e, "$.extent")?;
463            let mut out = ClassExtent::default();
464            for (k, x) in em {
465                let Value::String(x) = x else { return err(ErrorCode::Schema, "$.extent", "a function hash") };
466                lexical::check_hex(x, 64, &format!("$.extent.{k}"))?;
467                match k.as_str() {
468                    "exists" => out.exists = Some(x.clone()),
469                    _ => out.keys = Some(x.clone()),
470                }
471            }
472            Some(out)
473        }
474        None => None,
475    };
476
477    // implements
478    let implements: Vec<String> = match schema::opt(m, "implements") {
479        Some(a) => {
480            let items = string_array(a, "$.implements")?;
481            ascending_unique(&items, "$.implements")?;
482            for h in &items {
483                lexical::check_hex(h, 64, "$.implements")?;
484            }
485            items.iter().map(|s| s.to_string()).collect()
486        }
487        None => Vec::new(),
488    };
489
490    Ok(ClassDescriptor {
491        keys,
492        order,
493        methods,
494        steward,
495        parent,
496        is_final,
497        open,
498        maps,
499        inverse,
500        lookup,
501        extent,
502        implements,
503    })
504}
505
506/// What a definer knows when it defines a class (16.2): who it is, the descriptors of the
507/// method functions, and the flattened descriptors of the classes it knows (parents,
508/// interfaces). Both are looked up by hash.
509#[derive(Clone, Debug, Default)]
510pub struct ClassEnv {
511    definer: String,
512    functions: BTreeMap<String, FunctionDescriptor>,
513    classes: BTreeMap<String, ClassDescriptor>,
514}
515
516impl ClassEnv {
517    /// An environment for `definer`, the namespace defining (a class is defined under it, its own
518    /// namespace or one below: `E_CLASS_OWNER`).
519    pub fn new(definer: &str) -> ClassEnv {
520        ClassEnv { definer: definer.into(), functions: BTreeMap::new(), classes: BTreeMap::new() }
521    }
522
523    /// The definer's namespace.
524    pub fn definer(&self) -> &str {
525        &self.definer
526    }
527
528    /// A function descriptor the definer knows, under its function hash.
529    pub fn insert_function(&mut self, d: FunctionDescriptor) {
530        self.functions.insert(d.hash(), d);
531    }
532
533    /// A flattened class descriptor the definer knows, under its class hash.
534    pub fn insert_class(&mut self, c: ClassDescriptor) {
535        self.classes.insert(c.hash(), c);
536    }
537
538    /// The function descriptor with this hash.
539    pub fn function(&self, hash: &str) -> Option<&FunctionDescriptor> {
540        self.functions.get(hash)
541    }
542
543    /// The flattened class descriptor with this class hash.
544    pub fn class(&self, hash: &str) -> Option<&ClassDescriptor> {
545        self.classes.get(hash)
546    }
547}
548
549/// Defines a class (16.2): checks `descriptor_json`, the descriptor as the author wrote it,
550/// flattens it onto its parent and checks the result. Returns the **flattened descriptor**;
551/// its [`hash`](ClassDescriptor::hash) is the class hash. Checks in this order and reports the
552/// first failure:
553///
554/// 1. `name` is a full name (2.3, `E_CANON_NAME`) under `env.definer()`, its namespace being the
555///    definer's or below it (`E_CLASS_OWNER`);
556/// 2. the descriptor as written ([`ClassDescriptor::from_json`]);
557/// 3. the parent, when there is one: known to `env` (`E_CLASS_PARENT`), no parent key declared
558///    again (`E_CLASS_INHERIT`); then flattening (keys: the parent's then the class's own;
559///    `order`: the parent's then the class's own; `methods`: the parent's overlaid by the
560///    class's own; `implements`: the union; every other member the class's own; `parent`
561///    stays);
562/// 4. overrides (`E_CLASS_FINAL`, then `E_CLASS_OVERRIDE`);
563/// 5. the flattened descriptor, by 16.1;
564/// 6. the methods in JCS order of names (`E_CLASS_METHOD`; the lookup method's own rule is
565///    `E_CLASS_MEMBER`);
566/// 7. `extent` functions (`E_CLASS_MEMBER`);
567/// 8. `implements` (`E_CLASS_INTERFACE`).
568pub fn define_class(name: &str, descriptor_json: &[u8], env: &ClassEnv) -> Result<ClassDescriptor> {
569    // 1. the name, and the owner
570    lexical::check_function_name(name, "$.name")?;
571    // A namespace defines classes under itself: its own namespace or one below it (16.2, as the
572    // reference tools check it since spec-0.5.0; `class/dns-segment-name` since spec-0.6.1).
573    let owner = name.rsplit_once('/').map(|(ns, _)| ns).unwrap_or_default();
574    let definer = env.definer();
575    let under = owner == definer || owner.strip_prefix(definer).is_some_and(|rest| rest.starts_with('/'));
576    if !under {
577        return err(ErrorCode::ClassOwner, "$.name", format!("a namespace defines classes under itself: {name:?}"));
578    }
579    // 2. the descriptor as written
580    let own = ClassDescriptor::from_json(descriptor_json)?;
581    // 3. the parent, and flattening
582    let parent = match &own.parent {
583        None => None,
584        Some(p) => {
585            let parent = env.class(p).ok_or_else(|| {
586                crate::error::Error::new(ErrorCode::ClassParent, "$.parent", "the parent class is not known")
587            })?;
588            if let Some(k) = own.keys.keys().find(|k| parent.keys.contains_key(*k)) {
589                return err(ErrorCode::ClassInherit, &format!("$.keys.{k}"), "a parent key is declared again");
590            }
591            Some(parent)
592        }
593    };
594    let mut flat = own.clone();
595    if let Some(parent) = parent {
596        // 4. overrides, against the parent's methods
597        for (m, h) in &own.methods {
598            let Some(ph) = parent.methods.get(m) else { continue };
599            if ph == h {
600                continue;
601            }
602            if parent.is_final && !parent.open.iter().any(|o| o == m) {
603                return err(ErrorCode::ClassFinal, &format!("$.methods.{m}"), "a final class's method is not open");
604            }
605            if let (Some(new), Some(old)) = (env.function(h), env.function(ph)) {
606                if new.signature != old.signature {
607                    return err(
608                        ErrorCode::ClassOverride,
609                        &format!("$.methods.{m}"),
610                        "an override changes the signature",
611                    );
612                }
613            }
614        }
615        flat.keys = parent.keys.iter().chain(own.keys.iter()).map(|(k, v)| (k.clone(), v.clone())).collect();
616        flat.order = parent.order.iter().chain(own.order.iter()).cloned().collect();
617        flat.methods = parent.methods.iter().chain(own.methods.iter()).map(|(k, v)| (k.clone(), v.clone())).collect();
618        let mut implements: BTreeSet<String> = parent.implements.iter().cloned().collect();
619        implements.extend(own.implements.iter().cloned());
620        flat.implements = implements.into_iter().collect();
621    }
622    // 5. the flattened descriptor is a descriptor
623    let flat = ClassDescriptor::from_value(&flat.to_value())?;
624    // 6. the methods
625    for (m, h) in &flat.methods {
626        let f = env.function(h).ok_or_else(|| {
627            crate::error::Error::new(
628                ErrorCode::ClassMethod,
629                format!("$.methods.{m}"),
630                "the method's function is not known",
631            )
632        })?;
633        let p = format!("$.methods.{m}");
634        if flat.lookup.as_deref() == Some(m.as_str()) {
635            check_lookup(f, name, &p)?;
636            continue;
637        }
638        let n = method_key_count(&flat, parent, m);
639        check_key_arguments(&flat, f, n, &p, ErrorCode::ClassMethod, true)?;
640        if m == "same_as" {
641            match &f.returns_classes {
642                Some(list) if !list.iter().any(|c| c == name) => {}
643                _ => return err(ErrorCode::ClassMethod, &p, "same_as returns a key of another class"),
644            }
645        }
646        if let Some(attr) = m.strip_prefix("by_") {
647            if flat.inverse.iter().any(|a| a == attr) && !returns_key_of(f, name) {
648                return err(ErrorCode::ClassMethod, &p, "an inverse method returns a key of this class");
649            }
650        }
651    }
652    // 7. the extent functions take the class keys
653    if let Some(ext) = &flat.extent {
654        for h in [&ext.exists, &ext.keys].into_iter().flatten() {
655            let f = env.function(h).ok_or_else(|| {
656                crate::error::Error::new(ErrorCode::ClassMember, "$.extent", "the extent function is not known")
657            })?;
658            check_key_arguments(&flat, f, flat.order.len(), "$.extent", ErrorCode::ClassMember, false)?;
659            if Some(h) == ext.exists.as_ref() && f.signature.returns.ty != Type::Boolean {
660                return err(ErrorCode::ClassMember, "$.extent.exists", "exists returns a boolean");
661            }
662        }
663    }
664    // 8. interfaces: keyless classes whose methods the class has, with their signatures
665    for c in &flat.implements {
666        let iface = env.class(c).ok_or_else(|| {
667            crate::error::Error::new(ErrorCode::ClassInterface, "$.implements", "the interface is not known")
668        })?;
669        if !iface.keys.is_empty() {
670            return err(ErrorCode::ClassInterface, "$.implements", "an interface has no keys");
671        }
672        for (m, ih) in &iface.methods {
673            let p = format!("$.implements.{m}");
674            let class_h = flat.methods.get(m).ok_or_else(|| {
675                crate::error::Error::new(ErrorCode::ClassInterface, &p, "the class lacks an interface method")
676            })?;
677            let (Some(cf), Some(ifn)) = (env.function(class_h), env.function(ih)) else {
678                return err(ErrorCode::ClassInterface, &p, "a function is not known");
679            };
680            let n = method_key_count(&flat, parent, m);
681            let rest = remaining_signature(cf, n);
682            if rest != remaining_signature(ifn, 0) {
683                return err(ErrorCode::ClassInterface, &p, "the method's signature differs from the interface's");
684            }
685        }
686    }
687    Ok(flat)
688}
689
690/// The number of leading key arguments a method takes: the parent's keys for a method the
691/// parent declared (overridden or not), all the class's keys otherwise (16.2 step 6).
692fn method_key_count(flat: &ClassDescriptor, parent: Option<&ClassDescriptor>, m: &str) -> usize {
693    match parent {
694        Some(p) if p.methods.contains_key(m) => p.order.len(),
695        _ => flat.order.len(),
696    }
697}
698
699/// The signature of a function once its first `n` arguments (the keys) are taken away: the
700/// remaining order, the remaining declarations and the return.
701fn remaining_signature(f: &FunctionDescriptor, n: usize) -> (Vec<String>, Vec<(String, ArgDecl)>, Returns) {
702    let order = f.order.clone().unwrap_or_default();
703    let rest: Vec<String> = order.iter().skip(n).cloned().collect();
704    let decls = rest.iter().filter_map(|a| f.signature.args.get(a).map(|d| (a.clone(), d.clone()))).collect();
705    (rest, decls, f.signature.returns.clone())
706}
707
708/// Checks that a function takes the first `n` class keys, in class order, with their types,
709/// units and normalisations (16.2 step 6). `code` is the code of a failure.
710///
711/// `normalised` says whether the keys' `key_normalisation` must also match (methods do, 16.2
712/// step 6; an extent function's keys need only their order and types).
713fn check_key_arguments(
714    flat: &ClassDescriptor,
715    f: &FunctionDescriptor,
716    n: usize,
717    path: &str,
718    code: ErrorCode,
719    normalised: bool,
720) -> Result<()> {
721    let Some(order) = &f.order else {
722        return err(code, path, "a method's function has an order");
723    };
724    if order.len() < n {
725        return err(code, path, "a method takes the class keys first");
726    }
727    for (i, name) in flat.order.iter().take(n).enumerate() {
728        let key = &flat.keys[name];
729        if order.get(i) != Some(name) {
730            return err(code, path, format!("key {name:?} is not the first argument in class order"));
731        }
732        let Some(decl) = f.signature.args.get(name) else {
733            return err(code, path, format!("key {name:?} is not an argument"));
734        };
735        let extras = f.arg_extras.get(name).cloned().unwrap_or_default();
736        let ok = match key {
737            ClassKey::Class(c) => decl.ty == Type::String && extras.classes.as_deref() == Some(&[c.clone()][..]),
738            ClassKey::Scalar { ty, unit, key_normalisation } => {
739                decl.ty == *ty
740                    && decl.unit == *unit
741                    && (*ty != Type::String
742                        || !normalised
743                        || (extras.classes.is_none()
744                            && extras.key_normalisation.unwrap_or(KeyNormalisation::NoRule)
745                                == key_normalisation.unwrap_or(KeyNormalisation::NoRule)))
746            }
747        };
748        if !ok {
749            return err(code, path, format!("key {name:?} does not match the class's declaration"));
750        }
751    }
752    Ok(())
753}
754
755/// Whether a function returns a key of the class `class` (its `returns.classes` names it).
756fn returns_key_of(f: &FunctionDescriptor, class: &str) -> bool {
757    f.returns_classes.as_ref().is_some_and(|l| l.iter().any(|c| c == class))
758}
759
760/// The lookup method's signature (D93, 16.1): one `string` argument `label`, `"order":
761/// ["label"]`, not valid-time and without classes, returning a key of this class.
762fn check_lookup(f: &FunctionDescriptor, class: &str, path: &str) -> Result<()> {
763    let bad = |why: &str| err(ErrorCode::ClassMember, path, format!("the lookup method {why}"));
764    if f.signature.args.len() != 1 || f.order.as_deref() != Some(&["label".to_string()][..]) {
765        return bad("takes exactly one argument, label");
766    }
767    let Some(label) = f.signature.args.get("label") else { return bad("takes exactly one argument, label") };
768    if label.ty != Type::String || label.valid || f.arg_extras.get("label").is_some_and(|e| e.classes.is_some()) {
769        return bad("takes a string label");
770    }
771    if f.signature.returns.ty != Type::String || !returns_key_of(f, class) {
772        return bad("returns a key of this class");
773    }
774    Ok(())
775}