Skip to main content

meta_language/translation/
ir.rs

1//! The checked portable core: every expression carries its type and every
2//! operator its source semantics. Emitters consume it; the renaming passes
3//! give each target unique, legal local names.
4//!
5//! The JSON form is the JavaScript runtime's checked program, except that
6//! `declarations` is an array and `items` refer to declarations by name.
7
8use std::collections::{BTreeSet, HashMap, HashSet};
9
10use serde::{Deserialize, Serialize};
11
12use super::surface::{BinaryOp, External, Flavor, Guard, Rounding, SImport, UnaryOp};
13use super::types::Type;
14use super::{Language, Span};
15
16mod declarations;
17mod record_entry;
18mod reference_type;
19mod rename;
20pub use record_entry::RecordEntry;
21mod nodes;
22pub use nodes::Node;
23#[allow(clippy::trivially_copy_pass_by_ref)] // serde passes fields by reference
24const fn is_false(value: &bool) -> bool {
25    !*value
26}
27
28pub use self::declarations::{
29    Ctor, DataDecl, Decl, Field, FnDecl, LambdaParam, Param, TheoremDecl,
30};
31pub use self::rename::*;
32
33/// Arithmetic semantics: exact on unbounded integers, checked (aborting)
34/// machine arithmetic, truncated natural subtraction, or IEEE-754 binary64
35/// arithmetic on JavaScript Numbers.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "camelCase")]
38pub enum Semantics {
39    Exact,
40    Checked,
41    Truncated,
42    /// Round to nearest, even on a tie; `%` is the exact truncated remainder
43    /// (C `fmod`); nothing aborts.
44    Ieee,
45}
46
47/// What division by zero does: abort (JavaScript, Rust) or yield a total value (Lean, Rocq).
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "camelCase")]
50pub enum ByZero {
51    Abort,
52    Total,
53}
54
55/// A literal's value: numerals and strings are text, booleans are booleans.
56#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(untagged)]
58pub enum LitValue {
59    Bool(bool),
60    Text(String),
61}
62
63impl LitValue {
64    /// The value as JavaScript's `String(value)` renders it.
65    #[must_use]
66    pub fn text(&self) -> String {
67        match self {
68            Self::Bool(value) => value.to_string(),
69            Self::Text(text) => text.clone(),
70        }
71    }
72}
73
74#[derive(Clone, Debug, PartialEq, Eq)]
75pub struct Expr {
76    pub node: Node,
77    pub ty: Type,
78    pub span: Option<Span>,
79}
80
81impl Expr {
82    #[must_use]
83    pub const fn new(node: Node, ty: Type) -> Self {
84        Self {
85            node,
86            ty,
87            span: None,
88        }
89    }
90
91    #[must_use]
92    pub fn var(name: impl Into<String>, ty: Type) -> Self {
93        Self::new(Node::Var { name: name.into() }, ty)
94    }
95
96    #[must_use]
97    pub const fn lit(ty: Type, value: LitValue) -> Self {
98        Self::new(Node::Lit { value }, ty)
99    }
100
101    #[must_use]
102    pub const fn with_span(mut self, span: Option<Span>) -> Self {
103        self.span = span;
104        self
105    }
106
107    /// The name of the variable this expression is, if it is one.
108    #[must_use]
109    pub fn var_name(&self) -> Option<&str> {
110        match &self.node {
111            Node::Var { name } => Some(name),
112            _ => None,
113        }
114    }
115
116    /// The `k` discriminant.
117    #[must_use]
118    pub const fn kind(&self) -> &'static str {
119        self.node.kind()
120    }
121
122    /// Direct subexpressions in the JavaScript runtime's key order.
123    #[must_use]
124    pub fn children(&self) -> Vec<&Self> {
125        match &self.node {
126            Node::Lit { .. }
127            | Node::Unit
128            | Node::None { .. }
129            | Node::Var { .. }
130            | Node::FunctionRef { .. }
131            | Node::Abort { .. }
132            | Node::OutNil => Vec::new(),
133            Node::Call { args, .. }
134            | Node::Ctor { args, .. }
135            | Node::Array { items: args }
136            | Node::Tuple { items: args, .. }
137            | Node::Math { args, .. } => args.iter().collect(),
138            Node::Apply { func, args } => {
139                std::iter::once(func.as_ref()).chain(args.iter()).collect()
140            }
141            Node::Lambda { body, .. } => vec![body],
142            Node::Unary { arg, .. }
143            | Node::Set { items: arg }
144            | Node::Map { entries: arg }
145            | Node::Some { value: arg }
146            | Node::FlattenOption { value: arg }
147            | Node::OptionalField { object: arg, .. }
148            | Node::OptionalProject { object: arg, .. }
149            | Node::NullishNumber { arg }
150            | Node::OptionalText { arg, .. }
151            | Node::OptionalTypeOf { arg, .. }
152            | Node::Truthy { arg }
153            | Node::UnwrapOption { arg }
154            | Node::OptionalPredicate { arg, .. }
155            | Node::ReferenceAllocate { value: arg }
156            | Node::ReferenceRead { reference: arg }
157            | Node::CellAllocate { value: arg }
158            | Node::CellRead { cell: arg }
159            | Node::OptionalIndexNumber { arg }
160            | Node::StringPoints { object: arg }
161            | Node::CollectionItems { object: arg, .. }
162            | Node::StringMap { string: arg, .. }
163            | Node::ToString { arg, .. }
164            | Node::Cast { arg, .. }
165            | Node::TupleIndex { object: arg, .. }
166            | Node::RecordField { object: arg, .. }
167            | Node::Length { array: arg } => vec![arg],
168            Node::Record { entries } => entries.iter().map(|entry| &entry.value).collect(),
169            Node::Method { object, args, .. } => std::iter::once(object.as_ref())
170                .chain(args.iter().flatten())
171                .collect(),
172            Node::StringTest {
173                string: left,
174                search: right,
175                ..
176            }
177            | Node::Binary { left, right, .. }
178            | Node::Coalesce { left, right }
179            | Node::StrictEqual { left, right, .. }
180            | Node::Append { left, right }
181            | Node::Index {
182                array: left,
183                index: right,
184                ..
185            }
186            | Node::OptionalIndex {
187                array: left,
188                index: right,
189            } => vec![left, right],
190            Node::If {
191                cond,
192                then,
193                otherwise,
194            } => vec![cond, then, otherwise],
195            Node::Let { value, body, .. } => vec![value, body],
196            Node::CellWrite { cell, value, body } => vec![cell, value, body],
197            Node::Print { text, body } => vec![text, body],
198            Node::OutCons { head, tail } => vec![head, tail],
199            Node::Match { scrutinee, cases } => {
200                let mut children = vec![&**scrutinee];
201                children.extend(cases.iter().map(|kase| &kase.body));
202                children
203            }
204        }
205    }
206
207    /// Rebuilds the node with every direct subexpression mapped, in key order.
208    #[must_use]
209    pub fn map_children(&self, visit: &mut impl FnMut(&Self) -> Self) -> Self {
210        let node = match &self.node {
211            Node::Lit { .. }
212            | Node::Unit
213            | Node::None { .. }
214            | Node::Var { .. }
215            | Node::FunctionRef { .. }
216            | Node::Abort { .. }
217            | Node::OutNil => self.node.clone(),
218            Node::Print { text, body } => {
219                let text = Box::new(visit(text));
220                let body = Box::new(visit(body));
221                Node::Print { text, body }
222            }
223            Node::OutCons { head, tail } => {
224                let head = Box::new(visit(head));
225                let tail = Box::new(visit(tail));
226                Node::OutCons { head, tail }
227            }
228            Node::Array { items } => Node::Array {
229                items: items.iter().map(&mut *visit).collect(),
230            },
231            Node::Set { items } => Node::Set {
232                items: Box::new(visit(items)),
233            },
234            Node::Map { entries } => Node::Map {
235                entries: Box::new(visit(entries)),
236            },
237            Node::Record { entries } => Node::Record {
238                entries: entries
239                    .iter()
240                    .map(|entry| RecordEntry {
241                        name: entry.name.clone(),
242                        value: visit(&entry.value),
243                    })
244                    .collect(),
245            },
246            Node::RecordField {
247                object,
248                field,
249                index,
250            } => Node::RecordField {
251                object: Box::new(visit(object)),
252                field: field.clone(),
253                index: *index,
254            },
255            Node::Tuple {
256                items,
257                frozen,
258                product_model,
259            } => Node::Tuple {
260                items: items.iter().map(&mut *visit).collect(),
261                frozen: *frozen,
262                product_model: product_model.clone(),
263            },
264            Node::TupleIndex { object, index } => Node::TupleIndex {
265                object: Box::new(visit(object)),
266                index: *index,
267            },
268            Node::Append { left, right } => {
269                let left = Box::new(visit(left));
270                let right = Box::new(visit(right));
271                Node::Append { left, right }
272            }
273            Node::Index {
274                array,
275                index,
276                proven_in_bounds,
277            } => {
278                let array = Box::new(visit(array));
279                let index = Box::new(visit(index));
280                Node::Index {
281                    array,
282                    index,
283                    proven_in_bounds: *proven_in_bounds,
284                }
285            }
286            Node::OptionalIndex { array, index } => Node::OptionalIndex {
287                array: Box::new(visit(array)),
288                index: Box::new(visit(index)),
289            },
290            Node::OptionalIndexNumber { arg } => Node::OptionalIndexNumber {
291                arg: Box::new(visit(arg)),
292            },
293            Node::Some { value } => Node::Some {
294                value: Box::new(visit(value)),
295            },
296            Node::FlattenOption { value } => Node::FlattenOption {
297                value: Box::new(visit(value)),
298            },
299            Node::Coalesce { left, right } => Node::Coalesce {
300                left: Box::new(visit(left)),
301                right: Box::new(visit(right)),
302            },
303            Node::OptionalField {
304                object,
305                field,
306                index,
307            } => Node::OptionalField {
308                object: Box::new(visit(object)),
309                field: field.clone(),
310                index: *index,
311            },
312            Node::OptionalProject { object, field } => Node::OptionalProject {
313                object: Box::new(visit(object)),
314                field: field.clone(),
315            },
316            Node::NullishNumber { arg } => Node::NullishNumber {
317                arg: Box::new(visit(arg)),
318            },
319            Node::OptionalText { arg, console } => Node::OptionalText {
320                arg: Box::new(visit(arg)),
321                console: *console,
322            },
323            Node::OptionalTypeOf { arg, present } => Node::OptionalTypeOf {
324                arg: Box::new(visit(arg)),
325                present: present.clone(),
326            },
327            Node::Truthy { arg } => Node::Truthy {
328                arg: Box::new(visit(arg)),
329            },
330            Node::StrictEqual {
331                left,
332                right,
333                negate,
334            } => Node::StrictEqual {
335                left: Box::new(visit(left)),
336                right: Box::new(visit(right)),
337                negate: *negate,
338            },
339            Node::UnwrapOption { arg } => Node::UnwrapOption {
340                arg: Box::new(visit(arg)),
341            },
342            Node::OptionalPredicate { arg, op } => Node::OptionalPredicate {
343                arg: Box::new(visit(arg)),
344                op: op.clone(),
345            },
346            Node::StringPoints { object } => Node::StringPoints {
347                object: Box::new(visit(object)),
348            },
349            Node::CollectionItems { object, op } => Node::CollectionItems {
350                object: Box::new(visit(object)),
351                op: op.clone(),
352            },
353            Node::Length { array } => Node::Length {
354                array: Box::new(visit(array)),
355            },
356            Node::ReferenceAllocate { value } => Node::ReferenceAllocate {
357                value: Box::new(visit(value)),
358            },
359            Node::ReferenceRead { reference } => Node::ReferenceRead {
360                reference: Box::new(visit(reference)),
361            },
362            Node::Math { op, args } => Node::Math {
363                op: op.clone(),
364                args: args.iter().map(&mut *visit).collect(),
365            },
366            Node::Call { func, args } => Node::Call {
367                func: func.clone(),
368                args: args.iter().map(&mut *visit).collect(),
369            },
370            Node::Apply { func, args } => Node::Apply {
371                func: Box::new(visit(func)),
372                args: args.iter().map(&mut *visit).collect(),
373            },
374            Node::Lambda { params, body } => Node::Lambda {
375                params: params.clone(),
376                body: Box::new(visit(body)),
377            },
378            Node::CellAllocate { value } => Node::CellAllocate {
379                value: Box::new(visit(value)),
380            },
381            Node::CellRead { cell } => Node::CellRead {
382                cell: Box::new(visit(cell)),
383            },
384            Node::CellWrite { cell, value, body } => Node::CellWrite {
385                cell: Box::new(visit(cell)),
386                value: Box::new(visit(value)),
387                body: Box::new(visit(body)),
388            },
389            Node::Ctor {
390                data,
391                ctor,
392                args,
393                frozen,
394            } => Node::Ctor {
395                data: data.clone(),
396                ctor: ctor.clone(),
397                args: args.iter().map(&mut *visit).collect(),
398                frozen: *frozen,
399            },
400            Node::Unary { op, arg, semantics } => Node::Unary {
401                op: *op,
402                arg: Box::new(visit(arg)),
403                semantics: *semantics,
404            },
405            Node::StringMap { op, string } => Node::StringMap {
406                op: op.clone(),
407                string: Box::new(visit(string)),
408            },
409            Node::Method { object, op, args } => Node::Method {
410                object: Box::new(visit(object)),
411                op: op.clone(),
412                args: args
413                    .iter()
414                    .map(|arg| arg.as_ref().map(&mut *visit))
415                    .collect(),
416            },
417            Node::StringTest { op, string, search } => Node::StringTest {
418                op: op.clone(),
419                string: Box::new(visit(string)),
420                search: Box::new(visit(search)),
421            },
422            Node::ToString { arg, console } => Node::ToString {
423                arg: Box::new(visit(arg)),
424                console: *console,
425            },
426            Node::Cast {
427                arg,
428                from,
429                to,
430                flavor,
431                message,
432                order,
433            } => Node::Cast {
434                arg: Box::new(visit(arg)),
435                from: from.clone(),
436                to: to.clone(),
437                flavor: *flavor,
438                message: message.clone(),
439                order: *order,
440            },
441            Node::Binary {
442                op,
443                left,
444                right,
445                domain,
446                semantics,
447                rounding,
448                by_zero,
449            } => {
450                let left = Box::new(visit(left));
451                let right = Box::new(visit(right));
452                Node::Binary {
453                    op: *op,
454                    left,
455                    right,
456                    domain: domain.clone(),
457                    semantics: *semantics,
458                    rounding: *rounding,
459                    by_zero: *by_zero,
460                }
461            }
462            Node::If {
463                cond,
464                then,
465                otherwise,
466            } => {
467                let cond = Box::new(visit(cond));
468                let then = Box::new(visit(then));
469                let otherwise = Box::new(visit(otherwise));
470                Node::If {
471                    cond,
472                    then,
473                    otherwise,
474                }
475            }
476            Node::Let { name, value, body } => {
477                let value = Box::new(visit(value));
478                let body = Box::new(visit(body));
479                Node::Let {
480                    name: name.clone(),
481                    value,
482                    body,
483                }
484            }
485            Node::Match { scrutinee, cases } => {
486                let scrutinee = Box::new(visit(scrutinee));
487                let cases = cases
488                    .iter()
489                    .map(|kase| Case {
490                        pattern: kase.pattern.clone(),
491                        body: visit(&kase.body),
492                    })
493                    .collect();
494                Node::Match { scrutinee, cases }
495            }
496        };
497        Self {
498            node,
499            ty: self.ty.clone(),
500            span: self.span,
501        }
502    }
503}
504
505#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
506pub struct Case {
507    pub pattern: Pattern,
508    pub body: Expr,
509}
510
511/// A single-level match pattern.
512#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
513#[serde(tag = "k", rename_all = "camelCase", rename_all_fields = "camelCase")]
514pub enum Pattern {
515    Wild,
516    Bind {
517        name: String,
518    },
519    NatZero,
520    NatSucc {
521        name: String,
522    },
523    Ctor {
524        data: String,
525        ctor: String,
526        binds: Vec<Option<String>>,
527    },
528}
529
530impl Pattern {
531    /// Locals the pattern binds.
532    #[must_use]
533    pub fn bound(&self) -> Vec<&str> {
534        match self {
535            Self::Bind { name } | Self::NatSucc { name } => vec![name],
536            Self::Ctor { binds, .. } => binds.iter().flatten().map(String::as_str).collect(),
537            Self::Wild | Self::NatZero => Vec::new(),
538        }
539    }
540}
541
542#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
543pub struct Binder {
544    pub name: String,
545    #[serde(rename = "type")]
546    pub ty: Type,
547}
548
549#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
550pub struct Comparison {
551    pub left: Expr,
552    pub right: Expr,
553    pub domain: Type,
554    /// Over Numbers, `assert.strictEqual` compares with `SameValue`, not
555    /// `===`: `NaN` equals `NaN`, and `0` differs from `-0`.
556    #[serde(default, rename = "sameValue", skip_serializing_if = "is_false")]
557    pub same_value: bool,
558}
559
560#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
561#[serde(tag = "p", rename_all = "camelCase", rename_all_fields = "camelCase")]
562pub enum Prop {
563    Forall {
564        binders: Vec<Binder>,
565        body: Box<Self>,
566    },
567    And {
568        left: Box<Self>,
569        right: Box<Self>,
570    },
571    Or {
572        left: Box<Self>,
573        right: Box<Self>,
574    },
575    Implies {
576        left: Box<Self>,
577        right: Box<Self>,
578    },
579    Not {
580        arg: Box<Self>,
581    },
582    Bool {
583        expr: Expr,
584    },
585    Eq(Comparison),
586    Ne(Comparison),
587    Lt(Comparison),
588    Le(Comparison),
589    Gt(Comparison),
590    Ge(Comparison),
591}
592
593impl Prop {
594    /// The comparison operator and operands of an `eq` … `ge` proposition.
595    #[must_use]
596    pub const fn comparison(&self) -> Option<(BinaryOp, &Comparison)> {
597        match self {
598            Self::Eq(comparison) => Some((BinaryOp::Eq, comparison)),
599            Self::Ne(comparison) => Some((BinaryOp::Ne, comparison)),
600            Self::Lt(comparison) => Some((BinaryOp::Lt, comparison)),
601            Self::Le(comparison) => Some((BinaryOp::Le, comparison)),
602            Self::Gt(comparison) => Some((BinaryOp::Gt, comparison)),
603            Self::Ge(comparison) => Some((BinaryOp::Ge, comparison)),
604            _ => None,
605        }
606    }
607
608    /// Builds the comparison proposition for `op`.
609    ///
610    /// # Panics
611    /// When `op` is not a comparison.
612    #[must_use]
613    pub fn compare(op: BinaryOp, comparison: Comparison) -> Self {
614        match op {
615            BinaryOp::Eq => Self::Eq(comparison),
616            BinaryOp::Ne => Self::Ne(comparison),
617            BinaryOp::Lt => Self::Lt(comparison),
618            BinaryOp::Le => Self::Le(comparison),
619            BinaryOp::Gt => Self::Gt(comparison),
620            BinaryOp::Ge => Self::Ge(comparison),
621            other => panic!("{other:?} is not a comparison"),
622        }
623    }
624}
625
626#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
627pub struct Hints {
628    pub unfold: Vec<String>,
629    pub lemmas: Vec<String>,
630    pub hyps: Vec<String>,
631    pub library: Vec<String>,
632    pub arith: bool,
633    pub compute: bool,
634}
635
636#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
637#[serde(tag = "k", rename_all = "camelCase")]
638pub enum Plan {
639    Close { hints: Hints },
640    Induction(Split),
641    Cases(Split),
642}
643
644#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
645pub struct Split {
646    pub variable: String,
647    #[serde(rename = "type")]
648    pub ty: Type,
649    pub cases: Vec<PlanCase>,
650}
651
652#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
653pub struct PlanCase {
654    pub ctor: String,
655    pub fields: Vec<String>,
656    pub ihs: Vec<String>,
657    pub recursive: Vec<bool>,
658    pub plan: Plan,
659}
660
661#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
662#[serde(rename_all = "camelCase")]
663pub struct Proof {
664    pub plan: Plan,
665    pub source: String,
666    pub source_language: Language,
667}
668
669/// A program item: a declaration, named by its full name, or a module.
670#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
671#[serde(tag = "k", rename_all = "camelCase", rename_all_fields = "camelCase")]
672pub enum Item {
673    Decl {
674        full_name: String,
675    },
676    Module {
677        name: String,
678        full_name: String,
679        items: Vec<Self>,
680        #[serde(default)]
681        span: Option<Span>,
682    },
683}
684
685#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
686#[serde(tag = "k", rename_all = "camelCase")]
687#[allow(clippy::large_enum_variant)]
688pub enum Effect {
689    Print {
690        expr: Expr,
691        #[serde(default)]
692        span: Option<Span>,
693    },
694    Let {
695        /// Actual ordered owned Unit-call statement site.
696        #[serde(
697            default,
698            rename = "sourcePureUnitCall",
699            skip_serializing_if = "Option::is_none"
700        )]
701        source_pure_unit_call: Option<serde_json::Value>,
702        name: String,
703        value: Expr,
704        #[serde(default, skip_serializing_if = "is_false")]
705        constant: bool,
706        #[serde(default)]
707        span: Option<Span>,
708    },
709    Assert {
710        prop: Prop,
711        #[serde(default)]
712        span: Option<Span>,
713    },
714    /// Prints the lines `expr` holds, oldest first (see `output`).
715    Output {
716        expr: Expr,
717        #[serde(default)]
718        span: Option<Span>,
719    },
720    /// Binds `name` to the value of `pair`, made by the first of `ctors`, or
721    /// stops main with the message of its abort, made by the second (see `output`).
722    Unwrap {
723        name: String,
724        pair: Expr,
725        data: String,
726        ctors: Vec<String>,
727        #[serde(rename = "type")]
728        ty: Type,
729        #[serde(default)]
730        span: Option<Span>,
731    },
732}
733
734#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
735pub struct Main {
736    /// Owned worker context for an independently selected complete runtime.
737    #[serde(
738        default,
739        rename = "sourceRuntimeWorker",
740        skip_serializing_if = "Option::is_none"
741    )]
742    pub source_runtime_worker: Option<serde_json::Value>,
743    pub effects: Vec<Effect>,
744    #[serde(default)]
745    pub span: Option<Span>,
746    /// Every call of an async function is awaited where it is made.
747    #[serde(rename = "sequentialAsync", default, skip_serializing_if = "is_false")]
748    pub sequential_async: bool,
749}
750
751fn read_present_program_string_representation<'de, D: serde::Deserializer<'de>>(
752    deserializer: D,
753) -> Result<Option<bool>, D::Error> {
754    bool::deserialize(deserializer).map(Some)
755}
756
757/// A checked portable-core program.
758#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
759#[serde(rename_all = "camelCase")]
760pub struct Program {
761    /// Selected shared-reference representation; false retains its default omission.
762    #[serde(default, skip_serializing_if = "is_false")]
763    pub reference_semantics: bool,
764    /// Explicit UTF-16 string encoding selection; absence and false stay distinct.
765    #[serde(
766        default,
767        skip_serializing_if = "Option::is_none",
768        deserialize_with = "read_present_program_string_representation"
769    )]
770    pub utf16_strings: Option<bool>,
771    /// Complete owned source runtime interpretation, separate from its pure core.
772    #[serde(default, skip_serializing_if = "Option::is_none")]
773    pub source_runtime_shell: Option<serde_json::Value>,
774    /// Independently selected complete pure Unit program interpretation.
775    #[serde(default, skip_serializing_if = "Option::is_none")]
776    pub source_pure_unit_calls: Option<serde_json::Value>,
777    pub schema_version: u32,
778    pub source_language: Language,
779    pub items: Vec<Item>,
780    pub main: Option<Main>,
781    /// Every declaration in source order.
782    pub declarations: Vec<Decl>,
783    /// Functions that print take and return the lines printed (see `output`).
784    #[serde(default, skip_serializing_if = "is_false")]
785    pub output_threaded: bool,
786    /// Functions that may abort return the abort's message instead of a value (see `output`).
787    #[serde(default, skip_serializing_if = "is_false")]
788    pub aborts_threaded: bool,
789    /// Imports of the items of other modules of the crate (self-translation only).
790    #[serde(default, skip_serializing_if = "Vec::is_empty")]
791    pub imports: Vec<SImport>,
792    /// The other items of the module, which the program calls and reads but
793    /// does not declare: a call of one is a `call` of its name.
794    #[serde(default, skip_serializing_if = "Vec::is_empty")]
795    pub externals: Vec<External>,
796}
797
798impl Program {
799    /// The other item of the module that a call of `name` calls or reads,
800    /// when the program declares nothing under that name.
801    #[must_use]
802    pub fn external(&self, name: &str) -> Option<&External> {
803        if self.declaration(name).is_some() {
804            return None;
805        }
806        self.externals
807            .iter()
808            .find(|external| external.name() == name)
809    }
810
811    #[must_use]
812    pub fn declaration(&self, full_name: &str) -> Option<&Decl> {
813        self.declarations
814            .iter()
815            .find(|decl| decl.full_name() == full_name)
816    }
817
818    /// The data declaration named `full_name`.
819    ///
820    /// # Panics
821    /// When there is none; the checker resolves every data type it records.
822    #[must_use]
823    pub fn data(&self, full_name: &str) -> &DataDecl {
824        match self.declaration(full_name) {
825            Some(Decl::Data(decl)) => decl,
826            _ => panic!("no data declaration {full_name}"),
827        }
828    }
829
830    /// Declarations in item order, modules flattened.
831    #[must_use]
832    pub fn flat_items(&self) -> Vec<&Decl> {
833        fn walk<'a>(program: &'a Program, items: &[Item], into: &mut Vec<&'a Decl>) {
834            for item in items {
835                match item {
836                    Item::Decl { full_name } => into.extend(program.declaration(full_name)),
837                    Item::Module { items, .. } => walk(program, items, into),
838                }
839            }
840        }
841        let mut into = Vec::new();
842        walk(self, &self.items, &mut into);
843        into
844    }
845}
846
847/// A per-declaration name supply: target-legal, unique, deterministic.
848#[derive(Clone)]
849pub struct Scope<'a> {
850    ident: &'a dyn Fn(&str) -> String,
851    used: HashSet<String>,
852}
853
854impl<'a> Scope<'a> {
855    pub fn new(ident: &'a dyn Fn(&str) -> String, reserved: &BTreeSet<String>) -> Self {
856        Self {
857            ident,
858            used: reserved.iter().cloned().collect(),
859        }
860    }
861
862    pub fn fresh(&mut self, name: &str) -> String {
863        // A suffixed name is legal on its own: `end_2` needs none of the quoting of Lean's `«end»`.
864        let mut candidate = (self.ident)(name);
865        let mut index = 2;
866        while self.used.contains(&candidate) {
867            candidate = (self.ident)(&format!("{name}_{index}"));
868            index += 1;
869        }
870        self.used.insert(candidate.clone());
871        candidate
872    }
873
874    #[must_use]
875    pub fn child(&self) -> Self {
876        self.clone()
877    }
878}
879
880type Env = HashMap<String, String>;