1use 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
16pub enum RateSide {
17 Currency(String),
19 Arg(String),
21}
22
23#[derive(Clone, Debug, PartialEq, Eq, Hash)]
25pub enum Unit {
26 Literal(String),
28 Arg(String),
30 Rate {
32 of: RateSide,
34 per: RateSide,
36 },
37}
38
39impl Unit {
40 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
61pub struct ArgDecl {
62 pub ty: Type,
64 pub unit: Option<Unit>,
66 pub valid: bool,
68}
69
70#[derive(Clone, Debug, PartialEq, Eq, Hash)]
72pub struct Returns {
73 pub ty: Type,
75 pub unit: Option<Unit>,
77}
78
79#[derive(Clone, Debug, PartialEq, Eq, Hash)]
81pub struct Signature {
82 pub args: BTreeMap<String, ArgDecl>,
84 pub returns: Returns,
86}
87
88impl Signature {
89 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
117#[non_exhaustive]
118pub enum Extent {
119 Values(Vec<String>),
123 Range {
126 lo: String,
128 hi: String,
130 },
131}
132
133impl Extent {
134 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
154pub struct Descriptor {
155 pub lang: String,
157 pub body: String,
159 pub inputs: Vec<String>,
161 pub signature: Signature,
163}
164
165impl Descriptor {
166 pub fn from_json(bytes: &[u8]) -> Result<Descriptor> {
170 Descriptor::from_value(&json::parse(bytes)?)
171 }
172
173 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 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 pub fn canonical(&self) -> Vec<u8> {
198 self.to_value().to_jcs()
199 }
200
201 pub fn hash(&self) -> String {
203 crate::crypto::sha256_hex(&self.canonical())
204 }
205}
206
207#[derive(Clone, Debug, PartialEq, Eq, Hash)]
214#[non_exhaustive]
215pub struct FunctionDescriptor {
216 pub lang: String,
218 pub body: String,
220 pub inputs: Vec<String>,
222 pub signature: Signature,
225 pub order: Option<Vec<String>>,
228 pub extents: BTreeMap<String, Extent>,
230 pub arg_extras: BTreeMap<String, ArgExtras>,
235 pub returns_classes: Option<Vec<String>>,
238}
239
240#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
246#[non_exhaustive]
247pub struct ArgExtras {
248 pub classes: Option<Vec<String>>,
251 pub default_asof: bool,
254 pub default_literal: Option<String>,
259 pub key_normalisation: Option<KeyNormalisation>,
263}
264
265impl FunctionDescriptor {
266 pub fn from_json(bytes: &[u8]) -> Result<FunctionDescriptor> {
270 FunctionDescriptor::from_value(&json::parse(bytes)?)
271 }
272
273 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 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 pub fn canonical(&self) -> Vec<u8> {
296 self.to_value().to_jcs()
297 }
298
299 pub fn hash(&self) -> String {
301 crate::crypto::sha256_hex(&self.canonical())
302 }
303
304 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 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
427fn 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
447pub(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 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
541fn 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
549fn 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
583fn 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
592pub(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 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
626pub(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
637fn 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 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
840pub 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
851pub 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
864pub 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 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 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}