1use std::fmt::Write;
34
35use flux_arc_interner::List;
36use flux_macros::{TypeFoldable, TypeVisitable};
37use itertools::Itertools;
38use rustc_ast::Mutability;
39use rustc_span::Symbol;
40use rustc_type_ir::{BoundVar, INNERMOST};
41
42use super::{
43 BaseTy, Binder, BoundVariableKind, Expr, FnSig, GenericArg, GenericArgsExt, PolyFnSig,
44 SubsetTy, Ty, TyCtor, TyKind, TyOrBase,
45 fold::{TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable},
46};
47use crate::rty::{BoundReftKind, ExprKind, HoleKind};
48
49pub struct Hoister<D> {
56 pub delegate: D,
57 in_boxes: bool,
58 in_downcast: bool,
59 in_mut_refs: bool,
60 in_shr_refs: bool,
61 in_strg_refs: bool,
62 in_tuples: bool,
63 existentials: bool,
64 slices: bool,
65}
66
67pub trait HoisterDelegate {
68 fn hoist_exists(&mut self, ty_ctor: &TyCtor) -> Ty;
69 fn hoist_constr(&mut self, pred: Expr);
70}
71
72impl<D> Hoister<D> {
73 pub fn with_delegate(delegate: D) -> Self {
74 Hoister {
75 delegate,
76 in_tuples: false,
77 in_shr_refs: false,
78 in_mut_refs: false,
79 in_strg_refs: false,
80 in_boxes: false,
81 in_downcast: false,
82 existentials: true,
83 slices: false,
84 }
85 }
86
87 pub fn hoist_inside_shr_refs(mut self, shr_refs: bool) -> Self {
88 self.in_shr_refs = shr_refs;
89 self
90 }
91
92 pub fn hoist_inside_mut_refs(mut self, mut_refs: bool) -> Self {
93 self.in_mut_refs = mut_refs;
94 self
95 }
96
97 pub fn hoist_inside_strg_refs(mut self, strg_refs: bool) -> Self {
98 self.in_strg_refs = strg_refs;
99 self
100 }
101
102 pub fn hoist_inside_tuples(mut self, tuples: bool) -> Self {
103 self.in_tuples = tuples;
104 self
105 }
106
107 pub fn hoist_inside_boxes(mut self, boxes: bool) -> Self {
108 self.in_boxes = boxes;
109 self
110 }
111
112 pub fn hoist_inside_downcast(mut self, downcast: bool) -> Self {
113 self.in_downcast = downcast;
114 self
115 }
116
117 pub fn hoist_existentials(mut self, exists: bool) -> Self {
118 self.existentials = exists;
119 self
120 }
121
122 pub fn hoist_slices(mut self, slices: bool) -> Self {
123 self.slices = slices;
124 self
125 }
126
127 pub fn transparent(self) -> Self {
128 self.hoist_inside_boxes(true)
129 .hoist_inside_downcast(true)
130 .hoist_inside_mut_refs(false)
131 .hoist_inside_shr_refs(true)
132 .hoist_inside_strg_refs(true)
133 .hoist_inside_tuples(true)
134 .hoist_slices(true)
135 }
136
137 pub fn shallow(self) -> Self {
138 self.hoist_inside_boxes(false)
139 .hoist_inside_downcast(false)
140 .hoist_inside_mut_refs(false)
141 .hoist_inside_shr_refs(false)
142 .hoist_inside_strg_refs(false)
143 .hoist_inside_tuples(false)
144 }
145}
146
147impl<D: HoisterDelegate> Hoister<D> {
148 pub fn hoist(&mut self, ty: &Ty) -> Ty {
149 ty.fold_with(self)
150 }
151}
152
153fn is_indexed_slice(ty: &Ty) -> bool {
157 let Some(bty) = ty.as_bty_skipping_existentials() else {
158 return false;
159 };
160 match bty {
161 BaseTy::Slice(_) => true,
162 BaseTy::Ref(_, ty, _) => is_indexed_slice(ty),
163 _ => false,
164 }
165}
166
167impl<D: HoisterDelegate> TypeFolder for Hoister<D> {
168 fn fold_ty(&mut self, ty: &Ty) -> Ty {
169 match ty.kind() {
170 TyKind::Indexed(bty, idx) => Ty::indexed(bty.fold_with(self), idx.clone()),
171 TyKind::Exists(ty_ctor) if self.existentials => {
172 match &ty_ctor.vars()[..] {
178 [BoundVariableKind::Refine(sort, ..)] => {
179 if sort.is_unit() {
180 ty_ctor.replace_bound_reft(&Expr::unit())
181 } else if let Some(def_id) = sort.is_unit_adt() {
182 ty_ctor.replace_bound_reft(&Expr::unit_struct(def_id))
183 } else {
184 self.delegate.hoist_exists(ty_ctor)
185 }
186 }
187 _ => self.delegate.hoist_exists(ty_ctor),
188 }
189 .fold_with(self)
190 }
191 TyKind::Constr(pred, ty) => {
192 self.delegate.hoist_constr(pred.clone());
193 ty.fold_with(self)
194 }
195 TyKind::StrgRef(..) if self.in_strg_refs => ty.super_fold_with(self),
196 TyKind::Downcast(..) if self.in_downcast => ty.super_fold_with(self),
197 _ => ty.clone(),
198 }
199 }
200
201 fn fold_bty(&mut self, bty: &BaseTy) -> BaseTy {
202 match bty {
203 BaseTy::Adt(adt_def, args) if adt_def.is_box() && self.in_boxes => {
204 let (boxed, alloc) = args.box_args();
205 let args = List::from_arr([
206 GenericArg::Ty(boxed.fold_with(self)),
207 GenericArg::Ty(alloc.clone()),
208 ]);
209 BaseTy::Adt(adt_def.clone(), args)
210 }
211 BaseTy::Ref(re, ty, mutability) if is_indexed_slice(ty) && self.slices => {
212 BaseTy::Ref(*re, ty.fold_with(self), *mutability)
213 }
214 BaseTy::Ref(re, ty, Mutability::Not) if self.in_shr_refs => {
215 BaseTy::Ref(*re, ty.fold_with(self), Mutability::Not)
216 }
217 BaseTy::Ref(re, ty, Mutability::Mut) if self.in_mut_refs => {
218 BaseTy::Ref(*re, ty.fold_with(self), Mutability::Mut)
219 }
220 BaseTy::Tuple(tys) if self.in_tuples => BaseTy::Tuple(tys.fold_with(self)),
221 _ => bty.clone(),
222 }
223 }
224}
225
226#[derive(Default)]
227pub struct LocalHoister {
228 vars: Vec<BoundVariableKind>,
229 preds: Vec<Expr>,
230 pub name: Option<Symbol>,
231}
232
233impl LocalHoister {
234 pub fn new(vars: Vec<BoundVariableKind>) -> Self {
235 LocalHoister { vars, preds: vec![], name: None }
236 }
237
238 pub fn bind<T>(self, f: impl FnOnce(List<BoundVariableKind>, Vec<Expr>) -> T) -> Binder<T> {
239 let vars = List::from_vec(self.vars);
240 Binder::bind_with_vars(f(vars.clone(), self.preds), vars)
241 }
242}
243
244impl HoisterDelegate for &mut LocalHoister {
245 fn hoist_exists(&mut self, ty_ctor: &TyCtor) -> Ty {
246 ty_ctor.replace_bound_refts_with(|sort, mode, kind| {
247 let idx = self.vars.len();
248 let kind = if let Some(name) = self.name { BoundReftKind::Named(name) } else { kind };
249 self.vars
250 .push(BoundVariableKind::Refine(sort.clone(), mode, kind));
251 Expr::bvar(INNERMOST, BoundVar::from_usize(idx), kind)
252 })
253 }
254
255 fn hoist_constr(&mut self, pred: Expr) {
256 self.preds.push(pred);
257 }
258}
259
260impl PolyFnSig {
261 pub fn hoist_input_binders(&self) -> Self {
271 let original_vars = self.vars().to_vec();
272 let fn_sig = self.skip_binder_ref();
273
274 let mut delegate =
275 LocalHoister { vars: original_vars, preds: fn_sig.requires().to_vec(), name: None };
276 let mut hoister = Hoister::with_delegate(&mut delegate).transparent();
277
278 let inputs = fn_sig
279 .inputs()
280 .iter()
281 .map(|ty| hoister.hoist(ty))
282 .collect_vec();
283
284 delegate.bind(|_vars, mut preds| {
285 let mut keep_hole = true;
286 preds.retain(|pred| {
287 if let ExprKind::Hole(HoleKind::Pred) = pred.kind() {
288 std::mem::replace(&mut keep_hole, false)
289 } else {
290 true
291 }
292 });
293
294 FnSig::new(
295 fn_sig.safety,
296 fn_sig.abi,
297 preds.into(),
298 inputs.into(),
299 fn_sig.output().clone(),
300 fn_sig.no_panic,
301 fn_sig.lifted,
302 )
303 })
304 }
305}
306
307impl Ty {
308 pub fn shallow_canonicalize(&self) -> CanonicalTy {
311 let mut delegate = LocalHoister::default();
312 let ty = self.shift_in_escaping(1);
313 let ty = Hoister::with_delegate(&mut delegate).hoist(&ty);
314 let constr_ty = delegate.bind(|_, preds| {
315 let pred = Expr::and_from_iter(preds);
316 CanonicalConstrTy { ty, pred }
317 });
318 if constr_ty.vars().is_empty() {
319 CanonicalTy::Constr(constr_ty.skip_binder().shift_out_escaping(1))
320 } else {
321 CanonicalTy::Exists(constr_ty)
322 }
323 }
324}
325
326#[derive(TypeVisitable, TypeFoldable)]
327pub struct CanonicalConstrTy {
328 ty: Ty,
333 pred: Expr,
334}
335
336impl CanonicalConstrTy {
337 pub fn ty(&self) -> Ty {
338 self.ty.clone()
339 }
340
341 pub fn pred(&self) -> Expr {
342 self.pred.clone()
343 }
344
345 pub fn to_ty(&self) -> Ty {
346 Ty::constr(self.pred(), self.ty())
347 }
348}
349
350#[derive(TypeVisitable)]
358pub enum CanonicalTy {
359 Constr(CanonicalConstrTy),
361 Exists(Binder<CanonicalConstrTy>),
363}
364
365impl CanonicalTy {
366 pub fn to_ty(&self) -> Ty {
367 match self {
368 CanonicalTy::Constr(constr_ty) => constr_ty.to_ty(),
369 CanonicalTy::Exists(poly_constr_ty) => {
370 Ty::exists(poly_constr_ty.as_ref().map(CanonicalConstrTy::to_ty))
371 }
372 }
373 }
374
375 pub fn as_ty_or_base(&self) -> TyOrBase {
376 match self {
377 CanonicalTy::Constr(constr_ty) => {
378 if let TyKind::Indexed(bty, idx) = constr_ty.ty.kind() {
379 let pred = if idx.is_unit() {
386 constr_ty.pred.clone()
387 } else {
388 Expr::and(&constr_ty.pred, Expr::eq(Expr::nu(), idx.shift_in_escaping(1)))
389 };
390 let sort = bty.sort();
391 let constr = SubsetTy::new(bty.shift_in_escaping(1), Expr::nu(), pred);
392 TyOrBase::Base(Binder::bind_with_sort(constr, sort))
393 } else {
394 TyOrBase::Ty(self.to_ty())
395 }
396 }
397 CanonicalTy::Exists(poly_constr_ty) => {
398 let constr = poly_constr_ty.as_ref().skip_binder();
399 if let TyKind::Indexed(bty, idx) = constr.ty.kind()
400 && idx.is_nu()
401 {
402 let ctor = poly_constr_ty
403 .as_ref()
404 .map(|constr| SubsetTy::new(bty.clone(), idx, &constr.pred));
405 TyOrBase::Base(ctor)
406 } else {
407 TyOrBase::Ty(self.to_ty())
408 }
409 }
410 }
411 }
412}
413
414mod pretty {
415 use super::*;
416 use crate::pretty::*;
417
418 impl Pretty for CanonicalConstrTy {
419 fn fmt(&self, cx: &PrettyCx, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
420 if self.pred().is_trivially_true() {
421 w!(cx, f, "{:?}", &self.ty)
422 } else {
423 w!(cx, f, "{{ {:?} | {:?} }}", &self.ty, &self.pred)
424 }
425 }
426 }
427
428 impl Pretty for CanonicalTy {
429 fn fmt(&self, cx: &PrettyCx, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
430 match self {
431 CanonicalTy::Constr(constr) => w!(cx, f, "{:?}", constr),
432 CanonicalTy::Exists(poly_constr) => {
433 let redundant_bvars = poly_constr.skip_binder_ref().redundant_bvars();
434 cx.with_bound_vars_removable(
435 poly_constr.vars(),
436 redundant_bvars,
437 None,
438 |f_body| {
439 let constr = poly_constr.skip_binder_ref();
440 if constr.pred().is_trivially_true() {
441 w!(cx, f_body, "{:?}", &constr.ty)
442 } else {
443 w!(cx, f_body, "{:?} | {:?}", &constr.ty, &constr.pred)
444 }
445 },
446 |(), bound_var_layer, body| {
447 let vars = poly_constr
448 .vars()
449 .into_iter()
450 .enumerate()
451 .filter_map(|(idx, var)| {
452 let not_removed = !bound_var_layer
453 .successfully_removed_vars
454 .contains(&BoundVar::from_usize(idx));
455 let refine_var = matches!(var, BoundVariableKind::Refine(..));
456 if not_removed && refine_var { Some(var.clone()) } else { None }
457 })
458 .collect_vec();
459 if vars.is_empty() {
460 write!(f, "{}", body)
461 } else {
462 let left = "{";
463 let right = format!(". {} }}", body);
464 cx.fmt_bound_vars(false, left, &vars, &right, f)
465 }
466 },
467 )
468 }
469 }
470 }
471 }
472
473 impl_debug_with_default_cx!(CanonicalTy, CanonicalConstrTy);
474}