| // Copyright 2026 The Fuchsia Authors | |
| // | |
| // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| // This file may not be copied, modified, or distributed except according to | |
| // those terms. | |
| //! Pure rendering of the owned syntax. Every emitted token is fixed here or is | |
| //! a numeric/Boolean literal. Function identities use numeric Unicode scalar | |
| //! constructors, so names never enter the emitted command or literal syntax. | |
| use std::cell::RefCell; | |
| use std::fmt::Write as _; | |
| use crate::ir::{ | |
| self, AssertKind, BinOp, CastKind, ConstLit, CoreCallOp, Operand, Place, PlaceElem, | |
| RodataByte, Rvalue, Statement, SysrootNumKind, Terminator, Ty, UnOp, | |
| }; | |
| const LICENSE_PREAMBLE: &str = "-- Copyright 2026 The Fuchsia Authors\n--\n\ | |
| -- Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0\n\ | |
| -- <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT\n\ | |
| -- license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.\n\ | |
| -- This file may not be copied, modified, or distributed except according to\n\ | |
| -- those terms.\n\n"; | |
| const HEADER: &str = "-- Copyright 2026 The Fuchsia Authors\n--\n\ | |
| -- Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0\n\ | |
| -- <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT\n\ | |
| -- license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.\n\ | |
| -- This file may not be copied, modified, or distributed except according to\n\ | |
| -- those terms.\n\n\ | |
| module\nprelude\npublic import Trusted.MirAst\n\n@[expose] public section\n\nnamespace Captured\n\n"; | |
| const MAX_LIST_CHUNK_LEN: usize = 16; | |
| fn join_balanced_with<T>( | |
| chunks: &[T], | |
| indent: Option<usize>, | |
| empty: &str, | |
| join_op: &str, | |
| render_leaf: &impl Fn(&T, Option<usize>) -> String, | |
| ) -> String { | |
| match chunks { | |
| [] => empty.into(), | |
| [single] => render_leaf(single, indent), | |
| _ => { | |
| let mid = chunks.len() / 2; | |
| let (left, right) = chunks.split_at(mid); | |
| match indent { | |
| None => format!( | |
| "({join_op} {} {})", | |
| join_balanced_with(left, None, empty, join_op, render_leaf), | |
| join_balanced_with(right, None, empty, join_op, render_leaf) | |
| ), | |
| Some(col) => { | |
| let child_col = col + 2; | |
| let pad = " ".repeat(child_col); | |
| format!( | |
| "({join_op} {}\n{pad}{})", | |
| join_balanced_with(left, Some(child_col), empty, join_op, render_leaf), | |
| join_balanced_with(right, Some(child_col), empty, join_op, render_leaf) | |
| ) | |
| } | |
| } | |
| } | |
| } | |
| } | |
| fn join_balanced_slice<T>( | |
| chunks: &[T], | |
| indent: Option<usize>, | |
| render_leaf: &impl Fn(&T, Option<usize>) -> String, | |
| ) -> String { | |
| join_balanced_with(chunks, indent, "[]", "_root_.List.append", render_leaf) | |
| } | |
| fn list_literal_at<T>( | |
| values: &[T], | |
| indent: Option<usize>, | |
| render: &impl Fn(&T, Option<usize>) -> String, | |
| ) -> String { | |
| if values.is_empty() { | |
| return "[]".into(); | |
| } | |
| match indent { | |
| None => { | |
| let items: Vec<String> = values.iter().map(|v| render(v, None)).collect(); | |
| format!("[{}]", items.join(", ")) | |
| } | |
| Some(col) => { | |
| let item_col = col + 2; | |
| let item_pad = " ".repeat(item_col); | |
| let close_pad = " ".repeat(col); | |
| let items: Vec<String> = | |
| values.iter().map(|v| format!("{item_pad}{}", render(v, Some(item_col)))).collect(); | |
| format!("[\n{}\n{close_pad}]", items.join(",\n")) | |
| } | |
| } | |
| } | |
| fn list_literal<T>(values: &[T], render: impl Fn(&T) -> String) -> String { | |
| list_literal_at(values, None, &|v, _| render(v)) | |
| } | |
| /// Render a Lean list literal, chunking lists longer than `MAX_LIST_CHUNK_LEN` | |
| /// into a balanced binary tree of `_root_.List.append` over 1..=16-element | |
| /// leaves. | |
| /// | |
| /// Lean 4.34.1 expands `[...]` literals of `>= 33` elements via | |
| /// `Init.NotationExtra`'s `%[...|...]` macro into nested `let` bindings, which | |
| /// adds elaboration recursion overhead on top of per-element `OfNat` synthesis | |
| /// (e.g., failing elaboration with `maximum recursion depth has been reached` | |
| /// at `~1950+` distinct `Nat` literals in one definition, while chunking passes | |
| /// up to `~2000`). `_root_.List.append` lives in `Init.Prelude`, avoids | |
| /// namespace shadowing under `namespace Captured`, preserves `rfl` definitional | |
| /// equality with a flat list in the Lean kernel, and bounds AST depth to | |
| /// `O(log N)` (note `List.length` by `rfl` and `2050+` distinct `OfNat`s in | |
| /// one definition still hit Lean's `maxRecDepth` limit independently of list | |
| /// representation). | |
| fn list<T>(values: &[T], render: impl Fn(&T) -> String) -> String { | |
| let chunks: Vec<&[T]> = values.chunks(MAX_LIST_CHUNK_LEN).collect(); | |
| join_balanced_slice(&chunks, None, &|chunk, _| list_literal(chunk, &render)) | |
| } | |
| fn list_pretty<T>(values: &[T], indent: usize, render: impl Fn(&T, usize) -> String) -> String { | |
| let chunks: Vec<&[T]> = values.chunks(MAX_LIST_CHUNK_LEN).collect(); | |
| join_balanced_slice(&chunks, Some(indent), &|chunk, chunk_indent| { | |
| list_literal_at(chunk, chunk_indent, &|item, item_indent| { | |
| render(item, item_indent.unwrap_or(indent)) | |
| }) | |
| }) | |
| } | |
| fn list_chunk_lines<T>(values: &[T], indent: usize, render: impl Fn(&T) -> String) -> String { | |
| let chunks: Vec<&[T]> = values.chunks(MAX_LIST_CHUNK_LEN).collect(); | |
| if chunks.len() <= 1 { | |
| list(values, render) | |
| } else { | |
| join_balanced_slice(&chunks, Some(indent), &|chunk, _| list_literal(chunk, &render)) | |
| } | |
| } | |
| /// The `MirTy.recAdt` types of one rendered module, each emitted once as a | |
| /// `def ty_<k> : Trusted.MirAst.MirTy` that the module's bodies name. | |
| /// | |
| /// A recursive ADT's type carries its whole definition, so inlining it at every | |
| /// local, operand, and projection that mentions it multiplies its size by the | |
| /// number of uses. A crate-local enum nesting other recursive ADTs rendered to | |
| /// a 6.5 MB module whose largest body exceeded Lean's elaboration heartbeat | |
| /// limit. A `def` unfolds to its right-hand side, so naming a type changes | |
| /// nothing that `rfl`, `decide`, or kernel reduction can observe. | |
| #[derive(Default)] | |
| struct TyDefs { | |
| /// Each hoisted type with its rendered right-hand side, in definition | |
| /// order: the `recAdt` types nested in a type precede it. | |
| defs: RefCell<Vec<(Ty, String)>>, | |
| } | |
| impl TyDefs { | |
| fn name(index: usize) -> String { | |
| format!("ty_{index}") | |
| } | |
| /// The name of `t`'s definition, adding one with right-hand side `rhs()` | |
| /// if `t` has none yet. | |
| fn reference(&self, t: &Ty, rhs: impl FnOnce() -> String) -> String { | |
| if let Some(index) = self.defs.borrow().iter().position(|(u, _)| u == t) { | |
| return Self::name(index); | |
| } | |
| // `rhs` adds the types nested in `t`, so no borrow is held across it. | |
| let rhs = rhs(); | |
| let mut defs = self.defs.borrow_mut(); | |
| defs.push((t.clone(), rhs)); | |
| Self::name(defs.len() - 1) | |
| } | |
| fn render_defs(&self) -> String { | |
| let mut out = String::new(); | |
| for (index, (_, rhs)) in self.defs.borrow().iter().enumerate() { | |
| let name = Self::name(index); | |
| let _ = writeln!(out, "def {name} : Trusted.MirAst.MirTy :=\n {rhs}\n"); | |
| } | |
| out | |
| } | |
| } | |
| /// Render `def body_<i>` for each of `bodies`, preceded by the `def ty_<k>` | |
| /// definitions they share ([`TyDefs`]), and return the text with the body | |
| /// definition names. | |
| fn body_defs(bodies: &[ir::Body]) -> (String, Vec<String>) { | |
| let tys = TyDefs::default(); | |
| let mut body_text = String::new(); | |
| let mut names = Vec::with_capacity(bodies.len()); | |
| for (index, item) in bodies.iter().enumerate() { | |
| let name = format!("body_{index}"); | |
| write_body_def(&mut body_text, &tys, &name, item); | |
| names.push(name); | |
| } | |
| let mut out = tys.render_defs(); | |
| out.push_str(&body_text); | |
| (out, names) | |
| } | |
| fn ty_at(tys: &TyDefs, t: &Ty, indent: usize) -> String { | |
| match t { | |
| Ty::Bool => "Trusted.MirAst.MirTy.bool".into(), | |
| Ty::Char => "Trusted.MirAst.MirTy.char".into(), | |
| Ty::Ordering => "Trusted.MirAst.MirTy.ordering".into(), | |
| Ty::Unit => "Trusted.MirAst.MirTy.unit".into(), | |
| Ty::Never => "Trusted.MirAst.MirTy.never".into(), | |
| Ty::Int(ity) => format!( | |
| "(Trusted.MirAst.MirTy.int Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| Ty::OverflowPair(ity) => format!( | |
| "(Trusted.MirAst.MirTy.tuple [(Trusted.MirAst.MirTy.int Trusted.MirAst.IntWidth.{} {}), Trusted.MirAst.MirTy.bool])", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| Ty::Tuple { fields } => format!( | |
| "(Trusted.MirAst.MirTy.tuple {})", | |
| list_pretty(fields, indent, |v, i| ty_at(tys, v, i)) | |
| ), | |
| Ty::Ref { | |
| mutability, | |
| pointee, | |
| } => format!( | |
| "(Trusted.MirAst.MirTy.ref Trusted.MirAst.Mutability.{} {})", | |
| mutability.lean_name(), | |
| ty_at(tys, pointee, indent) | |
| ), | |
| Ty::RawPtr { | |
| mutability, | |
| pointee, | |
| } => format!( | |
| "(Trusted.MirAst.MirTy.rawPtr Trusted.MirAst.Mutability.{} {})", | |
| mutability.lean_name(), | |
| ty_at(tys, pointee, indent) | |
| ), | |
| Ty::Slice { elem } => format!("(Trusted.MirAst.MirTy.slice {})", ty_at(tys, elem, indent)), | |
| Ty::Str => "Trusted.MirAst.MirTy.str".into(), | |
| Ty::Array { elem, len } => { | |
| format!("(Trusted.MirAst.MirTy.array {} {len})", ty_at(tys, elem, indent)) | |
| } | |
| Ty::Vec { elem } => format!("(Trusted.MirAst.MirTy.vec {})", ty_at(tys, elem, indent)), | |
| Ty::Box { pointee } => { | |
| format!("(Trusted.MirAst.MirTy.box {})", ty_at(tys, pointee, indent)) | |
| } | |
| Ty::Struct(sty) => { | |
| let layout = sty.layout(); | |
| format!( | |
| "(Trusted.MirAst.MirTy.struct_ (Trusted.MirAst.StructLayout.mk {} {} {} {}) {})", | |
| layout.id(), | |
| layout.size(), | |
| layout.align_log2(), | |
| list(layout.field_offsets(), usize::to_string), | |
| list_pretty(sty.fields(), indent, |v, i| ty_at(tys, v, i)) | |
| ) | |
| } | |
| Ty::RangeTo { elem } => { | |
| format!("(Trusted.MirAst.MirTy.rangeTo {})", ty_at(tys, elem, indent)) | |
| } | |
| Ty::RangeFrom { elem } => { | |
| format!("(Trusted.MirAst.MirTy.rangeFrom {})", ty_at(tys, elem, indent)) | |
| } | |
| Ty::Range { elem } => format!("(Trusted.MirAst.MirTy.range {})", ty_at(tys, elem, indent)), | |
| Ty::Option { elem } => { | |
| format!("(Trusted.MirAst.MirTy.option {})", ty_at(tys, elem, indent)) | |
| } | |
| Ty::RecAdt { id, defn } => tys.reference(t, || { | |
| format!("(Trusted.MirAst.MirTy.recAdt {id} {})", ty_at(tys, defn, 2)) | |
| }), | |
| Ty::RecSelf { id } => format!("(Trusted.MirAst.MirTy.recSelf {id})"), | |
| Ty::AdtEnum(aty) => { | |
| let l = aty.layout(); | |
| let encoding = match l.encoding() { | |
| ir::AdtTagEncoding::Single => "Trusted.MirAst.AdtTagEncoding.single".into(), | |
| ir::AdtTagEncoding::Direct => "Trusted.MirAst.AdtTagEncoding.direct".into(), | |
| ir::AdtTagEncoding::Niche { untagged, first, last, start } => format!( | |
| "(Trusted.MirAst.AdtTagEncoding.niche {untagged} {first} {last} {start})" | |
| ), | |
| }; | |
| let (valid_start, valid_end) = l.tag_valid_range(); | |
| let field_pad = " ".repeat(indent + 2); | |
| let close_pad = " ".repeat(indent); | |
| let discriminants = list_chunk_lines(l.discriminants(), indent + 2, u128::to_string); | |
| format!( | |
| "(Trusted.MirAst.MirTy.adtEnum {{\n\ | |
| {field_pad}id := {},\n\ | |
| {field_pad}size := {},\n\ | |
| {field_pad}alignLog2 := {},\n\ | |
| {field_pad}discrWidth := Trusted.MirAst.IntWidth.{},\n\ | |
| {field_pad}discrSigned := {},\n\ | |
| {field_pad}discriminants := {discriminants},\n\ | |
| {field_pad}tagOffset := {},\n\ | |
| {field_pad}tagWidth := Trusted.MirAst.IntWidth.{},\n\ | |
| {field_pad}tagSigned := {},\n\ | |
| {field_pad}tagValidStart := {valid_start},\n\ | |
| {field_pad}tagValidEnd := {valid_end},\n\ | |
| {field_pad}encoding := {encoding}\n\ | |
| {close_pad}}} {})", | |
| l.id(), | |
| l.size(), | |
| l.align_log2(), | |
| l.discr().width.lean_name(), | |
| l.discr().signed, | |
| l.tag_offset(), | |
| l.tag().width.lean_name(), | |
| l.tag().signed, | |
| list_pretty(aty.variants(), indent, |v, i| ty_at(tys, v, i)), | |
| ) | |
| } | |
| Ty::Enum(ety) => { | |
| let tag_repr = match ety.tag_repr() { | |
| ir::EnumTagRepr::ZeroSized => "Trusted.MirAst.EnumTagRepr.zeroSized".into(), | |
| ir::EnumTagRepr::Scalar(tag) => format!( | |
| "(Trusted.MirAst.EnumTagRepr.scalar Trusted.MirAst.IntWidth.{} {})", | |
| tag.width.lean_name(), | |
| tag.signed | |
| ), | |
| }; | |
| let discr = ety.discr(); | |
| let field_pad = " ".repeat(indent + 2); | |
| let close_pad = " ".repeat(indent); | |
| let discriminants = list_chunk_lines(ety.discriminants(), indent + 2, u128::to_string); | |
| format!( | |
| "(Trusted.MirAst.MirTy.enum {{\n\ | |
| {field_pad}id := {},\n\ | |
| {field_pad}discrWidth := Trusted.MirAst.IntWidth.{},\n\ | |
| {field_pad}discrSigned := {},\n\ | |
| {field_pad}tagRepr := {tag_repr},\n\ | |
| {field_pad}discriminants := {discriminants}\n\ | |
| {close_pad}}})", | |
| ety.id(), | |
| discr.width.lean_name(), | |
| discr.signed, | |
| ) | |
| } | |
| } | |
| } | |
| fn rodata_bytes_at(bytes: &[RodataByte], indent: usize) -> String { | |
| list_chunk_lines(bytes, indent, |b| match b { | |
| RodataByte::Uninit => "Trusted.MirAst.RodataByte.uninit".into(), | |
| RodataByte::Init { byte } => format!("(Trusted.MirAst.RodataByte.init {byte})"), | |
| }) | |
| } | |
| fn const_lit_at(lit: &ConstLit, indent: usize) -> String { | |
| match lit { | |
| ConstLit::ZeroSized => "Trusted.MirAst.ConstLit.zeroSized".into(), | |
| ConstLit::Scalar { bits } => { | |
| format!("(Trusted.MirAst.ConstLit.scalar (BitVec.ofNat 128 {bits}))") | |
| } | |
| ConstLit::RodataBytes { bytes } => { | |
| format!( | |
| "(Trusted.MirAst.ConstLit.rodataBytes {})", | |
| rodata_bytes_at(bytes, indent + 2) | |
| ) | |
| } | |
| ConstLit::RodataRef { | |
| bytes, | |
| align_log2, | |
| offset_bytes, | |
| slice_len, | |
| } => { | |
| let slice_str = match slice_len { | |
| None => "none".into(), | |
| Some(n) => format!("(some {n})"), | |
| }; | |
| format!( | |
| "(Trusted.MirAst.ConstLit.rodataRef {} {align_log2} {offset_bytes} {slice_str})", | |
| rodata_bytes_at(bytes, indent + 2) | |
| ) | |
| } | |
| } | |
| } | |
| fn place_at(tys: &TyDefs, place: &Place, indent: usize) -> String { | |
| if place.projection.is_empty() { | |
| format!("(Trusted.MirAst.Place.mk {} [])", place.local) | |
| } else { | |
| let projs = list(&place.projection, |elem| match elem { | |
| PlaceElem::Deref => "Trusted.MirAst.ProjectionElem.deref".into(), | |
| PlaceElem::Field { index, ty } => format!( | |
| "(Trusted.MirAst.ProjectionElem.field {index} {})", | |
| ty_at(tys, ty, indent) | |
| ), | |
| PlaceElem::ConstantIndex { | |
| offset, | |
| min_length, | |
| from_end, | |
| } => format!( | |
| "(Trusted.MirAst.ProjectionElem.constantIndex {offset} {min_length} {from_end})" | |
| ), | |
| PlaceElem::Downcast { variant_idx } => { | |
| format!("(Trusted.MirAst.ProjectionElem.downcast {variant_idx})") | |
| } | |
| PlaceElem::Index { local } => { | |
| format!("(Trusted.MirAst.ProjectionElem.index {local})") | |
| } | |
| }); | |
| format!("(Trusted.MirAst.Place.mk {} {projs})", place.local) | |
| } | |
| } | |
| fn operand_at(tys: &TyDefs, op: &Operand, indent: usize) -> String { | |
| match op { | |
| Operand::Copy { local } => { | |
| format!("(Trusted.MirAst.Operand.copy (Trusted.MirAst.Place.mk {local} []))") | |
| } | |
| Operand::Move { local } => { | |
| format!("(Trusted.MirAst.Operand.move (Trusted.MirAst.Place.mk {local} []))") | |
| } | |
| Operand::CopyPlace { place } => { | |
| format!("(Trusted.MirAst.Operand.copy {})", place_at(tys, place, indent)) | |
| } | |
| Operand::MovePlace { place } => { | |
| format!("(Trusted.MirAst.Operand.move {})", place_at(tys, place, indent)) | |
| } | |
| Operand::Constant { ty: t, lit } => format!( | |
| "(Trusted.MirAst.Operand.constant (Trusted.MirAst.ConstOperand.mk {} {}))", | |
| ty_at(tys, t, indent), | |
| const_lit_at(lit, indent) | |
| ), | |
| } | |
| } | |
| fn un_op(op: UnOp) -> &'static str { | |
| match op { | |
| UnOp::Not => "not", | |
| UnOp::Neg => "neg", | |
| UnOp::PtrMetadata => "ptrMetadata", | |
| } | |
| } | |
| fn cast_kind(kind: CastKind) -> &'static str { | |
| match kind { | |
| CastKind::IntToInt => "intToInt", | |
| CastKind::PtrToPtr => "ptrToPtr", | |
| CastKind::IntToPtr => "intToPtr", | |
| CastKind::Unsize => "unsize", | |
| CastKind::BoxAsRawPtr => unreachable!("refused by ir::check_cast_types"), | |
| CastKind::BoxAsRef => "boxAsRef", | |
| } | |
| } | |
| fn bin_op(op: BinOp) -> &'static str { | |
| match op { | |
| BinOp::BitAnd => "bitAnd", | |
| BinOp::BitOr => "bitOr", | |
| BinOp::BitXor => "bitXor", | |
| BinOp::Shl => "shl", | |
| BinOp::Shr => "shr", | |
| BinOp::Add => "add", | |
| BinOp::Sub => "sub", | |
| BinOp::Mul => "mul", | |
| BinOp::AddUnchecked => "addUnchecked", | |
| BinOp::SubUnchecked => "subUnchecked", | |
| BinOp::MulUnchecked => "mulUnchecked", | |
| BinOp::Div => "div", | |
| BinOp::Rem => "rem", | |
| BinOp::AddWithOverflow => "addWithOverflow", | |
| BinOp::SubWithOverflow => "subWithOverflow", | |
| BinOp::MulWithOverflow => "mulWithOverflow", | |
| BinOp::Eq => "eq", | |
| BinOp::Ne => "ne", | |
| BinOp::Lt => "lt", | |
| BinOp::Le => "le", | |
| BinOp::Gt => "gt", | |
| BinOp::Ge => "ge", | |
| BinOp::Cmp => "cmp", | |
| BinOp::Offset => "offset", | |
| } | |
| } | |
| fn rvalue_at(tys: &TyDefs, value: &Rvalue, indent: usize) -> String { | |
| match value { | |
| // `ir::Body::try_new` admits `with_retag == true` only when the | |
| // destination type satisfies `Ty::is_retag_noop()`. | |
| Rvalue::Use { operand: op, .. } => { | |
| format!("(Trusted.MirAst.Rvalue.use {})", operand_at(tys, op, indent)) | |
| } | |
| Rvalue::UseRetag { operand: op } => { | |
| format!("(Trusted.MirAst.Rvalue.useRetag {})", operand_at(tys, op, indent)) | |
| } | |
| Rvalue::Binary { op, left, right } => format!( | |
| "(Trusted.MirAst.Rvalue.binaryOp Trusted.MirAst.BinOp.{} {} {})", | |
| bin_op(*op), | |
| operand_at(tys, left, indent), | |
| operand_at(tys, right, indent) | |
| ), | |
| Rvalue::Unary { op, operand: opnd } => format!( | |
| "(Trusted.MirAst.Rvalue.unaryOp Trusted.MirAst.UnOp.{} {})", | |
| un_op(*op), | |
| operand_at(tys, opnd, indent) | |
| ), | |
| Rvalue::Cast { | |
| cast_kind: kind, | |
| operand: opnd, | |
| ty: target_ty, | |
| } => format!( | |
| "(Trusted.MirAst.Rvalue.cast Trusted.MirAst.CastKind.{} {} {})", | |
| cast_kind(*kind), | |
| operand_at(tys, opnd, indent), | |
| ty_at(tys, target_ty, indent) | |
| ), | |
| Rvalue::Discriminant { place } => { | |
| format!("(Trusted.MirAst.Rvalue.discriminant {})", place_at(tys, place, indent)) | |
| } | |
| Rvalue::Ref { mutability, place } => format!( | |
| "(Trusted.MirAst.Rvalue.ref Trusted.MirAst.Mutability.{} {})", | |
| mutability.lean_name(), | |
| place_at(tys, place, indent) | |
| ), | |
| Rvalue::AddressOf { mutability, place } => format!( | |
| "(Trusted.MirAst.Rvalue.addressOf Trusted.MirAst.Mutability.{} {})", | |
| mutability.lean_name(), | |
| place_at(tys, place, indent) | |
| ), | |
| Rvalue::FakeAddressOf { place } => format!( | |
| "(Trusted.MirAst.Rvalue.fakeAddressOf {})", | |
| place_at(tys, place, indent) | |
| ), | |
| Rvalue::AggregateTuple { fields } => format!( | |
| "(Trusted.MirAst.Rvalue.aggregateTuple {})", | |
| list_pretty(fields, indent, |v, i| operand_at(tys, v, i)) | |
| ), | |
| Rvalue::AggregateArray { elem_ty, elems } => format!( | |
| "(Trusted.MirAst.Rvalue.aggregateArray {} {})", | |
| ty_at(tys, elem_ty, indent), | |
| list_pretty(elems, indent, |v, i| operand_at(tys, v, i)) | |
| ), | |
| Rvalue::AggregateStruct { ty, fields } => format!( | |
| "(Trusted.MirAst.Rvalue.aggregateStruct {} {})", | |
| ty_at(tys, ty, indent), | |
| list_pretty(fields, indent, |v, i| operand_at(tys, v, i)) | |
| ), | |
| Rvalue::AggregateAdtEnum { ty, variant_idx, fields } => format!( | |
| "(Trusted.MirAst.Rvalue.aggregateAdtEnum {} {variant_idx} {})", | |
| ty_at(tys, ty, indent), | |
| list_pretty(fields, indent, |v, i| operand_at(tys, v, i)) | |
| ), | |
| Rvalue::Repeat { | |
| operand, | |
| elem_ty, | |
| count, | |
| } => format!( | |
| "(Trusted.MirAst.Rvalue.repeat_ {} {} {count})", | |
| operand_at(tys, operand, indent), | |
| ty_at(tys, elem_ty, indent) | |
| ), | |
| Rvalue::AggregateRangeTo { elem_ty, end } => format!( | |
| "(Trusted.MirAst.Rvalue.aggregateRangeTo {} {})", | |
| ty_at(tys, elem_ty, indent), | |
| operand_at(tys, end, indent) | |
| ), | |
| Rvalue::AggregateRangeFrom { elem_ty, start } => format!( | |
| "(Trusted.MirAst.Rvalue.aggregateRangeFrom {} {})", | |
| ty_at(tys, elem_ty, indent), | |
| operand_at(tys, start, indent) | |
| ), | |
| Rvalue::AggregateRange { | |
| elem_ty, | |
| start, | |
| end, | |
| } => format!( | |
| "(Trusted.MirAst.Rvalue.aggregateRange {} {} {})", | |
| ty_at(tys, elem_ty, indent), | |
| operand_at(tys, start, indent), | |
| operand_at(tys, end, indent) | |
| ), | |
| Rvalue::AggregateOption { | |
| variant_idx, | |
| inner_ty, | |
| payload, | |
| } => { | |
| let p_str = match payload { | |
| None => "none".into(), | |
| Some(op) => format!("(some {})", operand_at(tys, op, indent)), | |
| }; | |
| format!( | |
| "(Trusted.MirAst.Rvalue.aggregateOption {variant_idx} {} {p_str})", | |
| ty_at(tys, inner_ty, indent) | |
| ) | |
| } | |
| Rvalue::AggregateOrdering { tag_bits } => { | |
| format!("(Trusted.MirAst.Rvalue.aggregateOrdering {tag_bits})") | |
| } | |
| } | |
| } | |
| fn statement_at(tys: &TyDefs, stmt: &Statement, indent: usize) -> String { | |
| match stmt { | |
| Statement::Assign { local, value } => format!( | |
| "(Trusted.MirAst.StatementKind.assign (Trusted.MirAst.Place.mk {local} []) {})", | |
| rvalue_at(tys, value, indent) | |
| ), | |
| Statement::AssignPlace { place, value } => format!( | |
| "(Trusted.MirAst.StatementKind.assign {} {})", | |
| place_at(tys, place, indent), | |
| rvalue_at(tys, value, indent) | |
| ), | |
| Statement::StorageLive { local } => { | |
| format!("(Trusted.MirAst.StatementKind.storageLive {local})") | |
| } | |
| Statement::StorageDead { local } => { | |
| format!("(Trusted.MirAst.StatementKind.storageDead {local})") | |
| } | |
| // `extract::statement` records a `PlaceMention` with projections as | |
| // `Statement::PlaceMentionPlace`, and | |
| // `ir::Body::try_new` admits `Statement::PlaceMention` only for an | |
| // in-bounds `Sized` local, where `rustc`'s `eval_place` | |
| // (`local_to_place`) and `lean-miri`'s `Step.evalStatement` perform no | |
| // memory load and no liveness check. | |
| Statement::PlaceMention { .. } | Statement::Nop => "Trusted.MirAst.StatementKind.nop".into(), | |
| Statement::PlaceMentionPlace { place } => { | |
| format!("(Trusted.MirAst.StatementKind.placeMention {})", place_at(tys, place, indent)) | |
| } | |
| } | |
| } | |
| fn assert_kind(kind: AssertKind) -> String { | |
| match kind { | |
| AssertKind::Overflow { op } => { | |
| format!("(Trusted.MirAst.AssertKind.overflow Trusted.MirAst.BinOp.{})", bin_op(op)) | |
| } | |
| AssertKind::OverflowNeg => "Trusted.MirAst.AssertKind.overflowNeg".into(), | |
| AssertKind::DivByZero => "Trusted.MirAst.AssertKind.divByZero".into(), | |
| AssertKind::RemByZero => "Trusted.MirAst.AssertKind.remByZero".into(), | |
| AssertKind::BoundsCheck => "Trusted.MirAst.AssertKind.boundsCheck".into(), | |
| AssertKind::MisalignedPtrDeref => "Trusted.MirAst.AssertKind.misalignedPtrDeref".into(), | |
| AssertKind::NullPtrDeref => "Trusted.MirAst.AssertKind.nullPtrDeref".into(), | |
| } | |
| } | |
| fn core_call_op(tys: &TyDefs, op: &CoreCallOp, indent: usize) -> String { | |
| match op { | |
| CoreCallOp::SliceLen => "Trusted.MirAst.CoreCallOp.sliceLen".into(), | |
| CoreCallOp::SliceGetUncheckedRangeTo => { | |
| "Trusted.MirAst.CoreCallOp.sliceGetUncheckedRangeTo".into() | |
| } | |
| CoreCallOp::SliceGetUncheckedRangeFrom => { | |
| "Trusted.MirAst.CoreCallOp.sliceGetUncheckedRangeFrom".into() | |
| } | |
| CoreCallOp::SliceGetUncheckedRange => { | |
| "Trusted.MirAst.CoreCallOp.sliceGetUncheckedRange".into() | |
| } | |
| CoreCallOp::SliceGetUncheckedIndex => { | |
| "Trusted.MirAst.CoreCallOp.sliceGetUncheckedIndex".into() | |
| } | |
| CoreCallOp::PtrAdd { | |
| mutability, | |
| pointee, | |
| } => format!( | |
| "(Trusted.MirAst.CoreCallOp.ptrAdd Trusted.MirAst.Mutability.{} {})", | |
| mutability.lean_name(), | |
| ty_at(tys, pointee, indent) | |
| ), | |
| CoreCallOp::SliceIndexRange { mutability, elem } => format!( | |
| "(Trusted.MirAst.CoreCallOp.sliceIndexRange Trusted.MirAst.Mutability.{} {})", | |
| mutability.lean_name(), | |
| ty_at(tys, elem, indent) | |
| ), | |
| CoreCallOp::SliceIndexRangeFrom { mutability, elem } => format!( | |
| "(Trusted.MirAst.CoreCallOp.sliceIndexRangeFrom Trusted.MirAst.Mutability.{} {})", | |
| mutability.lean_name(), | |
| ty_at(tys, elem, indent) | |
| ), | |
| CoreCallOp::SliceIsEmpty { elem } => { | |
| format!("(Trusted.MirAst.CoreCallOp.sliceIsEmpty {})", ty_at(tys, elem, indent)) | |
| } | |
| CoreCallOp::SliceSplitAt { mutability, elem } => format!( | |
| "(Trusted.MirAst.CoreCallOp.sliceSplitAt Trusted.MirAst.Mutability.{} {})", | |
| mutability.lean_name(), | |
| ty_at(tys, elem, indent) | |
| ), | |
| CoreCallOp::NumIsMultipleOf(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numIsMultipleOf Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumNextMultipleOf(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numNextMultipleOf Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumDivCeil(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numDivCeil Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumCheckedAdd(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numCheckedAdd Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumCheckedMul(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numCheckedMul Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumCheckedSub(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numCheckedSub Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumCheckedShl(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numCheckedShl Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumSaturatingAdd(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numSaturatingAdd Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumWrappingShl(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numWrappingShl Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumWrappingShr(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numWrappingShr Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumLeadingZeros(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numLeadingZeros Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumCountOnes(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numCountOnes Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumTrailingZeros(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numTrailingZeros Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumNextPowerOfTwo(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numNextPowerOfTwo Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumOverflowingAdd(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numOverflowingAdd Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumOverflowingSub(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numOverflowingSub Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::NumOverflowingMul(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.numOverflowingMul Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::CmpMin(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.cmpMin Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::CmpMax(ity) => format!( | |
| "(Trusted.MirAst.CoreCallOp.cmpMax Trusted.MirAst.IntWidth.{} {})", | |
| ity.width.lean_name(), | |
| ity.signed | |
| ), | |
| CoreCallOp::MemReplace { ty } => { | |
| format!("(Trusted.MirAst.CoreCallOp.memReplace {})", ty_at(tys, ty, indent)) | |
| } | |
| CoreCallOp::MemSizeOf { ty } => { | |
| format!("(Trusted.MirAst.CoreCallOp.memSizeOf {})", ty_at(tys, ty, indent)) | |
| } | |
| CoreCallOp::OptionIsSome { inner } => { | |
| format!("(Trusted.MirAst.CoreCallOp.optionIsSome {})", ty_at(tys, inner, indent)) | |
| } | |
| CoreCallOp::OptionIsNone { inner } => { | |
| format!("(Trusted.MirAst.CoreCallOp.optionIsNone {})", ty_at(tys, inner, indent)) | |
| } | |
| CoreCallOp::OptionTake { inner } => { | |
| format!("(Trusted.MirAst.CoreCallOp.optionTake {})", ty_at(tys, inner, indent)) | |
| } | |
| CoreCallOp::OptionUnwrap { inner } => { | |
| format!("(Trusted.MirAst.CoreCallOp.optionUnwrap {})", ty_at(tys, inner, indent)) | |
| } | |
| CoreCallOp::TryBranchResult { ok, err } => format!( | |
| "(Trusted.MirAst.CoreCallOp.tryBranchResult {} {})", | |
| ty_at(tys, ok, indent), | |
| ty_at(tys, err, indent) | |
| ), | |
| CoreCallOp::TryBranchOption { inner } => { | |
| format!("(Trusted.MirAst.CoreCallOp.tryBranchOption {})", ty_at(tys, inner, indent)) | |
| } | |
| CoreCallOp::FromResidualResult { ok, err } => format!( | |
| "(Trusted.MirAst.CoreCallOp.fromResidualResult {} {})", | |
| ty_at(tys, ok, indent), | |
| ty_at(tys, err, indent) | |
| ), | |
| CoreCallOp::FromResidualOption { inner } => { | |
| format!("(Trusted.MirAst.CoreCallOp.fromResidualOption {})", ty_at(tys, inner, indent)) | |
| } | |
| CoreCallOp::DefaultVal { ty } => { | |
| format!("(Trusted.MirAst.CoreCallOp.defaultVal {})", ty_at(tys, ty, indent)) | |
| } | |
| CoreCallOp::RefIntPartialEq { int_ty, is_ne } => format!( | |
| "(Trusted.MirAst.CoreCallOp.refIntPartialEq Trusted.MirAst.IntWidth.{} {} {is_ne})", | |
| int_ty.width.lean_name(), | |
| int_ty.signed | |
| ), | |
| CoreCallOp::UnitPartialEq { is_ne } => { | |
| format!("(Trusted.MirAst.CoreCallOp.unitPartialEq {is_ne})") | |
| } | |
| CoreCallOp::ScalarClone { ty } => { | |
| format!("(Trusted.MirAst.CoreCallOp.scalarClone {})", ty_at(tys, ty, indent)) | |
| } | |
| CoreCallOp::UsizeUncheckedSub => "Trusted.MirAst.CoreCallOp.usizeUncheckedSub".into(), | |
| CoreCallOp::IntToLeBytes { int_ty } => format!( | |
| "(Trusted.MirAst.CoreCallOp.intToLeBytes Trusted.MirAst.IntWidth.{} {})", | |
| int_ty.width.lean_name(), | |
| int_ty.signed | |
| ), | |
| CoreCallOp::IntFromLeBytes { int_ty } => format!( | |
| "(Trusted.MirAst.CoreCallOp.intFromLeBytes Trusted.MirAst.IntWidth.{} {})", | |
| int_ty.width.lean_name(), | |
| int_ty.signed | |
| ), | |
| CoreCallOp::ArrayEq { elem, len } => { | |
| format!("(Trusted.MirAst.CoreCallOp.arrayEq {} {len})", ty_at(tys, elem, indent)) | |
| } | |
| CoreCallOp::VecNew { elem } => { | |
| format!("(Trusted.MirAst.CoreCallOp.vecNew {})", ty_at(tys, elem, indent)) | |
| } | |
| CoreCallOp::VecWithCapacity { elem } => format!( | |
| "(Trusted.MirAst.CoreCallOp.vecWithCapacity {})", | |
| ty_at(tys, elem, indent) | |
| ), | |
| CoreCallOp::PanicAbort => "Trusted.MirAst.CoreCallOp.panicAbort".into(), | |
| CoreCallOp::VecLen => "Trusted.MirAst.CoreCallOp.vecLen".into(), | |
| CoreCallOp::VecPush => "Trusted.MirAst.CoreCallOp.vecPush".into(), | |
| CoreCallOp::VecResize => "Trusted.MirAst.CoreCallOp.vecResize".into(), | |
| CoreCallOp::VecExtendFromSlice => { | |
| "Trusted.MirAst.CoreCallOp.vecExtendFromSlice".into() | |
| } | |
| CoreCallOp::VecIndex => "Trusted.MirAst.CoreCallOp.vecIndex".into(), | |
| CoreCallOp::VecIndexMut => "Trusted.MirAst.CoreCallOp.vecIndexMut".into(), | |
| CoreCallOp::VecDeref => "Trusted.MirAst.CoreCallOp.vecDeref".into(), | |
| CoreCallOp::VecDerefMut => "Trusted.MirAst.CoreCallOp.vecDerefMut".into(), | |
| CoreCallOp::VecReserve => "Trusted.MirAst.CoreCallOp.vecReserve".into(), | |
| CoreCallOp::BoxFromVec => "Trusted.MirAst.CoreCallOp.boxFromVec".into(), | |
| CoreCallOp::BoxDeref => "Trusted.MirAst.CoreCallOp.boxDeref".into(), | |
| CoreCallOp::BoxDerefMut => "Trusted.MirAst.CoreCallOp.boxDerefMut".into(), | |
| CoreCallOp::BoxClone => "Trusted.MirAst.CoreCallOp.boxClone".into(), | |
| CoreCallOp::BoxNew { pointee } => format!( | |
| "(Trusted.MirAst.CoreCallOp.boxNew {})", | |
| ty_at(tys, pointee, indent) | |
| ), | |
| CoreCallOp::PartialEqNe { ty } => { | |
| format!("(Trusted.MirAst.CoreCallOp.partialEqNe {})", ty_at(tys, ty, indent)) | |
| } | |
| } | |
| } | |
| fn terminator_at(tys: &TyDefs, term: &Terminator, indent: usize) -> String { | |
| match term { | |
| Terminator::Goto { block } => { | |
| format!("(Trusted.MirAst.TerminatorKind.goto {block})") | |
| } | |
| Terminator::SwitchInt { | |
| operand: op, | |
| targets, | |
| otherwise, | |
| } => { | |
| let child_pad = " ".repeat(indent + 2); | |
| let target_pad = " ".repeat(indent + 4); | |
| format!( | |
| "(Trusted.MirAst.TerminatorKind.switchInt\n\ | |
| {child_pad}{}\n\ | |
| {child_pad}(Trusted.MirAst.SwitchTargets.mk\n\ | |
| {target_pad}{}\n\ | |
| {target_pad}{otherwise}))", | |
| operand_at(tys, op, indent + 2), | |
| list_pretty(targets, indent + 4, |(value, block), _| format!( | |
| "((BitVec.ofNat 128 {value}), {block})" | |
| )) | |
| ) | |
| } | |
| // `Assert` and returning `Call` keep their captured `UnwindAction` | |
| // (`ir::UnwindAction`, without the upstream terminate reason) rather | |
| // than a fixed `continue_`. | |
| Terminator::Assert { | |
| cond, | |
| expected, | |
| msg, | |
| target, | |
| unwind, | |
| } => format!( | |
| "(Trusted.MirAst.TerminatorKind.assert {} {expected} {} {target} Trusted.MirAst.UnwindAction.{})", | |
| operand_at(tys, cond, indent + 2), | |
| assert_kind(*msg), | |
| unwind.lean_name(), | |
| ), | |
| Terminator::CoreCall { | |
| op, | |
| args, | |
| dst, | |
| target, | |
| unwind, | |
| } => { | |
| let target_str = match target { | |
| Some(block) => format!("(some {block})"), | |
| None => "none".into(), | |
| }; | |
| format!( | |
| "(Trusted.MirAst.TerminatorKind.coreCall {} {} {} \ | |
| {target_str} Trusted.MirAst.UnwindAction.{})", | |
| core_call_op(tys, op, indent + 2), | |
| list_pretty(args, indent + 2, |v, i| operand_at(tys, v, i)), | |
| place_at(tys, dst, indent + 2), | |
| unwind.lean_name(), | |
| ) | |
| } | |
| Terminator::Drop { | |
| place, | |
| target, | |
| unwind, | |
| } => format!( | |
| "(Trusted.MirAst.TerminatorKind.drop {} {target} Trusted.MirAst.UnwindAction.{})", | |
| place_at(tys, place, indent + 2), | |
| unwind.lean_name(), | |
| ), | |
| Terminator::Ret => "Trusted.MirAst.TerminatorKind.return_".into(), | |
| Terminator::Unreachable => "Trusted.MirAst.TerminatorKind.unreachable".into(), | |
| Terminator::Unsupported => "Trusted.MirAst.TerminatorKind.unsupported".into(), | |
| Terminator::Call { | |
| callee, | |
| args, | |
| dst, | |
| target, | |
| unwind, | |
| } => { | |
| let child_pad = " ".repeat(indent + 2); | |
| format!( | |
| "(Trusted.MirAst.TerminatorKind.call\n\ | |
| {child_pad}{callee}\n\ | |
| {child_pad}{}\n\ | |
| {child_pad}(Trusted.MirAst.Place.mk {dst} [])\n\ | |
| {child_pad}{}\n\ | |
| {child_pad}Trusted.MirAst.UnwindAction.{})", | |
| list_pretty(args, indent + 2, |v, i| operand_at(tys, v, i)), | |
| block_target_opt(*target), | |
| unwind.lean_name(), | |
| ) | |
| } | |
| Terminator::CallNe { | |
| eq_callee, | |
| args, | |
| dst, | |
| target, | |
| unwind, | |
| } => { | |
| let child_pad = " ".repeat(indent + 2); | |
| format!( | |
| "(Trusted.MirAst.TerminatorKind.callNe\n\ | |
| {child_pad}{eq_callee}\n\ | |
| {child_pad}{}\n\ | |
| {child_pad}(Trusted.MirAst.Place.mk {dst} [])\n\ | |
| {child_pad}{}\n\ | |
| {child_pad}Trusted.MirAst.UnwindAction.{})", | |
| list_pretty(args, indent + 2, |v, i| operand_at(tys, v, i)), | |
| block_target_opt(*target), | |
| unwind.lean_name(), | |
| ) | |
| } | |
| Terminator::CallVia { | |
| via, | |
| callee, | |
| args, | |
| dst, | |
| target, | |
| unwind, | |
| } => { | |
| let child_pad = " ".repeat(indent + 2); | |
| let via = match via { | |
| crate::ir::CallVia::RefPartialEq { negate } => { | |
| format!("(Trusted.MirAst.CallVia.refPartialEq {negate})") | |
| } | |
| crate::ir::CallVia::BoxClone { pointee } => { | |
| format!("(Trusted.MirAst.CallVia.boxClone {})", ty_at(tys, pointee, indent + 2)) | |
| } | |
| }; | |
| format!( | |
| "(Trusted.MirAst.TerminatorKind.callVia\n\ | |
| {child_pad}{via}\n\ | |
| {child_pad}{callee}\n\ | |
| {child_pad}{}\n\ | |
| {child_pad}(Trusted.MirAst.Place.mk {dst} [])\n\ | |
| {child_pad}{}\n\ | |
| {child_pad}Trusted.MirAst.UnwindAction.{})", | |
| list_pretty(args, indent + 2, |v, i| operand_at(tys, v, i)), | |
| block_target_opt(*target), | |
| unwind.lean_name(), | |
| ) | |
| } | |
| Terminator::SysrootCall { | |
| op, | |
| args, | |
| dst, | |
| target, | |
| unwind, | |
| } => { | |
| let child_pad = " ".repeat(indent + 2); | |
| format!( | |
| "(Trusted.MirAst.TerminatorKind.sysrootCall\n\ | |
| {child_pad}(Trusted.MirAst.SysrootNumOp.mk Trusted.MirAst.SysrootNumKind.{} Trusted.MirAst.IntWidth.{} {})\n\ | |
| {child_pad}{}\n\ | |
| {child_pad}(Trusted.MirAst.Place.mk {dst} [])\n\ | |
| {child_pad}{}\n\ | |
| {child_pad}Trusted.MirAst.UnwindAction.{})", | |
| sysroot_num_kind(op.kind), | |
| op.ty.width.lean_name(), | |
| op.ty.signed, | |
| list_pretty(args, indent + 2, |v, i| operand_at(tys, v, i)), | |
| block_target_opt(*target), | |
| unwind.lean_name(), | |
| ) | |
| } | |
| } | |
| } | |
| fn sysroot_num_kind(kind: SysrootNumKind) -> &'static str { | |
| match kind { | |
| SysrootNumKind::UncheckedAdd => "uncheckedAdd", | |
| SysrootNumKind::UncheckedSub => "uncheckedSub", | |
| SysrootNumKind::UncheckedMul => "uncheckedMul", | |
| SysrootNumKind::WrappingAdd => "wrappingAdd", | |
| SysrootNumKind::WrappingSub => "wrappingSub", | |
| SysrootNumKind::WrappingMul => "wrappingMul", | |
| } | |
| } | |
| fn block_target_opt(target: Option<u32>) -> String { | |
| match target { | |
| None => "none".into(), | |
| Some(b) => format!("(some {b})"), | |
| } | |
| } | |
| /// Construct a Lean string without interpolating its contents into Lean syntax. | |
| /// The identity selects a reviewed safety predicate, so it must enter the | |
| /// logical subject without gaining authority to add commands or change names. | |
| /// Rust characters are Unicode scalar values; numeric Char constructors retain | |
| /// them even when a name contains quotes, backslashes or other syntax. This | |
| /// keeps every emitted token fixed or numeric and requires no escaping grammar. | |
| /// Chunk strings longer than `MAX_LIST_CHUNK_LEN` characters into a balanced | |
| /// binary tree of `Trusted.MirAst.stringAppend` over `<= 16`-character | |
| /// `(_root_.String.ofList [...])` leaves so Lean kernel evaluation avoids | |
| /// `List.utf8Encode`'s linear `ByteArray.push` recursion (`maxRecDepth`). | |
| fn identity_at(value: &str, indent: usize) -> String { | |
| let characters: Vec<char> = value.chars().collect(); | |
| let chunks: Vec<&[char]> = characters.chunks(MAX_LIST_CHUNK_LEN).collect(); | |
| join_balanced_with( | |
| &chunks, | |
| (chunks.len() > 1).then_some(indent), | |
| "(_root_.String.ofList [])", | |
| "Trusted.MirAst.stringAppend", | |
| &|chunk, _| { | |
| let chars_list = | |
| list_literal(chunk, |ch| format!("(_root_.Char.ofNat {})", u32::from(*ch))); | |
| format!("(_root_.String.ofList {chars_list})") | |
| }, | |
| ) | |
| } | |
| #[cfg(test)] | |
| fn identity(value: &str) -> String { | |
| identity_at(value, 0) | |
| } | |
| fn block_at(tys: &TyDefs, block: &ir::Block, block_indent: usize) -> String { | |
| let bf_col = block_indent + 2; | |
| let bf_pad = " ".repeat(bf_col); | |
| let bc_pad = " ".repeat(block_indent); | |
| format!( | |
| "({{\n\ | |
| {bf_pad}statements := {},\n\ | |
| {bf_pad}terminator := {},\n\ | |
| {bf_pad}cleanup := false\n\ | |
| {bc_pad}}} : Trusted.MirAst.BasicBlock)", | |
| list_pretty(&block.statements, bf_col, |v, i| statement_at(tys, v, i)), | |
| terminator_at(tys, &block.terminator, bf_col) | |
| ) | |
| } | |
| fn body_record(tys: &TyDefs, body: &ir::Body, indent: usize, basic_blocks: &str) -> String { | |
| let field_col = indent + 2; | |
| let field_pad = " ".repeat(field_col); | |
| let close_pad = " ".repeat(indent); | |
| format!( | |
| "{{\n\ | |
| {field_pad}argumentCount := {},\n\ | |
| {field_pad}isUnsafe := {},\n\ | |
| {field_pad}locals := {},\n\ | |
| {field_pad}basicBlocks := {basic_blocks},\n\ | |
| {field_pad}identity := {},\n\ | |
| {field_pad}isExternal := {}\n\ | |
| {close_pad}}}", | |
| body.arg_count(), | |
| body.is_unsafe(), | |
| list_pretty(body.local_tys(), field_col, |v, i| ty_at(tys, v, i)), | |
| identity_at(body.identity(), field_col), | |
| body.is_external(), | |
| ) | |
| } | |
| /// Write `def {name} : Trusted.MirAst.Body` to `out`. | |
| /// | |
| /// Lean's elaborator hits `maxRecDepth` once a single definition contains a | |
| /// few thousand numeric literals, independently of how its lists are nested | |
| /// (see [`list`]), and a large body's basic blocks carry nearly all of its | |
| /// literals. A body with more than [`MAX_LIST_CHUNK_LEN`] blocks therefore | |
| /// emits each [`MAX_LIST_CHUNK_LEN`]-block slice as its own | |
| /// `{name}_blocks_c<k>` definition, and `basicBlocks` joins those names with | |
| /// the same balanced `_root_.List.append` tree that [`list_pretty`] builds over | |
| /// inline chunk literals. Unfolding the chunk definitions recovers the inline | |
| /// term exactly, so the body is unchanged up to delta reduction, and bodies | |
| /// with at most [`MAX_LIST_CHUNK_LEN`] blocks render exactly as before. | |
| fn write_body_def(out: &mut String, tys: &TyDefs, name: &str, body: &ir::Body) { | |
| let blocks = body.blocks(); | |
| let basic_blocks = if blocks.len() <= MAX_LIST_CHUNK_LEN { | |
| list_pretty(blocks, 4, |b, i| block_at(tys, b, i)) | |
| } else { | |
| let mut chunk_names = Vec::new(); | |
| for (chunk_idx, chunk) in blocks.chunks(MAX_LIST_CHUNK_LEN).enumerate() { | |
| let chunk_name = format!("{name}_blocks_c{chunk_idx}"); | |
| let chunk_lit = list_literal_at(chunk, Some(2), &|block, indent| { | |
| block_at(tys, block, indent.unwrap_or(2)) | |
| }); | |
| let _ = writeln!( | |
| out, | |
| "def {chunk_name} : _root_.List Trusted.MirAst.BasicBlock :=\n {chunk_lit}\n" | |
| ); | |
| chunk_names.push(chunk_name); | |
| } | |
| join_balanced_slice(&chunk_names, Some(4), &|name, _| name.clone()) | |
| }; | |
| let record = body_record(tys, body, 2, &basic_blocks); | |
| let _ = writeln!(out, "def {name} : Trusted.MirAst.Body :=\n {record}\n"); | |
| } | |
| /// Target pointer width pinned by capture (`capture.rs` refuses any target | |
| /// that is not 64-bit little-endian, matching `Trusted.MirAst.Program`). The | |
| /// MIR semantic profile version is not pinned: [`render`] emits | |
| /// `ir::Program::mir_profile_version`, computed from the captured bodies. | |
| const POINTER_WIDTH_BITS: u32 = 64; | |
| /// Entry body index of every captured program. `Trusted.MirAst.Program` gives | |
| /// `entryDefId` a default only for hand-written canaries ("`Program.entryDefId | |
| /// := 0` selects body `0` as the entry point"), and its producer obligations | |
| /// say any MIR producer "MUST explicitly populate all of these fields", | |
| /// including `entryDefId`. Body `0` always exists because | |
| /// `ir::Program::try_new` refuses empty programs, so the | |
| /// `p.entryDefId < p.bodies.length` check in `ProgramVerified` holds. That | |
| /// judgment verifies each body through `entryProgForBody`, which replaces | |
| /// this field. In unsharded captures `entryDefId := 0` selects the first | |
| /// captured body; when sharding is active, `program.bodies` is canonicalized | |
| /// into callee-first Tarjan/Kahn order so body order and `entryDefId := 0` | |
| /// depend on the `--shard-*` CLI flags (not recorded in `request_sha256`). | |
| /// Per-body obligations, identity uniqueness, and `entryProgForBody` checks | |
| /// are order-independent, so specifications must identify bodies by | |
| /// `Body.identity`. | |
| const ENTRY_DEF_ID: u32 = 0; | |
| /// Render data constructors under one fixed module/definition skeleton. | |
| /// Capture emits a subject, not a proof or a dynamically chosen theorem. The | |
| /// verifier separately authenticates this source and checks the authored root; | |
| /// neither diagnostics nor census text can add commands through this renderer. | |
| /// | |
| /// Each body is emitted as its own `Captured.body_<i>` definition, after the | |
| /// `Captured.ty_<k>` definitions of the recursive ADT types it names | |
| /// ([`TyDefs`]), and `program.bodies` assembles more than | |
| /// [`MAX_LIST_CHUNK_LEN`] bodies via | |
| /// `Captured.bodies_chunk_<k>` slices combined with a balanced | |
| /// `_root_.List.append` tree so elaboration recursion depth stays bounded on | |
| /// multi-hundred- and multi-thousand-function crates. | |
| pub fn render(program: &ir::Program) -> String { | |
| let scope = match program.scope() { | |
| ir::Scope::SelectedUnit { .. } => "unit", | |
| ir::Scope::Crate { .. } => "crate", | |
| }; | |
| let mut out = String::from(HEADER); | |
| let (defs, body_names) = body_defs(program.bodies()); | |
| out.push_str(&defs); | |
| let bodies_expr = match body_names.as_slice() { | |
| [] => "[]".into(), | |
| [single] => format!("[{single}]"), | |
| _ if body_names.len() <= MAX_LIST_CHUNK_LEN => { | |
| list_literal_at(&body_names, Some(4), &|name, _| name.clone()) | |
| } | |
| _ => { | |
| let mut chunk_names = Vec::new(); | |
| for (chunk_idx, chunk) in body_names.chunks(MAX_LIST_CHUNK_LEN).enumerate() { | |
| let chunk_name = format!("bodies_chunk_{chunk_idx}"); | |
| let chunk_lit = list_literal_at(chunk, Some(2), &|name, _| name.clone()); | |
| let _ = writeln!( | |
| out, | |
| "def {chunk_name} : _root_.List Trusted.MirAst.Body :=\n {chunk_lit}\n" | |
| ); | |
| chunk_names.push(chunk_name); | |
| } | |
| join_balanced_slice(&chunk_names, Some(4), &|name, _| name.clone()) | |
| } | |
| }; | |
| let profile_version = program.mir_profile_version(); | |
| let overflow_checks = program.overflow_checks(); | |
| let panic_strategy = program.panic().as_str(); | |
| let has_local_panic_handler = program.has_local_panic_handler(); | |
| let _ = write!( | |
| out, | |
| "def program : Trusted.MirAst.Program :=\n\ | |
| \x20 {{\n\ | |
| \x20 pointerWidthBits := {POINTER_WIDTH_BITS},\n\ | |
| \x20 mirProfileVersion := {profile_version},\n\ | |
| \x20 scope := Trusted.MirAst.VerificationScope.{scope},\n\ | |
| \x20 entryDefId := {ENTRY_DEF_ID},\n\ | |
| \x20 bodies := {bodies_expr},\n\ | |
| \x20 overflowChecks := {overflow_checks},\n\ | |
| \x20 panicStrategy := Trusted.MirAst.PanicStrategy.{panic_strategy},\n\ | |
| \x20 hasLocalPanicHandler := {has_local_panic_handler}\n\ | |
| \x20 }}\n\nend Captured\n\nend\n" | |
| ); | |
| out | |
| } | |
| /// Render a standalone `Captured/Shard_<k>.lean` module (`TargetRole::Capture`) | |
| /// in Lean 4 `module` mode importing only `Trusted.MirAst` (`D = 1` parallel | |
| /// shard compilation). | |
| /// | |
| /// `shard_bodies` uses the exact midpoint split (`mid = len / 2`) over | |
| /// singleton `[body_i]` leaves (`shard_bodies = BinChunkTree.toList` by `rfl`) | |
| /// inside `Proof/Shard_<k>.lean` with list literals `<= MAX_LIST_CHUNK_LEN`. | |
| pub(crate) fn render_shard_module(shard_idx: usize, bodies: &[ir::Body]) -> String { | |
| let shard_ns = format!("Captured.Shard_{shard_idx:03}"); | |
| let mut out = String::from(LICENSE_PREAMBLE); | |
| let _ = writeln!( | |
| out, | |
| "module\nprelude\npublic import Trusted.MirAst\n\n@[expose] public section\n\nnamespace {shard_ns}\n" | |
| ); | |
| let (defs, body_names) = body_defs(bodies); | |
| out.push_str(&defs); | |
| let leaf_lists: Vec<String> = body_names.iter().map(|name| format!("[{name}]")).collect(); | |
| let bodies_expr = join_balanced_slice(&leaf_lists, Some(2), &|leaf, _| leaf.clone()); | |
| let _ = write!( | |
| out, | |
| "def shard_bodies : _root_.List Trusted.MirAst.Body :=\n\ | |
| \x20 {bodies_expr}\n\n\ | |
| end {shard_ns}\n\nend\n" | |
| ); | |
| out | |
| } | |
| /// Render the sharded root `Captured.lean` module in Lean 4 `module` mode | |
| /// importing `Captured.Shard_000 .. Captured.Shard_{K-1}`, re-exporting `N` | |
| /// `Captured.body_<idx>` aliases for shard-transparent compatibility, and | |
| /// concatenating `shard_bodies` along the balanced midpoint binary tree | |
| /// (`mid = K / 2`) matching `BinChunkTree.toList_branch`. Body order follows | |
| /// canonical callee-first Tarjan/Kahn sharding, with `entryDefId := 0` naming | |
| /// body `0` of that canonical order. | |
| pub(crate) fn render_sharded_root( | |
| scope: &ir::Scope, | |
| profile_version: u32, | |
| overflow_checks: bool, | |
| panic: ir::PanicStrategy, | |
| has_local_panic_handler: bool, | |
| shards: &[crate::shard::CaptureShardEntry], | |
| ) -> String { | |
| let scope_name = match scope { | |
| ir::Scope::SelectedUnit { .. } => "unit", | |
| ir::Scope::Crate { .. } => "crate", | |
| }; | |
| let panic_strategy = panic.as_str(); | |
| let mut out = String::from(LICENSE_PREAMBLE); | |
| out.push_str("module\nprelude\npublic import Trusted.MirAst\n"); | |
| let mut shard_refs = Vec::with_capacity(shards.len()); | |
| for shard in shards { | |
| let _ = writeln!(out, "public import {}", shard.capture_module); | |
| shard_refs.push(format!("{}.shard_bodies", shard.capture_module)); | |
| } | |
| out.push_str("\n@[expose] public section\n\nnamespace Captured\n\n"); | |
| for shard in shards { | |
| let base = shard.global_def_id_range[0]; | |
| for local_idx in 0..shard.num_bodies { | |
| let global_idx = base + local_idx; | |
| let _ = writeln!( | |
| out, | |
| "def body_{global_idx} : Trusted.MirAst.Body :=\n \ | |
| {}.body_{local_idx}\n", | |
| shard.capture_module | |
| ); | |
| } | |
| } | |
| let bodies_expr = join_balanced_slice(&shard_refs, Some(4), &|s, _| s.clone()); | |
| let _ = write!( | |
| out, | |
| "def program : Trusted.MirAst.Program :=\n\ | |
| \x20 {{\n\ | |
| \x20 pointerWidthBits := {POINTER_WIDTH_BITS},\n\ | |
| \x20 mirProfileVersion := {profile_version},\n\ | |
| \x20 scope := Trusted.MirAst.VerificationScope.{scope_name},\n\ | |
| \x20 entryDefId := {ENTRY_DEF_ID},\n\ | |
| \x20 bodies := {bodies_expr},\n\ | |
| \x20 overflowChecks := {overflow_checks},\n\ | |
| \x20 panicStrategy := Trusted.MirAst.PanicStrategy.{panic_strategy},\n\ | |
| \x20 hasLocalPanicHandler := {has_local_panic_handler}\n\ | |
| \x20 }}\n\nend Captured\n\nend\n" | |
| ); | |
| out | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use std::collections::BTreeSet; | |
| use super::{ | |
| MAX_LIST_CHUNK_LEN, TyDefs, block_at, identity, list, list_pretty, render, | |
| render_shard_module, ty_at, | |
| }; | |
| use crate::ir::{ | |
| Block, Body, ConstLit, EnumTagRepr, EnumTy, IntTy, IntWidth, Mutability, Operand, Place, | |
| PlaceElem, Program, Rvalue, Scope, Statement, StructTy, Terminator, Ty, | |
| }; | |
| fn max_paren_depth(text: &str) -> usize { | |
| let mut depth = 0usize; | |
| let mut max_depth = 0usize; | |
| for ch in text.chars() { | |
| match ch { | |
| '(' => { | |
| depth += 1; | |
| max_depth = max_depth.max(depth); | |
| } | |
| ')' => { | |
| depth = depth.checked_sub(1).expect("unbalanced closing parenthesis"); | |
| } | |
| _ => {} | |
| } | |
| } | |
| assert_eq!(depth, 0, "unbalanced parentheses in {text}"); | |
| max_depth | |
| } | |
| fn assert_list_literals_at_most(text: &str, max_elems: usize) { | |
| let mut paren_depth = 0usize; | |
| // Track (paren_depth_at_open, top_level_commas, saw_element_token) | |
| // per active `[` so nested lists inside body/tuple elements are bounded | |
| // independently of enclosing list literals. | |
| let mut brackets: Vec<(usize, usize, bool)> = Vec::new(); | |
| for ch in text.chars() { | |
| if let Some(&(open_p, _, _)) = brackets.last() | |
| && paren_depth == open_p | |
| && !ch.is_whitespace() | |
| && ch != ',' | |
| && ch != ']' | |
| { | |
| brackets.last_mut().unwrap().2 = true; | |
| } | |
| match ch { | |
| '(' => paren_depth += 1, | |
| ')' => { | |
| paren_depth = | |
| paren_depth.checked_sub(1).expect("unbalanced closing parenthesis"); | |
| } | |
| '[' => brackets.push((paren_depth, 0, false)), | |
| ',' => { | |
| if let Some(&mut (open_p, ref mut commas, _)) = brackets.last_mut() | |
| && paren_depth == open_p | |
| { | |
| *commas += 1; | |
| } | |
| } | |
| ']' => { | |
| let (open_p, commas, saw_token) = | |
| brackets.pop().expect("unbalanced closing bracket"); | |
| assert_eq!(paren_depth, open_p, "unbalanced parens inside list literal"); | |
| let elems = if commas > 0 || saw_token { commas + 1 } else { 0 }; | |
| assert!( | |
| elems <= max_elems, | |
| "list literal has {elems} elements (limit {max_elems})" | |
| ); | |
| } | |
| _ => {} | |
| } | |
| } | |
| assert!(brackets.is_empty(), "unclosed bracket in {text}"); | |
| } | |
| #[test] | |
| fn identity_names_are_only_numeric_character_data() { | |
| assert_eq!(identity(""), "(_root_.String.ofList [])"); | |
| assert_eq!( | |
| identity("a\"\\\nλ/- --"), | |
| "(_root_.String.ofList [(_root_.Char.ofNat 97), (_root_.Char.ofNat 34), (_root_.Char.ofNat 92), (_root_.Char.ofNat 10), (_root_.Char.ofNat 955), (_root_.Char.ofNat 47), (_root_.Char.ofNat 45), (_root_.Char.ofNat 32), (_root_.Char.ofNat 45), (_root_.Char.ofNat 45)])" | |
| ); | |
| let seventeen = identity("0123456789abcdefX"); | |
| assert!( | |
| seventeen.starts_with("(Trusted.MirAst.stringAppend (_root_.String.ofList ["), | |
| "{seventeen}" | |
| ); | |
| assert_list_literals_at_most(&seventeen, MAX_LIST_CHUNK_LEN); | |
| // Balanced `stringAppend` trees print their leaves in concatenation | |
| // order, so reading every `Char.ofNat` code point left to right must | |
| // reproduce the original identity, including multibyte characters | |
| // that straddle leaf boundaries. | |
| fn decode(rendered: &str) -> String { | |
| rendered | |
| .split("(_root_.Char.ofNat ") | |
| .skip(1) | |
| .map(|rest| { | |
| let code: u32 = rest[..rest.find(')').unwrap()].parse().unwrap(); | |
| char::from_u32(code).unwrap() | |
| }) | |
| .collect() | |
| } | |
| for value in [ | |
| "0123456789abcdefX".to_owned(), | |
| "λ".repeat(17), | |
| format!("rust-path-v1::{}::λ_{}", "m".repeat(40), "é".repeat(60)), | |
| "x".repeat(16 * 9 + 3), | |
| ] { | |
| let rendered = identity(&value); | |
| assert_eq!(decode(&rendered), value, "{rendered}"); | |
| assert!(rendered.contains("Trusted.MirAst.stringAppend"), "{rendered}"); | |
| assert_list_literals_at_most(&rendered, MAX_LIST_CHUNK_LEN); | |
| } | |
| let sixteen = "λ".repeat(16); | |
| assert!(!identity(&sixteen).contains("stringAppend")); | |
| assert_eq!(decode(&identity(&sixteen)), sixteen); | |
| } | |
| /// Each distinct `recAdt` type is rendered once, as a `def ty_<k>` placed | |
| /// after the `recAdt` types nested in it and before the bodies, and every | |
| /// use names that definition. Its right-hand side is the type's full | |
| /// rendering, so the bodies denote the same `MirTy` values as before. | |
| #[test] | |
| fn render_hoists_each_recursive_adt_into_one_shared_definition() { | |
| let u64_ty = Ty::Int(IntTy { width: IntWidth::I64, signed: false }); | |
| let back = |id| Ty::Box { pointee: Box::new(Ty::RecSelf { id }) }; | |
| let node_defn = Ty::Struct( | |
| StructTy::try_new( | |
| 7, | |
| 16, | |
| 3, | |
| vec![0, 8], | |
| vec![u64_ty, Ty::Option { elem: Box::new(back(7)) }], | |
| ) | |
| .unwrap(), | |
| ); | |
| let node = Ty::RecAdt { id: 7, defn: Box::new(node_defn.clone()) }; | |
| let outer = Ty::RecAdt { | |
| id: 8, | |
| defn: Box::new(Ty::Struct( | |
| StructTy::try_new(8, 24, 3, vec![0, 16], vec![node.clone(), back(8)]).unwrap(), | |
| )), | |
| }; | |
| let body = Body::try_new( | |
| 0, | |
| false, | |
| vec![Ty::Unit, node.clone(), outer, node], | |
| vec![Block { statements: vec![], terminator: Terminator::Ret }], | |
| "rust-path-v1::f".into(), | |
| ) | |
| .unwrap(); | |
| let program = | |
| Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![body]) | |
| .unwrap(); | |
| let rendered = render(&program); | |
| let node_rhs = | |
| format!("(Trusted.MirAst.MirTy.recAdt 7 {})", ty_at(&TyDefs::default(), &node_defn, 2)); | |
| let ty_0 = format!("def ty_0 : Trusted.MirAst.MirTy :=\n {node_rhs}\n\n"); | |
| let ty_1 = "def ty_1 : Trusted.MirAst.MirTy :=\n (Trusted.MirAst.MirTy.recAdt 8 "; | |
| let at = |needle: &str| rendered.find(needle).unwrap_or_else(|| panic!("{needle}")); | |
| assert!(at(&ty_0) < at(ty_1), "{rendered}"); | |
| assert!(at(ty_1) < at("def body_0 "), "{rendered}"); | |
| for id in [7, 8] { | |
| let needle = format!("MirTy.recAdt {id} "); | |
| assert_eq!(rendered.matches(&needle).count(), 1, "{rendered}"); | |
| } | |
| // `outer`'s definition names `node`'s, and the locals name both. | |
| let ty_1_rhs = &rendered[at(ty_1)..at("def body_0 ")]; | |
| assert_eq!(ty_1_rhs.matches("ty_0").count(), 1, "{rendered}"); | |
| let body_0 = &rendered[at("def body_0 ")..]; | |
| assert_eq!(body_0.matches("ty_0").count(), 2, "{rendered}"); | |
| assert_eq!(body_0.matches("ty_1").count(), 1, "{rendered}"); | |
| } | |
| #[test] | |
| fn render_emits_total_deterministic_lean_for_validated_program() { | |
| let body = Body::try_new( | |
| 0, | |
| false, | |
| vec![Ty::Unit], | |
| vec![Block { | |
| statements: vec![Statement::Assign { | |
| local: 0, | |
| value: Rvalue::Use { | |
| operand: Operand::Constant { ty: Ty::Unit, lit: ConstLit::ZeroSized }, | |
| with_retag: true, | |
| }, | |
| }], | |
| terminator: Terminator::Ret, | |
| }], | |
| "rust-path-v1::unit_fn".into(), | |
| ) | |
| .unwrap(); | |
| let program = | |
| Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![body.clone()]) | |
| .unwrap(); | |
| let rendered = render(&program); | |
| assert!(rendered.contains("pointerWidthBits := 64"), "{rendered}"); | |
| assert!(rendered.contains("mirProfileVersion := 1"), "{rendered}"); | |
| // Producers must not rely on the Lean default for the entry body. | |
| assert!(rendered.contains("entryDefId := 0"), "{rendered}"); | |
| assert!(rendered.contains("Trusted.MirAst.VerificationScope.crate"), "{rendered}"); | |
| assert_eq!( | |
| rendered | |
| .matches("(Trusted.MirAst.Rvalue.use (Trusted.MirAst.Operand.constant (Trusted.MirAst.ConstOperand.mk Trusted.MirAst.MirTy.unit Trusted.MirAst.ConstLit.zeroSized)))") | |
| .count(), | |
| 1, | |
| "{rendered}" | |
| ); | |
| assert!(!rendered.contains("unit_fn"), "{rendered}"); | |
| let selected = Program::try_new( | |
| Scope::SelectedUnit { | |
| roots: BTreeSet::from(["raw\"selector".into()]), | |
| instantiations: BTreeSet::new(), | |
| }, | |
| vec![body], | |
| ) | |
| .unwrap(); | |
| let selected_rendered = render(&selected); | |
| assert!( | |
| selected_rendered.contains("Trusted.MirAst.VerificationScope.unit"), | |
| "{selected_rendered}" | |
| ); | |
| assert!(selected_rendered.contains("entryDefId := 0"), "{selected_rendered}"); | |
| assert!(!selected_rendered.contains("selector"), "{selected_rendered}"); | |
| assert!( | |
| selected_rendered.contains("def body_0 : Trusted.MirAst.Body :="), | |
| "{selected_rendered}" | |
| ); | |
| assert!(selected_rendered.contains("bodies := [body_0]"), "{selected_rendered}"); | |
| assert!(!selected_rendered.contains("bodies_chunk_"), "{selected_rendered}"); | |
| } | |
| #[test] | |
| fn render_chunks_large_programs_and_long_lists_with_balanced_append() { | |
| let bodies: Vec<Body> = (0..130) | |
| .map(|i| { | |
| Body::try_new( | |
| 0, | |
| false, | |
| vec![Ty::Unit], | |
| vec![Block { | |
| statements: vec![Statement::Nop; if i == 0 { 70 } else { 0 }], | |
| terminator: Terminator::Ret, | |
| }], | |
| format!("rust-path-v1::fn_{i}"), | |
| ) | |
| .unwrap() | |
| }) | |
| .collect(); | |
| let program = | |
| Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, bodies).unwrap(); | |
| let rendered = render(&program); | |
| assert!(rendered.contains("def body_0 : Trusted.MirAst.Body :="), "{rendered}"); | |
| assert!(rendered.contains("def body_129 : Trusted.MirAst.Body :="), "{rendered}"); | |
| assert!( | |
| rendered.contains("def bodies_chunk_0 : _root_.List Trusted.MirAst.Body :="), | |
| "{rendered}" | |
| ); | |
| assert!( | |
| rendered.contains("def bodies_chunk_8 : _root_.List Trusted.MirAst.Body :="), | |
| "{rendered}" | |
| ); | |
| assert!(rendered.contains("(_root_.List.append "), "{rendered}"); | |
| assert_list_literals_at_most(&rendered, MAX_LIST_CHUNK_LEN); | |
| } | |
| fn goto_chain(identity: &str, len: u32) -> Body { | |
| let mut blocks: Vec<Block> = (1..len) | |
| .map(|next| Block { statements: vec![], terminator: Terminator::Goto { block: next } }) | |
| .collect(); | |
| blocks.push(Block { statements: vec![], terminator: Terminator::Ret }); | |
| Body::try_new(0, false, vec![Ty::Unit], blocks, identity.into()).unwrap() | |
| } | |
| #[test] | |
| fn render_emits_large_body_blocks_as_chunk_defs_that_unfold_to_the_inline_list() { | |
| let large = goto_chain("rust-path-v1::large", 40); | |
| let small = goto_chain("rust-path-v1::small", MAX_LIST_CHUNK_LEN as u32); | |
| let program = Program::try_new( | |
| Scope::Crate { excluded_traits: BTreeSet::new() }, | |
| vec![large.clone(), small], | |
| ) | |
| .unwrap(); | |
| let rendered = render(&program); | |
| assert_list_literals_at_most(&rendered, MAX_LIST_CHUNK_LEN); | |
| assert!(!rendered.contains("body_0_blocks_c3"), "{rendered}"); | |
| assert!(!rendered.contains("body_1_blocks_c"), "{rendered}"); | |
| // Substituting each chunk definition back into `basicBlocks` must yield | |
| // the inline list the renderer would otherwise emit. | |
| let body_def = rendered.find("def body_0 : Trusted.MirAst.Body :=").unwrap(); | |
| let start = body_def + rendered[body_def..].find("basicBlocks := ").unwrap() + 15; | |
| let end = start + rendered[start..].find(",\n identity := ").unwrap(); | |
| let mut unfolded = rendered[start..end].to_owned(); | |
| for chunk_idx in (0..3).rev() { | |
| let header = format!( | |
| "def body_0_blocks_c{chunk_idx} : _root_.List Trusted.MirAst.BasicBlock :=\n " | |
| ); | |
| let def_start = rendered.find(&header).expect(&header) + header.len(); | |
| assert!(def_start < body_def, "chunk {chunk_idx} must precede body_0"); | |
| let def_end = def_start + rendered[def_start..].find("\n\n").unwrap(); | |
| let name = format!("body_0_blocks_c{chunk_idx}"); | |
| assert_eq!(unfolded.matches(&name).count(), 1, "{unfolded}"); | |
| unfolded = unfolded.replace(&name, &rendered[def_start..def_end]); | |
| } | |
| let squash = |text: &str| text.split_whitespace().collect::<String>(); | |
| assert_eq!(squash(&unfolded), squash(&list_pretty(large.blocks(), 4, |b, i| block_at(&TyDefs::default(), b, i)))); | |
| let shard = render_shard_module(0, &[large]); | |
| assert!(shard.contains("def body_0_blocks_c2 : _root_.List Trusted.MirAst.BasicBlock :=")); | |
| assert_list_literals_at_most(&shard, MAX_LIST_CHUNK_LEN); | |
| } | |
| #[test] | |
| fn list_preserves_small_lists_and_balances_large_chunks() { | |
| let empty: Vec<u32> = Vec::new(); | |
| assert_eq!(list(&empty, u32::to_string), "[]"); | |
| let one = [42u32]; | |
| assert_eq!(list(&one, u32::to_string), "[42]"); | |
| let sixteen: Vec<u32> = (0..16).collect(); | |
| assert_eq!( | |
| list(&sixteen, u32::to_string), | |
| "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]" | |
| ); | |
| let seventeen: Vec<u32> = (0..17).collect(); | |
| assert_eq!( | |
| list(&seventeen, u32::to_string), | |
| "(_root_.List.append [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] [16])" | |
| ); | |
| let two_fifty: Vec<u32> = (0..250).collect(); | |
| let rendered = list(&two_fifty, u32::to_string); | |
| assert!(max_paren_depth(&rendered) <= 10, "excessive paren depth in {rendered}"); | |
| assert_list_literals_at_most(&rendered, MAX_LIST_CHUNK_LEN); | |
| // Extract every leaf number in source order to ensure zero reordering | |
| // or dropped items across recursive `_root_.List.append` nodes. | |
| let cleaned: String = rendered | |
| .replace("(_root_.List.append ", " ") | |
| .chars() | |
| .filter(|ch| ch.is_ascii_digit() || *ch == ' ') | |
| .collect(); | |
| let recovered: Vec<u32> = | |
| cleaned.split_whitespace().map(|tok| tok.parse::<u32>().unwrap()).collect(); | |
| assert_eq!(recovered, two_fifty); | |
| } | |
| #[test] | |
| fn identity_and_render_balance_all_large_list_fields() { | |
| let long_id = identity(&"a".repeat(250)); | |
| assert!(max_paren_depth(&long_id) <= 10, "{long_id}"); | |
| assert_list_literals_at_most(&long_id, MAX_LIST_CHUNK_LEN); | |
| let u64_ty = Ty::Int(IntTy { width: IntWidth::I64, signed: false }); | |
| let big_enum = Ty::Enum( | |
| EnumTy::try_new( | |
| 7, | |
| IntTy { width: IntWidth::I64, signed: false }, | |
| EnumTagRepr::Scalar(IntTy { width: IntWidth::I64, signed: false }), | |
| (0..70).collect(), | |
| ) | |
| .unwrap(), | |
| ); | |
| let mut locals = vec![Ty::Unit, u64_ty.clone(), big_enum]; | |
| locals.resize(70, u64_ty); | |
| let targets = (0..70u128).map(|v| (v, 1u32)).collect(); | |
| let statements = vec![Statement::Nop; 250]; | |
| let body0 = Body::try_new( | |
| 0, | |
| false, | |
| locals, | |
| vec![ | |
| Block { | |
| statements, | |
| terminator: Terminator::SwitchInt { | |
| operand: Operand::Copy { local: 1 }, | |
| targets, | |
| otherwise: 1, | |
| }, | |
| }, | |
| Block { statements: vec![], terminator: Terminator::Ret }, | |
| ], | |
| format!("rust-path-v1::{}", "f".repeat(86)), | |
| ) | |
| .unwrap(); | |
| let mut bodies = vec![body0]; | |
| for i in 1..70 { | |
| bodies.push( | |
| Body::try_new( | |
| 0, | |
| false, | |
| vec![Ty::Unit], | |
| vec![Block { statements: vec![], terminator: Terminator::Ret }], | |
| format!("rust-path-v1::fn_{i}"), | |
| ) | |
| .unwrap(), | |
| ); | |
| } | |
| let program = | |
| Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, bodies).unwrap(); | |
| let rendered = render(&program); | |
| // `bodies` (depth 3) + Body/BasicBlock/SwitchInt/BitVec wrappers (5) | |
| // + 250-statement or 70-target append tree (depth 4/3) stays O(log N). | |
| assert!( | |
| max_paren_depth(&rendered) <= 16, | |
| "excessive paren depth: {}", | |
| max_paren_depth(&rendered) | |
| ); | |
| assert_list_literals_at_most(&rendered, MAX_LIST_CHUNK_LEN); | |
| assert!(rendered.contains("(_root_.List.append ")); | |
| let max_line = rendered.lines().map(str::len).max().unwrap_or(0); | |
| assert!(max_line <= 500, "expected pretty-printed line width <= 500, got {max_line}"); | |
| assert!( | |
| rendered.lines().all(|line| !line.ends_with(' ') && !line.ends_with('\t')), | |
| "unexpected trailing whitespace in rendered Lean" | |
| ); | |
| } | |
| #[test] | |
| fn render_pretty_prints_structured_multiline_lean() { | |
| let enum_ty = Ty::Enum( | |
| EnumTy::try_new( | |
| 9, | |
| IntTy { width: IntWidth::I32, signed: true }, | |
| EnumTagRepr::Scalar(IntTy { width: IntWidth::I8, signed: true }), | |
| vec![0, 1], | |
| ) | |
| .unwrap(), | |
| ); | |
| let i32_ty = Ty::Int(IntTy { width: IntWidth::I32, signed: true }); | |
| let body0 = Body::try_new( | |
| 1, | |
| true, | |
| vec![i32_ty.clone(), i32_ty, enum_ty.clone()], | |
| vec![ | |
| Block { | |
| statements: vec![ | |
| Statement::StorageLive { local: 1 }, | |
| Statement::Assign { | |
| local: 0, | |
| value: Rvalue::Use { | |
| operand: Operand::Copy { local: 1 }, | |
| with_retag: true, | |
| }, | |
| }, | |
| Statement::Assign { | |
| local: 2, | |
| value: Rvalue::Use { | |
| operand: Operand::Constant { | |
| ty: enum_ty, | |
| lit: ConstLit::Scalar { bits: 0 }, | |
| }, | |
| with_retag: false, | |
| }, | |
| }, | |
| Statement::Nop, | |
| ], | |
| terminator: Terminator::SwitchInt { | |
| operand: Operand::Copy { local: 1 }, | |
| targets: vec![(0, 1), (1, 1)], | |
| otherwise: 1, | |
| }, | |
| }, | |
| Block { statements: vec![], terminator: Terminator::Ret }, | |
| ], | |
| "rust-path-v1::multi_block_secret_fn".into(), | |
| ) | |
| .unwrap(); | |
| let body1 = Body::try_new( | |
| 0, | |
| false, | |
| vec![Ty::Unit], | |
| vec![Block { statements: vec![], terminator: Terminator::Ret }], | |
| "rust-path-v1::helper_fn".into(), | |
| ) | |
| .unwrap(); | |
| let program = Program::try_new( | |
| Scope::Crate { excluded_traits: BTreeSet::new() }, | |
| vec![body0, body1], | |
| ) | |
| .unwrap(); | |
| let rendered = render(&program); | |
| for expected in [ | |
| "def body_0 : Trusted.MirAst.Body :=\n {\n", | |
| " argumentCount := 1,\n isUnsafe := true,\n", | |
| " locals := [\n", | |
| " (Trusted.MirAst.MirTy.enum {\n", | |
| " id := 9,\n", | |
| " discriminants := [0, 1]\n", | |
| " })\n", | |
| " basicBlocks := [\n", | |
| " ({\n statements := [\n", | |
| " (Trusted.MirAst.StatementKind.assign (Trusted.MirAst.Place.mk 2 []) (Trusted.MirAst.Rvalue.use (Trusted.MirAst.Operand.constant (Trusted.MirAst.ConstOperand.mk (Trusted.MirAst.MirTy.enum {\n id := 9,\n discrWidth := Trusted.MirAst.IntWidth.i32,\n discrSigned := true,\n tagRepr := (Trusted.MirAst.EnumTagRepr.scalar Trusted.MirAst.IntWidth.i8 true),\n discriminants := [0, 1]\n }) (Trusted.MirAst.ConstLit.scalar (BitVec.ofNat 128 0)))))),\n", | |
| " terminator := (Trusted.MirAst.TerminatorKind.switchInt\n", | |
| " (Trusted.MirAst.SwitchTargets.mk\n", | |
| " [\n", | |
| " ((BitVec.ofNat 128 0), 1),\n", | |
| " ((BitVec.ofNat 128 1), 1)\n", | |
| " ]\n 1)),\n", | |
| " bodies := [\n body_0,\n body_1\n ],\n overflowChecks := false,\n", | |
| " panicStrategy := Trusted.MirAst.PanicStrategy.unwind,\n", | |
| " hasLocalPanicHandler := false\n", | |
| ] { | |
| assert!( | |
| rendered.contains(expected), | |
| "missing pretty block {expected:?} in:\n{rendered}" | |
| ); | |
| } | |
| assert!(!rendered.contains("secret_fn")); | |
| assert!(!rendered.contains("helper_fn")); | |
| assert!(rendered.lines().all(|line| !line.ends_with(' ') && !line.ends_with('\t'))); | |
| let div_body = Body::try_new( | |
| 0, | |
| false, | |
| vec![Ty::Never], | |
| vec![Block { statements: vec![], terminator: Terminator::Unsupported }], | |
| "rust-path-v1::div_call".into(), | |
| ) | |
| .unwrap(); | |
| let div_prog = Program::try_new( | |
| Scope::Crate { excluded_traits: BTreeSet::new() }, | |
| vec![div_body], | |
| ) | |
| .unwrap(); | |
| let div_rendered = render(&div_prog); | |
| assert!( | |
| div_rendered.contains("terminator := Trusted.MirAst.TerminatorKind.unsupported,"), | |
| "{div_rendered}" | |
| ); | |
| } | |
| #[test] | |
| fn render_lowers_validated_place_mention_and_nop_to_statement_kind_nop() { | |
| let u64_ty = Ty::Int(IntTy { width: IntWidth::I64, signed: false }); | |
| let body = Body::try_new( | |
| 1, | |
| false, | |
| vec![u64_ty.clone(), u64_ty], | |
| vec![Block { | |
| statements: vec![Statement::PlaceMention { local: 1 }, Statement::Nop], | |
| terminator: Terminator::Ret, | |
| }], | |
| "rust-path-v1::place_mention_nop".into(), | |
| ) | |
| .unwrap(); | |
| let program = | |
| Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![body]) | |
| .unwrap(); | |
| let rendered = render(&program); | |
| assert_eq!(rendered.matches("Trusted.MirAst.StatementKind.nop").count(), 2, "{rendered}"); | |
| assert!(rendered.contains("isExternal := false"), "{rendered}"); | |
| } | |
| #[test] | |
| fn render_emits_is_external_explicitly_for_normal_and_stub_bodies() { | |
| let u32_ty = Ty::Int(IntTy { width: IntWidth::I32, signed: false }); | |
| let normal = Body::try_new( | |
| 1, | |
| false, | |
| vec![u32_ty.clone(), u32_ty.clone()], | |
| vec![Block { | |
| statements: vec![Statement::Assign { | |
| local: 0, | |
| value: Rvalue::Use { | |
| operand: Operand::Copy { local: 1 }, | |
| with_retag: false, | |
| }, | |
| }], | |
| terminator: Terminator::Ret, | |
| }], | |
| "rust-path-v1::portable".into(), | |
| ) | |
| .unwrap(); | |
| let stub = Body::try_new_external_stub( | |
| 1, | |
| true, | |
| vec![u32_ty.clone(), u32_ty], | |
| "rust-path-v1::ext_stub".into(), | |
| ) | |
| .unwrap(); | |
| let program = Program::try_new( | |
| Scope::Crate { excluded_traits: BTreeSet::new() }, | |
| vec![normal, stub], | |
| ) | |
| .unwrap(); | |
| let rendered = render(&program); | |
| assert!(rendered.contains("mirProfileVersion := 2"), "{rendered}"); | |
| assert_eq!(rendered.matches("isExternal := false").count(), 1, "{rendered}"); | |
| assert_eq!(rendered.matches("isExternal := true").count(), 1, "{rendered}"); | |
| assert!(rendered.contains("basicBlocks := [],"), "{rendered}"); | |
| } | |
| #[test] | |
| fn render_lowers_projected_place_mention_to_statement_kind_place_mention() { | |
| let u64_ty = Ty::Int(IntTy { width: IntWidth::I64, signed: false }); | |
| let body = Body::try_new( | |
| 1, | |
| false, | |
| vec![ | |
| Ty::Unit, | |
| Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(u64_ty) }, | |
| ], | |
| vec![Block { | |
| statements: vec![Statement::PlaceMentionPlace { | |
| place: Place { local: 1, projection: vec![PlaceElem::Deref] }, | |
| }], | |
| terminator: Terminator::Ret, | |
| }], | |
| "rust-path-v1::place_mention_place".into(), | |
| ) | |
| .unwrap(); | |
| let program = | |
| Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![body]) | |
| .unwrap(); | |
| let rendered = render(&program); | |
| assert!( | |
| rendered.contains( | |
| "(Trusted.MirAst.StatementKind.placeMention \ | |
| (Trusted.MirAst.Place.mk 1 [Trusted.MirAst.ProjectionElem.deref]))" | |
| ), | |
| "{rendered}" | |
| ); | |
| assert!(!rendered.contains("Trusted.MirAst.StatementKind.nop"), "{rendered}"); | |
| } | |
| } |