1use std::{fmt, hash::Hash, iter, ops::ControlFlow, sync::OnceLock};
2
3use flux_arc_interner::{Interned, List, impl_internable, impl_slice_internable};
4use flux_common::{bug, dbg::as_subscript};
5use flux_macros::{TypeFoldable, TypeVisitable};
6use flux_rustc_bridge::{
7 ToRustc,
8 const_eval::{scalar_to_bits, scalar_to_int, scalar_to_uint},
9 ty::{Const, ConstKind, ValTree, VariantIdx},
10};
11use flux_syntax::symbols::sym;
12use itertools::Itertools;
13use liquid_fixpoint::ThyFunc;
14use rustc_abi::{FIRST_VARIANT, FieldIdx};
15use rustc_data_structures::{snapshot_map::SnapshotMap, unord::UnordMap};
16use rustc_hir::def_id::DefId;
17use rustc_index::newtype_index;
18use rustc_macros::{Decodable, Encodable, TyDecodable, TyEncodable};
19use rustc_middle::{
20 mir::Local,
21 ty::{ParamConst, ScalarInt, TyCtxt},
22};
23use rustc_span::{Span, Symbol};
24use rustc_type_ir::{BoundVar, DebruijnIndex, INNERMOST};
25
26use super::{
27 BaseTy, Binder, BoundReftKind, BoundVariableKinds, FuncSort, GenericArgs, GenericArgsExt as _,
28 IntTy, Sort, UintTy,
29};
30use crate::{
31 big_int::BigInt,
32 def_id::FluxDefId,
33 fhir::{self},
34 global_env::GlobalEnv,
35 pretty::*,
36 queries::QueryResult,
37 rty::{
38 BoundVariableKind, SortArg, SortCtor, SubsetTyCtor,
39 fold::{
40 TypeFoldable, TypeFolder, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable,
41 TypeVisitor,
42 },
43 },
44};
45
46#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)]
49pub struct Lambda {
50 body: Binder<Expr>,
51 output: Sort,
52}
53
54impl Lambda {
55 pub fn bind_with_vars(body: Expr, inputs: BoundVariableKinds, output: Sort) -> Self {
56 debug_assert!(inputs.iter().all(BoundVariableKind::is_refine));
57 Self { body: Binder::bind_with_vars(body, inputs), output }
58 }
59
60 pub fn bind_with_fsort(body: Expr, fsort: FuncSort) -> Self {
61 Self { body: Binder::bind_with_sorts(body, fsort.inputs()), output: fsort.output().clone() }
62 }
63
64 pub fn apply(&self, args: &[Expr]) -> Expr {
65 self.body.replace_bound_refts(args)
66 }
67
68 pub fn vars(&self) -> &BoundVariableKinds {
69 self.body.vars()
70 }
71
72 pub fn output(&self) -> Sort {
73 self.output.clone()
74 }
75
76 pub fn fsort(&self) -> FuncSort {
77 let inputs_and_output = self
78 .vars()
79 .iter()
80 .map(|kind| kind.expect_sort().clone())
81 .chain(iter::once(self.output()))
82 .collect();
83 FuncSort { inputs_and_output }
84 }
85}
86
87#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)]
88pub struct AliasReft {
89 pub assoc_id: FluxDefId,
91 pub args: GenericArgs,
92}
93
94impl AliasReft {
95 pub fn self_ty(&self) -> SubsetTyCtor {
96 self.args[0].expect_base().clone()
97 }
98
99 pub fn to_rustc_trait_ref<'tcx>(&self, tcx: TyCtxt<'tcx>) -> rustc_middle::ty::TraitRef<'tcx> {
100 let trait_def_id = self.assoc_id.parent();
101 let args = self
102 .args
103 .to_rustc(tcx)
104 .truncate_to(tcx, tcx.generics_of(trait_def_id));
105 rustc_middle::ty::TraitRef::new(tcx, trait_def_id, args)
106 }
107}
108
109#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
110pub struct Expr {
111 kind: Interned<ExprKind>,
112 espan: Option<ESpan>,
113}
114
115impl Expr {
116 pub fn at_opt(self, espan: Option<ESpan>) -> Expr {
117 Expr { kind: self.kind, espan }
118 }
119
120 pub fn at(self, espan: ESpan) -> Expr {
121 self.at_opt(Some(espan))
122 }
123
124 pub fn at_base(self, base: ESpan) -> Expr {
125 if let Some(espan) = self.espan { self.at(espan.with_base(base)) } else { self }
126 }
127
128 pub fn span(&self) -> Option<ESpan> {
129 self.espan
130 }
131
132 pub fn tt() -> Expr {
133 static TRUE: OnceLock<Expr> = OnceLock::new();
134 TRUE.get_or_init(|| ExprKind::Constant(Constant::Bool(true)).intern())
135 .clone()
136 }
137
138 pub fn ff() -> Expr {
139 static FALSE: OnceLock<Expr> = OnceLock::new();
140 FALSE
141 .get_or_init(|| ExprKind::Constant(Constant::Bool(false)).intern())
142 .clone()
143 }
144
145 pub fn and_from_iter(exprs: impl IntoIterator<Item = Expr>) -> Expr {
146 exprs
147 .into_iter()
148 .reduce(|acc, e| Expr::binary_op(BinOp::And, acc, e))
149 .unwrap_or_else(Expr::tt)
150 }
151
152 pub fn conjoin_bodies<'a>(
155 binders: impl IntoIterator<Item = &'a Binder<Expr>>,
156 ) -> Option<Binder<Expr>> {
157 let mut binders = binders.into_iter().peekable();
158 let Some(first) = binders.peek() else { return None };
159 let sorts = first.sorts();
160 let body = Expr::and_from_iter(binders.into_iter().map(|b| b.skip_binder_ref().clone()));
161 Some(Binder::bind_with_sorts(body, &sorts))
162 }
163
164 pub fn or_from_iter(exprs: impl IntoIterator<Item = Expr>) -> Expr {
165 exprs
166 .into_iter()
167 .reduce(|acc, e| Expr::binary_op(BinOp::Or, acc, e))
168 .unwrap_or_else(Expr::ff)
169 }
170
171 pub fn and(e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
172 Expr::and_from_iter([e1.into(), e2.into()])
173 }
174
175 pub fn or(e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
176 Expr::or_from_iter([e1.into(), e2.into()])
177 }
178
179 pub fn zero() -> Expr {
180 static ZERO: OnceLock<Expr> = OnceLock::new();
181 ZERO.get_or_init(|| ExprKind::Constant(Constant::ZERO).intern())
182 .clone()
183 }
184
185 pub fn int_max(int_ty: IntTy) -> Expr {
186 let bit_width: u64 = int_ty
187 .bit_width()
188 .unwrap_or(flux_config::pointer_width().bits());
189 Expr::constant(Constant::int_max(bit_width.try_into().unwrap()))
190 }
191
192 pub fn int_min(int_ty: IntTy) -> Expr {
193 let bit_width: u64 = int_ty
194 .bit_width()
195 .unwrap_or(flux_config::pointer_width().bits());
196 Expr::constant(Constant::int_min(bit_width.try_into().unwrap()))
197 }
198
199 pub fn uint_max(uint_ty: UintTy) -> Expr {
200 let bit_width: u64 = uint_ty
201 .bit_width()
202 .unwrap_or(flux_config::pointer_width().bits());
203 Expr::constant(Constant::uint_max(bit_width.try_into().unwrap()))
204 }
205
206 pub fn nu() -> Expr {
207 Expr::bvar(INNERMOST, BoundVar::ZERO, BoundReftKind::Anon)
208 }
209
210 pub fn is_nu(&self) -> bool {
211 if let ExprKind::Var(Var::Bound(INNERMOST, var)) = self.kind()
212 && var.var == BoundVar::ZERO
213 {
214 true
215 } else {
216 false
217 }
218 }
219
220 pub fn unit() -> Expr {
221 Expr::tuple(List::empty())
222 }
223
224 pub fn var(var: Var) -> Expr {
225 ExprKind::Var(var).intern()
226 }
227
228 pub fn fvar(name: Name) -> Expr {
229 Var::Free(name).to_expr()
230 }
231
232 pub fn evar(evid: EVid) -> Expr {
233 Var::EVar(evid).to_expr()
234 }
235
236 pub fn bvar(debruijn: DebruijnIndex, var: BoundVar, kind: BoundReftKind) -> Expr {
237 Var::Bound(debruijn, BoundReft { var, kind }).to_expr()
238 }
239
240 pub fn early_param(index: u32, name: Symbol) -> Expr {
241 Var::EarlyParam(EarlyReftParam { index, name }).to_expr()
242 }
243
244 pub fn local(local: Local) -> Expr {
245 ExprKind::Local(local).intern()
246 }
247
248 pub fn constant(c: Constant) -> Expr {
249 ExprKind::Constant(c).intern()
250 }
251
252 pub fn const_def_id(c: DefId) -> Expr {
253 ExprKind::ConstDefId(c).intern()
254 }
255
256 pub fn const_generic(param: ParamConst) -> Expr {
257 ExprKind::Var(Var::ConstGeneric(param)).intern()
258 }
259
260 pub fn tuple(flds: List<Expr>) -> Expr {
261 ExprKind::Tuple(flds).intern()
262 }
263
264 pub fn ctor_struct(def_id: DefId, flds: List<Expr>) -> Expr {
265 ExprKind::Ctor(Ctor::Struct(def_id), flds).intern()
266 }
267
268 pub fn ctor_raw_ptr(flds: List<Expr>) -> Expr {
269 ExprKind::Ctor(Ctor::RawPtr, flds).intern()
270 }
271
272 pub fn ctor_enum(def_id: DefId, idx: VariantIdx) -> Expr {
273 ExprKind::Ctor(Ctor::Enum(def_id, idx), List::empty()).intern()
274 }
275
276 pub fn ctor(ctor: Ctor, flds: List<Expr>) -> Expr {
277 ExprKind::Ctor(ctor, flds).intern()
278 }
279
280 pub fn is_ctor(def_id: DefId, variant_idx: VariantIdx, idx: impl Into<Expr>) -> Expr {
281 ExprKind::IsCtor(def_id, variant_idx, idx.into()).intern()
282 }
283
284 pub fn from_bits(bty: &BaseTy, bits: u128) -> Expr {
285 match bty {
287 BaseTy::Int(_) => {
288 let bits = bits as i128;
289 ExprKind::Constant(Constant::from(bits)).intern()
290 }
291 BaseTy::Uint(_) => ExprKind::Constant(Constant::from(bits)).intern(),
292 BaseTy::Bool => ExprKind::Constant(Constant::Bool(bits != 0)).intern(),
293 BaseTy::Char => {
294 let c = char::from_u32(bits.try_into().unwrap()).unwrap();
295 ExprKind::Constant(Constant::Char(c)).intern()
296 }
297 _ => bug!(),
298 }
299 }
300
301 pub fn ite(p: impl Into<Expr>, e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
302 ExprKind::IfThenElse(p.into(), e1.into(), e2.into()).intern()
303 }
304
305 fn empty() -> Expr {
306 let func = Self::global_func(SpecFuncKind::Thy(ThyFunc::SetEmpty));
307 Expr::app(func, List::empty(), List::from_arr([Expr::zero()]))
308 }
309
310 fn singleton(elem: Expr) -> Expr {
311 let func = Self::global_func(SpecFuncKind::Thy(ThyFunc::SetSng));
312 Expr::app(func, List::empty(), List::from_arr([elem]))
313 }
314
315 fn union(expr1: Expr, expr2: Expr) -> Expr {
316 let func = Self::global_func(SpecFuncKind::Thy(ThyFunc::SetCup));
317 Expr::app(func, List::empty(), List::from_arr([expr1, expr2]))
318 }
319
320 pub fn set(elems: List<Expr>) -> Expr {
321 let mut expr = Expr::empty();
322 for elem in &elems {
323 expr = Self::union(expr, Self::singleton(elem.clone()));
324 }
325 expr
326 }
327
328 pub fn abs(lam: Lambda) -> Expr {
329 ExprKind::Abs(lam).intern()
330 }
331
332 pub fn let_(init: Expr, body: Binder<Expr>) -> Expr {
333 ExprKind::Let(init, body).intern()
334 }
335
336 pub fn quant(kind: fhir::QuantKind, dom: QuantDom, body: Binder<Expr>) -> Expr {
337 ExprKind::Quant(kind, dom, body).intern()
338 }
339
340 pub fn hole(kind: HoleKind) -> Expr {
341 ExprKind::Hole(kind).intern()
342 }
343
344 pub fn kvar(kvar: KVar) -> Expr {
345 ExprKind::KVar(kvar).intern()
346 }
347
348 pub fn wkvar(wkvar: WKVar) -> Expr {
349 ExprKind::WKVar(wkvar).intern()
350 }
351
352 pub fn alias(alias: AliasReft, args: List<Expr>) -> Expr {
353 ExprKind::Alias(alias, args).intern()
354 }
355
356 pub fn forall(expr: Binder<Expr>) -> Expr {
357 ExprKind::Quant(fhir::QuantKind::Forall, QuantDom::Unbounded, expr).intern()
358 }
359
360 pub fn exists(expr: Binder<Expr>) -> Expr {
361 ExprKind::Quant(fhir::QuantKind::Exists, QuantDom::Unbounded, expr).intern()
362 }
363
364 pub fn binary_op(op: BinOp, e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
365 ExprKind::BinaryOp(op, e1.into(), e2.into()).intern()
366 }
367
368 pub fn prim_rel(op: BinOp, e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
369 Expr::app(InternalFuncKind::Rel(op), List::empty(), List::from_arr([e1.into(), e2.into()]))
370 }
371
372 pub fn unit_struct(def_id: DefId) -> Expr {
373 Expr::ctor_struct(def_id, List::empty())
374 }
375
376 pub fn cast(from: Sort, to: Sort, idx: Expr) -> Expr {
377 Expr::app(
378 InternalFuncKind::Cast,
379 List::from_arr([SortArg::Sort(from), SortArg::Sort(to)]),
380 List::from_arr([idx]),
381 )
382 }
383
384 pub fn app(func: impl Into<Expr>, sort_args: List<SortArg>, args: List<Expr>) -> Expr {
385 ExprKind::App(func.into(), sort_args, args).intern()
386 }
387
388 pub fn global_func(kind: SpecFuncKind) -> Expr {
389 ExprKind::GlobalFunc(kind).intern()
390 }
391
392 pub fn internal_func(kind: InternalFuncKind) -> Expr {
393 ExprKind::InternalFunc(kind).intern()
394 }
395
396 pub fn eq(e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
397 ExprKind::BinaryOp(BinOp::Eq, e1.into(), e2.into()).intern()
398 }
399
400 pub fn unary_op(op: UnOp, e: impl Into<Expr>) -> Expr {
401 ExprKind::UnaryOp(op, e.into()).intern()
402 }
403
404 pub fn ne(e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
405 ExprKind::BinaryOp(BinOp::Ne, e1.into(), e2.into()).intern()
406 }
407
408 pub fn ge(e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
409 ExprKind::BinaryOp(BinOp::Ge(Sort::Int), e1.into(), e2.into()).intern()
410 }
411
412 pub fn gt(e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
413 ExprKind::BinaryOp(BinOp::Gt(Sort::Int), e1.into(), e2.into()).intern()
414 }
415
416 pub fn lt(e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
417 ExprKind::BinaryOp(BinOp::Lt(Sort::Int), e1.into(), e2.into()).intern()
418 }
419
420 pub fn le(e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
421 ExprKind::BinaryOp(BinOp::Le(Sort::Int), e1.into(), e2.into()).intern()
422 }
423
424 pub fn implies(e1: impl Into<Expr>, e2: impl Into<Expr>) -> Expr {
425 ExprKind::BinaryOp(BinOp::Imp, e1.into(), e2.into()).intern()
426 }
427
428 pub fn field_proj(e: impl Into<Expr>, proj: FieldProj) -> Expr {
429 ExprKind::FieldProj(e.into(), proj).intern()
430 }
431
432 pub fn field_projs(e: impl Into<Expr>, projs: &[FieldProj]) -> Expr {
433 projs.iter().copied().fold(e.into(), Expr::field_proj)
434 }
435
436 pub fn path_proj(base: Expr, field: FieldIdx) -> Expr {
437 ExprKind::PathProj(base, field).intern()
438 }
439
440 pub fn not(&self) -> Expr {
441 ExprKind::UnaryOp(UnOp::Not, self.clone()).intern()
442 }
443
444 pub fn neg(&self) -> Expr {
445 ExprKind::UnaryOp(UnOp::Neg, self.clone()).intern()
446 }
447
448 pub fn kind(&self) -> &ExprKind {
449 &self.kind
450 }
451
452 pub fn is_atom(&self) -> bool {
455 !matches!(self.kind(), ExprKind::Abs(..) | ExprKind::BinaryOp(..) | ExprKind::Quant(..))
456 }
457
458 pub fn is_trivially_true(&self) -> bool {
461 self.is_true()
462 || matches!(self.kind(), ExprKind::BinaryOp(BinOp::Eq | BinOp::Iff | BinOp::Imp, e1, e2) if e1.erase_spans() == e2.erase_spans())
463 }
464
465 pub fn is_trivially_false(&self) -> bool {
467 self.is_false()
468 }
469
470 fn is_true(&self) -> bool {
472 matches!(self.kind(), ExprKind::Constant(Constant::Bool(true)))
473 }
474
475 fn is_false(&self) -> bool {
477 matches!(self.kind(), ExprKind::Constant(Constant::Bool(false)))
478 }
479
480 pub fn from_const(tcx: TyCtxt, c: &Const) -> Expr {
481 match &c.kind {
482 ConstKind::Param(param_const) => Expr::const_generic(*param_const),
483 ConstKind::Value(ty, ValTree::Leaf(scalar)) => {
484 Expr::constant(Constant::from_scalar_int(tcx, *scalar, ty).unwrap())
485 }
486 ConstKind::Value(_ty, ValTree::Branch(_)) => {
487 bug!("todo: ValTree::Branch {c:?}")
488 }
489 ConstKind::Alias(_) => bug!("unexpected `ConstKind::Alias`"),
491
492 ConstKind::Infer(_) => bug!("unexpected `ConstKind::Infer`"),
493 }
494 }
495
496 fn const_op(op: &BinOp, c1: &Constant, c2: &Constant) -> Option<Constant> {
497 match op {
498 BinOp::Iff => c1.iff(c2),
499 BinOp::Imp => c1.imp(c2),
500 BinOp::Or => c1.or(c2),
501 BinOp::And => c1.and(c2),
502 BinOp::Gt(Sort::Int) => c1.gt(c2),
503 BinOp::Ge(Sort::Int) => c1.ge(c2),
504 BinOp::Lt(Sort::Int) => c2.gt(c1),
505 BinOp::Le(Sort::Int) => c2.ge(c1),
506 BinOp::Eq => Some(c1.eq(c2)),
507 BinOp::Ne => Some(c1.ne(c2)),
508 _ => None,
509 }
510 }
511
512 pub fn simplify(&self, assumed_preds: &SnapshotMap<Expr, ()>) -> Expr {
518 struct Simplify<'a> {
519 assumed_preds: &'a SnapshotMap<Expr, ()>,
520 }
521
522 impl TypeFolder for Simplify<'_> {
523 fn fold_expr(&mut self, expr: &Expr) -> Expr {
524 if self.assumed_preds.get(&expr.erase_spans()).is_some() {
525 return Expr::tt();
526 }
527 let span = expr.span();
528 match expr.kind() {
529 ExprKind::BinaryOp(op, e1, e2) => {
530 let e1 = e1.fold_with(self);
531 let e2 = e2.fold_with(self);
532 match (op, e1.kind(), e2.kind()) {
533 (BinOp::And, ExprKind::Constant(Constant::Bool(false)), _) => {
534 Expr::constant(Constant::Bool(false)).at_opt(e1.span())
535 }
536 (BinOp::And, _, ExprKind::Constant(Constant::Bool(false))) => {
537 Expr::constant(Constant::Bool(false)).at_opt(e2.span())
538 }
539 (BinOp::And, ExprKind::Constant(Constant::Bool(true)), _) => e2,
540 (BinOp::And, _, ExprKind::Constant(Constant::Bool(true))) => e1,
541 (op, ExprKind::Constant(c1), ExprKind::Constant(c2)) => {
542 if let Some(c) = Expr::const_op(op, c1, c2) {
543 Expr::constant(c).at_opt(span.or(e2.span()))
544 } else {
545 Expr::binary_op(op.clone(), e1, e2).at_opt(span)
546 }
547 }
548 _ => Expr::binary_op(op.clone(), e1, e2).at_opt(span),
549 }
550 }
551 ExprKind::UnaryOp(UnOp::Not, e) => {
552 let e = e.fold_with(self);
553 match e.kind() {
554 ExprKind::Constant(Constant::Bool(b)) => {
555 Expr::constant(Constant::Bool(!b))
556 }
557 ExprKind::UnaryOp(UnOp::Not, e) => e.clone(),
558 ExprKind::BinaryOp(BinOp::Eq, e1, e2) => {
559 Expr::binary_op(BinOp::Ne, e1, e2).at_opt(span)
560 }
561 _ => Expr::unary_op(UnOp::Not, e).at_opt(span),
562 }
563 }
564 ExprKind::IfThenElse(p, e1, e2) => {
565 let p = p.fold_with(self);
566 if p.is_trivially_true() {
567 e1.fold_with(self).at_opt(span)
568 } else if p.is_trivially_false() {
569 e2.fold_with(self).at_opt(span)
570 } else {
571 Expr::ite(p, e1.fold_with(self), e2.fold_with(self)).at_opt(span)
572 }
573 }
574 _ => expr.super_fold_with(self),
575 }
576 }
577 }
578 self.fold_with(&mut Simplify { assumed_preds })
579 }
580
581 pub fn to_loc(&self) -> Option<Loc> {
582 match self.kind() {
583 ExprKind::Local(local) => Some(Loc::Local(*local)),
584 ExprKind::Var(var) => Some(Loc::Var(*var)),
585 _ => None,
586 }
587 }
588
589 pub fn to_path(&self) -> Option<Path> {
590 let mut expr = self;
591 let mut proj = vec![];
592 while let ExprKind::PathProj(e, field) = expr.kind() {
593 proj.push(*field);
594 expr = e;
595 }
596 proj.reverse();
597 Some(Path::new(expr.to_loc()?, proj))
598 }
599
600 pub fn is_unit(&self) -> bool {
602 matches!(self.kind(), ExprKind::Tuple(flds) if flds.is_empty())
603 || matches!(self.kind(), ExprKind::Ctor(Ctor::Struct(_), flds) if flds.is_empty())
604 }
605
606 pub fn eta_expand_abs(&self, inputs: &BoundVariableKinds, output: Sort) -> Lambda {
607 let args = (0..inputs.len())
608 .map(|idx| Expr::bvar(INNERMOST, BoundVar::from_usize(idx), BoundReftKind::Anon))
609 .collect();
610 let body = Expr::app(self, List::empty(), args);
611 Lambda::bind_with_vars(body, inputs.clone(), output)
612 }
613
614 pub fn proj_and_reduce(&self, proj: FieldProj) -> Expr {
616 match self.kind() {
617 ExprKind::Tuple(flds) | ExprKind::Ctor(Ctor::Struct(_) | Ctor::RawPtr, flds) => {
618 flds[proj.field_idx() as usize].clone()
619 }
620 _ => Expr::field_proj(self.clone(), proj),
621 }
622 }
623
624 pub fn reduce_ptr_addr(&self) -> Expr {
626 self.proj_and_reduce(FieldProj::RawPtr { field: RawPtrField::Addr })
627 }
628
629 pub fn visit_conj<'a>(&'a self, mut f: impl FnMut(&'a Expr)) {
630 fn go<'a>(e: &'a Expr, f: &mut impl FnMut(&'a Expr)) {
631 if let ExprKind::BinaryOp(BinOp::And, e1, e2) = e.kind() {
632 go(e1, f);
633 go(e2, f);
634 } else {
635 f(e);
636 }
637 }
638 go(self, &mut f);
639 }
640
641 pub fn flatten_conjs(&self) -> Vec<&Expr> {
642 let mut vec = vec![];
643 self.visit_conj(|e| vec.push(e));
644 vec
645 }
646
647 pub fn has_evars(&self) -> bool {
648 struct HasEvars;
649
650 impl TypeVisitor for HasEvars {
651 type BreakTy = ();
652 fn visit_expr(&mut self, expr: &Expr) -> ControlFlow<Self::BreakTy> {
653 if let ExprKind::Var(Var::EVar(_)) = expr.kind() {
654 ControlFlow::Break(())
655 } else {
656 expr.super_visit_with(self)
657 }
658 }
659 }
660
661 self.visit_with(&mut HasEvars).is_break()
662 }
663
664 pub fn erase_spans(&self) -> Expr {
665 struct SpanEraser;
666 impl TypeFolder for SpanEraser {
667 fn fold_expr(&mut self, e: &Expr) -> Expr {
668 e.super_fold_with(self).at_opt(None)
669 }
670 }
671 self.fold_with(&mut SpanEraser)
672 }
673
674 pub fn erase_bound_reft_kind(&self) -> Expr {
682 struct BoundReftKindEraser;
683 impl TypeFolder for BoundReftKindEraser {
684 fn fold_expr(&mut self, expr: &Expr) -> Expr {
685 if let ExprKind::Var(Var::Bound(
686 db_index,
687 BoundReft { var, kind: BoundReftKind::Named(_) },
688 )) = expr.kind()
689 {
690 Expr::bvar(*db_index, *var, BoundReftKind::Anon)
691 } else {
692 expr.super_fold_with(self)
693 }
694 }
695 }
696 self.fold_with(&mut BoundReftKindEraser)
697 }
698
699 pub fn erase_metadata(&self) -> Expr {
700 self.erase_spans().erase_bound_reft_kind()
701 }
702
703 pub fn expand_bin_rels(&self) -> Expr {
717 struct BinRelExpander;
718 impl BinRelExpander {
719 fn expand_bin_rel(&mut self, sort: &Sort, rel: &BinOp, e1: &Expr, e2: &Expr) -> Expr {
720 match sort {
721 Sort::Tuple(sorts) => {
722 let arity = sorts.len();
723 self.apply_bin_rel_rec(sorts, rel, e1, e2, |field| {
724 FieldProj::Tuple { arity, field }
725 })
726 }
727 Sort::App(SortCtor::Adt(sort_def), args)
728 if let Some(variant) = sort_def.opt_struct_variant() =>
729 {
730 let def_id = sort_def.did();
731 let sorts = variant.field_sorts(args);
732 self.apply_bin_rel_rec(&sorts, rel, e1, e2, |field| {
733 FieldProj::Adt { def_id, field }
734 })
735 }
736 _ => {
737 Expr::binary_op(
738 rel.clone(),
739 e1.super_fold_with(self),
740 e2.super_fold_with(self),
741 )
742 }
743 }
744 }
745 fn apply_bin_rel_rec(
747 &mut self,
748 sorts: &[Sort],
749 rel: &BinOp,
750 e1: &Expr,
751 e2: &Expr,
752 mk_proj: impl Fn(u32) -> FieldProj,
753 ) -> Expr {
754 Expr::and_from_iter(sorts.iter().enumerate().map(|(idx, s)| {
755 let proj = mk_proj(idx as u32);
756 let e1 = e1.proj_and_reduce(proj);
757 let e2 = e2.proj_and_reduce(proj);
758 self.expand_bin_rel(s, rel, &e1, &e2)
759 }))
760 }
761 }
762 impl TypeFolder for BinRelExpander {
763 fn fold_expr(&mut self, expr: &Expr) -> Expr {
764 if let ExprKind::BinaryOp(
765 rel @ (BinOp::Le(sort) | BinOp::Lt(sort) | BinOp::Ge(sort) | BinOp::Gt(sort)),
766 e1,
767 e2,
768 ) = expr.kind()
769 {
770 self.expand_bin_rel(sort, rel, e1, e2)
771 } else {
772 expr.super_fold_with(self)
773 }
774 }
775 }
776
777 let mut expander = BinRelExpander {};
778 self.fold_with(&mut expander)
779 }
780
781 pub fn eta_reduce_projs(&self) -> Self {
789 struct EtaReducer;
790 impl TypeFolder for EtaReducer {
791 fn fold_expr(&mut self, expr: &Expr) -> Expr {
792 match expr.kind() {
793 ExprKind::Tuple(subexprs) => {
794 let new_subexprs = subexprs
795 .iter()
796 .map(|subexpr| subexpr.fold_with(self))
797 .collect_vec();
798 if let Some(ExprKind::FieldProj(
799 e_inner,
800 FieldProj::Tuple { arity: _, field: 0 },
801 )) = subexprs.first().map(|e| e.kind())
802 && new_subexprs[1..].iter().zip(1..).all(|(other_e, i)| {
803 if let ExprKind::FieldProj(
804 other_e_inner,
805 FieldProj::Tuple { arity: _, field },
806 ) = other_e.kind()
807 {
808 field == &i && &e_inner.erase_metadata() == other_e_inner
809 } else {
810 false
811 }
812 })
813 {
814 e_inner.clone()
815 } else {
816 expr.clone()
817 }
818 }
819 ExprKind::Ctor(_ctor, subexprs) => {
820 let new_subexprs = subexprs
821 .iter()
822 .map(|subexpr| subexpr.fold_with(self))
823 .collect_vec();
824 if let Some(ExprKind::FieldProj(
825 e_inner,
826 FieldProj::Adt { def_id: _, field: 0 },
827 )) = subexprs.first().map(|e| e.kind())
828 && new_subexprs[1..].iter().zip(1..).all(|(other_e, i)| {
829 if let ExprKind::FieldProj(
830 other_e_inner,
831 FieldProj::Adt { def_id: _, field },
832 ) = other_e.kind()
833 {
834 field == &i && &e_inner.erase_metadata() == other_e_inner
835 } else {
836 false
837 }
838 })
839 {
840 e_inner.clone()
841 } else {
842 expr.clone()
843 }
844 }
845 _ => expr.super_fold_with(self),
846 }
847 }
848 }
849 self.fold_with(&mut EtaReducer)
850 }
851}
852
853#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug)]
854pub struct ESpan {
855 pub span: Span,
857 pub base: Option<Span>,
859}
860
861impl ESpan {
862 pub fn new(span: Span) -> Self {
863 Self { span, base: None }
864 }
865
866 pub fn with_base(&self, espan: ESpan) -> Self {
867 Self { span: self.span, base: Some(espan.span) }
868 }
869}
870
871#[derive(
872 Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, TypeFoldable, TypeVisitable,
873)]
874pub enum BinOp {
875 Iff,
876 Imp,
877 Or,
878 And,
879 Eq,
880 Ne,
881 Gt(Sort),
882 Ge(Sort),
883 Lt(Sort),
884 Le(Sort),
885 Add(Sort),
886 Sub(Sort),
887 Mul(Sort),
888 Div(Sort),
889 Mod(Sort),
890 BitAnd(Sort),
891 BitOr(Sort),
892 BitXor(Sort),
893 BitShl(Sort),
894 BitShr(Sort),
895}
896
897impl BinOp {
898 pub fn is_uninterpreted(&self) -> bool {
902 matches!(
903 self,
904 BinOp::BitAnd(Sort::Int)
905 | BinOp::BitOr(Sort::Int)
906 | BinOp::BitXor(Sort::Int)
907 | BinOp::BitShl(Sort::Int)
908 | BinOp::BitShr(Sort::Int)
909 )
910 }
911
912 pub fn uif_sort(&self) -> Option<super::PolyFuncSort> {
918 let sort = match self {
919 BinOp::Add(sort)
920 | BinOp::Sub(sort)
921 | BinOp::Mul(sort)
922 | BinOp::Div(sort)
923 | BinOp::Mod(sort)
924 | BinOp::BitAnd(sort)
925 | BinOp::BitOr(sort)
926 | BinOp::BitXor(sort)
927 | BinOp::BitShl(sort)
928 | BinOp::BitShr(sort) => sort,
929 BinOp::Iff
930 | BinOp::Imp
931 | BinOp::Or
932 | BinOp::And
933 | BinOp::Eq
934 | BinOp::Ne
935 | BinOp::Gt(_)
936 | BinOp::Ge(_)
937 | BinOp::Lt(_)
938 | BinOp::Le(_) => return None,
939 };
940 let fsort = FuncSort::new(vec![sort.clone(), sort.clone()], sort.clone());
941 Some(super::PolyFuncSort::new(List::empty(), fsort))
942 }
943}
944
945#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Debug, Decodable)]
946pub enum UnOp {
947 Not,
948 Neg,
949}
950
951#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, TyEncodable, TyDecodable)]
952pub enum Ctor {
953 Struct(DefId),
955 Enum(DefId, VariantIdx),
957 RawPtr,
959}
960
961impl Ctor {
962 fn is_enum(&self) -> bool {
963 matches!(self, Self::Enum(..))
964 }
965
966 pub fn def_id_and_variant(&self) -> Option<(DefId, VariantIdx)> {
967 match self {
968 Self::Struct(def_id) => Some((*def_id, FIRST_VARIANT)),
969 Self::Enum(def_id, variant_idx) => Some((*def_id, *variant_idx)),
970 Self::RawPtr => None,
971 }
972 }
973}
974
975#[derive(Debug, Clone, TyEncodable, TyDecodable, PartialEq, Eq, Hash)]
989pub enum InternalFuncKind {
990 Rel(BinOp),
992 Cast,
994}
995
996#[derive(Debug, Clone, TyEncodable, TyDecodable, PartialEq, Eq, Hash)]
997pub enum SpecFuncKind {
998 Thy(liquid_fixpoint::ThyFunc),
1000 Def(FluxDefId),
1002}
1003
1004#[derive(
1005 Clone, PartialEq, Eq, Hash, TyEncodable, Debug, TyDecodable, TypeVisitable, TypeFoldable,
1006)]
1007pub enum QuantDom {
1008 Bounded { start: usize, end: usize },
1009 Unbounded,
1010}
1011
1012#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, Debug, TyDecodable)]
1013pub enum ExprKind {
1014 Var(Var),
1015 Local(Local),
1016 Constant(Constant),
1017 ConstDefId(DefId),
1019 BinaryOp(BinOp, Expr, Expr),
1020 GlobalFunc(SpecFuncKind),
1021 InternalFunc(InternalFuncKind),
1022 UnaryOp(UnOp, Expr),
1023 FieldProj(Expr, FieldProj),
1024 Ctor(Ctor, List<Expr>),
1026 Tuple(List<Expr>),
1027 PathProj(Expr, FieldIdx),
1028 IfThenElse(Expr, Expr, Expr),
1029 KVar(KVar),
1030 WKVar(WKVar),
1031 Alias(AliasReft, List<Expr>),
1032 Let(Expr, Binder<Expr>),
1033 App(Expr, List<SortArg>, List<Expr>),
1039 Abs(Lambda),
1049
1050 Quant(fhir::QuantKind, QuantDom, Binder<Expr>),
1052 Hole(HoleKind),
1066 IsCtor(DefId, VariantIdx, Expr),
1068}
1069
1070impl ExprKind {
1071 fn intern(self) -> Expr {
1072 Expr { kind: Interned::new(self), espan: None }
1073 }
1074}
1075
1076#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug)]
1077pub enum AggregateKind {
1078 Tuple(usize),
1079 Adt(DefId),
1080}
1081
1082#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug)]
1083pub enum FieldProj {
1084 Tuple { arity: usize, field: u32 },
1085 Adt { def_id: DefId, field: u32 },
1086 RawPtr { field: RawPtrField },
1087}
1088
1089#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug)]
1090pub enum RawPtrField {
1091 Base,
1092 Addr,
1093 Size,
1094}
1095
1096struct RawPtrFieldData {
1097 field: RawPtrField,
1098 index: u32,
1099 name: &'static str,
1100 sort: Sort,
1101}
1102
1103impl FieldProj {
1104 pub fn arity(&self, genv: GlobalEnv) -> QueryResult<usize> {
1105 match self {
1106 FieldProj::Tuple { arity, .. } => Ok(*arity),
1107 FieldProj::Adt { def_id, .. } => {
1108 Ok(genv.adt_sort_def_of(*def_id)?.struct_variant().fields())
1109 }
1110 FieldProj::RawPtr { .. } => Ok(RawPtrField::arity()),
1111 }
1112 }
1113
1114 pub fn field_idx(&self) -> u32 {
1115 match self {
1116 FieldProj::Tuple { field, .. } | FieldProj::Adt { field, .. } => *field,
1117 FieldProj::RawPtr { field } => field.index(),
1118 }
1119 }
1120}
1121
1122impl RawPtrField {
1123 const DATA: [RawPtrFieldData; 3] = [
1124 RawPtrFieldData { field: Self::Base, index: 0, name: "base", sort: Sort::Int },
1125 RawPtrFieldData { field: Self::Addr, index: 1, name: "addr", sort: Sort::Int },
1126 RawPtrFieldData { field: Self::Size, index: 2, name: "size", sort: Sort::Int },
1127 ];
1128
1129 pub fn iter() -> impl ExactSizeIterator<Item = Self> {
1130 Self::DATA.iter().map(|data| data.field)
1131 }
1132
1133 pub fn arity() -> usize {
1134 Self::DATA.len()
1135 }
1136
1137 fn data(self) -> &'static RawPtrFieldData {
1138 Self::DATA.iter().find(|data| data.field == self).unwrap()
1139 }
1140
1141 pub fn from_name(name: Symbol) -> Option<Self> {
1142 Self::DATA
1143 .iter()
1144 .find(|data| data.name == name.as_str())
1145 .map(|data| data.field)
1146 }
1147
1148 pub fn from_index(index: u32) -> Option<Self> {
1149 Self::DATA
1150 .iter()
1151 .find(|data| data.index == index)
1152 .map(|data| data.field)
1153 }
1154
1155 pub fn sort(self) -> Sort {
1156 self.data().sort.clone()
1157 }
1158
1159 pub fn index(self) -> u32 {
1160 self.data().index
1161 }
1162
1163 pub fn name(self) -> &'static str {
1164 self.data().name
1165 }
1166
1167 pub fn symbol(self) -> Symbol {
1168 match self {
1169 Self::Base => sym::base,
1170 Self::Addr => sym::addr,
1171 Self::Size => rustc_span::sym::size,
1172 }
1173 }
1174}
1175
1176#[derive(
1182 Debug, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable,
1183)]
1184pub enum HoleKind {
1185 Pred,
1190 Expr(Sort),
1197}
1198
1199#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)]
1205pub struct KVar {
1206 pub kvid: KVid,
1207 pub self_args: usize,
1209 pub args: List<Expr>,
1212}
1213
1214#[derive(
1215 Debug, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
1216)]
1217pub struct WKVid {
1218 pub parent_fn: DefId,
1221 pub id: KVid,
1224}
1225
1226impl WKVid {
1227 pub fn new(parent_fn: DefId, id: KVid) -> Self {
1228 Self { parent_fn, id }
1229 }
1230}
1231
1232#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)]
1237pub struct WKVar {
1238 pub wkvid: WKVid,
1239 pub self_args: usize,
1273 pub args: List<Expr>,
1275}
1276
1277#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Encodable, Decodable)]
1278pub struct EarlyReftParam {
1279 pub index: u32,
1280 pub name: Symbol,
1281}
1282
1283#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Encodable, Decodable, Debug)]
1284pub struct BoundReft {
1285 pub var: BoundVar,
1286 pub kind: BoundReftKind,
1287}
1288
1289#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)]
1290pub enum Var {
1291 Free(Name),
1292 Bound(DebruijnIndex, BoundReft),
1293 EarlyParam(EarlyReftParam),
1294 EVar(EVid),
1295 ConstGeneric(ParamConst),
1296}
1297
1298#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)]
1299pub struct Path {
1300 pub loc: Loc,
1301 projection: List<FieldIdx>,
1302}
1303
1304#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)]
1305pub enum Loc {
1306 Local(Local),
1307 Var(Var),
1308}
1309
1310newtype_index! {
1311 #[debug_format = "?{}e"]
1313 #[orderable]
1314 #[encodable]
1315 pub struct EVid {}
1316}
1317
1318newtype_index! {
1319 #[debug_format = "$k{}"]
1320 #[encodable]
1321 pub struct KVid {}
1322}
1323
1324impl liquid_fixpoint::Identifier for KVid {
1325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1326 write!(f, "k{}", self.as_u32())
1327 }
1328}
1329
1330newtype_index! {
1331 #[debug_format = "a{}"]
1332 #[orderable]
1333 #[encodable]
1334 pub struct Name {}
1335}
1336
1337#[derive(Copy, Debug, Clone)]
1338pub enum NameProvenance {
1339 Unknown,
1340 UnfoldBoundReft(BoundReftKind),
1341}
1342
1343impl NameProvenance {
1344 pub fn opt_symbol(&self) -> Option<Symbol> {
1345 match &self {
1346 NameProvenance::UnfoldBoundReft(BoundReftKind::Named(name)) => Some(*name),
1347 _ => None,
1348 }
1349 }
1350}
1351
1352#[derive(PartialEq, Eq, Hash, Debug)]
1353pub enum PrettyVar<V> {
1354 Local(V),
1355 Param(EarlyReftParam),
1356}
1357
1358impl<V: Copy + Into<usize>> PrettyVar<V> {
1359 pub fn as_subscript(&self) -> String {
1360 let idx = match self {
1361 PrettyVar::Local(v) => (*v).into(),
1362 PrettyVar::Param(p) => p.index as usize,
1363 };
1364 as_subscript(idx)
1365 }
1366}
1367
1368pub struct PrettyMap<V: Eq + Hash> {
1369 map: UnordMap<PrettyVar<V>, String>,
1370 count: UnordMap<Symbol, usize>,
1371}
1372
1373impl<V: Eq + Hash + Copy + Into<usize>> PrettyMap<V> {
1374 pub fn new() -> Self {
1375 PrettyMap { map: UnordMap::default(), count: UnordMap::default() }
1376 }
1377
1378 pub fn set(&mut self, var: PrettyVar<V>, prefix: Option<Symbol>) -> String {
1379 if let Some(symbol) = self.map.get(&var) {
1381 return symbol.clone();
1382 }
1383 let symbol = if let Some(prefix) = prefix {
1385 let index = self.count.entry(prefix).or_insert(0);
1386 let symbol = format!("{}{}", prefix, as_subscript(*index));
1387 *index += 1;
1388 symbol
1389 } else {
1390 format!("a'{}", var.as_subscript())
1391 };
1392 self.map.insert(var, symbol.clone());
1393 symbol
1394 }
1395
1396 pub fn get(&self, key: &PrettyVar<V>) -> String {
1397 match self.map.get(key) {
1398 Some(s) => s.clone(),
1399 None => format!("a'{}", key.as_subscript()),
1400 }
1401 }
1402}
1403
1404impl KVar {
1405 pub fn new(kvid: KVid, self_args: usize, args: Vec<Expr>) -> Self {
1406 KVar { kvid, self_args, args: List::from_vec(args) }
1407 }
1408
1409 fn self_args(&self) -> &[Expr] {
1410 &self.args[..self.self_args]
1411 }
1412
1413 fn scope(&self) -> &[Expr] {
1414 &self.args[self.self_args..]
1415 }
1416}
1417
1418impl WKVar {
1419 fn self_args(&self) -> &[Expr] {
1420 &self.args[..self.self_args]
1421 }
1422
1423 fn scope(&self) -> &[Expr] {
1424 &self.args[self.self_args..]
1425 }
1426}
1427
1428impl Var {
1429 pub fn to_expr(&self) -> Expr {
1430 Expr::var(*self)
1431 }
1432
1433 pub fn shift_in(&self, amount: u32) -> Self {
1434 match self {
1435 Var::Bound(idx, breft) => Var::Bound(idx.shifted_in(amount), *breft),
1436 _ => *self,
1437 }
1438 }
1439
1440 pub fn shift_out(&self, amount: u32) -> Self {
1441 match self {
1442 Var::Bound(idx, breft) => Var::Bound(idx.shifted_out(amount), *breft),
1443 _ => *self,
1444 }
1445 }
1446}
1447
1448impl Path {
1449 pub fn new(loc: Loc, projection: impl Into<List<FieldIdx>>) -> Path {
1450 Path { loc, projection: projection.into() }
1451 }
1452
1453 pub fn projection(&self) -> &[FieldIdx] {
1454 &self.projection[..]
1455 }
1456
1457 pub fn to_expr(&self) -> Expr {
1458 self.projection
1459 .iter()
1460 .fold(self.loc.to_expr(), |e, f| Expr::path_proj(e, *f))
1461 }
1462
1463 pub fn to_loc(&self) -> Option<Loc> {
1464 if self.projection.is_empty() { Some(self.loc) } else { None }
1465 }
1466}
1467
1468impl Loc {
1469 pub fn to_expr(&self) -> Expr {
1470 match self {
1471 Loc::Local(local) => Expr::local(*local),
1472 Loc::Var(var) => Expr::var(*var),
1473 }
1474 }
1475}
1476
1477macro_rules! impl_ops {
1478 ($($op:ident: $method:ident),*) => {$(
1479 impl<Rhs> std::ops::$op<Rhs> for Expr
1480 where
1481 Rhs: Into<Expr>,
1482 {
1483 type Output = Expr;
1484
1485 fn $method(self, rhs: Rhs) -> Self::Output {
1486 let sort = crate::rty::Sort::Int;
1487 Expr::binary_op(BinOp::$op(sort), self, rhs)
1488 }
1489 }
1490
1491 impl<Rhs> std::ops::$op<Rhs> for &Expr
1492 where
1493 Rhs: Into<Expr>,
1494 {
1495 type Output = Expr;
1496
1497 fn $method(self, rhs: Rhs) -> Self::Output {
1498 let sort = crate::rty::Sort::Int;
1499 Expr::binary_op(BinOp::$op(sort), self, rhs)
1500 }
1501 }
1502 )*};
1503}
1504impl_ops!(Add: add, Sub: sub, Mul: mul, Div: div);
1505
1506impl From<i32> for Expr {
1507 fn from(value: i32) -> Self {
1508 Expr::constant(Constant::from(value))
1509 }
1510}
1511
1512impl From<&Expr> for Expr {
1513 fn from(e: &Expr) -> Self {
1514 e.clone()
1515 }
1516}
1517
1518impl From<Path> for Expr {
1519 fn from(path: Path) -> Self {
1520 path.to_expr()
1521 }
1522}
1523
1524impl From<Name> for Expr {
1525 fn from(name: Name) -> Self {
1526 Expr::fvar(name)
1527 }
1528}
1529
1530impl From<Var> for Expr {
1531 fn from(var: Var) -> Self {
1532 Expr::var(var)
1533 }
1534}
1535
1536impl From<SpecFuncKind> for Expr {
1537 fn from(kind: SpecFuncKind) -> Self {
1538 Expr::global_func(kind)
1539 }
1540}
1541
1542impl From<InternalFuncKind> for Expr {
1543 fn from(kind: InternalFuncKind) -> Self {
1544 Expr::internal_func(kind)
1545 }
1546}
1547
1548impl From<Loc> for Path {
1549 fn from(loc: Loc) -> Self {
1550 Path::new(loc, vec![])
1551 }
1552}
1553
1554impl From<Name> for Loc {
1555 fn from(name: Name) -> Self {
1556 Loc::Var(Var::Free(name))
1557 }
1558}
1559
1560impl From<Local> for Loc {
1561 fn from(local: Local) -> Self {
1562 Loc::Local(local)
1563 }
1564}
1565
1566#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable)]
1567pub struct Real(pub Symbol);
1568
1569#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable)]
1570pub enum Constant {
1571 Int(BigInt),
1572 Real(Real),
1573 Bool(bool),
1574 Str(Symbol),
1575 Char(char),
1576 BitVec(u128, u32),
1577}
1578
1579impl Constant {
1580 pub const ZERO: Constant = Constant::Int(BigInt::ZERO);
1581 pub const ONE: Constant = Constant::Int(BigInt::ONE);
1582 pub const TRUE: Constant = Constant::Bool(true);
1583
1584 fn to_bool(self) -> Option<bool> {
1585 match self {
1586 Constant::Bool(b) => Some(b),
1587 _ => None,
1588 }
1589 }
1590
1591 fn to_int(self) -> Option<BigInt> {
1592 match self {
1593 Constant::Int(n) => Some(n),
1594 _ => None,
1595 }
1596 }
1597
1598 pub fn iff(&self, other: &Constant) -> Option<Constant> {
1599 let b1 = self.to_bool()?;
1600 let b2 = other.to_bool()?;
1601 Some(Constant::Bool(b1 == b2))
1602 }
1603
1604 pub fn imp(&self, other: &Constant) -> Option<Constant> {
1605 let b1 = self.to_bool()?;
1606 let b2 = other.to_bool()?;
1607 Some(Constant::Bool(!b1 || b2))
1608 }
1609
1610 pub fn or(&self, other: &Constant) -> Option<Constant> {
1611 let b1 = self.to_bool()?;
1612 let b2 = other.to_bool()?;
1613 Some(Constant::Bool(b1 || b2))
1614 }
1615
1616 pub fn and(&self, other: &Constant) -> Option<Constant> {
1617 let b1 = self.to_bool()?;
1618 let b2 = other.to_bool()?;
1619 Some(Constant::Bool(b1 && b2))
1620 }
1621
1622 pub fn eq(&self, other: &Constant) -> Constant {
1623 Constant::Bool(*self == *other)
1624 }
1625
1626 pub fn ne(&self, other: &Constant) -> Constant {
1627 Constant::Bool(*self != *other)
1628 }
1629
1630 pub fn gt(&self, other: &Constant) -> Option<Constant> {
1631 let n1 = self.to_int()?;
1632 let n2 = other.to_int()?;
1633 Some(Constant::Bool(n1 > n2))
1634 }
1635
1636 pub fn ge(&self, other: &Constant) -> Option<Constant> {
1637 let n1 = self.to_int()?;
1638 let n2 = other.to_int()?;
1639 Some(Constant::Bool(n1 >= n2))
1640 }
1641
1642 pub fn from_scalar_int<'tcx, T>(tcx: TyCtxt<'tcx>, scalar: ScalarInt, t: &T) -> Option<Self>
1643 where
1644 T: ToRustc<'tcx, T = rustc_middle::ty::Ty<'tcx>>,
1645 {
1646 use rustc_middle::ty::TyKind;
1647 let ty = t.to_rustc(tcx);
1648 match ty.kind() {
1649 TyKind::Int(int_ty) => Some(Constant::from(scalar_to_int(tcx, scalar, *int_ty))),
1650 TyKind::Uint(uint_ty) => Some(Constant::from(scalar_to_uint(tcx, scalar, *uint_ty))),
1651 TyKind::Bool => {
1652 let b = scalar_to_bits(tcx, scalar, ty);
1653 Some(Constant::Bool(b != 0))
1654 }
1655 TyKind::Char => {
1656 let b = scalar_to_bits(tcx, scalar, ty);
1657 Some(Constant::Char(char::from_u32(b as u32)?))
1658 }
1659 _ => bug!(),
1660 }
1661 }
1662
1663 pub fn int_min(bit_width: u32) -> Constant {
1665 Constant::Int(BigInt::int_min(bit_width))
1666 }
1667
1668 pub fn int_max(bit_width: u32) -> Constant {
1670 Constant::Int(BigInt::int_max(bit_width))
1671 }
1672
1673 pub fn uint_max(bit_width: u32) -> Constant {
1675 Constant::Int(BigInt::uint_max(bit_width))
1676 }
1677}
1678
1679impl From<i32> for Constant {
1680 fn from(c: i32) -> Self {
1681 Constant::Int(c.into())
1682 }
1683}
1684
1685impl From<usize> for Constant {
1686 fn from(u: usize) -> Self {
1687 Constant::Int(u.into())
1688 }
1689}
1690
1691impl From<u32> for Constant {
1692 fn from(c: u32) -> Self {
1693 Constant::Int(c.into())
1694 }
1695}
1696
1697impl From<u64> for Constant {
1698 fn from(c: u64) -> Self {
1699 Constant::Int(c.into())
1700 }
1701}
1702
1703impl From<u128> for Constant {
1704 fn from(c: u128) -> Self {
1705 Constant::Int(c.into())
1706 }
1707}
1708
1709impl From<i128> for Constant {
1710 fn from(c: i128) -> Self {
1711 Constant::Int(c.into())
1712 }
1713}
1714
1715impl From<bool> for Constant {
1716 fn from(b: bool) -> Self {
1717 Constant::Bool(b)
1718 }
1719}
1720
1721impl From<Symbol> for Constant {
1722 fn from(s: Symbol) -> Self {
1723 Constant::Str(s)
1724 }
1725}
1726
1727impl From<char> for Constant {
1728 fn from(c: char) -> Self {
1729 Constant::Char(c)
1730 }
1731}
1732
1733impl_internable!(ExprKind);
1734impl_slice_internable!(Expr, KVar);
1735
1736#[derive(Debug)]
1737pub struct FieldBind<T> {
1738 pub name: Symbol,
1739 pub value: T,
1740}
1741
1742impl<T: Pretty> Pretty for FieldBind<T> {
1743 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1744 w!(cx, f, "{}: {:?}", ^self.name, &self.value)
1745 }
1746}
1747
1748pub(crate) mod pretty {
1749
1750 use flux_rustc_bridge::def_id_to_string;
1751
1752 use super::*;
1753 use crate::name_of_thy_func;
1754
1755 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1756 enum Precedence {
1757 Iff,
1758 Imp,
1759 Or,
1760 And,
1761 Cmp,
1762 Bitvec,
1763 AddSub,
1764 MulDiv,
1765 }
1766
1767 impl BinOp {
1768 fn precedence(&self) -> Precedence {
1769 match self {
1770 BinOp::Iff => Precedence::Iff,
1771 BinOp::Imp => Precedence::Imp,
1772 BinOp::Or => Precedence::Or,
1773 BinOp::And => Precedence::And,
1774 BinOp::Eq
1775 | BinOp::Ne
1776 | BinOp::Gt(_)
1777 | BinOp::Lt(_)
1778 | BinOp::Ge(_)
1779 | BinOp::Le(_) => Precedence::Cmp,
1780 BinOp::Add(_) | BinOp::Sub(_) => Precedence::AddSub,
1781 BinOp::Mul(_) | BinOp::Div(_) | BinOp::Mod(_) => Precedence::MulDiv,
1782 BinOp::BitAnd(_)
1783 | BinOp::BitOr(_)
1784 | BinOp::BitShl(_)
1785 | BinOp::BitShr(_)
1786 | BinOp::BitXor(_) => Precedence::Bitvec,
1787 }
1788 }
1789 }
1790
1791 impl Precedence {
1792 pub fn is_associative(&self) -> bool {
1793 !matches!(self, Precedence::Imp | Precedence::Cmp)
1794 }
1795 }
1796
1797 pub fn should_parenthesize(op: &BinOp, child: &Expr) -> bool {
1798 if let ExprKind::BinaryOp(child_op, ..) = child.kind() {
1799 child_op.precedence() < op.precedence()
1800 || (child_op.precedence() == op.precedence() && !op.precedence().is_associative())
1801 } else {
1802 false
1803 }
1804 }
1805
1806 impl Pretty for Ctor {
1807 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1808 match self {
1809 Ctor::Struct(def_id) => {
1810 w!(cx, f, "{:?}", def_id)
1811 }
1812 Ctor::Enum(def_id, variant_idx) => {
1813 w!(cx, f, "{:?}::{:?}", def_id, ^variant_idx)
1814 }
1815 Ctor::RawPtr => w!(cx, f, "ptr"),
1816 }
1817 }
1818 }
1819
1820 impl Pretty for fhir::QuantKind {
1821 fn fmt(&self, _cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1822 match self {
1823 fhir::QuantKind::Exists => w!(cx, f, "∃"),
1824 fhir::QuantKind::Forall => w!(cx, f, "∀"),
1825 }
1826 }
1827 }
1828
1829 impl Pretty for InternalFuncKind {
1830 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1831 match self {
1832 InternalFuncKind::Rel(op) => w!(cx, f, "[{:?}]?", op),
1833 InternalFuncKind::Cast => w!(cx, f, "cast"),
1834 }
1835 }
1836 }
1837
1838 impl Pretty for QuantDom {
1839 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1840 match self {
1841 QuantDom::Bounded { start, end } => w!(cx, f, "in {} .. {}", ^start, ^end),
1842 QuantDom::Unbounded => Ok(()),
1843 }
1844 }
1845 }
1846
1847 impl Pretty for Expr {
1848 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1849 let e = if cx.simplify_exprs {
1850 self.simplify(&SnapshotMap::default())
1851 } else {
1852 self.clone()
1853 };
1854 match e.kind() {
1855 ExprKind::Var(var) => w!(cx, f, "{:?}", var),
1856 ExprKind::Local(local) => w!(cx, f, "{:?}", ^local),
1857 ExprKind::ConstDefId(did) => w!(cx, f, "{}", ^def_id_to_string(*did)),
1858 ExprKind::Constant(c) => w!(cx, f, "{:?}", c),
1859
1860 ExprKind::BinaryOp(op, e1, e2) => {
1861 if should_parenthesize(op, e1) {
1862 w!(cx, f, "({:?})", e1)?;
1863 } else {
1864 w!(cx, f, "{:?}", e1)?;
1865 }
1866 if matches!(op, BinOp::Div(_)) {
1867 w!(cx, f, "{:?}", op)?;
1868 } else {
1869 w!(cx, f, " {:?} ", op)?;
1870 }
1871 if should_parenthesize(op, e2) {
1872 w!(cx, f, "({:?})", e2)?;
1873 } else {
1874 w!(cx, f, "{:?}", e2)?;
1875 }
1876 Ok(())
1877 }
1878 ExprKind::UnaryOp(op, e) => {
1879 if e.is_atom() {
1880 w!(cx, f, "{:?}{:?}", op, e)
1881 } else {
1882 w!(cx, f, "{:?}({:?})", op, e)
1883 }
1884 }
1885 ExprKind::FieldProj(e, proj) if let ExprKind::Ctor(_, _) = e.kind() => {
1886 w!(cx, f, "{:?}", e.proj_and_reduce(*proj))
1889 }
1890 ExprKind::FieldProj(e, proj) => {
1891 if e.is_atom() {
1892 w!(cx, f, "{:?}.{}", e, ^fmt_field_proj(cx, *proj))
1893 } else {
1894 w!(cx, f, "({:?}).{}", e, ^fmt_field_proj(cx, *proj))
1895 }
1896 }
1897 ExprKind::Tuple(flds) => {
1898 if let [e] = &flds[..] {
1899 w!(cx, f, "({:?},)", e)
1900 } else {
1901 w!(cx, f, "({:?})", join!(", ", flds))
1902 }
1903 }
1904 ExprKind::IsCtor(def_id, variant_idx, idx) => {
1905 w!(cx, f, "({:?} is {:?}::{:?})", idx, def_id, ^variant_idx)
1906 }
1907 ExprKind::Ctor(ctor, flds) => {
1908 if matches!(ctor, Ctor::RawPtr) {
1909 let fields = iter::zip(RawPtrField::iter(), flds)
1910 .map(|(field, value)| {
1911 FieldBind { name: field.symbol(), value: value.clone() }
1912 })
1913 .collect_vec();
1914 return w!(cx, f, "ptr {{ {:?} }}", join!(", ", fields));
1915 }
1916 let Some((def_id, variant_idx)) = ctor.def_id_and_variant() else {
1917 unreachable!()
1918 };
1919 if let Some(adt_sort_def) = cx.adt_sort_def_of(def_id) {
1920 let variant = adt_sort_def.variant(variant_idx).field_names();
1921 let fields = iter::zip(variant, flds)
1922 .map(|(name, value)| FieldBind { name: *name, value: value.clone() })
1923 .collect_vec();
1924 match ctor {
1925 Ctor::Struct(_) => {
1926 w!(cx, f, "{:?} {{ {:?} }}", def_id, join!(", ", fields))
1927 }
1928 Ctor::Enum(_, idx) => {
1929 if fields.is_empty() {
1930 w!(cx, f, "{:?}::{:?}", def_id, ^idx.index())
1931 } else {
1932 w!(cx, f, "{:?}::{:?}({:?})", def_id, ^idx.index(), join!(", ", fields))
1933 }
1934 }
1935 Ctor::RawPtr => unreachable!(),
1936 }
1937 } else {
1938 match ctor {
1939 Ctor::Struct(_) => {
1940 w!(cx, f, "{:?} {{ {:?} }}", def_id, join!(", ", flds))
1941 }
1942 Ctor::Enum(_, idx) => {
1943 w!(cx, f, "{:?}::{:?} {{ {:?} }}", def_id, ^idx, join!(", ", flds))
1944 }
1945 Ctor::RawPtr => unreachable!(),
1946 }
1947 }
1948 }
1949 ExprKind::PathProj(e, field) => {
1950 if e.is_atom() {
1951 w!(cx, f, "{:?}.{:?}", e, field)
1952 } else {
1953 w!(cx, f, "({:?}).{:?}", e, field)
1954 }
1955 }
1956 ExprKind::App(func, _, args) => {
1957 w!(cx, f, "{:?}({})",
1958 parens!(func, !func.is_atom()),
1959 ^args
1960 .iter()
1961 .format_with(", ", |arg, f| f(&format_args_cx!(cx, "{:?}", arg)))
1962 )
1963 }
1964 ExprKind::IfThenElse(p, e1, e2) => {
1965 w!(cx, f, "if {:?} {{ {:?} }} else {{ {:?} }}", p, e1, e2)
1966 }
1967 ExprKind::Hole(_) => {
1968 w!(cx, f, "*")
1969 }
1970 ExprKind::KVar(kvar) => {
1971 w!(cx, f, "{:?}", kvar)
1972 }
1973 ExprKind::WKVar(wkvar) => {
1974 w!(cx, f, "{:?}", wkvar)
1975 }
1976 ExprKind::Alias(alias, args) => {
1977 w!(cx, f, "{:?}({:?})", alias, join!(", ", args))
1978 }
1979 ExprKind::Abs(lam) => {
1980 w!(cx, f, "{:?}", lam)
1981 }
1982 ExprKind::GlobalFunc(SpecFuncKind::Def(did)) => {
1983 w!(cx, f, "{}", ^did.name())
1984 }
1985 ExprKind::GlobalFunc(SpecFuncKind::Thy(itf)) => {
1986 if let Some(name) = name_of_thy_func(*itf) {
1987 w!(cx, f, "{}", ^name)
1988 } else {
1989 w!(cx, f, "<error>")
1990 }
1991 }
1992 ExprKind::InternalFunc(func) => {
1993 w!(cx, f, "{:?}", func)
1994 }
1995 ExprKind::Quant(kind, dom, body) => {
1996 let vars = body.vars();
1997 cx.with_bound_vars(vars, || {
1998 w!(cx, f, "{:?} {:?} {{ {:?} }}", kind, dom, body.skip_binder_ref())
1999 })
2000 }
2001 ExprKind::Let(init, body) => {
2002 let vars = body.vars();
2003 cx.with_bound_vars(vars, || {
2004 cx.fmt_bound_vars(false, "(let ", vars, " = ", f)?;
2005 w!(cx, f, "{:?} in {:?})", init, body.skip_binder_ref())
2006 })
2007 }
2008 }
2009 }
2010 }
2011
2012 fn fmt_field_proj(cx: &PrettyCx, proj: FieldProj) -> String {
2013 if let FieldProj::Adt { def_id, field } = proj
2014 && let Some(adt_sort_def) = cx.adt_sort_def_of(def_id)
2015 {
2016 format!("{}", adt_sort_def.struct_variant().field_names()[field as usize])
2017 } else if let FieldProj::RawPtr { field } = proj {
2018 field.name().to_string()
2019 } else {
2020 format!("{}", proj.field_idx())
2021 }
2022 }
2023
2024 impl Pretty for Constant {
2025 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2026 match self {
2027 Constant::Int(i) => w!(cx, f, "{i}"),
2028 Constant::BitVec(i, sz) => w!(cx, f, "bv({i}, {sz})"),
2029 Constant::Real(r) => w!(cx, f, "{}", ^r.0),
2030 Constant::Bool(b) => w!(cx, f, "{b}"),
2031 Constant::Str(sym) => w!(cx, f, "\"{sym}\""),
2032 Constant::Char(c) => w!(cx, f, "\'{c}\'"),
2033 }
2034 }
2035 }
2036
2037 impl Pretty for AliasReft {
2038 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2039 w!(cx, f, "<({:?}) as {:?}", &self.args[0], self.assoc_id.parent())?;
2040 let args = &self.args[1..];
2041 if !args.is_empty() {
2042 w!(cx, f, "<{:?}>", join!(", ", args))?;
2043 }
2044 w!(cx, f, ">::{}", ^self.assoc_id.name())
2045 }
2046 }
2047
2048 impl Pretty for Lambda {
2049 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2050 let vars = self.body.vars();
2051 cx.with_bound_vars(vars, || {
2054 cx.fmt_bound_vars(false, "λ", vars, ". ", f)?;
2055 w!(cx, f, "{:?}", self.body.as_ref().skip_binder())
2056 })
2057 }
2058 }
2059
2060 impl Pretty for Var {
2061 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2062 match self {
2063 Var::Bound(debruijn, var) => cx.fmt_bound_reft(*debruijn, *var, f),
2064 Var::EarlyParam(var) => w!(cx, f, "{}", ^var.name),
2065 Var::Free(name) => w!(cx, f, "{:?}", ^name),
2066 Var::EVar(evar) => w!(cx, f, "{:?}", ^evar),
2067 Var::ConstGeneric(param) => w!(cx, f, "{}", ^param.name),
2068 }
2069 }
2070 }
2071
2072 impl Pretty for KVar {
2073 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2074 w!(cx, f, "{:?}", ^self.kvid)?;
2075 match cx.kvar_args {
2076 KVarArgs::All => {
2077 w!(
2078 cx,
2079 f,
2080 "({:?})[{:?}]",
2081 join!(", ", self.self_args()),
2082 join!(", ", self.scope())
2083 )?;
2084 }
2085 KVarArgs::SelfOnly => w!(cx, f, "({:?})", join!(", ", self.self_args()))?,
2086 KVarArgs::Hide => {}
2087 }
2088 Ok(())
2089 }
2090 }
2091
2092 impl Pretty for WKVar {
2093 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2094 w!(cx, f, "$wk{}_{}", ^self.wkvid.id.index(), ^cx.tcx().def_path_str(self.wkvid.parent_fn))?;
2097 w!(cx, f, "({:?})[{:?}]", join!(", ", self.self_args()), join!(", ", self.scope()))?;
2098 Ok(())
2099 }
2100 }
2101
2102 impl Pretty for Path {
2103 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2104 w!(cx, f, "{:?}", &self.loc)?;
2105 for field in &self.projection {
2106 w!(cx, f, ".{}", ^u32::from(*field))?;
2107 }
2108 Ok(())
2109 }
2110 }
2111
2112 impl Pretty for Loc {
2113 fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2114 match self {
2115 Loc::Local(local) => w!(cx, f, "{:?}", ^local),
2116 Loc::Var(var) => w!(cx, f, "{:?}", var),
2117 }
2118 }
2119 }
2120
2121 impl Pretty for BinOp {
2122 fn fmt(&self, _cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2123 match self {
2124 BinOp::Iff => w!(cx, f, "<=>"),
2125 BinOp::Imp => w!(cx, f, "=>"),
2126 BinOp::Or => w!(cx, f, "||"),
2127 BinOp::And => w!(cx, f, "&&"),
2128 BinOp::Eq => w!(cx, f, "=="),
2129 BinOp::Ne => w!(cx, f, "!="),
2130 BinOp::Gt(_) => w!(cx, f, ">"),
2131 BinOp::Ge(_) => w!(cx, f, ">="),
2132 BinOp::Lt(_) => w!(cx, f, "<"),
2133 BinOp::Le(_) => w!(cx, f, "<="),
2134 BinOp::Add(_) => w!(cx, f, "+"),
2135 BinOp::Sub(_) => w!(cx, f, "-"),
2136 BinOp::Mul(_) => w!(cx, f, "*"),
2137 BinOp::Div(_) => w!(cx, f, "/"),
2138 BinOp::Mod(_) => w!(cx, f, "mod"),
2139 BinOp::BitAnd(_) => w!(cx, f, "&"),
2140 BinOp::BitOr(_) => w!(cx, f, "|"),
2141 BinOp::BitXor(_) => w!(cx, f, "^"),
2142 BinOp::BitShl(_) => w!(cx, f, "<<"),
2143 BinOp::BitShr(_) => w!(cx, f, ">>"),
2144 }
2145 }
2146 }
2147
2148 impl Pretty for UnOp {
2149 fn fmt(&self, _cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2150 match self {
2151 UnOp::Not => w!(cx, f, "!"),
2152 UnOp::Neg => w!(cx, f, "-"),
2153 }
2154 }
2155 }
2156
2157 impl_debug_with_default_cx!(Expr, Loc, Path, Var, KVar, WKVar, Lambda, AliasReft);
2158
2159 impl PrettyNested for Lambda {
2160 fn fmt_nested(&self, cx: &PrettyCx) -> Result<NestedString, fmt::Error> {
2161 cx.nested_with_bound_vars("λ", self.body.vars(), None, |prefix| {
2163 let expr_d = self.body.skip_binder_ref().fmt_nested(cx)?;
2164 let text = format!("{}{}", prefix, expr_d.text);
2165 Ok(NestedString { text, children: expr_d.children, key: None })
2166 })
2167 }
2168 }
2169
2170 pub fn aggregate_nested(
2171 cx: &PrettyCx,
2172 ctor: &Ctor,
2173 flds: &[Expr],
2174 is_named: bool,
2175 ) -> Result<NestedString, fmt::Error> {
2176 let mut text =
2177 if is_named && ctor.is_enum() { format_cx!(cx, "{:?}", ctor) } else { "".to_string() };
2178 if flds.is_empty() {
2179 Ok(NestedString { text, children: None, key: None })
2181 } else if flds.len() == 1 {
2182 text += &flds[0].fmt_nested(cx)?.text;
2184 Ok(NestedString { text, children: None, key: None })
2185 } else {
2186 let keys = if let Some((def_id, variant_idx)) = ctor.def_id_and_variant()
2187 && let Some(adt_sort_def) = cx.adt_sort_def_of(def_id)
2188 {
2189 adt_sort_def
2190 .variant(variant_idx)
2191 .field_names()
2192 .iter()
2193 .map(|name| format!("{name}"))
2194 .collect_vec()
2195 } else if matches!(ctor, Ctor::RawPtr) {
2196 RawPtrField::iter()
2197 .map(|field| field.name().to_string())
2198 .collect_vec()
2199 } else {
2200 (0..flds.len()).map(|i| format!("arg{i}")).collect_vec()
2201 };
2202 text += "{..}";
2204 let mut children = vec![];
2205 for (key, fld) in iter::zip(keys, flds) {
2206 let fld_d = fld.fmt_nested(cx)?;
2207 children.push(NestedString { key: Some(key), ..fld_d });
2208 }
2209 Ok(NestedString { text, children: Some(children), key: None })
2210 }
2211 }
2212
2213 impl PrettyNested for Name {
2214 fn fmt_nested(&self, cx: &PrettyCx) -> Result<NestedString, fmt::Error> {
2215 let text = cx.pretty_var_env.get(&PrettyVar::Local(*self));
2216 Ok(NestedString { text, key: None, children: None })
2217 }
2218 }
2219
2220 impl PrettyNested for Expr {
2221 fn fmt_nested(&self, cx: &PrettyCx) -> Result<NestedString, fmt::Error> {
2222 let e = if cx.simplify_exprs {
2223 self.simplify(&SnapshotMap::default())
2224 } else {
2225 self.clone()
2226 };
2227 match e.kind() {
2228 ExprKind::Var(Var::Free(name)) => name.fmt_nested(cx),
2229 ExprKind::Var(..)
2230 | ExprKind::Local(..)
2231 | ExprKind::Constant(..)
2232 | ExprKind::ConstDefId(..)
2233 | ExprKind::Hole(..)
2234 | ExprKind::GlobalFunc(..)
2235 | ExprKind::InternalFunc(..) => debug_nested(cx, &e),
2236 ExprKind::WKVar(..) => debug_nested(cx, &e),
2237 ExprKind::KVar(kvar) => {
2238 let kv = format!("{:?}", kvar.kvid);
2239 let mut strs = vec![kv];
2240 for arg in &kvar.args {
2241 strs.push(arg.fmt_nested(cx)?.text);
2242 }
2243 let text = format!("##[{}]##", strs.join("##"));
2244 Ok(NestedString { text, children: None, key: None })
2245 }
2246 ExprKind::IfThenElse(p, e1, e2) => {
2247 let p_d = p.fmt_nested(cx)?;
2248 let e1_d = e1.fmt_nested(cx)?;
2249 let e2_d = e2.fmt_nested(cx)?;
2250 let text = format!("(if {} then {} else {})", p_d.text, e1_d.text, e2_d.text);
2251 let children = float_children(vec![p_d.children, e1_d.children, e2_d.children]);
2252 Ok(NestedString { text, children, key: None })
2253 }
2254 ExprKind::BinaryOp(op, e1, e2) => {
2255 let e1_d = e1.fmt_nested(cx)?;
2256 let e2_d = e2.fmt_nested(cx)?;
2257 let e1_text = if should_parenthesize(op, e1) {
2258 format!("({})", e1_d.text)
2259 } else {
2260 e1_d.text
2261 };
2262 let e2_text = if should_parenthesize(op, e2) {
2263 format!("({})", e2_d.text)
2264 } else {
2265 e2_d.text
2266 };
2267 let op_d = debug_nested(cx, op)?;
2268 let op_text = if matches!(op, BinOp::Div(_)) {
2269 op_d.text
2270 } else {
2271 format!(" {} ", op_d.text)
2272 };
2273 let text = format!("{e1_text}{op_text}{e2_text}");
2274 let children = float_children(vec![e1_d.children, e2_d.children]);
2275 Ok(NestedString { text, children, key: None })
2276 }
2277 ExprKind::UnaryOp(op, e) => {
2278 let e_d = e.fmt_nested(cx)?;
2279 let op_d = debug_nested(cx, op)?;
2280 let text = if e.is_atom() {
2281 format!("{}{}", op_d.text, e_d.text)
2282 } else {
2283 format!("{}({})", op_d.text, e_d.text)
2284 };
2285 Ok(NestedString { text, children: e_d.children, key: None })
2286 }
2287 ExprKind::FieldProj(e, proj) if let ExprKind::Ctor(_, _) = e.kind() => {
2288 e.proj_and_reduce(*proj).fmt_nested(cx)
2291 }
2292 ExprKind::FieldProj(e, proj) => {
2293 let e_d = e.fmt_nested(cx)?;
2294 let text = if e.is_atom() {
2295 format!("{}.{}", e_d.text, fmt_field_proj(cx, *proj))
2296 } else {
2297 format!("({}).{}", e_d.text, fmt_field_proj(cx, *proj))
2298 };
2299 Ok(NestedString { text, children: e_d.children, key: None })
2300 }
2301 ExprKind::Tuple(flds) => {
2302 let mut texts = vec![];
2303 let mut kidss = vec![];
2304 for e in flds {
2305 let e_d = e.fmt_nested(cx)?;
2306 texts.push(e_d.text);
2307 kidss.push(e_d.children);
2308 }
2309 let text = if let [e] = &texts[..] {
2310 format!("({e},)")
2311 } else {
2312 format!("({})", texts.join(", "))
2313 };
2314 let children = float_children(kidss);
2315 Ok(NestedString { text, children, key: None })
2316 }
2317 ExprKind::Ctor(ctor, flds) => aggregate_nested(cx, ctor, flds, true),
2318 ExprKind::IsCtor(def_id, variant_idx, idx) => {
2319 let text = format!("is::{:?}::{:?}( {:?} )", def_id, variant_idx, idx);
2320 Ok(NestedString { text, children: None, key: None })
2321 }
2322 ExprKind::PathProj(e, field) => {
2323 let e_d = e.fmt_nested(cx)?;
2324 let text = if e.is_atom() {
2325 format!("{}.{:?}", e_d.text, field)
2326 } else {
2327 format!("({}).{:?}", e_d.text, field)
2328 };
2329 Ok(NestedString { text, children: e_d.children, key: None })
2330 }
2331 ExprKind::Alias(alias, args) => {
2332 let mut texts = vec![];
2333 let mut kidss = vec![];
2334 for arg in args {
2335 let arg_d = arg.fmt_nested(cx)?;
2336 texts.push(arg_d.text);
2337 kidss.push(arg_d.children);
2338 }
2339 let text = format_cx!(cx, "{:?}({:?})", alias, texts.join(", "));
2340 let children = float_children(kidss);
2341 Ok(NestedString { text, children, key: None })
2342 }
2343 ExprKind::App(func, _, args) => {
2344 let func_d = func.fmt_nested(cx)?;
2345 let mut texts = vec![];
2346 let mut kidss = vec![func_d.children];
2347 for arg in args {
2348 let arg_d = arg.fmt_nested(cx)?;
2349 texts.push(arg_d.text);
2350 kidss.push(arg_d.children);
2351 }
2352 let text = if func.is_atom() {
2353 format!("{}({})", func_d.text, texts.join(", "))
2354 } else {
2355 format!("({})({})", func_d.text, texts.join(", "))
2356 };
2357 let children = float_children(kidss);
2358 Ok(NestedString { text, children, key: None })
2359 }
2360 ExprKind::Abs(lambda) => lambda.fmt_nested(cx),
2361 ExprKind::Let(init, body) => {
2362 cx.nested_with_bound_vars("let", body.vars(), None, |prefix| {
2364 let body = body.skip_binder_ref().fmt_nested(cx)?;
2365 let text = format!("{:?} {}{}", init, prefix, body.text);
2366 Ok(NestedString { text, children: body.children, key: None })
2367 })
2368 }
2369 ExprKind::Quant(kind, dom, body) => {
2370 let left = match kind {
2371 fhir::QuantKind::Forall => "∀",
2372 fhir::QuantKind::Exists => "∃",
2373 };
2374 let right = Some(format!(" {:?}", dom));
2375
2376 cx.nested_with_bound_vars(left, body.vars(), right, |all_str| {
2377 let expr_d = body.as_ref().skip_binder().fmt_nested(cx)?;
2378 let text = format!("{}{}", all_str, expr_d.text);
2379 Ok(NestedString { text, children: expr_d.children, key: None })
2380 })
2381 }
2382 }
2383 }
2384 }
2385}
2386
2387impl Expr {
2388 pub fn prettify(&self) -> Self {
2390 self.fold_constants()
2391 .push_negations()
2392 .simplify_arithmetic()
2393 .simplify_bounds()
2394 }
2395
2396 pub fn fold_constants(&self) -> Self {
2398 let span = self.span();
2399 match self.kind() {
2400 ExprKind::UnaryOp(op, a) => {
2401 let a_fold = a.fold_constants();
2402
2403 if let ExprKind::Constant(c) = a_fold.kind() {
2404 match (op, c) {
2405 (UnOp::Not, Constant::Bool(b)) => {
2406 return Expr::constant(Constant::Bool(!b)).at_opt(span);
2407 }
2408 (UnOp::Neg, Constant::Int(n)) => {
2409 return Expr::constant(Constant::Int(n.neg())).at_opt(span);
2410 }
2411 _ => {}
2412 }
2413 }
2414 Expr::unary_op(*op, a_fold).at_opt(span)
2415 }
2416
2417 ExprKind::BinaryOp(op, a, b) => {
2418 let a_fold = a.fold_constants();
2419 let b_fold = b.fold_constants();
2420
2421 if let (ExprKind::Constant(c1), ExprKind::Constant(c2)) =
2422 (a_fold.kind(), b_fold.kind())
2423 {
2424 if let Some(c3) = Expr::const_op(op, c1, c2) {
2426 return Expr::constant(c3).at_opt(span);
2427 }
2428
2429 if let (Constant::Int(n1), Constant::Int(n2)) = (c1, c2) {
2431 let result = match op {
2432 BinOp::Add(_) => n1.checked_add(n2),
2433 BinOp::Sub(_) => n1.checked_sub(n2),
2434 BinOp::Mul(_) => n1.checked_mul(n2),
2435 BinOp::Div(_) => n1.checked_div(n2),
2436 BinOp::Mod(_) => n1.checked_rem(n2),
2437 _ => None,
2438 };
2439
2440 if let Some(res) = result {
2441 return Expr::constant(Constant::Int(res)).at_opt(span);
2442 }
2443 }
2444 }
2445
2446 Expr::binary_op(op.clone(), a_fold, b_fold).at_opt(span)
2447 }
2448
2449 ExprKind::IfThenElse(p, e1, e2) => {
2450 let p_fold = p.fold_constants();
2451
2452 if let ExprKind::Constant(Constant::Bool(b)) = p_fold.kind() {
2454 if *b {
2455 return e1.fold_constants().at_opt(span);
2456 } else {
2457 return e2.fold_constants().at_opt(span);
2458 }
2459 }
2460
2461 Expr::ite(p_fold, e1.fold_constants(), e2.fold_constants()).at_opt(span)
2462 }
2463
2464 _ => self.clone(),
2467 }
2468 }
2469
2470 pub fn push_negations(&self) -> Self {
2472 let span = self.span();
2473 match self.kind() {
2474 ExprKind::UnaryOp(UnOp::Not, inner) => {
2475 match inner.kind() {
2476 ExprKind::UnaryOp(UnOp::Not, a) => a.push_negations().at_opt(span),
2478
2479 ExprKind::BinaryOp(BinOp::Le(s), a, b) => {
2481 Expr::binary_op(
2482 BinOp::Gt(s.clone()),
2483 a.push_negations(),
2484 b.push_negations(),
2485 )
2486 .at_opt(span)
2487 }
2488 ExprKind::BinaryOp(BinOp::Lt(s), a, b) => {
2489 Expr::binary_op(
2490 BinOp::Ge(s.clone()),
2491 a.push_negations(),
2492 b.push_negations(),
2493 )
2494 .at_opt(span)
2495 }
2496 ExprKind::BinaryOp(BinOp::Ge(s), a, b) => {
2497 Expr::binary_op(
2498 BinOp::Lt(s.clone()),
2499 a.push_negations(),
2500 b.push_negations(),
2501 )
2502 .at_opt(span)
2503 }
2504 ExprKind::BinaryOp(BinOp::Gt(s), a, b) => {
2505 Expr::binary_op(
2506 BinOp::Le(s.clone()),
2507 a.push_negations(),
2508 b.push_negations(),
2509 )
2510 .at_opt(span)
2511 }
2512
2513 ExprKind::BinaryOp(BinOp::Eq, a, b) => {
2515 Expr::binary_op(BinOp::Ne, a.push_negations(), b.push_negations())
2516 .at_opt(span)
2517 }
2518 ExprKind::BinaryOp(BinOp::Ne, a, b) => {
2519 Expr::binary_op(BinOp::Eq, a.push_negations(), b.push_negations())
2520 .at_opt(span)
2521 }
2522
2523 ExprKind::BinaryOp(BinOp::Or, a, b) => {
2525 Expr::binary_op(
2526 BinOp::And,
2527 a.not().push_negations(),
2528 b.not().push_negations(),
2529 )
2530 .at_opt(span)
2531 }
2532 ExprKind::BinaryOp(BinOp::And, a, b) => {
2533 Expr::binary_op(
2534 BinOp::Or,
2535 a.not().push_negations(),
2536 b.not().push_negations(),
2537 )
2538 .at_opt(span)
2539 }
2540
2541 _ => Expr::unary_op(UnOp::Not, inner.push_negations()).at_opt(span),
2543 }
2544 }
2545 ExprKind::BinaryOp(op, a, b) => {
2546 Expr::binary_op(op.clone(), a.push_negations(), b.push_negations()).at_opt(span)
2547 }
2548 ExprKind::UnaryOp(op, a) => Expr::unary_op(*op, a.push_negations()).at_opt(span),
2549 ExprKind::IfThenElse(p, e1, e2) => {
2550 Expr::ite(p.push_negations(), e1.push_negations(), e2.push_negations()).at_opt(span)
2551 }
2552 _ => self.clone(),
2553 }
2554 }
2555
2556 pub fn simplify_arithmetic(&self) -> Self {
2558 let span = self.span();
2559 match self.kind() {
2560 ExprKind::BinaryOp(BinOp::Mul(s), a, b) => {
2561 let a_simp = a.simplify_arithmetic();
2562 let b_simp = b.simplify_arithmetic();
2563
2564 let is_minus_one = |e: &Expr| matches!(e.kind(), ExprKind::Constant(c) if *c == Constant::from(-1));
2565
2566 if is_minus_one(&b_simp) {
2567 return a_simp.neg().at_opt(span);
2568 }
2569 if is_minus_one(&a_simp) {
2570 return b_simp.neg().at_opt(span);
2571 }
2572
2573 Expr::binary_op(BinOp::Mul(s.clone()), a_simp, b_simp).at_opt(span)
2574 }
2575 ExprKind::BinaryOp(BinOp::Add(s), a, b) => {
2576 let a_simp = a.simplify_arithmetic();
2577 let b_simp = b.simplify_arithmetic();
2578
2579 if let ExprKind::UnaryOp(UnOp::Neg, x) = a_simp.kind() {
2580 return Expr::binary_op(BinOp::Sub(s.clone()), b_simp, x.clone()).at_opt(span);
2581 }
2582 if let ExprKind::UnaryOp(UnOp::Neg, y) = b_simp.kind() {
2583 return Expr::binary_op(BinOp::Sub(s.clone()), a_simp, y.clone()).at_opt(span);
2584 }
2585
2586 Expr::binary_op(BinOp::Add(s.clone()), a_simp, b_simp).at_opt(span)
2587 }
2588 ExprKind::BinaryOp(op, a, b) => {
2589 Expr::binary_op(op.clone(), a.simplify_arithmetic(), b.simplify_arithmetic())
2590 .at_opt(span)
2591 }
2592 ExprKind::UnaryOp(op, a) => Expr::unary_op(*op, a.simplify_arithmetic()).at_opt(span),
2593 ExprKind::IfThenElse(p, e1, e2) => {
2594 Expr::ite(
2595 p.simplify_arithmetic(),
2596 e1.simplify_arithmetic(),
2597 e2.simplify_arithmetic(),
2598 )
2599 .at_opt(span)
2600 }
2601 _ => self.clone(),
2602 }
2603 }
2604
2605 pub fn simplify_bounds(&self) -> Self {
2607 let span = self.span();
2608 match self.kind() {
2609 ExprKind::BinaryOp(op, a, b) => {
2610 let a_simp = a.simplify_bounds();
2611 let b_simp = b.simplify_bounds();
2612
2613 let is_minus_one = |e: &Expr| matches!(e.kind(), ExprKind::Constant(c) if *c == Constant::from(-1));
2614 let is_zero =
2615 |e: &Expr| matches!(e.kind(), ExprKind::Constant(c) if *c == Constant::from(0));
2616
2617 match op {
2619 BinOp::Gt(Sort::Int) => {
2620 if is_minus_one(&b_simp) {
2622 return Expr::binary_op(BinOp::Ge(Sort::Int), a_simp, Expr::zero())
2623 .at_opt(span)
2624 .simplify_bounds();
2625 }
2626 if is_zero(&b_simp)
2628 && let ExprKind::BinaryOp(BinOp::Sub(s_sub), x, y) = a_simp.kind()
2629 {
2630 return Expr::binary_op(BinOp::Gt(s_sub.clone()), x.clone(), y.clone())
2631 .at_opt(span);
2632 }
2633 }
2634 BinOp::Ge(Sort::Int) => {
2635 if is_zero(&b_simp)
2637 && let ExprKind::BinaryOp(BinOp::Sub(s_sub), x, y) = a_simp.kind()
2638 {
2639 return Expr::binary_op(BinOp::Ge(s_sub.clone()), x.clone(), y.clone())
2640 .at_opt(span);
2641 }
2642 }
2643 BinOp::Lt(Sort::Int) => {
2644 if is_zero(&b_simp)
2646 && let ExprKind::BinaryOp(BinOp::Sub(s_sub), x, y) = a_simp.kind()
2647 {
2648 return Expr::binary_op(BinOp::Lt(s_sub.clone()), x.clone(), y.clone())
2649 .at_opt(span);
2650 }
2651 }
2652 BinOp::Le(Sort::Int) => {
2653 if is_minus_one(&b_simp) {
2655 return Expr::binary_op(BinOp::Lt(Sort::Int), a_simp, Expr::zero())
2656 .at_opt(span)
2657 .simplify_bounds();
2658 }
2659 if is_zero(&b_simp)
2661 && let ExprKind::BinaryOp(BinOp::Sub(s_sub), x, y) = a_simp.kind()
2662 {
2663 return Expr::binary_op(BinOp::Le(s_sub.clone()), x.clone(), y.clone())
2664 .at_opt(span);
2665 }
2666 }
2667 _ => {}
2668 }
2669
2670 Expr::binary_op(op.clone(), a_simp, b_simp).at_opt(span)
2671 }
2672 ExprKind::UnaryOp(op, a) => Expr::unary_op(*op, a.simplify_bounds()).at_opt(span),
2673 ExprKind::IfThenElse(p, e1, e2) => {
2674 Expr::ite(p.simplify_bounds(), e1.simplify_bounds(), e2.simplify_bounds())
2675 .at_opt(span)
2676 }
2677 _ => self.clone(),
2678 }
2679 }
2680}