1use 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#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum ClassKey {
22 Scalar {
26 ty: Type,
28 unit: Option<Unit>,
30 key_normalisation: Option<KeyNormalisation>,
32 },
33 Class(String),
36}
37
38#[derive(Clone, Debug, PartialEq, Eq)]
40#[non_exhaustive]
41pub struct Steward {
42 pub namespace: String,
44 pub process: String,
46}
47
48#[derive(Clone, Debug, Default, PartialEq, Eq)]
50#[non_exhaustive]
51pub struct ClassExtent {
52 pub exists: Option<String>,
54 pub keys: Option<String>,
56}
57
58#[derive(Clone, Debug, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct ClassDescriptor {
67 pub keys: BTreeMap<String, ClassKey>,
69 pub order: Vec<String>,
71 pub methods: BTreeMap<String, String>,
73 pub steward: Steward,
75 pub parent: Option<String>,
77 pub is_final: bool,
79 pub open: Vec<String>,
81 pub maps: Vec<String>,
83 pub inverse: Vec<String>,
85 pub lookup: Option<String>,
87 pub extent: Option<ClassExtent>,
89 pub implements: Vec<String>,
91}
92
93impl ClassDescriptor {
94 pub fn from_json(bytes: &[u8]) -> Result<ClassDescriptor> {
106 ClassDescriptor::from_value(&json::parse(bytes)?)
107 }
108
109 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 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 pub fn canonical(&self) -> Vec<u8> {
191 self.to_value().to_jcs()
192 }
193
194 pub fn hash(&self) -> String {
198 crate::crypto::sha256_hex(&self.canonical())
199 }
200}
201
202const MAX_KEYS: usize = 32;
204
205const CLASS_REQUIRED: &[&str] = &["keys", "order", "methods", "steward"];
207const CLASS_OPTIONAL: &[&str] = &["parent", "final", "open", "maps", "inverse", "lookup", "extent", "implements"];
208
209fn 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
280fn 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
294fn 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
302fn 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
310fn 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
319fn class_canonical(v: &Value) -> Result<ClassDescriptor> {
321 let m = schema::object(v, "$")?;
322
323 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 (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 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 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 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 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 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 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 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 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 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 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#[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 pub fn new(definer: &str) -> ClassEnv {
520 ClassEnv { definer: definer.into(), functions: BTreeMap::new(), classes: BTreeMap::new() }
521 }
522
523 pub fn definer(&self) -> &str {
525 &self.definer
526 }
527
528 pub fn insert_function(&mut self, d: FunctionDescriptor) {
530 self.functions.insert(d.hash(), d);
531 }
532
533 pub fn insert_class(&mut self, c: ClassDescriptor) {
535 self.classes.insert(c.hash(), c);
536 }
537
538 pub fn function(&self, hash: &str) -> Option<&FunctionDescriptor> {
540 self.functions.get(hash)
541 }
542
543 pub fn class(&self, hash: &str) -> Option<&ClassDescriptor> {
545 self.classes.get(hash)
546 }
547}
548
549pub fn define_class(name: &str, descriptor_json: &[u8], env: &ClassEnv) -> Result<ClassDescriptor> {
569 lexical::check_function_name(name, "$.name")?;
571 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 let own = ClassDescriptor::from_json(descriptor_json)?;
581 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 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 let flat = ClassDescriptor::from_value(&flat.to_value())?;
624 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 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 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
690fn 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
699fn 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
708fn 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
755fn 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
760fn 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}