Skip to main content

cbcl_core/
contracts.rs

1//! SPEC-040: pure, bounded, representation-preserving flat contracts.
2use crate::{
3    sexpr::{Atom, SExpr},
4    shape::{ShapeRule, TypeConstraint},
5};
6use alloc::{collections::BTreeMap, format, string::String, sync::Arc, vec::Vec};
7use core::{
8    cmp::Ordering,
9    hash::{Hash, Hasher},
10};
11use num_bigint::BigInt;
12
13pub const PROFILE: &str = "cbcl-flat-v1-unicode16";
14pub const MAX_TYPES: usize = 128;
15pub const MAX_NODES: usize = 512;
16pub const MAX_DEPTH: usize = 32;
17pub const MAX_PATTERN_BYTES: usize = 1024;
18pub const MAX_INPUT_BYTES: usize = 65536;
19pub const MAX_NUMERIC_BYTES: usize = 4096;
20pub const MAX_LITERAL_BYTES: usize = 65536;
21pub const MAX_MEMBERS: usize = 256;
22pub const MAX_NFA_BYTES: usize = 262144;
23pub const MAX_STATES: usize = 16384;
24pub const DEFAULT_WORK: u64 = 1 << 35;
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum CheckError {
28    Violation(String),
29    ResourceLimit,
30    InvalidDefinition(String),
31}
32impl core::fmt::Display for CheckError {
33    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
34        match self {
35            Self::Violation(s) => write!(f, "contract violation: {s}"),
36            Self::ResourceLimit => f.write_str("resource-limit"),
37            Self::InvalidDefinition(s) => write!(f, "invalid contract: {s}"),
38        }
39    }
40}
41
42/// Source is signed; derived programs are private, rebuilt at installation after parsing or deserialization.
43#[derive(Debug, Clone)]
44#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
45pub struct Contract {
46    source: SExpr,
47    #[cfg_attr(feature = "serde", serde(skip))]
48    compiled: Option<Arc<Node>>,
49}
50impl PartialEq for Contract {
51    fn eq(&self, other: &Self) -> bool {
52        self.source == other.source
53    }
54}
55impl Eq for Contract {}
56impl Hash for Contract {
57    fn hash<H: Hasher>(&self, h: &mut H) {
58        self.source.hash(h)
59    }
60}
61impl Contract {
62    pub fn unresolved(source: SExpr) -> Self {
63        Self {
64            source,
65            compiled: None,
66        }
67    }
68    pub fn source(&self) -> &SExpr {
69        &self.source
70    }
71    pub fn representation(&self) -> Option<TypeConstraint> {
72        self.compiled.as_ref().and_then(|n| n.representation())
73    }
74    pub fn representations(&self) -> u16 {
75        self.compiled.as_ref().map_or(0, |n| n.mask)
76    }
77    pub fn check(&self, value: &SExpr, available_work: u64) -> Result<(), CheckError> {
78        let n = self
79            .compiled
80            .as_ref()
81            .ok_or_else(|| CheckError::InvalidDefinition("not installed".into()))?;
82        // Reserve the entire worst-case bound before running any branch.
83        if available_work < n.work || !input_fits(value) {
84            return Err(CheckError::ResourceLimit);
85        }
86        n.check(value)
87    }
88    pub fn required_work(&self) -> Option<u64> {
89        self.compiled.as_ref().map(|n| n.work)
90    }
91}
92#[derive(Debug)]
93struct Node {
94    mask: u16,
95    work: u64,
96    height: usize,
97    kind: Kind,
98}
99#[derive(Debug)]
100enum Kind {
101    Builtin(TypeConstraint),
102    Named(String, Arc<Node>),
103    All(Vec<Arc<Node>>),
104    Any(Vec<Arc<Node>>),
105    Enum(Vec<Atom>),
106    Refined(TypeConstraint, Vec<Predicate>),
107}
108#[derive(Debug)]
109enum Predicate {
110    Bound(Op, Atom),
111    Length(Vec<(Op, i64)>),
112    Pattern(crate::contracts::iregexp::Pattern),
113}
114#[derive(Debug, Clone, Copy)]
115enum Op {
116    Gt,
117    Ge,
118    Lt,
119    Le,
120}
121impl Op {
122    fn parse(s: &str) -> Option<Self> {
123        Some(match s {
124            ">" => Self::Gt,
125            ">=" => Self::Ge,
126            "<" => Self::Lt,
127            "<=" => Self::Le,
128            _ => return None,
129        })
130    }
131    fn accepts(self, o: Ordering) -> bool {
132        match self {
133            Self::Gt => o.is_gt(),
134            Self::Ge => !o.is_lt(),
135            Self::Lt => o.is_lt(),
136            Self::Le => !o.is_gt(),
137        }
138    }
139}
140fn symbol(e: &SExpr) -> Option<&str> {
141    if let SExpr::Atom(Atom::Symbol(s)) = e {
142        Some(s)
143    } else {
144        None
145    }
146}
147fn list(e: &SExpr) -> Result<&[SExpr], String> {
148    if let SExpr::List(v) = e {
149        Ok(v)
150    } else {
151        Err("expected contract list".into())
152    }
153}
154fn mask(t: &TypeConstraint) -> u16 {
155    match t {
156        TypeConstraint::Integer | TypeConstraint::Nonnegative => 1,
157        TypeConstraint::Float => 2,
158        TypeConstraint::Decimal => 4,
159        TypeConstraint::Number => 7,
160        TypeConstraint::String | TypeConstraint::Hlc => 8,
161        TypeConstraint::Bool => 16,
162        TypeConstraint::Symbol => 32,
163        TypeConstraint::Keyword => 64,
164        TypeConstraint::List => 128,
165        TypeConstraint::Contract(c) => c.compiled.as_ref().map_or(0, |n| n.mask),
166    }
167}
168fn mask_type(m: u16) -> Option<TypeConstraint> {
169    Some(match m {
170        1 => TypeConstraint::Integer,
171        2 => TypeConstraint::Float,
172        4 => TypeConstraint::Decimal,
173        7 | 3 | 5 | 6 => TypeConstraint::Number,
174        8 => TypeConstraint::String,
175        16 => TypeConstraint::Bool,
176        32 => TypeConstraint::Symbol,
177        64 => TypeConstraint::Keyword,
178        128 => TypeConstraint::List,
179        _ => return None,
180    })
181}
182fn atom_mask(a: &Atom) -> u16 {
183    match a {
184        Atom::Num(_) => 1,
185        Atom::Float(_) => 2,
186        Atom::Decimal(_) => 4,
187        Atom::Str(_) => 8,
188        Atom::Bool(_) => 16,
189        Atom::Symbol(_) => 32,
190        Atom::Keyword(_) => 64,
191    }
192}
193pub(crate) fn input_fits(e: &SExpr) -> bool {
194    check_input(e).is_ok()
195}
196pub(crate) fn check_input(e: &SExpr) -> Result<(), &'static str> {
197    fn size(e: &SExpr, depth: usize, left: &mut usize) -> Result<(), &'static str> {
198        if depth > MAX_DEPTH {
199            return Err("input nesting exceeds 32 levels");
200        }
201        let bytes = match e {
202            SExpr::Atom(Atom::Str(s) | Atom::Symbol(s) | Atom::Keyword(s)) => s.len() + 1,
203            SExpr::Atom(Atom::Decimal(d)) => {
204                if d.as_str().len() > MAX_NUMERIC_BYTES {
205                    return Err("decimal representation exceeds 4096 bytes");
206                }
207                d.as_str().len() + 1
208            }
209            SExpr::Atom(_) => 32,
210            SExpr::List(v) => {
211                if v.len() > MAX_INPUT_BYTES {
212                    return Err("input storage exceeds 65536 bytes");
213                }
214                for x in v {
215                    size(x, depth + 1, left)?;
216                }
217                1
218            }
219        };
220        if bytes > *left {
221            Err("input storage exceeds 65536 bytes")
222        } else {
223            *left -= bytes;
224            Ok(())
225        }
226    }
227    size(e, 0, &mut { MAX_INPUT_BYTES })
228}
229// Diagnostics are bounded even when a shared alias DAG has many failing paths.
230const MAX_DIAGNOSTIC_BYTES: usize = 2048;
231fn concise(mut text: String, limit: usize) -> String {
232    if text.len() > limit {
233        let mut end = limit.saturating_sub(3);
234        while !text.is_char_boundary(end) {
235            end -= 1;
236        }
237        text.truncate(end);
238        text.push_str("...");
239    }
240    text
241}
242fn violation(text: String) -> CheckError {
243    CheckError::Violation(concise(text, MAX_DIAGNOSTIC_BYTES))
244}
245fn context(error: String, location: &str) -> String {
246    let text = if let Some(reason) = error.strip_prefix("resource-limit:") {
247        format!("resource-limit: {location}:{}", reason)
248    } else {
249        format!("{location}: {error}")
250    };
251    concise(text, MAX_DIAGNOSTIC_BYTES)
252}
253impl core::fmt::Display for Op {
254    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
255        f.write_str(match self {
256            Self::Gt => ">",
257            Self::Ge => ">=",
258            Self::Lt => "<",
259            Self::Le => "<=",
260        })
261    }
262}
263impl Node {
264    fn representation(&self) -> Option<TypeConstraint> {
265        match &self.kind {
266            Kind::Builtin(t) => Some(t.clone()),
267            Kind::Named(_, n) => n.representation(),
268            _ => mask_type(self.mask),
269        }
270    }
271    fn check(&self, v: &SExpr) -> Result<(), CheckError> {
272        self.check_cached(v, &mut BTreeMap::new())
273    }
274    fn check_cached(
275        &self,
276        v: &SExpr,
277        memo: &mut BTreeMap<usize, Result<(), CheckError>>,
278    ) -> Result<(), CheckError> {
279        let key = self as *const Node as usize;
280        if let Some(result) = memo.get(&key) {
281            return result.clone();
282        }
283        let result = self.evaluate(v, memo);
284        memo.insert(key, result.clone());
285        result
286    }
287    fn evaluate(
288        &self,
289        v: &SExpr,
290        memo: &mut BTreeMap<usize, Result<(), CheckError>>,
291    ) -> Result<(), CheckError> {
292        let fail = || {
293            violation(format!(
294                "expected declared representation; found {}",
295                crate::shape::describe_type(v)
296            ))
297        };
298        let wrong_type = |t: &TypeConstraint| {
299            violation(format!(
300                "expected {t}; found {}",
301                crate::shape::describe_type(v)
302            ))
303        };
304        match &self.kind {
305            Kind::Builtin(t) => {
306                if t.matches_builtin(v) {
307                    Ok(())
308                } else {
309                    Err(wrong_type(t))
310                }
311            }
312            Kind::Named(name, n) => n.check_cached(v, memo).map_err(|e| match e {
313                CheckError::Violation(rule) => violation(format!("type {name}: {rule}")),
314                e => e,
315            }),
316            Kind::All(ns) => {
317                for (index, n) in ns.iter().enumerate() {
318                    n.check_cached(v, memo).map_err(|error| match error {
319                        CheckError::Violation(reason) => {
320                            violation(format!("and branch {}: {reason}", index + 1))
321                        }
322                        other => other,
323                    })?;
324                }
325                Ok(())
326            }
327            Kind::Any(ns) => {
328                let mut reasons = Vec::new();
329                for (index, n) in ns.iter().enumerate() {
330                    match n.check_cached(v, memo) {
331                        Ok(()) => return Ok(()),
332                        Err(CheckError::Violation(reason)) => {
333                            if reasons.len() < 8 {
334                                reasons.push(format!(
335                                    "branch {}: {}",
336                                    index + 1,
337                                    concise(reason, 224)
338                                ));
339                            }
340                        }
341                        Err(error) => return Err(error),
342                    }
343                }
344                let omitted = if ns.len() > reasons.len() {
345                    format!("; {} further branches failed", ns.len() - reasons.len())
346                } else {
347                    String::new()
348                };
349                Err(violation(format!(
350                    "or: no alternative matched; {}{omitted}",
351                    reasons.join("; ")
352                )))
353            }
354            Kind::Enum(xs) => {
355                if matches!(v,SExpr::Atom(a) if xs.contains(a)) {
356                    Ok(())
357                } else {
358                    Err(violation(format!(
359                        "one-of: expected one of {} declared scalar literals; found {}",
360                        xs.len(),
361                        crate::shape::describe_type(v)
362                    )))
363                }
364            }
365            Kind::Refined(t, ps) => {
366                if !t.matches_builtin(v) {
367                    return Err(wrong_type(t));
368                }
369                for (index, p) in ps.iter().enumerate() {
370                    let ok = match p {
371                        Predicate::Bound(op, b) => {
372                            if let SExpr::Atom(a) = v {
373                                op.accepts(compare_numeric(a, b).ok_or_else(fail)?)
374                            } else {
375                                false
376                            }
377                        }
378                        Predicate::Length(bs) => {
379                            let n = match v {
380                                SExpr::Atom(Atom::Str(s)) => s.chars().count(),
381                                SExpr::List(xs) => xs.len(),
382                                _ => return Err(fail()),
383                            };
384                            bs.iter().all(|(op, b)| op.accepts((n as i64).cmp(b)))
385                        }
386                        Predicate::Pattern(p) => {
387                            if let SExpr::Atom(Atom::Str(s)) = v {
388                                p.is_match(s)
389                            } else {
390                                false
391                            }
392                        }
393                    };
394                    if !ok {
395                        let reason = match p {
396                            Predicate::Bound(op, b) => format!("numeric bound ({op} {b})"),
397                            Predicate::Length(bounds) => {
398                                let length = match v {
399                                    SExpr::Atom(Atom::Str(s)) => s.chars().count(),
400                                    SExpr::List(xs) => xs.len(),
401                                    _ => 0,
402                                };
403                                let (op, bound) = bounds
404                                    .iter()
405                                    .find(|(op, bound)| !op.accepts((length as i64).cmp(bound)))
406                                    .expect("failed length bound");
407                                format!("length ({op} {bound})")
408                            }
409                            Predicate::Pattern(pattern) => format!(
410                                "matches {} (whole string)",
411                                SExpr::Atom(Atom::Str(pattern.source().into()))
412                            ),
413                        };
414                        return Err(violation(format!(
415                            "refinement clause {} failed: {reason}",
416                            index + 1
417                        )));
418                    }
419                }
420                Ok(())
421            }
422        }
423    }
424}
425
426/// Compare exact mathematical values, including the exact rational binary64 value.
427pub fn compare_numeric(a: &Atom, b: &Atom) -> Option<Ordering> {
428    fn rational(a: &Atom) -> Option<(BigInt, BigInt)> {
429        match a {
430            Atom::Num(n) => Some((BigInt::from(*n), BigInt::from(1))),
431            Atom::Decimal(d) => {
432                let s = d.as_str();
433                let scale = s.split_once('.').map_or(0, |(_, f)| f.len());
434                let digits = s.replace('.', "");
435                Some((
436                    BigInt::parse_bytes(digits.as_bytes(), 10)?,
437                    BigInt::from(10).pow(scale.try_into().ok()?),
438                ))
439            }
440            Atom::Float(f) => {
441                let bits = f.get().to_bits();
442                let exp = ((bits >> 52) & 2047) as i32;
443                let mant = (bits & ((1u64 << 52) - 1)) | if exp == 0 { 0 } else { 1u64 << 52 };
444                let shift = if exp == 0 { -1074 } else { exp - 1023 - 52 };
445                let mut n = BigInt::from(mant);
446                if bits >> 63 != 0 {
447                    n = -n
448                }
449                Some(if shift >= 0 {
450                    (n << (shift as usize), BigInt::from(1))
451                } else {
452                    (n, BigInt::from(1) << ((-shift) as usize))
453                })
454            }
455            _ => None,
456        }
457    }
458    let (an, ad) = rational(a)?;
459    let (bn, bd) = rational(b)?;
460    Some((an * bd).cmp(&(bn * ad)))
461}
462
463struct Compiler<'a> {
464    definitions: &'a BTreeMap<String, SExpr>,
465    ready: BTreeMap<String, Arc<Node>>,
466    visiting: Vec<String>,
467    nodes: usize,
468    literal_bytes: usize,
469    patterns: BTreeMap<String, crate::contracts::iregexp::Pattern>,
470}
471impl<'a> Compiler<'a> {
472    fn new(definitions: &'a BTreeMap<String, SExpr>) -> Self {
473        Self {
474            definitions,
475            ready: BTreeMap::new(),
476            visiting: Vec::new(),
477            nodes: 0,
478            literal_bytes: 0,
479            patterns: BTreeMap::new(),
480        }
481    }
482    fn named(&mut self, name: &str, depth: usize) -> Result<Arc<Node>, String> {
483        if let Some(n) = self.ready.get(name) {
484            if depth + n.height > MAX_DEPTH {
485                return Err("resource-limit: dependency depth".into());
486            }
487            return Ok(n.clone());
488        }
489        if self.visiting.iter().any(|n| n == name) {
490            return Err(format!(
491                "cyclic type dependency: {} -> {name}",
492                self.visiting.join(" -> ")
493            ));
494        }
495        let source = self
496            .definitions
497            .get(name)
498            .ok_or_else(|| format!("unknown type {name}"))?;
499        check_input(source)
500            .map_err(|reason| format!("resource-limit: contract source: {reason}"))?;
501        let source = source.clone();
502        self.visiting.push(name.into());
503        let node = self
504            .compile(&source, depth + 1)
505            .map_err(|error| context(error, &format!("type {name}")))?;
506        self.visiting.pop();
507        self.ready.insert(name.into(), node.clone());
508        Ok(node)
509    }
510    fn compile(&mut self, e: &SExpr, depth: usize) -> Result<Arc<Node>, String> {
511        check_input(e).map_err(|reason| format!("resource-limit: contract source: {reason}"))?;
512        self.nodes += 1;
513        if depth > MAX_DEPTH {
514            return Err(format!(
515                "resource-limit: contract depth {depth} exceeds {MAX_DEPTH}"
516            ));
517        }
518        if self.nodes > MAX_NODES {
519            return Err(format!(
520                "resource-limit: contract nodes {} exceed {MAX_NODES}",
521                self.nodes
522            ));
523        }
524        if let Some(name) = symbol(e) {
525            if let Some(t) = TypeConstraint::from_str(name) {
526                return Ok(Arc::new(Node {
527                    mask: mask(&t),
528                    work: 1,
529                    height: 1,
530                    kind: Kind::Builtin(t),
531                }));
532            }
533            let target = self.named(name, depth)?;
534            return Ok(Arc::new(Node {
535                mask: target.mask,
536                work: target
537                    .work
538                    .checked_add(1)
539                    .ok_or("resource-limit: work bound")?,
540                height: target.height + 1,
541                kind: Kind::Named(name.into(), target),
542            }));
543        }
544        let xs = list(e)?;
545        let head = xs.first().and_then(symbol).ok_or("missing contract head")?;
546        if head == "and" || head == "or" {
547            if xs.len() < 3 {
548                return Err("and/or require at least two operands".into());
549            }
550            let mut ns = Vec::new();
551            let mut m = if head == "and" { 255 } else { 0 };
552            let mut work = 1u64;
553            for (index, x) in xs[1..].iter().enumerate() {
554                let n = self
555                    .compile(x, depth + 1)
556                    .map_err(|error| context(error, &format!("{head} branch {}", index + 1)))?;
557                if head == "and" {
558                    m &= n.mask
559                } else {
560                    m |= n.mask
561                }
562                work = work
563                    .checked_add(n.work)
564                    .ok_or("resource-limit: work bound")?;
565                ns.push(n)
566            }
567            if m == 0 {
568                return Err("disjoint base representations".into());
569            }
570            return Ok(Arc::new(Node {
571                mask: m,
572                work,
573                height: ns.iter().map(|n| n.height).max().unwrap_or(0) + 1,
574                kind: if head == "and" {
575                    Kind::All(ns)
576                } else {
577                    Kind::Any(ns)
578                },
579            }));
580        }
581        if head == "one-of" {
582            if xs.len() < 2 {
583                return Err("empty enumeration".into());
584            }
585            if xs.len() > MAX_MEMBERS + 1 {
586                return Err("resource-limit: enumeration members".into());
587            }
588            let mut atoms = Vec::new();
589            let mut m = 0;
590            for x in &xs[1..] {
591                let SExpr::Atom(a) = x else {
592                    return Err("enumeration requires scalar literals".into());
593                };
594                if atoms.contains(a) {
595                    return Err("duplicate enumeration member".into());
596                }
597                m |= atom_mask(a);
598                atoms.push(a.clone());
599            }
600            self.add_literals(e)?;
601            return Ok(Arc::new(Node {
602                mask: m,
603                work: (MAX_INPUT_BYTES * atoms.len() + 1) as u64,
604                height: 1,
605                kind: Kind::Enum(atoms),
606            }));
607        }
608        let t = TypeConstraint::from_str(head).ok_or("unsupported refinement head")?;
609        if !matches!(
610            t,
611            TypeConstraint::String
612                | TypeConstraint::List
613                | TypeConstraint::Number
614                | TypeConstraint::Integer
615                | TypeConstraint::Float
616                | TypeConstraint::Decimal
617        ) || xs.len() < 2
618        {
619            return Err("invalid refinement domain or arity".into());
620        }
621        let mut ps = Vec::new();
622        let mut all_lengths = Vec::new();
623        let mut bounds = Vec::new();
624        let mut work = 1u64;
625        for (index, x) in xs[1..].iter().enumerate() {
626            let clause = list(x)?;
627            let op = clause
628                .first()
629                .and_then(symbol)
630                .ok_or("missing refinement operator")?;
631            if op == "matches" && t == TypeConstraint::String {
632                let [_, SExpr::Atom(Atom::Str(pattern))] = clause else {
633                    return Err("matches requires one string".into());
634                };
635                let p = if let Some(p) = self.patterns.get(pattern) {
636                    p.clone()
637                } else {
638                    let p = iregexp::Pattern::compile(pattern).map_err(|error| {
639                        context(error, &format!("matches refinement clause {}", index + 1))
640                    })?;
641                    self.patterns.insert(pattern.clone(), p.clone());
642                    p
643                };
644                work = work
645                    .checked_add(p.work())
646                    .ok_or("resource-limit: pattern work")?;
647                ps.push(Predicate::Pattern(p));
648            } else if op == "length" && matches!(t, TypeConstraint::String | TypeConstraint::List) {
649                if clause.len() < 2 {
650                    return Err("length requires bounds".into());
651                }
652                let mut bs = Vec::new();
653                for b in &clause[1..] {
654                    let bslice = list(b)?;
655                    let [h, SExpr::Atom(Atom::Num(n))] = bslice else {
656                        return Err("length bound requires nonnegative integer".into());
657                    };
658                    let o = symbol(h)
659                        .and_then(Op::parse)
660                        .ok_or("invalid length comparator")?;
661                    if *n < 0 {
662                        return Err("negative length bound".into());
663                    }
664                    bs.push((o, *n));
665                }
666                all_lengths.extend(bs.iter().copied());
667                work += MAX_INPUT_BYTES as u64 * (bs.len() as u64 + 1);
668                ps.push(Predicate::Length(bs));
669            } else if mask(&t) & 7 != 0 {
670                let o = Op::parse(op).ok_or("invalid numeric comparator")?;
671                let [_, SExpr::Atom(a)] = clause else {
672                    return Err("bound requires numeric literal".into());
673                };
674                if atom_mask(a) & 7 == 0 {
675                    return Err("bound requires numeric literal".into());
676                }
677                bounds.push((o, a.clone()));
678                ps.push(Predicate::Bound(o, a.clone()));
679                work += (MAX_NUMERIC_BYTES * MAX_NUMERIC_BYTES * 16) as u64;
680            } else {
681                return Err("invalid refinement clause".into());
682            }
683        }
684        validate_bounds(&bounds)?;
685        if !all_lengths.is_empty() {
686            let mut lo = 0i128;
687            let mut hi = i64::MAX as i128;
688            for (op, n) in all_lengths {
689                match op {
690                    Op::Ge => lo = lo.max(n as i128),
691                    Op::Gt => lo = lo.max(n as i128 + 1),
692                    Op::Le => hi = hi.min(n as i128),
693                    Op::Lt => hi = hi.min(n as i128 - 1),
694                }
695            }
696            if lo > hi {
697                return Err("empty length domain".into());
698            }
699        }
700        self.add_literals(e)?;
701        Ok(Arc::new(Node {
702            mask: mask(&t),
703            work,
704            height: 1,
705            kind: Kind::Refined(t, ps),
706        }))
707    }
708    fn add_literals(&mut self, e: &SExpr) -> Result<(), String> {
709        let bytes = crate::canonical::canonical_encode(e).len();
710        if bytes > MAX_INPUT_BYTES {
711            return Err("resource-limit: literal input".into());
712        }
713        self.literal_bytes += bytes;
714        if self.literal_bytes > MAX_LITERAL_BYTES {
715            return Err("resource-limit: literal bytes".into());
716        }
717        Ok(())
718    }
719}
720fn validate_bounds(bs: &[(Op, Atom)]) -> Result<(), String> {
721    for (lo, l) in bs {
722        if !matches!(lo, Op::Gt | Op::Ge) {
723            continue;
724        }
725        for (hi, h) in bs {
726            if !matches!(hi, Op::Lt | Op::Le) {
727                continue;
728            }
729            let c = compare_numeric(l, h).ok_or("invalid bound")?;
730            if c.is_gt() || (c.is_eq() && (matches!(lo, Op::Gt) || matches!(hi, Op::Lt))) {
731                return Err("empty or reversed numeric interval".into());
732            }
733        }
734    }
735    Ok(())
736}
737
738/// Installation rebuilds every program from signed source, including unused named definitions.
739pub fn install(d: &mut crate::dialect::Dialect) -> Result<(), String> {
740    if d.types.len() > MAX_TYPES {
741        return Err("resource-limit: type declarations".into());
742    }
743    for name in d.types.keys() {
744        if name.is_empty()
745            || name.len() > 48
746            || !name.as_bytes()[0].is_ascii_lowercase()
747            || !name
748                .bytes()
749                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
750            || TypeConstraint::from_str(name).is_some()
751            || matches!(
752                name.as_str(),
753                "and" | "or" | "matches" | "length" | "one-of" | "type" | "default"
754            )
755        {
756            return Err(format!("invalid or reserved type name {name}"));
757        }
758    }
759    let mut compiler = Compiler::new(&d.types);
760    for name in d.types.keys() {
761        compiler
762            .named(name, 0)
763            .map_err(|error| context(error, &format!("dialect {}", d.name)))?;
764    }
765    fn rules(
766        rs: &mut [ShapeRule],
767        compiler: &mut Compiler<'_>,
768        parent: &str,
769    ) -> Result<(), String> {
770        for r in rs {
771            let location = match &*r {
772                ShapeRule::Require { keyword, .. } | ShapeRule::Optional { keyword, .. } => {
773                    format!("{parent}/:{keyword}")
774                }
775                ShapeRule::MaxDepth(_) => String::from(parent),
776            };
777            match r {
778                ShapeRule::Require {
779                    type_constraint,
780                    children,
781                    ..
782                }
783                | ShapeRule::Optional {
784                    type_constraint,
785                    children,
786                    ..
787                } => {
788                    if let Some(TypeConstraint::Contract(c)) = type_constraint {
789                        c.compiled = Some(
790                            compiler
791                                .compile(&c.source, 0)
792                                .map_err(|error| context(error, &location))?,
793                        )
794                    }
795                    rules(children, compiler, &location)?;
796                }
797                ShapeRule::MaxDepth(_) => {}
798            }
799            if let ShapeRule::Optional {
800                type_constraint,
801                default: Some(v),
802                children,
803                ..
804            } = r
805            {
806                if let Some(t) = type_constraint {
807                    t.check(v, DEFAULT_WORK).map_err(|e| {
808                        if e == CheckError::ResourceLimit {
809                            context(
810                                t.resource_detail(v, DEFAULT_WORK),
811                                &format!("default {location}"),
812                            )
813                        } else {
814                            context(format!("invalid default: {e}"), &location)
815                        }
816                    })?;
817                }
818                for child in children {
819                    crate::shape::check_rule(child, v, DEFAULT_WORK).map_err(|e| {
820                        if e.rule == "resource-limit" {
821                            context(
822                                format!("resource-limit: {}", e.detail),
823                                &format!("default {location}"),
824                            )
825                        } else {
826                            context(format!("invalid default child: {e}"), &location)
827                        }
828                    })?;
829                }
830            }
831        }
832        Ok(())
833    }
834    for shape in &mut d.shapes {
835        let location = format!("dialect {} shape {}", d.name, shape.performative);
836        rules(&mut shape.rules, &mut compiler, &location)?;
837    }
838    Ok(())
839}
840
841mod iregexp;
842
843/// The finite conservative representation set for a type (SPEC-040 schema surface).
844pub fn representation_names(t: &TypeConstraint) -> Vec<&'static str> {
845    let m = mask(t);
846    [
847        (1, "integer"),
848        (2, "float"),
849        (4, "decimal"),
850        (8, "string"),
851        (16, "bool"),
852        (32, "symbol"),
853        (64, "keyword"),
854        (128, "list"),
855    ]
856    .into_iter()
857    .filter_map(|(bit, name)| if m & bit != 0 { Some(name) } else { None })
858    .collect()
859}
860
861pub type TypeSchemaEntry = (String, SExpr, Vec<&'static str>);
862
863pub fn type_schema(d: &crate::dialect::Dialect) -> Result<Vec<TypeSchemaEntry>, String> {
864    let mut compiler = Compiler::new(&d.types);
865    let mut out = Vec::new();
866    for (name, source) in &d.types {
867        let n = compiler.named(name, 0)?;
868        let names = [
869            (1, "integer"),
870            (2, "float"),
871            (4, "decimal"),
872            (8, "string"),
873            (16, "bool"),
874            (32, "symbol"),
875            (64, "keyword"),
876            (128, "list"),
877        ]
878        .into_iter()
879        .filter_map(|(b, s)| if n.mask & b != 0 { Some(s) } else { None })
880        .collect();
881        out.push((name.clone(), source.clone(), names));
882    }
883    Ok(out)
884}