Skip to main content

flux_middle/rty/
mod.rs

1//! Defines how flux represents refinement types internally. Definitions in this module are used
2//! during refinement type checking. A couple of important differences between definitions in this
3//! module and in [`crate::fhir`] are:
4//!
5//! * Types in this module use debruijn indices to represent local binders.
6//! * Data structures are interned so they can be cheaply cloned.
7mod binder;
8pub mod canonicalize;
9mod expr;
10pub mod fold;
11mod pretty;
12pub mod reduce;
13pub mod refining;
14pub mod region_matching;
15mod spec_func;
16pub mod subst;
17use std::{borrow::Cow, cmp::Ordering, fmt, hash::Hash, sync::LazyLock};
18
19pub use binder::{Binder, BoundReftKind, BoundVariableKind, BoundVariableKinds, EarlyBinder};
20use bitflags::bitflags;
21pub use expr::{
22    AggregateKind, AliasReft, BinOp, BoundReft, Constant, Ctor, ESpan, EVid, EarlyReftParam, Expr,
23    ExprKind, FieldProj, HoleKind, InternalFuncKind, KVar, KVid, Lambda, Loc, Name, NameProvenance,
24    Path, PrettyMap, PrettyVar, QuantDom, RawPtrField, Real, SpecFuncKind, UnOp, Var, WKVar, WKVid,
25};
26pub use flux_arc_interner::List;
27use flux_arc_interner::{Interned, impl_internable, impl_slice_internable};
28use flux_common::{bug, tracked_span_assert_eq, tracked_span_bug};
29use flux_config::OverflowMode;
30use flux_macros::{TypeFoldable, TypeVisitable};
31pub use flux_rustc_bridge::ty::{
32    AliasKind, AliasTermKind, BoundRegion, BoundRegionKind, BoundVar, Const, ConstKind, ConstVid,
33    DebruijnIndex, EarlyParamRegion, LateParamRegion, LateParamRegionKind,
34    Region::{self, *},
35    RegionVid,
36};
37use flux_rustc_bridge::{
38    ToRustc,
39    mir::{Place, RawPtrKind},
40    ty::{self, GenericArgsExt as _, VariantDef},
41};
42use itertools::Itertools;
43use rustc_abi;
44pub use rustc_abi::{FIRST_VARIANT, VariantIdx};
45use rustc_attr_ir::LangItem;
46use rustc_data_structures::{fx::FxIndexMap, snapshot_map::SnapshotMap, unord::UnordMap};
47use rustc_hir::{Safety, def_id::DefId};
48use rustc_index::{IndexSlice, IndexVec, newtype_index};
49use rustc_macros::{Decodable, Encodable, TyDecodable, TyEncodable, extension};
50pub use rustc_middle::{
51    mir::Mutability,
52    ty::{AdtFlags, ClosureKind, FloatTy, IntTy, ParamConst, ParamTy, ScalarInt, UintTy},
53};
54use rustc_middle::{
55    query::IntoQueryKey,
56    ty::{TyCtxt, fast_reject::SimplifiedType},
57};
58use rustc_span::{DUMMY_SP, Span, Symbol, sym, symbol::kw};
59use rustc_type_ir::Upcast as _;
60pub use rustc_type_ir::{INNERMOST, TyVid};
61pub use spec_func::{SpecFunc, SpecFuncs, deps};
62
63use self::fold::TypeFoldable;
64pub use crate::fhir::InferMode;
65use crate::{
66    LocalDefId,
67    def_id::{FluxDefId, FluxLocalDefId},
68    fhir::{self, FhirId, FluxOwnerId},
69    global_env::GlobalEnv,
70    pretty::{Pretty, PrettyCx},
71    queries::{QueryErr, QueryResult},
72    rty::subst::SortSubst,
73};
74
75/// The definition of the data sort automatically generated for a struct or enum.
76#[derive(Debug, Clone, Eq, PartialEq, Hash, TyEncodable, TyDecodable)]
77pub struct AdtSortDef(Interned<AdtSortDefData>);
78
79#[derive(Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
80pub struct AdtSortVariant {
81    /// The list of field names as declared in the `#[flux::refined_by(...)]` annotation
82    field_names: Vec<Symbol>,
83    /// The sort of each of the fields. Note that these can contain [sort variables]. Methods used
84    /// to access these sorts guarantee they are properly instantiated.
85    ///
86    /// [sort variables]: Sort::Var
87    sorts: List<Sort>,
88}
89
90impl AdtSortVariant {
91    pub fn new(fields: Vec<(Symbol, Sort)>) -> Self {
92        let (field_names, sorts) = fields.into_iter().unzip();
93        AdtSortVariant { field_names, sorts: List::from_vec(sorts) }
94    }
95
96    pub fn fields(&self) -> usize {
97        self.sorts.len()
98    }
99
100    pub fn field_names(&self) -> &Vec<Symbol> {
101        &self.field_names
102    }
103
104    pub fn sort_by_field_name(&self, args: &[Sort]) -> FxIndexMap<Symbol, Sort> {
105        std::iter::zip(&self.field_names, &self.sorts.fold_with(&mut SortSubst::new(args)))
106            .map(|(name, sort)| (*name, sort.clone()))
107            .collect()
108    }
109
110    pub fn field_by_name(
111        &self,
112        def_id: DefId,
113        args: &[Sort],
114        name: Symbol,
115    ) -> Option<(FieldProj, Sort)> {
116        let idx = self.field_names.iter().position(|it| name == *it)?;
117        let proj = FieldProj::Adt { def_id, field: idx as u32 };
118        let sort = self.sorts[idx].fold_with(&mut SortSubst::new(args));
119        Some((proj, sort))
120    }
121
122    pub fn field_sorts(&self, args: &[Sort]) -> List<Sort> {
123        self.sorts.fold_with(&mut SortSubst::new(args))
124    }
125
126    pub fn field_sorts_instantiate_identity(&self) -> List<Sort> {
127        self.sorts.clone()
128    }
129
130    pub fn projections(&self, def_id: DefId) -> impl Iterator<Item = FieldProj> {
131        (0..self.fields()).map(move |i| FieldProj::Adt { def_id, field: i as u32 })
132    }
133}
134
135#[derive(Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
136struct AdtSortDefData {
137    /// [`DefId`] of the struct or enum this data sort is associated to.
138    def_id: DefId,
139    /// The list of the type parameters used in the `#[flux::refined_by(..)]` annotation.
140    ///
141    /// See [`fhir::RefinedBy::sort_params`] for more details. This is a version of that but using
142    /// [`ParamTy`] instead of [`DefId`].
143    ///
144    /// The length of this list corresponds to the number of sort variables bound by this definition.
145    params: Vec<ParamTy>,
146    /// A vec of variants of the ADT;
147    /// - a `struct` sort -- used for types with a `refined_by` has a single variant;
148    /// - a `reflected` sort -- used for `reflected` enums have multiple variants
149    variants: IndexVec<VariantIdx, AdtSortVariant>,
150    is_reflected: bool,
151    is_struct: bool,
152}
153
154impl AdtSortDef {
155    pub fn new(
156        def_id: DefId,
157        params: Vec<ParamTy>,
158        variants: IndexVec<VariantIdx, AdtSortVariant>,
159        is_reflected: bool,
160        is_struct: bool,
161    ) -> Self {
162        Self(Interned::new(AdtSortDefData { def_id, params, variants, is_reflected, is_struct }))
163    }
164
165    pub fn did(&self) -> DefId {
166        self.0.def_id
167    }
168
169    pub fn variant(&self, idx: VariantIdx) -> &AdtSortVariant {
170        &self.0.variants[idx]
171    }
172
173    pub fn variants(&self) -> &IndexSlice<VariantIdx, AdtSortVariant> {
174        &self.0.variants
175    }
176
177    pub fn opt_struct_variant(&self) -> Option<&AdtSortVariant> {
178        if self.is_struct() { Some(self.struct_variant()) } else { None }
179    }
180
181    #[track_caller]
182    pub fn struct_variant(&self) -> &AdtSortVariant {
183        tracked_span_assert_eq!(self.0.is_struct, true);
184        &self.0.variants[FIRST_VARIANT]
185    }
186
187    pub fn is_reflected(&self) -> bool {
188        self.0.is_reflected
189    }
190
191    pub fn is_struct(&self) -> bool {
192        self.0.is_struct
193    }
194
195    pub fn to_sort(&self, args: &[GenericArg]) -> Sort {
196        let sorts = self
197            .filter_generic_args(args)
198            .map(|arg| arg.expect_base().sort())
199            .collect();
200
201        Sort::App(SortCtor::Adt(self.clone()), sorts)
202    }
203
204    /// Given a list of generic args, returns an iterator of the generic arguments that should be
205    /// mapped to sorts for instantiation.
206    pub fn filter_generic_args<'a, A>(&'a self, args: &'a [A]) -> impl Iterator<Item = &'a A> + 'a {
207        self.0.params.iter().map(|p| &args[p.index as usize])
208    }
209
210    pub fn identity_args(&self) -> List<Sort> {
211        (0..self.0.params.len())
212            .map(|i| Sort::Var(ParamSort::from(i)))
213            .collect()
214    }
215
216    /// Gives the number of sort variables bound by this definition.
217    pub fn param_count(&self) -> usize {
218        self.0.params.len()
219    }
220}
221
222#[derive(Debug, Clone, Default, Encodable, Decodable)]
223pub struct Generics {
224    pub parent: Option<DefId>,
225    pub parent_count: usize,
226    pub own_params: List<GenericParamDef>,
227    pub has_self: bool,
228}
229
230impl Generics {
231    pub fn count(&self) -> usize {
232        self.parent_count + self.own_params.len()
233    }
234
235    pub fn own_default_count(&self) -> usize {
236        self.own_params
237            .iter()
238            .filter(|param| {
239                match param.kind {
240                    GenericParamDefKind::Type { has_default }
241                    | GenericParamDefKind::Const { has_default }
242                    | GenericParamDefKind::Base { has_default } => has_default,
243                    GenericParamDefKind::Lifetime => false,
244                }
245            })
246            .count()
247    }
248
249    pub fn param_at(&self, param_index: usize, genv: GlobalEnv) -> QueryResult<GenericParamDef> {
250        if let Some(index) = param_index.checked_sub(self.parent_count) {
251            Ok(self.own_params[index].clone())
252        } else {
253            let parent = self.parent.expect("parent_count > 0 but no parent?");
254            genv.generics_of(parent)?.param_at(param_index, genv)
255        }
256    }
257
258    /// Returns the const generic params (including the parent's) together with their sort and
259    /// [`DefId`].
260    pub fn const_params(&self, genv: GlobalEnv) -> QueryResult<Vec<(ParamConst, Sort, DefId)>> {
261        let mut res = vec![];
262        for i in 0..self.count() {
263            let param = self.param_at(i, genv)?;
264            if let GenericParamDefKind::Const { .. } = param.kind
265                && let Some(sort) = genv.sort_of_def_id(param.def_id)?
266            {
267                let param_const = ParamConst { name: param.name, index: param.index };
268                res.push((param_const, sort, param.def_id));
269            }
270        }
271        Ok(res)
272    }
273}
274
275#[derive(Debug, Clone, TyEncodable, TyDecodable)]
276pub struct RefinementGenerics {
277    pub parent: Option<DefId>,
278    pub parent_count: usize,
279    pub own_params: List<RefineParam>,
280}
281
282#[derive(
283    PartialEq, Eq, Debug, Clone, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
284)]
285pub struct RefineParam {
286    pub sort: Sort,
287    pub name: Symbol,
288    pub mode: InferMode,
289}
290
291#[derive(Debug, Clone, PartialEq, Eq, Hash, Encodable, Decodable)]
292pub struct GenericParamDef {
293    pub kind: GenericParamDefKind,
294    pub def_id: DefId,
295    pub index: u32,
296    pub name: Symbol,
297}
298
299#[derive(Copy, Debug, Clone, PartialEq, Eq, Hash, Encodable, Decodable)]
300pub enum GenericParamDefKind {
301    Type { has_default: bool },
302    Base { has_default: bool },
303    Lifetime,
304    Const { has_default: bool },
305}
306
307pub const SELF_PARAM_TY: ParamTy = ParamTy { index: 0, name: kw::SelfUpper };
308
309#[derive(Debug, Clone, TyEncodable, TyDecodable)]
310pub struct GenericPredicates {
311    pub parent: Option<DefId>,
312    pub predicates: List<Clause>,
313}
314
315#[derive(
316    Debug, PartialEq, Eq, Hash, Clone, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
317)]
318pub struct Clause {
319    kind: Binder<ClauseKind>,
320}
321
322impl Clause {
323    pub fn new(vars: impl Into<List<BoundVariableKind>>, kind: ClauseKind) -> Self {
324        Clause { kind: Binder::bind_with_vars(kind, vars.into()) }
325    }
326
327    pub fn kind(&self) -> Binder<ClauseKind> {
328        self.kind.clone()
329    }
330
331    fn as_trait_clause(&self) -> Option<Binder<TraitPredicate>> {
332        let clause = self.kind();
333        if let ClauseKind::Trait(trait_clause) = clause.skip_binder_ref() {
334            Some(clause.rebind(trait_clause.clone()))
335        } else {
336            None
337        }
338    }
339
340    pub fn as_projection_clause(&self) -> Option<Binder<ProjectionPredicate>> {
341        let clause = self.kind();
342        if let ClauseKind::Projection(proj_clause) = clause.skip_binder_ref() {
343            Some(clause.rebind(proj_clause.clone()))
344        } else {
345            None
346        }
347    }
348
349    // FIXME(nilehmann) we should deal with the binder in all the places this is used instead of
350    // blindly skipping it here
351    pub fn kind_skipping_binder(&self) -> ClauseKind {
352        self.kind.clone().skip_binder()
353    }
354
355    /// Group `Fn` trait clauses with their corresponding `FnOnce::Output` projection
356    /// predicate. This assumes there's exactly one corresponding projection predicate and will
357    /// crash otherwise.
358    pub fn split_off_fn_trait_clauses(
359        genv: GlobalEnv,
360        clauses: &Clauses,
361    ) -> (Vec<Clause>, Vec<Binder<FnTraitPredicate>>) {
362        let mut fn_trait_clauses = vec![];
363        let mut fn_trait_output_clauses = vec![];
364        let mut rest = vec![];
365        for clause in clauses {
366            if let Some(trait_clause) = clause.as_trait_clause()
367                && let Some(kind) = genv.tcx().fn_trait_kind_from_def_id(trait_clause.def_id())
368            {
369                fn_trait_clauses.push((kind, trait_clause));
370            } else if let Some(proj_clause) = clause.as_projection_clause()
371                && genv.is_fn_output(proj_clause.projection_def_id())
372            {
373                fn_trait_output_clauses.push(proj_clause);
374            } else {
375                rest.push(clause.clone());
376            }
377        }
378        let fn_trait_clauses = fn_trait_clauses
379            .into_iter()
380            .map(|(kind, fn_trait_clause)| {
381                let mut candidates = vec![];
382                for fn_trait_output_clause in &fn_trait_output_clauses {
383                    if fn_trait_output_clause.self_ty() == fn_trait_clause.self_ty() {
384                        candidates.push(fn_trait_output_clause.clone());
385                    }
386                }
387                tracked_span_assert_eq!(candidates.len(), 1);
388                let proj_pred = candidates.pop().unwrap().skip_binder();
389                fn_trait_clause.map(|fn_trait_clause| {
390                    FnTraitPredicate {
391                        kind,
392                        self_ty: fn_trait_clause.self_ty().to_ty(),
393                        tupled_args: fn_trait_clause.trait_ref.args[1].expect_base().to_ty(),
394                        output: proj_pred.term.to_ty(),
395                    }
396                })
397            })
398            .collect_vec();
399        (rest, fn_trait_clauses)
400    }
401}
402
403impl<'tcx> ToRustc<'tcx> for Clause {
404    type T = rustc_middle::ty::Clause<'tcx>;
405
406    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
407        self.kind.to_rustc(tcx).upcast(tcx)
408    }
409}
410
411impl From<Binder<ClauseKind>> for Clause {
412    fn from(kind: Binder<ClauseKind>) -> Self {
413        Clause { kind }
414    }
415}
416
417pub type Clauses = List<Clause>;
418
419#[derive(
420    Debug, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
421)]
422pub enum ClauseKind {
423    Trait(TraitPredicate),
424    Projection(ProjectionPredicate),
425    RegionOutlives(RegionOutlivesPredicate),
426    TypeOutlives(TypeOutlivesPredicate),
427    ConstArgHasType(Const, Ty),
428    UnstableFeature(Symbol),
429}
430
431impl<'tcx> ToRustc<'tcx> for ClauseKind {
432    type T = rustc_middle::ty::ClauseKind<'tcx>;
433
434    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
435        match self {
436            ClauseKind::Trait(trait_predicate) => {
437                rustc_middle::ty::ClauseKind::Trait(trait_predicate.to_rustc(tcx))
438            }
439            ClauseKind::Projection(projection_predicate) => {
440                rustc_middle::ty::ClauseKind::Projection(projection_predicate.to_rustc(tcx))
441            }
442            ClauseKind::RegionOutlives(outlives_predicate) => {
443                rustc_middle::ty::ClauseKind::RegionOutlives(outlives_predicate.to_rustc(tcx))
444            }
445            ClauseKind::TypeOutlives(outlives_predicate) => {
446                rustc_middle::ty::ClauseKind::TypeOutlives(outlives_predicate.to_rustc(tcx))
447            }
448            ClauseKind::ConstArgHasType(constant, ty) => {
449                rustc_middle::ty::ClauseKind::ConstArgHasType(
450                    constant.to_rustc(tcx),
451                    ty.to_rustc(tcx),
452                )
453            }
454            ClauseKind::UnstableFeature(sym) => rustc_middle::ty::ClauseKind::UnstableFeature(*sym),
455        }
456    }
457}
458
459#[derive(Eq, PartialEq, Hash, Clone, Debug, TyEncodable, TyDecodable)]
460pub struct OutlivesPredicate<T>(pub T, pub Region);
461
462pub type TypeOutlivesPredicate = OutlivesPredicate<Ty>;
463pub type RegionOutlivesPredicate = OutlivesPredicate<Region>;
464
465impl<'tcx, V: ToRustc<'tcx>> ToRustc<'tcx> for OutlivesPredicate<V> {
466    type T = rustc_middle::ty::OutlivesClause<'tcx, V::T>;
467
468    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
469        rustc_middle::ty::OutlivesClause(self.0.to_rustc(tcx), self.1.to_rustc(tcx))
470    }
471}
472
473#[derive(
474    Debug, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
475)]
476pub struct TraitPredicate {
477    pub trait_ref: TraitRef,
478}
479
480impl TraitPredicate {
481    fn self_ty(&self) -> SubsetTyCtor {
482        self.trait_ref.self_ty()
483    }
484}
485
486impl<'tcx> ToRustc<'tcx> for TraitPredicate {
487    type T = rustc_middle::ty::TraitClause<'tcx>;
488
489    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
490        rustc_middle::ty::TraitClause {
491            polarity: rustc_middle::ty::ClausePolarity::Positive,
492            trait_ref: self.trait_ref.to_rustc(tcx),
493        }
494    }
495}
496
497pub type PolyTraitPredicate = Binder<TraitPredicate>;
498
499impl PolyTraitPredicate {
500    fn def_id(&self) -> DefId {
501        self.skip_binder_ref().trait_ref.def_id
502    }
503
504    fn self_ty(&self) -> Binder<SubsetTyCtor> {
505        self.clone().map(|predicate| predicate.self_ty())
506    }
507}
508
509#[derive(
510    Debug, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
511)]
512pub struct TraitRef {
513    pub def_id: DefId,
514    pub args: GenericArgs,
515}
516
517impl TraitRef {
518    pub fn self_ty(&self) -> SubsetTyCtor {
519        self.args[0].expect_base().clone()
520    }
521}
522
523impl<'tcx> ToRustc<'tcx> for TraitRef {
524    type T = rustc_middle::ty::TraitRef<'tcx>;
525
526    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
527        rustc_middle::ty::TraitRef::new(tcx, self.def_id, self.args.to_rustc(tcx))
528    }
529}
530
531pub type PolyTraitRef = Binder<TraitRef>;
532
533impl PolyTraitRef {
534    pub fn def_id(&self) -> DefId {
535        self.as_ref().skip_binder().def_id
536    }
537}
538
539#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)]
540pub enum ExistentialPredicate {
541    Trait(ExistentialTraitRef),
542    Projection(ExistentialProjection),
543    AutoTrait(DefId),
544}
545
546pub type PolyExistentialPredicate = Binder<ExistentialPredicate>;
547
548impl ExistentialPredicate {
549    /// See [`rustc_middle::ty::ExistentialPredicateStableCmpExt`]
550    pub fn stable_cmp(&self, tcx: TyCtxt, other: &Self) -> Ordering {
551        match (self, other) {
552            (ExistentialPredicate::Trait(_), ExistentialPredicate::Trait(_)) => Ordering::Equal,
553            (ExistentialPredicate::Projection(a), ExistentialPredicate::Projection(b)) => {
554                tcx.def_path_hash(a.def_id)
555                    .cmp(&tcx.def_path_hash(b.def_id))
556            }
557            (ExistentialPredicate::AutoTrait(a), ExistentialPredicate::AutoTrait(b)) => {
558                tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b))
559            }
560            (ExistentialPredicate::Trait(_), _) => Ordering::Less,
561            (ExistentialPredicate::Projection(_), ExistentialPredicate::Trait(_)) => {
562                Ordering::Greater
563            }
564            (ExistentialPredicate::Projection(_), _) => Ordering::Less,
565            (ExistentialPredicate::AutoTrait(_), _) => Ordering::Greater,
566        }
567    }
568}
569
570impl<'tcx> ToRustc<'tcx> for ExistentialPredicate {
571    type T = rustc_middle::ty::ExistentialPredicate<'tcx>;
572
573    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
574        match self {
575            ExistentialPredicate::Trait(trait_ref) => {
576                let trait_ref = rustc_middle::ty::ExistentialTraitRef::new_from_args(
577                    tcx,
578                    trait_ref.def_id,
579                    trait_ref.args.to_rustc(tcx),
580                );
581                rustc_middle::ty::ExistentialPredicate::Trait(trait_ref)
582            }
583            ExistentialPredicate::Projection(projection) => {
584                rustc_middle::ty::ExistentialPredicate::Projection(
585                    rustc_middle::ty::ExistentialProjection::new_from_args(
586                        tcx,
587                        projection.def_id,
588                        projection.args.to_rustc(tcx),
589                        projection.term.skip_binder_ref().to_rustc(tcx).into(),
590                    ),
591                )
592            }
593            ExistentialPredicate::AutoTrait(def_id) => {
594                rustc_middle::ty::ExistentialPredicate::AutoTrait(*def_id)
595            }
596        }
597    }
598}
599
600#[derive(
601    Debug, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
602)]
603pub struct ExistentialTraitRef {
604    pub def_id: DefId,
605    pub args: GenericArgs,
606}
607
608pub type PolyExistentialTraitRef = Binder<ExistentialTraitRef>;
609
610impl PolyExistentialTraitRef {
611    pub fn def_id(&self) -> DefId {
612        self.as_ref().skip_binder().def_id
613    }
614}
615
616#[derive(
617    Debug, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
618)]
619pub struct ExistentialProjection {
620    pub def_id: DefId,
621    pub args: GenericArgs,
622    pub term: SubsetTyCtor,
623}
624
625#[derive(
626    PartialEq, Eq, Hash, Debug, Clone, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
627)]
628pub struct ProjectionPredicate {
629    pub projection_term: AliasTerm,
630    pub term: SubsetTyCtor,
631}
632
633impl Pretty for ProjectionPredicate {
634    fn fmt(&self, _cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
635        write!(
636            f,
637            "ProjectionPredicate << projection_term = {:?}, term = {:?} >>",
638            self.projection_term, self.term
639        )
640    }
641}
642
643impl ProjectionPredicate {
644    pub fn self_ty(&self) -> SubsetTyCtor {
645        self.projection_term.self_ty().clone()
646    }
647}
648
649impl<'tcx> ToRustc<'tcx> for ProjectionPredicate {
650    type T = rustc_middle::ty::ProjectionClause<'tcx>;
651
652    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
653        rustc_middle::ty::ProjectionClause {
654            projection_term: self.projection_term.to_rustc(tcx),
655            term: self.term.as_bty_skipping_binder().to_rustc(tcx).into(),
656        }
657    }
658}
659
660pub type PolyProjectionPredicate = Binder<ProjectionPredicate>;
661
662impl PolyProjectionPredicate {
663    pub fn projection_def_id(&self) -> DefId {
664        self.skip_binder_ref().projection_term.def_id()
665    }
666
667    pub fn self_ty(&self) -> Binder<SubsetTyCtor> {
668        self.clone().map(|predicate| predicate.self_ty())
669    }
670}
671
672#[derive(
673    Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
674)]
675pub struct FnTraitPredicate {
676    pub self_ty: Ty,
677    pub tupled_args: Ty,
678    pub output: Ty,
679    pub kind: ClosureKind,
680}
681
682impl Pretty for FnTraitPredicate {
683    fn fmt(&self, _cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
684        write!(
685            f,
686            "self = {:?}, args = {:?}, output = {:?}, kind = {}",
687            self.self_ty, self.tupled_args, self.output, self.kind
688        )
689    }
690}
691
692impl FnTraitPredicate {
693    pub fn fndef_sig(&self) -> FnSig {
694        let inputs = self.tupled_args.expect_tuple().iter().cloned().collect();
695        let ret = self.output.clone().shift_in_escaping(1);
696        let output = Binder::bind_with_vars(FnOutput::new(ret, vec![]), List::empty());
697        FnSig::new(
698            Safety::Safe,
699            rustc_abi::ExternAbi::Rust,
700            List::empty(),
701            inputs,
702            output,
703            Expr::ff(),
704            false,
705        )
706    }
707}
708
709pub fn to_closure_sig(
710    tcx: TyCtxt,
711    closure_id: LocalDefId,
712    tys: &[Ty],
713    args: &flux_rustc_bridge::ty::GenericArgs,
714    poly_sig: &PolyFnSig,
715    no_panic: bool,
716) -> PolyFnSig {
717    let closure_args = args.as_closure();
718    let kind_ty = closure_args.kind_ty().to_rustc(tcx);
719    let Some(kind) = kind_ty.to_opt_closure_kind() else {
720        bug!("to_closure_sig: expected closure kind, found {kind_ty:?}");
721    };
722
723    let mut vars = poly_sig.vars().clone().to_vec();
724    let fn_sig = poly_sig.clone().skip_binder();
725    let closure_ty = Ty::closure(closure_id.into(), tys, args, no_panic);
726    let env_ty = match kind {
727        ClosureKind::Fn => {
728            vars.push(BoundVariableKind::Region(BoundRegionKind::ClosureEnv));
729            let br = BoundRegion {
730                var: BoundVar::from_usize(vars.len() - 1),
731                kind: BoundRegionKind::ClosureEnv,
732            };
733            Ty::mk_ref(ReBound(INNERMOST, br), closure_ty, Mutability::Not)
734        }
735        ClosureKind::FnMut => {
736            vars.push(BoundVariableKind::Region(BoundRegionKind::ClosureEnv));
737            let br = BoundRegion {
738                var: BoundVar::from_usize(vars.len() - 1),
739                kind: BoundRegionKind::ClosureEnv,
740            };
741            Ty::mk_ref(ReBound(INNERMOST, br), closure_ty, Mutability::Mut)
742        }
743        ClosureKind::FnOnce => closure_ty,
744    };
745
746    let inputs = std::iter::once(env_ty)
747        .chain(fn_sig.inputs().iter().cloned())
748        .collect::<Vec<_>>();
749    let output = fn_sig.output().clone();
750
751    let fn_sig = crate::rty::FnSig::new(
752        fn_sig.safety,
753        fn_sig.abi,
754        fn_sig.requires.clone(),
755        inputs.into(),
756        output,
757        if no_panic { crate::rty::Expr::tt() } else { crate::rty::Expr::ff() },
758        false,
759    );
760
761    PolyFnSig::bind_with_vars(fn_sig, List::from(vars))
762}
763
764#[derive(Clone, PartialEq, Eq, Hash, Debug)]
765pub struct CoroutineObligPredicate {
766    pub def_id: DefId,
767    pub resume_ty: Ty,
768    pub upvar_tys: List<Ty>,
769    pub output: Ty,
770    pub args: flux_rustc_bridge::ty::GenericArgs,
771}
772
773#[derive(Copy, Clone, Encodable, Decodable, Hash, PartialEq, Debug, Eq)]
774pub struct AssocReft {
775    pub def_id: FluxDefId,
776    // NOTE: Field is used to denote final associated generic refinements on Traits
777    pub final_: bool,
778    pub span: Span,
779}
780
781impl AssocReft {
782    pub fn new(def_id: FluxDefId, final_: bool, span: Span) -> Self {
783        Self { def_id, final_, span }
784    }
785
786    pub fn name(&self) -> Symbol {
787        self.def_id.name()
788    }
789
790    pub fn def_id(&self) -> FluxDefId {
791        self.def_id
792    }
793}
794
795#[derive(Clone, Encodable, Decodable)]
796pub struct AssocRefinements {
797    pub items: List<AssocReft>,
798}
799
800impl Default for AssocRefinements {
801    fn default() -> Self {
802        Self { items: List::empty() }
803    }
804}
805
806impl AssocRefinements {
807    pub fn get(&self, assoc_id: FluxDefId) -> AssocReft {
808        *self
809            .items
810            .into_iter()
811            .find(|it| it.def_id == assoc_id)
812            .unwrap_or_else(|| {
813                bug!("caller should guarantee existence of associated refinement {assoc_id:?}")
814            })
815    }
816
817    pub fn find(&self, name: Symbol) -> Option<AssocReft> {
818        Some(*self.items.into_iter().find(|it| it.name() == name)?)
819    }
820}
821
822#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
823pub enum SortCtor {
824    Set,
825    Map,
826    Adt(AdtSortDef),
827    User(FluxDefId),
828}
829
830newtype_index! {
831    /// [`ParamSort`] is used for polymorphic sorts (`Set`, `Map`, etc.) and [bit-vector size parameters].
832    /// They should occur "bound" under a [`PolyFuncSort`] or an [`AdtSortDef`]. We assume there's a
833    /// single binder and a [`ParamSort`] represents a variable as an index into the list of variables
834    /// bound by that binder, i.e., the representation doesnt't support higher-ranked sorts.
835    ///
836    /// [bit-vector size parameters]: BvSize::Param
837    #[debug_format = "?{}s"]
838    #[encodable]
839    pub struct ParamSort {}
840}
841
842newtype_index! {
843    /// A *sort* *v*variable *id*
844    #[debug_format = "?{}s"]
845    #[encodable]
846    pub struct SortVid {}
847}
848
849impl ena::unify::UnifyKey for SortVid {
850    type Value = SortVarVal;
851
852    #[inline]
853    fn index(&self) -> u32 {
854        self.as_u32()
855    }
856
857    #[inline]
858    fn from_index(u: u32) -> Self {
859        SortVid::from_u32(u)
860    }
861
862    fn tag() -> &'static str {
863        "SortVid"
864    }
865}
866
867bitflags! {
868    /// A *sort constraint* is a set of operations a sort must support.
869    ///
870    /// During sort checking, we accumulate the operations required for each sort variable. As
871    /// unification progresses, these constraints become more specific, i.e, a sort must support
872    /// more operations to satisfy them.
873    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
874    pub struct SortCstr: u16 {
875        /// An empty constraint (any sort satisfies it)
876        const BOT     = 0b0000000000;
877        /// `*`
878        const MUL     = 0b0000000001;
879        /// `/`
880        const DIV     = 0b0000000010;
881        /// `%`
882        const MOD     = 0b0000000100;
883        /// `+`
884        const ADD     = 0b0000001000;
885        /// `-`
886        const SUB     = 0b0000010000;
887        /// `|`
888        const BIT_OR  = 0b0000100000;
889        /// `&`
890        const BIT_AND = 0b0001000000;
891        /// `>>`
892        const BIT_SHL = 0b0010000000;
893        /// `<<`
894        const BIT_SHR = 0b0100000000;
895        /// `^`
896        const BIT_XOR = 0b1000000000;
897
898        /// The set of operations supported by all _numeric_ sorts.
899        const NUMERIC = Self::ADD.bits() | Self::SUB.bits() | Self::MUL.bits() | Self::DIV.bits();
900        /// The set of operations supported by integers.
901        const INT = Self::DIV.bits()
902            | Self::MUL.bits()
903            | Self::MOD.bits()
904            | Self::ADD.bits()
905            | Self::SUB.bits();
906        /// The set of operations supported by reals.
907        const REAL = Self::ADD.bits() | Self::SUB.bits() | Self::MUL.bits() | Self::DIV.bits();
908        /// The set of operations supported by bit vectors.
909        const BITVEC =  Self::DIV.bits()
910            | Self::MUL.bits()
911            | Self::MOD.bits()
912            | Self::ADD.bits()
913            | Self::SUB.bits()
914            | Self::BIT_OR.bits()
915            | Self::BIT_AND.bits()
916            | Self::BIT_SHL.bits()
917            | Self::BIT_SHR.bits()
918            | Self::BIT_XOR.bits();
919        /// The set of operations supported by sets.
920        const SET = Self::SUB.bits() | Self::BIT_OR.bits() | Self::BIT_AND.bits();
921    }
922}
923
924impl SortCstr {
925    /// Returns a constraint that only requires the specified binary operation.
926    pub fn from_bin_op(op: fhir::BinOp) -> Self {
927        match op {
928            fhir::BinOp::Add => Self::ADD,
929            fhir::BinOp::Sub => Self::SUB,
930            fhir::BinOp::Mul => Self::MUL,
931            fhir::BinOp::Div => Self::DIV,
932            fhir::BinOp::Mod => Self::MOD,
933            fhir::BinOp::BitAnd => Self::BIT_AND,
934            fhir::BinOp::BitOr => Self::BIT_OR,
935            fhir::BinOp::BitXor => Self::BIT_XOR,
936            fhir::BinOp::BitShl => Self::BIT_SHL,
937            fhir::BinOp::BitShr => Self::BIT_SHR,
938            _ => bug!("{op:?} not supported as a constraint"),
939        }
940    }
941
942    /// Returns whether a sort satisfies this constraint
943    fn satisfy(self, sort: &Sort) -> bool {
944        match sort {
945            Sort::Int => SortCstr::INT.contains(self),
946            Sort::Real => SortCstr::REAL.contains(self),
947            Sort::BitVec(_) => SortCstr::BITVEC.contains(self),
948            Sort::App(SortCtor::Set, _) => SortCstr::SET.contains(self),
949            _ => self == SortCstr::BOT,
950        }
951    }
952}
953
954/// Unification value for sort variables used during sort checking.
955#[derive(Debug, Clone, PartialEq, Eq)]
956pub enum SortVarVal {
957    /// The variable is not yet solved but the solution must satisfy some constraint.
958    Unsolved(SortCstr),
959    /// The variable has been solved to a sort.
960    Solved(Sort),
961}
962
963impl Default for SortVarVal {
964    fn default() -> Self {
965        SortVarVal::Unsolved(SortCstr::BOT)
966    }
967}
968
969impl SortVarVal {
970    pub fn solved_or(&self, sort: &Sort) -> Sort {
971        match self {
972            SortVarVal::Unsolved(_) => sort.clone(),
973            SortVarVal::Solved(sort) => sort.clone(),
974        }
975    }
976
977    pub fn map_solved(&self, f: impl FnOnce(&Sort) -> Sort) -> SortVarVal {
978        match self {
979            SortVarVal::Unsolved(cstr) => SortVarVal::Unsolved(*cstr),
980            SortVarVal::Solved(sort) => SortVarVal::Solved(f(sort)),
981        }
982    }
983}
984
985impl ena::unify::UnifyValue for SortVarVal {
986    type Error = ();
987
988    fn unify_values(value1: &Self, value2: &Self) -> Result<Self, Self::Error> {
989        match (value1, value2) {
990            (SortVarVal::Solved(s1), SortVarVal::Solved(s2)) if s1 == s2 => {
991                Ok(SortVarVal::Solved(s1.clone()))
992            }
993            (SortVarVal::Unsolved(a), SortVarVal::Unsolved(b)) => Ok(SortVarVal::Unsolved(*a | *b)),
994            (SortVarVal::Unsolved(v), SortVarVal::Solved(sort))
995            | (SortVarVal::Solved(sort), SortVarVal::Unsolved(v))
996                if v.satisfy(sort) =>
997            {
998                Ok(SortVarVal::Solved(sort.clone()))
999            }
1000            _ => Err(()),
1001        }
1002    }
1003}
1004
1005newtype_index! {
1006    /// A *b*it *v*ector *size* *v*variable *id*
1007    #[debug_format = "?{}size"]
1008    #[encodable]
1009    pub struct BvSizeVid {}
1010}
1011
1012impl ena::unify::UnifyKey for BvSizeVid {
1013    type Value = Option<BvSize>;
1014
1015    #[inline]
1016    fn index(&self) -> u32 {
1017        self.as_u32()
1018    }
1019
1020    #[inline]
1021    fn from_index(u: u32) -> Self {
1022        BvSizeVid::from_u32(u)
1023    }
1024
1025    fn tag() -> &'static str {
1026        "BvSizeVid"
1027    }
1028}
1029
1030impl ena::unify::EqUnifyValue for BvSize {}
1031
1032#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1033pub enum Sort {
1034    Int,
1035    Bool,
1036    Real,
1037    BitVec(BvSize),
1038    Str,
1039    Char,
1040    Loc,
1041    Param(ParamTy),
1042    Tuple(List<Sort>),
1043    Alias(AliasTy),
1044    Func(PolyFuncSort),
1045    App(SortCtor, List<Sort>),
1046    Var(ParamSort),
1047    Infer(SortVid),
1048    RawPtr,
1049    Err,
1050}
1051
1052pub enum CastKind {
1053    /// Identity cast, which is erasable (e.g. int -> int, char -> int)
1054    Identity,
1055    /// From bool to int
1056    BoolToInt,
1057    /// Casts to unit index, (e.g. int -> float)
1058    IntoUnit,
1059    /// Uninterpreted casts, only allowed with explicit flag
1060    Uninterpreted,
1061}
1062
1063impl Sort {
1064    pub fn tuple(sorts: impl Into<List<Sort>>) -> Self {
1065        Sort::Tuple(sorts.into())
1066    }
1067
1068    pub fn app(ctor: SortCtor, sorts: List<Sort>) -> Self {
1069        Sort::App(ctor, sorts)
1070    }
1071
1072    pub fn unit() -> Self {
1073        Self::tuple(vec![])
1074    }
1075
1076    pub fn field_sorts(&self) -> Option<List<Sort>> {
1077        match self {
1078            Sort::RawPtr => Some(RawPtrField::iter().map(RawPtrField::sort).collect()),
1079            Sort::App(SortCtor::Adt(sort_def), args) if sort_def.is_struct() => {
1080                Some(sort_def.struct_variant().field_sorts(args))
1081            }
1082            _ => None,
1083        }
1084    }
1085
1086    #[track_caller]
1087    pub fn expect_func(&self) -> &PolyFuncSort {
1088        if let Sort::Func(sort) = self { sort } else { bug!("expected `Sort::Func`") }
1089    }
1090
1091    pub fn is_loc(&self) -> bool {
1092        matches!(self, Sort::Loc)
1093    }
1094
1095    pub fn is_unit(&self) -> bool {
1096        matches!(self, Sort::Tuple(sorts) if sorts.is_empty())
1097    }
1098
1099    pub fn is_unit_adt(&self) -> Option<DefId> {
1100        if let Sort::App(SortCtor::Adt(sort_def), _) = self
1101            && let Some(variant) = sort_def.opt_struct_variant()
1102            && variant.fields() == 0
1103        {
1104            Some(sort_def.did())
1105        } else {
1106            None
1107        }
1108    }
1109
1110    /// Whether the sort is a function with return sort bool
1111    pub fn is_pred(&self) -> bool {
1112        matches!(self, Sort::Func(fsort) if fsort.skip_binders().output().is_bool())
1113    }
1114
1115    /// Returns `true` if the sort is [`Bool`].
1116    ///
1117    /// [`Bool`]: Sort::Bool
1118    #[must_use]
1119    pub fn is_bool(&self) -> bool {
1120        matches!(self, Self::Bool)
1121    }
1122
1123    pub fn cast_kind(self: &Sort, to: &Sort) -> CastKind {
1124        if self == to
1125            || (matches!(self, Sort::Char | Sort::Int) && matches!(to, Sort::Char | Sort::Int))
1126        {
1127            CastKind::Identity
1128        } else if matches!(self, Sort::Bool) && matches!(to, Sort::Int) {
1129            CastKind::BoolToInt
1130        } else if to.is_unit() {
1131            CastKind::IntoUnit
1132        } else {
1133            CastKind::Uninterpreted
1134        }
1135    }
1136
1137    pub fn walk(&self, mut f: impl FnMut(&Sort, &[FieldProj])) {
1138        fn go(sort: &Sort, f: &mut impl FnMut(&Sort, &[FieldProj]), proj: &mut Vec<FieldProj>) {
1139            match sort {
1140                Sort::Tuple(flds) => {
1141                    for (i, sort) in flds.iter().enumerate() {
1142                        proj.push(FieldProj::Tuple { arity: flds.len(), field: i as u32 });
1143                        go(sort, f, proj);
1144                        proj.pop();
1145                    }
1146                }
1147                Sort::App(SortCtor::Adt(sort_def), args) if sort_def.is_struct() => {
1148                    let field_sorts = sort_def.struct_variant().field_sorts(args);
1149                    for (i, sort) in field_sorts.iter().enumerate() {
1150                        proj.push(FieldProj::Adt { def_id: sort_def.did(), field: i as u32 });
1151                        go(sort, f, proj);
1152                        proj.pop();
1153                    }
1154                }
1155                Sort::RawPtr => {
1156                    for field in RawPtrField::iter() {
1157                        let sort = field.sort();
1158                        proj.push(FieldProj::RawPtr { field });
1159                        go(&sort, f, proj);
1160                        proj.pop();
1161                    }
1162                }
1163                _ => {
1164                    f(sort, proj);
1165                }
1166            }
1167        }
1168        go(self, &mut f, &mut vec![]);
1169    }
1170
1171    pub fn is_param(&self) -> bool {
1172        matches!(self, Self::Param(_))
1173    }
1174}
1175
1176/// The size of a [bit-vector]
1177///
1178/// [bit-vector]: Sort::BitVec
1179#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1180pub enum BvSize {
1181    /// A fixed size
1182    Fixed(u32),
1183    /// A size that has been parameterized, e.g., bound under a [`PolyFuncSort`]
1184    Param(ParamSort),
1185    /// A size that needs to be inferred. Used during sort checking to instantiate bit-vector
1186    /// sizes at call-sites.
1187    Infer(BvSizeVid),
1188}
1189
1190impl rustc_errors::IntoDiagArg for Sort {
1191    fn into_diag_arg(self, _path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
1192        rustc_errors::DiagArgValue::Str(Cow::Owned(format!("{self:?}")))
1193    }
1194}
1195
1196impl rustc_errors::IntoDiagArg for FuncSort {
1197    fn into_diag_arg(self, _path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
1198        rustc_errors::DiagArgValue::Str(Cow::Owned(format!("{self:?}")))
1199    }
1200}
1201
1202#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)]
1203pub struct FuncSort {
1204    pub inputs_and_output: List<Sort>,
1205}
1206
1207impl FuncSort {
1208    pub fn new(mut inputs: Vec<Sort>, output: Sort) -> Self {
1209        inputs.push(output);
1210        FuncSort { inputs_and_output: List::from_vec(inputs) }
1211    }
1212
1213    pub fn inputs(&self) -> &[Sort] {
1214        &self.inputs_and_output[0..self.inputs_and_output.len() - 1]
1215    }
1216
1217    pub fn output(&self) -> &Sort {
1218        &self.inputs_and_output[self.inputs_and_output.len() - 1]
1219    }
1220
1221    pub fn to_poly(&self) -> PolyFuncSort {
1222        PolyFuncSort::new(List::empty(), self.clone())
1223    }
1224}
1225
1226/// See [`PolyFuncSort`]
1227#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
1228pub enum SortParamKind {
1229    Sort,
1230    BvSize,
1231}
1232
1233/// A polymorphic function sort parametric over [sorts] or [bit-vector sizes].
1234///
1235/// Parameterizing over bit-vector sizes is a bit of a stretch, because smtlib doesn't support full
1236/// parametric reasoning over them. As long as we used functions parameterized over a size monomorphically
1237/// we should be fine. Right now, we can guarantee this, because size parameters are not exposed in
1238/// the surface syntax and they are only used for predefined (interpreted) theory functions.
1239///
1240/// [sorts]: Sort
1241/// [bit-vector sizes]: BvSize::Param
1242#[derive(Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
1243pub struct PolyFuncSort {
1244    /// The list of parameters including sorts and bit vector sizes
1245    params: List<SortParamKind>,
1246    fsort: FuncSort,
1247}
1248
1249impl PolyFuncSort {
1250    pub fn new(params: List<SortParamKind>, fsort: FuncSort) -> Self {
1251        PolyFuncSort { params, fsort }
1252    }
1253
1254    pub fn skip_binders(&self) -> FuncSort {
1255        self.fsort.clone()
1256    }
1257
1258    pub fn instantiate_identity(&self) -> FuncSort {
1259        self.fsort.clone()
1260    }
1261
1262    pub fn expect_mono(&self) -> FuncSort {
1263        assert!(self.params.is_empty());
1264        self.fsort.clone()
1265    }
1266
1267    pub fn params(&self) -> impl ExactSizeIterator<Item = SortParamKind> + '_ {
1268        self.params.iter().copied()
1269    }
1270
1271    pub fn instantiate(&self, args: &[SortArg]) -> FuncSort {
1272        self.fsort.fold_with(&mut SortSubst::new(args))
1273    }
1274}
1275
1276/// An argument for a generic parameter in a [`Sort`] which can be either a generic sort or a
1277/// generic bit-vector size.
1278#[derive(
1279    Debug, Clone, Eq, PartialEq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
1280)]
1281pub enum SortArg {
1282    Sort(Sort),
1283    BvSize(BvSize),
1284}
1285
1286#[derive(Debug, Clone, Eq, PartialEq, Hash, TyEncodable, TyDecodable)]
1287pub enum ConstantInfo {
1288    /// An uninterpreted constant
1289    Uninterpreted,
1290    /// A non-integral constant whose value is specified by the user
1291    Interpreted(Expr, Sort),
1292}
1293
1294#[derive(Debug, Clone, Eq, PartialEq, Hash, TyEncodable, TyDecodable)]
1295pub struct AdtDef(Interned<AdtDefData>);
1296
1297#[derive(Debug, Eq, PartialEq, Hash, TyEncodable, TyDecodable)]
1298pub struct AdtDefData {
1299    sort_def: AdtSortDef,
1300    opaque: bool,
1301    rustc: ty::AdtDef,
1302}
1303
1304/// Option-like enum to explicitly mark that we don't have information about an ADT because it was
1305/// annotated with `#[flux::opaque]`. Note that only structs can be marked as opaque.
1306#[derive(Clone, Debug, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)]
1307pub enum Opaqueness<T> {
1308    Opaque,
1309    Transparent(T),
1310}
1311
1312impl<T> Opaqueness<T> {
1313    pub fn map<S>(self, f: impl FnOnce(T) -> S) -> Opaqueness<S> {
1314        match self {
1315            Opaqueness::Opaque => Opaqueness::Opaque,
1316            Opaqueness::Transparent(value) => Opaqueness::Transparent(f(value)),
1317        }
1318    }
1319
1320    pub fn as_ref(&self) -> Opaqueness<&T> {
1321        match self {
1322            Opaqueness::Opaque => Opaqueness::Opaque,
1323            Opaqueness::Transparent(value) => Opaqueness::Transparent(value),
1324        }
1325    }
1326
1327    pub fn as_deref(&self) -> Opaqueness<&T::Target>
1328    where
1329        T: std::ops::Deref,
1330    {
1331        match self {
1332            Opaqueness::Opaque => Opaqueness::Opaque,
1333            Opaqueness::Transparent(value) => Opaqueness::Transparent(value.deref()),
1334        }
1335    }
1336
1337    pub fn ok_or_else<E>(self, err: impl FnOnce() -> E) -> Result<T, E> {
1338        match self {
1339            Opaqueness::Transparent(v) => Ok(v),
1340            Opaqueness::Opaque => Err(err()),
1341        }
1342    }
1343
1344    #[track_caller]
1345    pub fn expect(self, msg: &str) -> T {
1346        match self {
1347            Opaqueness::Transparent(val) => val,
1348            Opaqueness::Opaque => bug!("{}", msg),
1349        }
1350    }
1351
1352    pub fn ok_or_query_err(self, struct_id: DefId) -> Result<T, QueryErr> {
1353        self.ok_or_else(|| QueryErr::OpaqueStruct { struct_id })
1354    }
1355}
1356
1357impl<T, E> Opaqueness<Result<T, E>> {
1358    pub fn transpose(self) -> Result<Opaqueness<T>, E> {
1359        match self {
1360            Opaqueness::Transparent(Ok(x)) => Ok(Opaqueness::Transparent(x)),
1361            Opaqueness::Transparent(Err(e)) => Err(e),
1362            Opaqueness::Opaque => Ok(Opaqueness::Opaque),
1363        }
1364    }
1365}
1366
1367pub static INT_TYS: [IntTy; 6] =
1368    [IntTy::Isize, IntTy::I8, IntTy::I16, IntTy::I32, IntTy::I64, IntTy::I128];
1369pub static UINT_TYS: [UintTy; 6] =
1370    [UintTy::Usize, UintTy::U8, UintTy::U16, UintTy::U32, UintTy::U64, UintTy::U128];
1371
1372#[derive(
1373    Debug, Clone, Eq, PartialEq, Hash, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable,
1374)]
1375pub struct Invariant {
1376    // This predicate may have sort variables, but we don't explicitly mark it like in `PolyFuncSort`.
1377    // See comment on `apply` for details.
1378    pred: Binder<Expr>,
1379}
1380
1381impl Invariant {
1382    pub fn new(pred: Binder<Expr>) -> Self {
1383        Self { pred }
1384    }
1385
1386    pub fn apply(&self, idx: &Expr) -> Expr {
1387        // The predicate may have sort variables but we don't explicitly instantiate them. This
1388        // works because within an expression, sort variables can only appear inside the sort
1389        // annotation for a lambda and invariants cannot have lambdas. It remains to instantiate
1390        // variables in the sort of the binder itself, but since we are removing it, we can avoid
1391        // the explicit instantiation. Ultimately, this works because the expression we generate in
1392        // fixpoint doesn't need sort annotations (sorts are re-inferred).
1393        self.pred.replace_bound_reft(idx)
1394    }
1395}
1396
1397pub type PolyVariants = List<Binder<VariantSig>>;
1398pub type PolyVariant = Binder<VariantSig>;
1399
1400#[derive(Clone, Eq, PartialEq, Hash, TyEncodable, TyDecodable)]
1401pub struct VariantSig {
1402    pub adt_def: AdtDef,
1403    pub args: GenericArgs,
1404    pub fields: List<Ty>,
1405    pub idx: Expr,
1406    pub requires: List<Expr>,
1407}
1408
1409pub type PolyFnSig = Binder<FnSig>;
1410
1411#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)]
1412pub struct FnSig {
1413    pub safety: Safety,
1414    pub abi: rustc_abi::ExternAbi,
1415    pub requires: List<Expr>,
1416    pub inputs: List<Ty>,
1417    pub output: Binder<FnOutput>,
1418    pub no_panic: Expr,
1419    /// was this auto-lifted (or from a spec)
1420    pub lifted: bool,
1421}
1422
1423#[derive(
1424    Debug, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
1425)]
1426pub struct FnOutput {
1427    pub ret: Ty,
1428    pub ensures: List<Ensures>,
1429}
1430
1431#[derive(Clone, Eq, PartialEq, Hash, TyEncodable, TyDecodable)]
1432pub enum Ensures {
1433    Type(Path, Ty),
1434    Pred(Expr),
1435}
1436
1437#[derive(Debug, TypeVisitable, TypeFoldable)]
1438pub struct Qualifier {
1439    pub def_id: FluxLocalDefId,
1440    pub body: Binder<Expr>,
1441    pub wildcards: List<bool>,
1442    pub kind: HintKind,
1443}
1444
1445/// Determines which functions a hint to the solver (a qualifier, an axiom or a primop property) is
1446/// used for
1447#[derive(Debug, TypeFoldable, TypeVisitable, Copy, Clone)]
1448pub enum HintKind {
1449    /// Used when checking every function in the crate
1450    Global,
1451    /// Used only when checking functions that name it in `#[qualifiers(...)]` / `#[axioms(...)]`
1452    Local,
1453    /// Used only when checking the item enclosing its declaration (e.g., a qualifier declared
1454    /// with `invariant qualifier`)
1455    Enclosing,
1456}
1457
1458/// A `PrimOpProp` is a single property for a primitive operation which
1459/// can be conjoined to get the definition of the [`PrimRel`] for that
1460/// primitive operation.
1461#[derive(Debug, TypeVisitable, TypeFoldable)]
1462pub struct PrimOpProp {
1463    pub def_id: FluxLocalDefId,
1464    pub kind: HintKind,
1465    pub op: BinOp,
1466    pub body: Binder<Expr>,
1467}
1468
1469/// An `Axiom` is a (global) fact, typically about uninterpreted functions, that is assumed to
1470/// hold for all values of the variables bound in `body`.
1471#[derive(TypeVisitable, TypeFoldable)]
1472pub struct Axiom {
1473    pub def_id: FluxLocalDefId,
1474    pub body: Binder<AxiomBody>,
1475    pub kind: HintKind,
1476}
1477
1478/// The variable (by its position in the axiom's binder) that does not occur in any pattern of an
1479/// ill-formed axiom. See [`Axiom::new`].
1480#[derive(Debug, Clone, Copy)]
1481pub struct UncoveredAxiomVar(pub BoundVar);
1482
1483#[derive(Debug, TypeVisitable, TypeFoldable)]
1484pub struct AxiomBody {
1485    pub expr: Expr,
1486    /// The terms used as the pattern (trigger) to instantiate the axiom: *each* application of an
1487    /// uninterpreted function occurring in `expr`. See [`Axiom::new`].
1488    pub patterns: List<Expr>,
1489}
1490
1491impl Axiom {
1492    /// Creates an axiom, computing its patterns from `body`, which must have already been
1493    /// [reduced] so that the applications are the ones that will be sent to the solver.
1494    ///
1495    /// A function is considered uninterpreted if it has no body or if it is hidden. We also
1496    /// include the arithmetic and bitwise operations that can be encoded as UIFs (e.g.,
1497    /// `[&](x, y)` on `int`, or `x * y` under `uif_ops`), the casts that have no interpretation,
1498    /// and associated refinements. (Whether a hidden function is revealed, or an operation is
1499    /// uninterpreted, depends on the item being checked, so those are *candidates* that are
1500    /// filtered when encoding the axiom.) Applications mentioning variables bound *inside* the body (by
1501    /// a `let` or a quantifier) are skipped as they are not valid outside of their binder.
1502    ///
1503    /// [reduced]: fold::TypeFoldable::reduce
1504    ///
1505    /// Fails if some variable bound by the axiom does not occur in any of the patterns, as the
1506    /// axiom could then never be instantiated.
1507    pub fn new(
1508        genv: GlobalEnv,
1509        def_id: FluxLocalDefId,
1510        kind: HintKind,
1511        body: Binder<Expr>,
1512    ) -> Result<Self, UncoveredAxiomVar> {
1513        use fold::{TypeSuperVisitable as _, TypeVisitable as _};
1514
1515        struct Collector<'genv, 'tcx> {
1516            genv: GlobalEnv<'genv, 'tcx>,
1517            /// Number of binders we are currently under
1518            depth: usize,
1519            /// Total number of binders entered so far
1520            binders: usize,
1521            patterns: Vec<Expr>,
1522        }
1523
1524        impl Collector<'_, '_> {
1525            fn is_uif_app(&self, expr: &Expr) -> bool {
1526                match expr.kind() {
1527                    ExprKind::App(func, sort_args, _) => {
1528                        match func.kind() {
1529                            ExprKind::GlobalFunc(SpecFuncKind::Def(did)) => {
1530                                matches!(
1531                                    self.genv.spec_func(*did),
1532                                    SpecFunc::Uif | SpecFunc::Defined { hide: true, .. }
1533                                )
1534                            }
1535                            ExprKind::InternalFunc(InternalFuncKind::Cast) => {
1536                                matches!(
1537                                    &sort_args[..],
1538                                    [SortArg::Sort(from), SortArg::Sort(to)]
1539                                        if matches!(from.cast_kind(to), CastKind::Uninterpreted)
1540                                )
1541                            }
1542                            _ => false,
1543                        }
1544                    }
1545                    // An operation that *may* be encoded as a UIF, e.g., `[&](x, y)` or `x * y`
1546                    ExprKind::BinaryOp(op, ..) => op.uif_sort().is_some(),
1547                    ExprKind::Alias(..) => true,
1548                    _ => false,
1549                }
1550            }
1551        }
1552
1553        impl fold::TypeVisitor for Collector<'_, '_> {
1554            fn enter_binder(&mut self, _vars: &BoundVariableKinds) {
1555                self.depth += 1;
1556                self.binders += 1;
1557            }
1558
1559            fn exit_binder(&mut self) {
1560                self.depth -= 1;
1561            }
1562
1563            fn visit_expr(&mut self, expr: &Expr) -> std::ops::ControlFlow<!> {
1564                let binders = self.binders;
1565                expr.super_visit_with(self)?;
1566                // Skip applications under a binder or containing one
1567                if self.depth == 0 && self.binders == binders && self.is_uif_app(expr) {
1568                    let expr = expr.erase_spans();
1569                    if !self.patterns.contains(&expr) {
1570                        self.patterns.push(expr);
1571                    }
1572                }
1573                std::ops::ControlFlow::Continue(())
1574            }
1575        }
1576
1577        /// Marks the variables of the axiom's binder that occur in a pattern. Patterns never
1578        /// contain binders, so the axiom's variables are exactly those at [`INNERMOST`].
1579        struct CoverChecker(Vec<bool>);
1580
1581        impl fold::TypeVisitor for CoverChecker {
1582            fn visit_expr(&mut self, expr: &Expr) -> std::ops::ControlFlow<!> {
1583                if let ExprKind::Var(Var::Bound(INNERMOST, BoundReft { var, .. })) = expr.kind() {
1584                    self.0[var.as_usize()] = true;
1585                }
1586                expr.super_visit_with(self)
1587            }
1588        }
1589
1590        let mut collector = Collector { genv, depth: 0, binders: 0, patterns: vec![] };
1591        let _ = body.skip_binder_ref().visit_with(&mut collector);
1592
1593        // Every variable of the axiom must occur in some pattern, otherwise the solver
1594        // cannot instantiate it.
1595        let mut checker = CoverChecker(vec![false; body.vars().len()]);
1596        let _ = collector.patterns.visit_with(&mut checker);
1597        if let Some(idx) = checker.0.iter().position(|covered| !covered) {
1598            return Err(UncoveredAxiomVar(BoundVar::from_usize(idx)));
1599        }
1600
1601        let patterns = List::from_vec(collector.patterns);
1602        let body = body.map(|expr| AxiomBody { expr, patterns });
1603        Ok(Axiom { def_id, body, kind })
1604    }
1605}
1606
1607/// All the properties of a primitive operation. The properties that apply to a function are
1608/// conjoined to get the definition of the primitive relation for that operation; see
1609/// [`crate::global_env::GlobalEnv::prim_rel_for`].
1610#[derive(Debug)]
1611pub struct PrimRel {
1612    pub props: Vec<PrimOpProp>,
1613}
1614
1615pub type TyCtor = Binder<Ty>;
1616
1617impl TyCtor {
1618    pub fn to_ty(&self) -> Ty {
1619        match &self.vars()[..] {
1620            [] => {
1621                return self.skip_binder_ref().shift_out_escaping(1);
1622            }
1623            [BoundVariableKind::Refine(sort, ..)] => {
1624                if sort.is_unit() {
1625                    return self.replace_bound_reft(&Expr::unit());
1626                }
1627                if let Some(def_id) = sort.is_unit_adt() {
1628                    return self.replace_bound_reft(&Expr::unit_struct(def_id));
1629                }
1630            }
1631            _ => {}
1632        }
1633        Ty::exists(self.clone())
1634    }
1635}
1636
1637#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1638pub struct Ty(Interned<TyKind>);
1639
1640impl Ty {
1641    pub fn kind(&self) -> &TyKind {
1642        &self.0
1643    }
1644
1645    /// Dummy type used for the `Self` of a `TraitRef` created when converting a trait object, and
1646    /// which gets removed in `ExistentialTraitRef`. This type must not appear anywhere in other
1647    /// converted types and must be a valid `rustc` type (i.e., we must be able to call `to_rustc`
1648    /// on it). `TyKind::Infer(TyVid(0))` does the job, with the caveat that we must skip 0 when
1649    /// generating `TyKind::Infer` for "type holes".
1650    pub fn trait_object_dummy_self() -> Ty {
1651        Ty::infer(TyVid::from_u32(0))
1652    }
1653
1654    pub fn dynamic(preds: impl Into<List<Binder<ExistentialPredicate>>>, region: Region) -> Ty {
1655        BaseTy::Dynamic(preds.into(), region).to_ty()
1656    }
1657
1658    pub fn strg_ref(re: Region, path: Path, ty: Ty) -> Ty {
1659        TyKind::StrgRef(re, path, ty).intern()
1660    }
1661
1662    pub fn ptr(pk: impl Into<PtrKind>, path: impl Into<Path>) -> Ty {
1663        TyKind::Ptr(pk.into(), path.into()).intern()
1664    }
1665
1666    pub fn constr(p: impl Into<Expr>, ty: Ty) -> Ty {
1667        TyKind::Constr(p.into(), ty).intern()
1668    }
1669
1670    pub fn uninit() -> Ty {
1671        TyKind::Uninit.intern()
1672    }
1673
1674    pub fn indexed(bty: BaseTy, idx: impl Into<Expr>) -> Ty {
1675        TyKind::Indexed(bty, idx.into()).intern()
1676    }
1677
1678    pub fn exists(ty: Binder<Ty>) -> Ty {
1679        TyKind::Exists(ty).intern()
1680    }
1681
1682    pub fn exists_with_constr(bty: BaseTy, pred: Expr) -> Ty {
1683        let sort = bty.sort();
1684        let ty = Ty::indexed(bty, Expr::nu());
1685        Ty::exists(Binder::bind_with_sort(Ty::constr(pred, ty), sort))
1686    }
1687
1688    pub fn discr(adt_def: AdtDef, place: Place) -> Ty {
1689        TyKind::Discr(adt_def, place).intern()
1690    }
1691
1692    pub fn unit() -> Ty {
1693        Ty::tuple(vec![])
1694    }
1695
1696    pub fn bool() -> Ty {
1697        BaseTy::Bool.to_ty()
1698    }
1699
1700    pub fn int(int_ty: IntTy) -> Ty {
1701        BaseTy::Int(int_ty).to_ty()
1702    }
1703
1704    pub fn uint(uint_ty: UintTy) -> Ty {
1705        BaseTy::Uint(uint_ty).to_ty()
1706    }
1707
1708    pub fn param(param_ty: ParamTy) -> Ty {
1709        TyKind::Param(param_ty).intern()
1710    }
1711
1712    pub fn downcast(
1713        adt: AdtDef,
1714        args: GenericArgs,
1715        ty: Ty,
1716        variant: VariantIdx,
1717        fields: List<Ty>,
1718    ) -> Ty {
1719        TyKind::Downcast(adt, args, ty, variant, fields).intern()
1720    }
1721
1722    pub fn blocked(ty: Ty) -> Ty {
1723        TyKind::Blocked(ty).intern()
1724    }
1725
1726    pub fn str() -> Ty {
1727        BaseTy::Str.to_ty()
1728    }
1729
1730    pub fn char() -> Ty {
1731        BaseTy::Char.to_ty()
1732    }
1733
1734    pub fn float(float_ty: FloatTy) -> Ty {
1735        BaseTy::Float(float_ty).to_ty()
1736    }
1737
1738    pub fn mk_ref(region: Region, ty: Ty, mutbl: Mutability) -> Ty {
1739        BaseTy::Ref(region, ty, mutbl).to_ty()
1740    }
1741
1742    pub fn mk_slice(ty: Ty) -> Ty {
1743        BaseTy::Slice(ty).to_ty()
1744    }
1745
1746    pub fn mk_box(genv: GlobalEnv, deref_ty: Ty, alloc_ty: GenericArg) -> QueryResult<Ty> {
1747        let def_id = genv.tcx().require_lang_item(LangItem::OwnedBox, DUMMY_SP);
1748        let adt_def = genv.adt_def(def_id)?;
1749
1750        let args = List::from_arr([GenericArg::Ty(deref_ty), alloc_ty]);
1751
1752        let bty = BaseTy::adt(adt_def, args);
1753        Ok(Ty::indexed(bty, Expr::unit_struct(def_id)))
1754    }
1755    pub fn tuple(tys: impl Into<List<Ty>>) -> Ty {
1756        BaseTy::Tuple(tys.into()).to_ty()
1757    }
1758
1759    pub fn array(ty: Ty, c: Const) -> Ty {
1760        BaseTy::Array(ty, c).to_ty()
1761    }
1762
1763    pub fn closure(
1764        did: DefId,
1765        tys: impl Into<List<Ty>>,
1766        args: &flux_rustc_bridge::ty::GenericArgs,
1767        no_panic: bool,
1768    ) -> Ty {
1769        BaseTy::Closure(did, tys.into(), args.clone(), no_panic).to_ty()
1770    }
1771
1772    pub fn coroutine(
1773        did: DefId,
1774        resume_ty: Ty,
1775        upvar_tys: List<Ty>,
1776        args: flux_rustc_bridge::ty::GenericArgs,
1777    ) -> Ty {
1778        BaseTy::Coroutine(did, resume_ty, upvar_tys, args.clone()).to_ty()
1779    }
1780
1781    pub fn never() -> Ty {
1782        BaseTy::Never.to_ty()
1783    }
1784
1785    pub fn infer(vid: TyVid) -> Ty {
1786        TyKind::Infer(vid).intern()
1787    }
1788
1789    pub fn unconstr(&self) -> (Ty, Expr) {
1790        fn go(this: &Ty, preds: &mut Vec<Expr>) -> Ty {
1791            if let TyKind::Constr(pred, ty) = this.kind() {
1792                preds.push(pred.clone());
1793                go(ty, preds)
1794            } else {
1795                this.clone()
1796            }
1797        }
1798        let mut preds = vec![];
1799        (go(self, &mut preds), Expr::and_from_iter(preds))
1800    }
1801
1802    pub fn unblocked(&self) -> Ty {
1803        match self.kind() {
1804            TyKind::Blocked(ty) => ty.clone(),
1805            _ => self.clone(),
1806        }
1807    }
1808
1809    /// Whether the type is an `int` or a `uint`
1810    pub fn is_integral(&self) -> bool {
1811        self.as_bty_skipping_existentials()
1812            .map(BaseTy::is_integral)
1813            .unwrap_or_default()
1814    }
1815
1816    /// Whether the type is a `bool`
1817    pub fn is_bool(&self) -> bool {
1818        self.as_bty_skipping_existentials()
1819            .map(BaseTy::is_bool)
1820            .unwrap_or_default()
1821    }
1822
1823    /// Whether the type is a `char`
1824    pub fn is_char(&self) -> bool {
1825        self.as_bty_skipping_existentials()
1826            .map(BaseTy::is_char)
1827            .unwrap_or_default()
1828    }
1829
1830    pub fn is_uninit(&self) -> bool {
1831        matches!(self.kind(), TyKind::Uninit)
1832    }
1833
1834    pub fn is_box(&self) -> bool {
1835        self.as_bty_skipping_existentials()
1836            .map(BaseTy::is_box)
1837            .unwrap_or_default()
1838    }
1839
1840    pub fn is_struct(&self) -> bool {
1841        self.as_bty_skipping_existentials()
1842            .map(BaseTy::is_struct)
1843            .unwrap_or_default()
1844    }
1845
1846    pub fn is_raw_ptr(&self) -> bool {
1847        self.as_bty_skipping_existentials()
1848            .map(BaseTy::is_raw_ptr)
1849            .unwrap_or_default()
1850    }
1851
1852    pub fn is_array(&self) -> bool {
1853        self.as_bty_skipping_existentials()
1854            .map(BaseTy::is_array)
1855            .unwrap_or_default()
1856    }
1857
1858    pub fn is_slice(&self) -> bool {
1859        self.as_bty_skipping_existentials()
1860            .map(BaseTy::is_slice)
1861            .unwrap_or_default()
1862    }
1863
1864    pub fn as_bty_skipping_existentials(&self) -> Option<&BaseTy> {
1865        match self.kind() {
1866            TyKind::Indexed(bty, _) => Some(bty),
1867            TyKind::Exists(ty) => Some(ty.skip_binder_ref().as_bty_skipping_existentials()?),
1868            TyKind::Constr(_, ty) => ty.as_bty_skipping_existentials(),
1869            _ => None,
1870        }
1871    }
1872
1873    #[track_caller]
1874    pub fn expect_discr(&self) -> (&AdtDef, &Place) {
1875        if let TyKind::Discr(adt_def, place) = self.kind() {
1876            (adt_def, place)
1877        } else {
1878            tracked_span_bug!("expected discr")
1879        }
1880    }
1881
1882    #[track_caller]
1883    pub fn expect_adt(&self) -> (&AdtDef, &[GenericArg], &Expr) {
1884        if let TyKind::Indexed(BaseTy::Adt(adt_def, args), idx) = self.kind() {
1885            (adt_def, args, idx)
1886        } else {
1887            tracked_span_bug!("expected adt `{self:?}`")
1888        }
1889    }
1890
1891    #[track_caller]
1892    pub fn expect_tuple(&self) -> &[Ty] {
1893        if let TyKind::Indexed(BaseTy::Tuple(tys), _) = self.kind() {
1894            tys
1895        } else {
1896            tracked_span_bug!("expected tuple found `{self:?}` (kind: `{:?}`)", self.kind())
1897        }
1898    }
1899
1900    pub fn simplify_type(&self) -> Option<SimplifiedType> {
1901        self.as_bty_skipping_existentials()
1902            .and_then(BaseTy::simplify_type)
1903    }
1904}
1905
1906impl<'tcx> ToRustc<'tcx> for Ty {
1907    type T = rustc_middle::ty::Ty<'tcx>;
1908
1909    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
1910        match self.kind() {
1911            TyKind::Indexed(bty, _) => bty.to_rustc(tcx),
1912            TyKind::Exists(ty) => ty.skip_binder_ref().to_rustc(tcx),
1913            TyKind::Constr(_, ty) => ty.to_rustc(tcx),
1914            TyKind::Param(pty) => pty.to_ty(tcx),
1915            TyKind::StrgRef(re, _, ty) => {
1916                rustc_middle::ty::Ty::new_ref(
1917                    tcx,
1918                    re.to_rustc(tcx),
1919                    ty.to_rustc(tcx),
1920                    Mutability::Mut,
1921                )
1922            }
1923            TyKind::Infer(vid) => rustc_middle::ty::Ty::new_var(tcx, *vid),
1924            TyKind::Uninit
1925            | TyKind::Ptr(_, _)
1926            | TyKind::Discr(..)
1927            | TyKind::Downcast(..)
1928            | TyKind::Blocked(_) => bug!("TODO: to_rustc for `{self:?}`"),
1929        }
1930    }
1931}
1932
1933#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug)]
1934pub enum TyKind {
1935    Indexed(BaseTy, Expr),
1936    Exists(Binder<Ty>),
1937    Constr(Expr, Ty),
1938    Uninit,
1939    StrgRef(Region, Path, Ty),
1940    Ptr(PtrKind, Path),
1941    /// This is a bit of a hack. We use this type internally to represent the result of
1942    /// [`Rvalue::Discriminant`] in a way that we can recover the necessary control information
1943    /// when checking a [`match`]. The hack is that we assume the dicriminant remains the same from
1944    /// the creation of this type until we use it in a [`match`].
1945    ///
1946    ///
1947    /// [`Rvalue::Discriminant`]: flux_rustc_bridge::mir::Rvalue::Discriminant
1948    /// [`match`]: flux_rustc_bridge::mir::TerminatorKind::SwitchInt
1949    Discr(AdtDef, Place),
1950    Param(ParamTy),
1951    /// These only arise when you "narrow" an ADT down to a particular variant;
1952    /// either EXPLICITLY in a `match-of`, or IMPLICITLY when you access a field
1953    /// of a struct to "UNPACK" the struct.
1954    Downcast(AdtDef, GenericArgs, Ty, VariantIdx, List<Ty>),
1955    Blocked(Ty),
1956    /// A type that needs to be inferred by matching the signature against a rust signature.
1957    /// [`TyKind::Infer`] appear as an intermediate step during `conv` and should not be present in
1958    /// the final signature.
1959    Infer(TyVid),
1960}
1961
1962#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1963pub enum PtrKind {
1964    Mut(Region),
1965    Box,
1966}
1967
1968#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
1969pub enum BaseTy {
1970    Int(IntTy),
1971    Uint(UintTy),
1972    Bool,
1973    Str,
1974    Char,
1975    Slice(Ty),
1976    Adt(AdtDef, GenericArgs),
1977    Float(FloatTy),
1978    RawPtr(Ty, Mutability),
1979    RawPtrMetadata(Ty),
1980    Ref(Region, Ty, Mutability),
1981    FnPtr(PolyFnSig),
1982    FnDef(DefId, GenericArgs),
1983    Tuple(List<Ty>),
1984    Alias(AliasTy),
1985    Array(Ty, Const),
1986    Never,
1987    Closure(DefId, /* upvar_tys */ List<Ty>, flux_rustc_bridge::ty::GenericArgs, bool),
1988    Coroutine(
1989        DefId,
1990        /*resume_ty: */ Ty,
1991        /* upvar_tys: */ List<Ty>,
1992        flux_rustc_bridge::ty::GenericArgs,
1993    ),
1994    Dynamic(List<Binder<ExistentialPredicate>>, Region),
1995    Param(ParamTy),
1996    Infer(TyVid),
1997    Foreign(DefId),
1998    Pat,
1999}
2000
2001impl BaseTy {
2002    pub fn adt(adt_def: AdtDef, args: GenericArgs) -> BaseTy {
2003        BaseTy::Adt(adt_def, args)
2004    }
2005
2006    pub fn fn_def(def_id: DefId, args: impl Into<GenericArgs>) -> BaseTy {
2007        BaseTy::FnDef(def_id, args.into())
2008    }
2009
2010    pub fn from_primitive_str(s: &str) -> Option<BaseTy> {
2011        match s {
2012            "i8" => Some(BaseTy::Int(IntTy::I8)),
2013            "i16" => Some(BaseTy::Int(IntTy::I16)),
2014            "i32" => Some(BaseTy::Int(IntTy::I32)),
2015            "i64" => Some(BaseTy::Int(IntTy::I64)),
2016            "i128" => Some(BaseTy::Int(IntTy::I128)),
2017            "u8" => Some(BaseTy::Uint(UintTy::U8)),
2018            "u16" => Some(BaseTy::Uint(UintTy::U16)),
2019            "u32" => Some(BaseTy::Uint(UintTy::U32)),
2020            "u64" => Some(BaseTy::Uint(UintTy::U64)),
2021            "u128" => Some(BaseTy::Uint(UintTy::U128)),
2022            "f16" => Some(BaseTy::Float(FloatTy::F16)),
2023            "f32" => Some(BaseTy::Float(FloatTy::F32)),
2024            "f64" => Some(BaseTy::Float(FloatTy::F64)),
2025            "f128" => Some(BaseTy::Float(FloatTy::F128)),
2026            "isize" => Some(BaseTy::Int(IntTy::Isize)),
2027            "usize" => Some(BaseTy::Uint(UintTy::Usize)),
2028            "bool" => Some(BaseTy::Bool),
2029            "char" => Some(BaseTy::Char),
2030            "str" => Some(BaseTy::Str),
2031            _ => None,
2032        }
2033    }
2034
2035    /// If `self` is a primitive, return its [`Symbol`].
2036    pub fn primitive_symbol(&self) -> Option<Symbol> {
2037        match self {
2038            BaseTy::Bool => Some(sym::bool),
2039            BaseTy::Char => Some(sym::char),
2040            BaseTy::Float(f) => {
2041                match f {
2042                    FloatTy::F16 => Some(sym::f16),
2043                    FloatTy::F32 => Some(sym::f32),
2044                    FloatTy::F64 => Some(sym::f64),
2045                    FloatTy::F128 => Some(sym::f128),
2046                }
2047            }
2048            BaseTy::Int(f) => {
2049                match f {
2050                    IntTy::Isize => Some(sym::isize),
2051                    IntTy::I8 => Some(sym::i8),
2052                    IntTy::I16 => Some(sym::i16),
2053                    IntTy::I32 => Some(sym::i32),
2054                    IntTy::I64 => Some(sym::i64),
2055                    IntTy::I128 => Some(sym::i128),
2056                }
2057            }
2058            BaseTy::Uint(f) => {
2059                match f {
2060                    UintTy::Usize => Some(sym::usize),
2061                    UintTy::U8 => Some(sym::u8),
2062                    UintTy::U16 => Some(sym::u16),
2063                    UintTy::U32 => Some(sym::u32),
2064                    UintTy::U64 => Some(sym::u64),
2065                    UintTy::U128 => Some(sym::u128),
2066                }
2067            }
2068            BaseTy::Str => Some(sym::str),
2069            _ => None,
2070        }
2071    }
2072
2073    pub fn is_integral(&self) -> bool {
2074        matches!(self, BaseTy::Int(_) | BaseTy::Uint(_))
2075    }
2076
2077    pub fn is_signed(&self) -> bool {
2078        matches!(self, BaseTy::Int(_))
2079    }
2080
2081    pub fn is_unsigned(&self) -> bool {
2082        matches!(self, BaseTy::Uint(_))
2083    }
2084
2085    pub fn is_float(&self) -> bool {
2086        matches!(self, BaseTy::Float(_))
2087    }
2088
2089    pub fn is_bool(&self) -> bool {
2090        matches!(self, BaseTy::Bool)
2091    }
2092
2093    fn is_struct(&self) -> bool {
2094        matches!(self, BaseTy::Adt(adt_def, _) if adt_def.is_struct())
2095    }
2096
2097    fn is_array(&self) -> bool {
2098        matches!(self, BaseTy::Array(..))
2099    }
2100
2101    fn is_slice(&self) -> bool {
2102        matches!(self, BaseTy::Slice(..))
2103    }
2104
2105    pub fn is_box(&self) -> bool {
2106        matches!(self, BaseTy::Adt(adt_def, _) if adt_def.is_box())
2107    }
2108
2109    pub fn is_char(&self) -> bool {
2110        matches!(self, BaseTy::Char)
2111    }
2112
2113    pub fn is_str(&self) -> bool {
2114        matches!(self, BaseTy::Str)
2115    }
2116
2117    pub fn is_raw_ptr(&self) -> bool {
2118        matches!(self, BaseTy::RawPtr(..))
2119    }
2120
2121    pub fn invariants(
2122        &self,
2123        genv: GlobalEnv,
2124        overflow_mode: OverflowMode,
2125    ) -> std::vec::IntoIter<Invariant> {
2126        match self {
2127            BaseTy::Adt(adt_def, args) => {
2128                genv.invariants_of(adt_def.did())
2129                    .as_deref()
2130                    .iter_identity()
2131                    .map(|inv| EarlyBinder(inv).instantiate_ref(genv.tcx(), args, &[]))
2132                    .collect()
2133            }
2134            BaseTy::Uint(uint_ty) => uint_invariants(*uint_ty, overflow_mode).to_vec(),
2135            BaseTy::Int(int_ty) => int_invariants(*int_ty, overflow_mode).to_vec(),
2136            BaseTy::Char => char_invariants().to_vec(),
2137            BaseTy::Slice(ty) => slice_invariants(genv, ty, overflow_mode),
2138            BaseTy::RawPtr(..) => raw_ptr_invariants().to_vec(),
2139            _ => vec![],
2140        }
2141        .into_iter()
2142    }
2143
2144    pub fn to_ty(&self) -> Ty {
2145        let sort = self.sort();
2146        if sort.is_unit() {
2147            Ty::indexed(self.clone(), Expr::unit())
2148        } else {
2149            Ty::exists(Binder::bind_with_sort(
2150                Ty::indexed(self.shift_in_escaping(1), Expr::nu()),
2151                sort,
2152            ))
2153        }
2154    }
2155
2156    pub fn to_subset_ty_ctor(&self) -> SubsetTyCtor {
2157        let sort = self.sort();
2158        Binder::bind_with_sort(SubsetTy::trivial(self.clone(), Expr::nu()), sort)
2159    }
2160
2161    #[track_caller]
2162    pub fn expect_adt(&self) -> (&AdtDef, &[GenericArg]) {
2163        if let BaseTy::Adt(adt_def, args) = self {
2164            (adt_def, args)
2165        } else {
2166            tracked_span_bug!("expected adt `{self:?}`")
2167        }
2168    }
2169
2170    /// A type is an *atom* if it is "self-delimiting", i.e., it has a clear boundary
2171    /// when printed. This is used to avoid unnecessary parenthesis when pretty printing.
2172    pub fn is_atom(&self) -> bool {
2173        // (nilehmann) I'm not sure about this list, please adjust if you get any odd behavior
2174        matches!(
2175            self,
2176            BaseTy::Int(_)
2177                | BaseTy::Uint(_)
2178                | BaseTy::Slice(_)
2179                | BaseTy::Bool
2180                | BaseTy::Char
2181                | BaseTy::Str
2182                | BaseTy::Adt(..)
2183                | BaseTy::Tuple(..)
2184                | BaseTy::Param(_)
2185                | BaseTy::Array(..)
2186                | BaseTy::Never
2187                | BaseTy::Closure(..)
2188                | BaseTy::Coroutine(..)
2189                // opaque alias are atoms the way we print them now, but they won't
2190                // be if we print them as `impl Trait`
2191                | BaseTy::Alias(..)
2192        )
2193    }
2194
2195    /// Similar to [`rustc_infer::infer::canonical::ir::fast_reject::simplify_type`].
2196    ///
2197    /// This implementation is currently incomplete, so it should only be used in contexts
2198    /// where completeness is not required. Currently, it's used to find incoherent
2199    /// implementations when resolving associated constants. In this context, incompleteness
2200    /// is acceptable since the worst case outcome is simply failing to resolve a type-relative
2201    /// constant.
2202    fn simplify_type(&self) -> Option<SimplifiedType> {
2203        match self {
2204            BaseTy::Bool => Some(SimplifiedType::Bool),
2205            BaseTy::Char => Some(SimplifiedType::Char),
2206            BaseTy::Int(int_type) => Some(SimplifiedType::Int(*int_type)),
2207            BaseTy::Uint(uint_type) => Some(SimplifiedType::Uint(*uint_type)),
2208            BaseTy::Float(float_type) => Some(SimplifiedType::Float(*float_type)),
2209            BaseTy::Adt(def, _) => Some(SimplifiedType::Adt(def.did())),
2210            BaseTy::Str => Some(SimplifiedType::Str),
2211            BaseTy::Array(..) => Some(SimplifiedType::Array),
2212            BaseTy::Slice(..) => Some(SimplifiedType::Slice),
2213            BaseTy::RawPtr(_, mutbl) => Some(SimplifiedType::Ptr(*mutbl)),
2214            BaseTy::Ref(_, _, mutbl) => Some(SimplifiedType::Ref(*mutbl)),
2215            BaseTy::FnDef(def_id, _) | BaseTy::Closure(def_id, ..) => {
2216                Some(SimplifiedType::Closure(*def_id))
2217            }
2218            BaseTy::Coroutine(def_id, ..) => Some(SimplifiedType::Coroutine(*def_id)),
2219            BaseTy::Never => Some(SimplifiedType::Never),
2220            BaseTy::Tuple(tys) => Some(SimplifiedType::Tuple(tys.len())),
2221            BaseTy::FnPtr(poly_fn_sig) => {
2222                Some(SimplifiedType::Function(poly_fn_sig.skip_binder_ref().inputs().len()))
2223            }
2224            BaseTy::Foreign(def_id) => Some(SimplifiedType::Foreign(*def_id)),
2225            BaseTy::RawPtrMetadata(_)
2226            | BaseTy::Alias(..)
2227            | BaseTy::Param(_)
2228            | BaseTy::Dynamic(..)
2229            | BaseTy::Infer(_) => None,
2230            BaseTy::Pat => todo!(),
2231        }
2232    }
2233}
2234
2235impl<'tcx> ToRustc<'tcx> for BaseTy {
2236    type T = rustc_middle::ty::Ty<'tcx>;
2237
2238    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
2239        use rustc_middle::ty;
2240        match self {
2241            BaseTy::Int(i) => ty::Ty::new_int(tcx, *i),
2242            BaseTy::Uint(i) => ty::Ty::new_uint(tcx, *i),
2243            BaseTy::Param(pty) => pty.to_ty(tcx),
2244            BaseTy::Slice(ty) => ty::Ty::new_slice(tcx, ty.to_rustc(tcx)),
2245            BaseTy::Bool => tcx.types.bool,
2246            BaseTy::Char => tcx.types.char,
2247            BaseTy::Str => tcx.types.str_,
2248            BaseTy::Adt(adt_def, args) => {
2249                let did = adt_def.did();
2250                let adt_def = tcx.adt_def(did);
2251                let args = args.to_rustc(tcx);
2252                ty::Ty::new_adt(tcx, adt_def, args)
2253            }
2254            BaseTy::FnDef(def_id, args) => {
2255                let args = args.to_rustc(tcx);
2256                tcx.type_of(*def_id).instantiate(tcx, args).skip_norm_wip()
2257            }
2258            BaseTy::Float(f) => ty::Ty::new_float(tcx, *f),
2259            BaseTy::RawPtr(ty, mutbl) => ty::Ty::new_ptr(tcx, ty.to_rustc(tcx), *mutbl),
2260            BaseTy::Ref(re, ty, mutbl) => {
2261                ty::Ty::new_ref(tcx, re.to_rustc(tcx), ty.to_rustc(tcx), *mutbl)
2262            }
2263            BaseTy::FnPtr(poly_sig) => ty::Ty::new_fn_ptr(tcx, poly_sig.to_rustc(tcx)),
2264            BaseTy::Tuple(tys) => {
2265                let ts = tys.iter().map(|ty| ty.to_rustc(tcx)).collect_vec();
2266                ty::Ty::new_tup(tcx, &ts)
2267            }
2268            BaseTy::Alias(alias_ty) => {
2269                ty::Ty::new_alias(tcx, ty::IsRigid::No, alias_ty.to_rustc(tcx))
2270            }
2271            BaseTy::Array(ty, n) => {
2272                let ty = ty.to_rustc(tcx);
2273                let n = n.to_rustc(tcx);
2274                ty::Ty::new_array_with_const_len(tcx, ty, n)
2275            }
2276            BaseTy::Never => tcx.types.never,
2277            BaseTy::Closure(did, _, args, _) => ty::Ty::new_closure(tcx, *did, args.to_rustc(tcx)),
2278            BaseTy::Dynamic(exi_preds, re) => {
2279                let preds: Vec<_> = exi_preds
2280                    .iter()
2281                    .map(|pred| pred.to_rustc(tcx))
2282                    .collect_vec();
2283                let preds = tcx.mk_poly_existential_predicates(&preds);
2284                ty::Ty::new_dynamic(tcx, preds, re.to_rustc(tcx))
2285            }
2286            BaseTy::Coroutine(did, _, _, args) => {
2287                ty::Ty::new_coroutine(tcx, *did, args.to_rustc(tcx))
2288            }
2289            BaseTy::Infer(ty_vid) => ty::Ty::new_var(tcx, *ty_vid),
2290            BaseTy::Foreign(def_id) => ty::Ty::new_foreign(tcx, *def_id),
2291            BaseTy::RawPtrMetadata(ty) => {
2292                ty::Ty::new_ptr(
2293                    tcx,
2294                    ty.to_rustc(tcx),
2295                    RawPtrKind::FakeForPtrMetadata.to_mutbl_lossy(),
2296                )
2297            }
2298            BaseTy::Pat => todo!(),
2299        }
2300    }
2301}
2302
2303#[derive(
2304    Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
2305)]
2306pub struct AliasTy {
2307    pub kind: AliasKind,
2308    pub args: GenericArgs,
2309    /// Holds the refinement-arguments for opaque-types; empty for projections
2310    pub refine_args: RefineArgs,
2311}
2312
2313impl AliasTy {
2314    pub fn new(kind: AliasKind, args: GenericArgs, refine_args: RefineArgs) -> Self {
2315        AliasTy { kind, args, refine_args }
2316    }
2317
2318    pub fn to_alias_term(&self) -> AliasTerm {
2319        let kind = match self.kind {
2320            AliasKind::Projection { def_id } => AliasTermKind::ProjectionTy { def_id },
2321            AliasKind::Opaque { def_id } => AliasTermKind::OpaqueTy { def_id },
2322            AliasKind::Free { def_id } => AliasTermKind::FreeTy { def_id },
2323        };
2324        AliasTerm::new(kind, self.args.clone())
2325    }
2326}
2327
2328/// Mirrors [`flux_rustc_bridge::ty::AliasTerm`].
2329#[derive(
2330    Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable,
2331)]
2332pub struct AliasTerm {
2333    pub kind: AliasTermKind,
2334    pub args: GenericArgs,
2335}
2336
2337impl AliasTerm {
2338    pub fn new(kind: AliasTermKind, args: GenericArgs) -> Self {
2339        AliasTerm { kind, args }
2340    }
2341
2342    pub fn def_id(&self) -> DefId {
2343        self.kind.def_id()
2344    }
2345
2346    pub fn to_alias_ty(&self) -> AliasTy {
2347        let kind = match self.kind {
2348            AliasTermKind::ProjectionTy { def_id } => AliasKind::Projection { def_id },
2349            AliasTermKind::OpaqueTy { def_id } => AliasKind::Opaque { def_id },
2350            AliasTermKind::FreeTy { def_id } => AliasKind::Free { def_id },
2351        };
2352        AliasTy::new(kind, self.args.clone(), List::empty())
2353    }
2354
2355    pub fn self_ty(&self) -> SubsetTyCtor {
2356        self.args[0].expect_base().clone()
2357    }
2358
2359    pub fn with_self_ty(&self, self_ty: SubsetTyCtor) -> Self {
2360        Self {
2361            kind: self.kind,
2362            args: [GenericArg::Base(self_ty)]
2363                .into_iter()
2364                .chain(self.args.iter().skip(1).cloned())
2365                .collect(),
2366        }
2367    }
2368}
2369
2370/// This methods work only with associated type projections (i.e., no opaque types)
2371impl AliasTy {
2372    pub fn self_ty(&self) -> SubsetTyCtor {
2373        self.args[0].expect_base().clone()
2374    }
2375
2376    pub fn with_self_ty(&self, self_ty: SubsetTyCtor) -> Self {
2377        Self {
2378            kind: self.kind,
2379            args: [GenericArg::Base(self_ty)]
2380                .into_iter()
2381                .chain(self.args.iter().skip(1).cloned())
2382                .collect(),
2383            refine_args: self.refine_args.clone(),
2384        }
2385    }
2386}
2387
2388impl<'tcx> ToRustc<'tcx> for AliasTerm {
2389    type T = rustc_middle::ty::AliasTerm<'tcx>;
2390
2391    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
2392        rustc_middle::ty::AliasTerm::new_from_args(
2393            tcx,
2394            self.kind.to_rustc_kind(),
2395            self.args.to_rustc(tcx),
2396        )
2397    }
2398}
2399
2400impl<'tcx> ToRustc<'tcx> for AliasTy {
2401    type T = rustc_middle::ty::AliasTy<'tcx>;
2402
2403    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
2404        rustc_middle::ty::AliasTy::new_from_args(
2405            tcx,
2406            self.kind.to_rustc_kind(),
2407            self.args.to_rustc(tcx),
2408        )
2409    }
2410}
2411
2412pub type RefineArgs = List<Expr>;
2413
2414#[extension(pub trait RefineArgsExt)]
2415impl RefineArgs {
2416    fn identity_for_item(genv: GlobalEnv, def_id: DefId) -> QueryResult<RefineArgs> {
2417        Self::for_item(genv, def_id, |param, index| {
2418            Ok(Expr::var(Var::EarlyParam(EarlyReftParam {
2419                index: index as u32,
2420                name: param.name(),
2421            })))
2422        })
2423    }
2424
2425    fn for_item<F>(genv: GlobalEnv, def_id: DefId, mut mk: F) -> QueryResult<RefineArgs>
2426    where
2427        F: FnMut(EarlyBinder<RefineParam>, usize) -> QueryResult<Expr>,
2428    {
2429        let reft_generics = genv.refinement_generics_of(def_id)?;
2430        let count = reft_generics.count();
2431        let mut args = Vec::with_capacity(count);
2432        reft_generics.fill_item(genv, &mut args, &mut mk)?;
2433        Ok(List::from_vec(args))
2434    }
2435}
2436
2437/// A type constructor meant to be used as generic a argument of [kind base]. This is just an alias
2438/// to [`Binder<SubsetTy>`], but we expect the binder to have a single bound variable of the sort of
2439/// the underlying [base type].
2440///
2441/// [kind base]: GenericParamDefKind::Base
2442/// [base type]: SubsetTy::bty
2443pub type SubsetTyCtor = Binder<SubsetTy>;
2444
2445impl SubsetTyCtor {
2446    pub fn as_bty_skipping_binder(&self) -> &BaseTy {
2447        &self.as_ref().skip_binder().bty
2448    }
2449
2450    pub fn to_ty(&self) -> Ty {
2451        let sort = self.sort();
2452        if sort.is_unit() {
2453            self.replace_bound_reft(&Expr::unit()).to_ty()
2454        } else if let Some(def_id) = sort.is_unit_adt() {
2455            self.replace_bound_reft(&Expr::unit_struct(def_id)).to_ty()
2456        } else {
2457            Ty::exists(self.as_ref().map(SubsetTy::to_ty))
2458        }
2459    }
2460
2461    pub fn to_ty_ctor(&self) -> TyCtor {
2462        self.as_ref().map(SubsetTy::to_ty)
2463    }
2464}
2465
2466/// A subset type is a simplified version of a type that has the form `{b[e] | p}` where `b` is a
2467/// [`BaseTy`], `e` a refinement index, and `p` a predicate.
2468///
2469/// These are mainly found under a [`Binder`] with a single variable of the base type's sort. This
2470/// can be interpreted as a type constructor or an existential type. For example, under a binder with a
2471/// variable `v` of sort `int`, we can interpret `{i32[v] | v > 0}` as:
2472/// - A lambda `λv:int. {i32[v] | v > 0}` that "constructs" types when applied to ints, or
2473/// - An existential type `∃v:int. {i32[v] | v > 0}`.
2474///
2475/// This second interpretation is the reason we call this a subset type, i.e., the type `∃v. {b[v] | p}`
2476/// corresponds to the subset of values of  type `b` whose index satisfies `p`. These are the types
2477/// written as `B{v: p}` in the surface syntax and correspond to the types supported in other
2478/// refinement type systems like Liquid Haskell (with the difference that we are explicit
2479/// about separating refinements from program values via an index).
2480///
2481/// The main purpose for subset types is to be used as generic arguments of [kind base] when
2482/// interpreted as type constructors. They have two key properties that makes them suitable
2483/// for this:
2484///
2485/// 1. **Syntactic Restriction**: Subset types are syntactically restricted, making it easier to
2486///    relate them structurally (e.g., for subtyping). For instance, given two types `S<λv. T1>` and
2487///    `S<λ. T2>`, if `T1` and `T2` are subset types, we know they match structurally (at least
2488///    shallowly). In particularly, the syntactic restriction rules out complex types like
2489///    `S<λv. (i32[v], i32[v])>` simplifying some operations.
2490///
2491/// 2. **Eager Canonicalization**: Subset types can be eagerly canonicalized via [*strengthening*]
2492///    during substitution. For example, suppose we have a function:
2493///    ```text
2494///    fn foo<T>(x: T[@a], y: { T[@b] | b == a }) { }
2495///    ```
2496///    If we instantiate `T` with `λv. { i32[v] | v > 0}`, after substitution and applying the
2497///    lambda (the indexing syntax `T[a]` corresponds to an application of the lambda), we get:
2498///    ```text
2499///    fn foo(x: {i32[@a] | a > 0}, y: { { i32[@b] | b > 0 } | b == a }) { }
2500///    ```
2501///    Via *strengthening* we can canonicalize this to
2502///    ```text
2503///    fn foo(x: {i32[@a] | a > 0}, y: { i32[@b] | b == a && b > 0 }) { }
2504///    ```
2505///    As a result, we can guarantee the syntactic restriction through substitution.
2506///
2507/// [kind base]: GenericParamDefKind::Base
2508/// [*strengthening*]: https://arxiv.org/pdf/2010.07763.pdf
2509#[derive(PartialEq, Clone, Eq, Hash, TyEncodable, TyDecodable)]
2510pub struct SubsetTy {
2511    /// The base type `b` in the subset type `{b[e] | p}`.
2512    ///
2513    /// **NOTE:** This is mostly going to be under a [`Binder`]. It is not yet clear to me whether
2514    /// this [`BaseTy`] should be able to mention variables in the binder. In general, in a type
2515    /// `∃v. {b[e] | p}`, it's fine to mention `v` inside `b`, but since [`SubsetTy`] is meant to
2516    /// facilitate syntactic manipulation we may want to restrict this.
2517    pub bty: BaseTy,
2518    /// The refinement index `e` in the subset type `{b[e] | p}`. This can be an arbitrary expression,
2519    /// which makes manipulation easier. However, since this is mostly found under a binder, we expect
2520    /// it to be [`Expr::nu()`].
2521    pub idx: Expr,
2522    /// The predicate `p` in the subset type `{b[e] | p}`.
2523    pub pred: Expr,
2524}
2525
2526impl SubsetTy {
2527    pub fn new(bty: BaseTy, idx: impl Into<Expr>, pred: impl Into<Expr>) -> Self {
2528        Self { bty, idx: idx.into(), pred: pred.into() }
2529    }
2530
2531    pub fn trivial(bty: BaseTy, idx: impl Into<Expr>) -> Self {
2532        Self::new(bty, idx, Expr::tt())
2533    }
2534
2535    pub fn strengthen(&self, pred: impl Into<Expr>) -> Self {
2536        let this = self.clone();
2537        let pred = Expr::and(this.pred, pred).simplify(&SnapshotMap::default());
2538        Self { bty: this.bty, idx: this.idx, pred }
2539    }
2540
2541    pub fn to_ty(&self) -> Ty {
2542        let bty = self.bty.clone();
2543        if self.pred.is_trivially_true() {
2544            Ty::indexed(bty, &self.idx)
2545        } else {
2546            Ty::constr(&self.pred, Ty::indexed(bty, &self.idx))
2547        }
2548    }
2549}
2550
2551impl<'tcx> ToRustc<'tcx> for SubsetTy {
2552    type T = rustc_middle::ty::Ty<'tcx>;
2553
2554    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> rustc_middle::ty::Ty<'tcx> {
2555        self.bty.to_rustc(tcx)
2556    }
2557}
2558
2559#[derive(PartialEq, Clone, Eq, Hash, TyEncodable, TyDecodable)]
2560pub enum GenericArg {
2561    Ty(Ty),
2562    Base(SubsetTyCtor),
2563    Lifetime(Region),
2564    Const(Const),
2565}
2566
2567impl GenericArg {
2568    #[track_caller]
2569    pub fn expect_type(&self) -> &Ty {
2570        if let GenericArg::Ty(ty) = self {
2571            ty
2572        } else {
2573            bug!("expected `rty::GenericArg::Ty`, found `{self:?}`")
2574        }
2575    }
2576
2577    #[track_caller]
2578    pub fn expect_base(&self) -> &SubsetTyCtor {
2579        if let GenericArg::Base(ctor) = self {
2580            ctor
2581        } else {
2582            bug!("expected `rty::GenericArg::Base`, found `{self:?}`")
2583        }
2584    }
2585
2586    pub fn from_param_def(param: &GenericParamDef) -> Self {
2587        match param.kind {
2588            GenericParamDefKind::Type { .. } => {
2589                let param_ty = ParamTy { index: param.index, name: param.name };
2590                GenericArg::Ty(Ty::param(param_ty))
2591            }
2592            GenericParamDefKind::Base { .. } => {
2593                // λv. T[v]
2594                let param_ty = ParamTy { index: param.index, name: param.name };
2595                GenericArg::Base(Binder::bind_with_sort(
2596                    SubsetTy::trivial(BaseTy::Param(param_ty), Expr::nu()),
2597                    Sort::Param(param_ty),
2598                ))
2599            }
2600            GenericParamDefKind::Lifetime => {
2601                let region = EarlyParamRegion { index: param.index, name: param.name };
2602                GenericArg::Lifetime(Region::ReEarlyParam(region))
2603            }
2604            GenericParamDefKind::Const { .. } => {
2605                let param_const = ParamConst { index: param.index, name: param.name };
2606                let kind = ConstKind::Param(param_const);
2607                GenericArg::Const(Const { kind })
2608            }
2609        }
2610    }
2611
2612    /// Creates a `GenericArgs` from the definition of generic parameters, by calling a closure to
2613    /// obtain arg. The closures get to observe the `GenericArgs` as they're being built, which can
2614    /// be used to correctly replace defaults of generic parameters.
2615    pub fn for_item<F>(genv: GlobalEnv, def_id: DefId, mut mk_kind: F) -> QueryResult<GenericArgs>
2616    where
2617        F: FnMut(&GenericParamDef, &[GenericArg]) -> GenericArg,
2618    {
2619        let defs = genv.generics_of(def_id)?;
2620        let count = defs.count();
2621        let mut args = Vec::with_capacity(count);
2622        Self::fill_item(genv, &mut args, &defs, &mut mk_kind)?;
2623        Ok(List::from_vec(args))
2624    }
2625
2626    pub fn identity_for_item(genv: GlobalEnv, def_id: DefId) -> QueryResult<GenericArgs> {
2627        Self::for_item(genv, def_id, |param, _| GenericArg::from_param_def(param))
2628    }
2629
2630    fn fill_item<F>(
2631        genv: GlobalEnv,
2632        args: &mut Vec<GenericArg>,
2633        generics: &Generics,
2634        mk_kind: &mut F,
2635    ) -> QueryResult<()>
2636    where
2637        F: FnMut(&GenericParamDef, &[GenericArg]) -> GenericArg,
2638    {
2639        if let Some(def_id) = generics.parent {
2640            let parent_generics = genv.generics_of(def_id)?;
2641            Self::fill_item(genv, args, &parent_generics, mk_kind)?;
2642        }
2643        for param in &generics.own_params {
2644            let kind = mk_kind(param, args);
2645            tracked_span_assert_eq!(param.index as usize, args.len());
2646            args.push(kind);
2647        }
2648        Ok(())
2649    }
2650}
2651
2652impl From<TyOrBase> for GenericArg {
2653    fn from(v: TyOrBase) -> Self {
2654        match v {
2655            TyOrBase::Ty(ty) => GenericArg::Ty(ty),
2656            TyOrBase::Base(ctor) => GenericArg::Base(ctor),
2657        }
2658    }
2659}
2660
2661impl<'tcx> ToRustc<'tcx> for GenericArg {
2662    type T = rustc_middle::ty::GenericArg<'tcx>;
2663
2664    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
2665        use rustc_middle::ty;
2666        match self {
2667            GenericArg::Ty(ty) => ty::GenericArg::from(ty.to_rustc(tcx)),
2668            GenericArg::Base(ctor) => ty::GenericArg::from(ctor.skip_binder_ref().to_rustc(tcx)),
2669            GenericArg::Lifetime(re) => ty::GenericArg::from(re.to_rustc(tcx)),
2670            GenericArg::Const(c) => ty::GenericArg::from(c.to_rustc(tcx)),
2671        }
2672    }
2673}
2674
2675pub type GenericArgs = List<GenericArg>;
2676
2677#[extension(pub trait GenericArgsExt)]
2678impl GenericArgs {
2679    #[track_caller]
2680    fn box_args(&self) -> (&Ty, &GenericArg) {
2681        if let [GenericArg::Ty(deref), alloc] = &self[..] {
2682            (deref, alloc)
2683        } else {
2684            bug!("invalid generic arguments for box");
2685        }
2686    }
2687
2688    // We can't implement [`ToRustc`] because of coherence so we add it here
2689    fn to_rustc<'tcx>(&self, tcx: TyCtxt<'tcx>) -> rustc_middle::ty::GenericArgs<'tcx> {
2690        tcx.mk_args_from_iter(self.iter().map(|arg| arg.to_rustc(tcx)))
2691    }
2692
2693    fn rebase_onto(
2694        &self,
2695        tcx: &TyCtxt,
2696        source_ancestor: DefId,
2697        target_args: &GenericArgs,
2698    ) -> List<GenericArg> {
2699        let defs = tcx.generics_of(source_ancestor);
2700        target_args
2701            .iter()
2702            .chain(self.iter().skip(defs.count()))
2703            .cloned()
2704            .collect()
2705    }
2706}
2707
2708#[derive(Debug)]
2709pub enum TyOrBase {
2710    Ty(Ty),
2711    Base(SubsetTyCtor),
2712}
2713
2714impl TyOrBase {
2715    pub fn into_ty(self) -> Ty {
2716        match self {
2717            TyOrBase::Ty(ty) => ty,
2718            TyOrBase::Base(ctor) => ctor.to_ty(),
2719        }
2720    }
2721
2722    #[track_caller]
2723    pub fn expect_base(self) -> SubsetTyCtor {
2724        match self {
2725            TyOrBase::Base(ctor) => ctor,
2726            TyOrBase::Ty(_) => tracked_span_bug!("expected `TyOrBase::Base`"),
2727        }
2728    }
2729
2730    pub fn as_base(self) -> Option<SubsetTyCtor> {
2731        match self {
2732            TyOrBase::Base(ctor) => Some(ctor),
2733            TyOrBase::Ty(_) => None,
2734        }
2735    }
2736}
2737
2738#[derive(Debug, Clone, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)]
2739pub enum TyOrCtor {
2740    Ty(Ty),
2741    Ctor(TyCtor),
2742}
2743
2744impl TyOrCtor {
2745    #[track_caller]
2746    pub fn expect_ctor(self) -> TyCtor {
2747        match self {
2748            TyOrCtor::Ctor(ctor) => ctor,
2749            TyOrCtor::Ty(_) => tracked_span_bug!("expected `TyOrCtor::Ctor`"),
2750        }
2751    }
2752
2753    pub fn expect_subset_ty_ctor(self) -> SubsetTyCtor {
2754        self.expect_ctor().map(|ty| {
2755            if let canonicalize::CanonicalTy::Constr(constr_ty) = ty.shallow_canonicalize()
2756                && let TyKind::Indexed(bty, idx) = constr_ty.ty().kind()
2757                && idx.is_nu()
2758            {
2759                SubsetTy::new(bty.clone(), Expr::nu(), constr_ty.pred())
2760            } else {
2761                tracked_span_bug!()
2762            }
2763        })
2764    }
2765
2766    pub fn to_ty(&self) -> Ty {
2767        match self {
2768            TyOrCtor::Ctor(ctor) => ctor.to_ty(),
2769            TyOrCtor::Ty(ty) => ty.clone(),
2770        }
2771    }
2772}
2773
2774impl From<TyOrBase> for TyOrCtor {
2775    fn from(v: TyOrBase) -> Self {
2776        match v {
2777            TyOrBase::Ty(ty) => TyOrCtor::Ty(ty),
2778            TyOrBase::Base(ctor) => TyOrCtor::Ctor(ctor.to_ty_ctor()),
2779        }
2780    }
2781}
2782
2783impl CoroutineObligPredicate {
2784    pub fn to_poly_fn_sig(&self) -> PolyFnSig {
2785        let vars = vec![];
2786
2787        let resume_ty = &self.resume_ty;
2788        let env_ty = Ty::coroutine(
2789            self.def_id,
2790            resume_ty.clone(),
2791            self.upvar_tys.clone(),
2792            self.args.clone(),
2793        );
2794
2795        let inputs = List::from_arr([env_ty, resume_ty.clone()]);
2796        let output =
2797            Binder::bind_with_vars(FnOutput::new(self.output.clone(), vec![]), List::empty());
2798
2799        PolyFnSig::bind_with_vars(
2800            FnSig::new(
2801                Safety::Safe,
2802                rustc_abi::ExternAbi::RustCall,
2803                List::empty(),
2804                inputs,
2805                output,
2806                Expr::ff(),
2807                false,
2808            ),
2809            List::from(vars),
2810        )
2811    }
2812}
2813
2814impl RefinementGenerics {
2815    pub fn count(&self) -> usize {
2816        self.parent_count + self.own_params.len()
2817    }
2818
2819    pub fn own_count(&self) -> usize {
2820        self.own_params.len()
2821    }
2822}
2823
2824impl EarlyBinder<RefinementGenerics> {
2825    pub fn parent(&self) -> Option<DefId> {
2826        self.skip_binder_ref().parent
2827    }
2828
2829    pub fn parent_count(&self) -> usize {
2830        self.skip_binder_ref().parent_count
2831    }
2832
2833    pub fn count(&self) -> usize {
2834        self.skip_binder_ref().count()
2835    }
2836
2837    pub fn own_count(&self) -> usize {
2838        self.skip_binder_ref().own_count()
2839    }
2840
2841    pub fn own_param_at(&self, index: usize) -> EarlyBinder<RefineParam> {
2842        self.as_ref().map(|this| this.own_params[index].clone())
2843    }
2844
2845    pub fn param_at(
2846        &self,
2847        param_index: usize,
2848        genv: GlobalEnv,
2849    ) -> QueryResult<EarlyBinder<RefineParam>> {
2850        if let Some(index) = param_index.checked_sub(self.parent_count()) {
2851            Ok(self.own_param_at(index))
2852        } else {
2853            let parent = self.parent().expect("parent_count > 0 but no parent?");
2854            genv.refinement_generics_of(parent)?
2855                .param_at(param_index, genv)
2856        }
2857    }
2858
2859    pub fn iter_own_params(&self) -> impl Iterator<Item = EarlyBinder<RefineParam>> + use<'_> {
2860        self.skip_binder_ref()
2861            .own_params
2862            .iter()
2863            .cloned()
2864            .map(EarlyBinder)
2865    }
2866
2867    pub fn fill_item<F, R>(&self, genv: GlobalEnv, vec: &mut Vec<R>, mk: &mut F) -> QueryResult
2868    where
2869        F: FnMut(EarlyBinder<RefineParam>, usize) -> QueryResult<R>,
2870    {
2871        if let Some(def_id) = self.parent() {
2872            genv.refinement_generics_of(def_id)?
2873                .fill_item(genv, vec, mk)?;
2874        }
2875        for param in self.iter_own_params() {
2876            vec.push(mk(param, vec.len())?);
2877        }
2878        Ok(())
2879    }
2880}
2881
2882impl EarlyBinder<GenericPredicates> {
2883    pub fn predicates(&self) -> EarlyBinder<List<Clause>> {
2884        EarlyBinder(self.0.predicates.clone())
2885    }
2886}
2887
2888impl EarlyBinder<FuncSort> {
2889    /// See [`subst::GenericsSubstForSort`]
2890    pub fn instantiate_func_sort<E>(
2891        self,
2892        sort_for_param: impl FnMut(ParamTy) -> Result<Sort, E>,
2893    ) -> Result<FuncSort, E> {
2894        self.0.try_fold_with(&mut subst::GenericsSubstFolder::new(
2895            subst::GenericsSubstForSort { sort_for_param },
2896            &[],
2897        ))
2898    }
2899}
2900
2901impl VariantSig {
2902    pub fn new(
2903        adt_def: AdtDef,
2904        args: GenericArgs,
2905        fields: List<Ty>,
2906        idx: Expr,
2907        requires: List<Expr>,
2908    ) -> Self {
2909        VariantSig { adt_def, args, fields, idx, requires }
2910    }
2911
2912    pub fn fields(&self) -> &[Ty] {
2913        &self.fields
2914    }
2915
2916    pub fn ret(&self) -> Ty {
2917        let bty = BaseTy::Adt(self.adt_def.clone(), self.args.clone());
2918        let idx = self.idx.clone();
2919        Ty::indexed(bty, idx)
2920    }
2921}
2922
2923impl FnSig {
2924    pub fn new(
2925        safety: Safety,
2926        abi: rustc_abi::ExternAbi,
2927        requires: List<Expr>,
2928        inputs: List<Ty>,
2929        output: Binder<FnOutput>,
2930        no_panic: Expr,
2931        lifted: bool,
2932    ) -> Self {
2933        FnSig { safety, abi, requires, inputs, output, no_panic, lifted }
2934    }
2935
2936    pub fn requires(&self) -> &[Expr] {
2937        &self.requires
2938    }
2939
2940    pub fn inputs(&self) -> &[Ty] {
2941        &self.inputs
2942    }
2943
2944    pub fn no_panic(&self) -> Expr {
2945        self.no_panic.clone()
2946    }
2947
2948    pub fn output(&self) -> Binder<FnOutput> {
2949        self.output.clone()
2950    }
2951}
2952
2953impl<'tcx> ToRustc<'tcx> for FnSig {
2954    type T = rustc_middle::ty::FnSig<'tcx>;
2955
2956    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
2957        tcx.mk_fn_sig(
2958            self.inputs().iter().map(|ty| ty.to_rustc(tcx)),
2959            self.output().as_ref().skip_binder().to_rustc(tcx),
2960            rustc_middle::ty::FnSigKind::default()
2961                .set_abi(self.abi)
2962                .set_safety(self.safety)
2963                .set_c_variadic(false),
2964        )
2965    }
2966}
2967
2968impl FnOutput {
2969    pub fn new(ret: Ty, ensures: impl Into<List<Ensures>>) -> Self {
2970        Self { ret, ensures: ensures.into() }
2971    }
2972}
2973
2974impl<'tcx> ToRustc<'tcx> for FnOutput {
2975    type T = rustc_middle::ty::Ty<'tcx>;
2976
2977    fn to_rustc(&self, tcx: TyCtxt<'tcx>) -> Self::T {
2978        self.ret.to_rustc(tcx)
2979    }
2980}
2981
2982impl AdtDef {
2983    pub fn new(rustc: ty::AdtDef, sort_def: AdtSortDef, opaque: bool) -> Self {
2984        AdtDef(Interned::new(AdtDefData { sort_def, opaque, rustc }))
2985    }
2986
2987    pub fn did(&self) -> DefId {
2988        self.0.rustc.did()
2989    }
2990
2991    pub fn sort_def(&self) -> &AdtSortDef {
2992        &self.0.sort_def
2993    }
2994
2995    pub fn sort(&self, args: &[GenericArg]) -> Sort {
2996        self.sort_def().to_sort(args)
2997    }
2998
2999    pub fn is_box(&self) -> bool {
3000        self.0.rustc.is_box()
3001    }
3002
3003    pub fn is_enum(&self) -> bool {
3004        self.0.rustc.is_enum()
3005    }
3006
3007    pub fn is_struct(&self) -> bool {
3008        self.0.rustc.is_struct()
3009    }
3010
3011    pub fn is_union(&self) -> bool {
3012        self.0.rustc.is_union()
3013    }
3014
3015    pub fn variants(&self) -> &IndexSlice<VariantIdx, VariantDef> {
3016        self.0.rustc.variants()
3017    }
3018
3019    pub fn variant(&self, idx: VariantIdx) -> &VariantDef {
3020        self.0.rustc.variant(idx)
3021    }
3022
3023    pub fn discriminants(&self) -> impl Iterator<Item = (VariantIdx, u128)> + '_ {
3024        self.0.rustc.discriminants()
3025    }
3026
3027    pub fn is_opaque(&self) -> bool {
3028        self.0.opaque
3029    }
3030}
3031
3032impl EarlyBinder<PolyVariant> {
3033    // The field_idx is `Some(i)` when we have the `i`-th field of a `union`, in which case,
3034    // the `inputs` are _just_ the `i`-th type (and not all the types...)
3035    pub fn to_poly_fn_sig(&self, field_idx: Option<crate::FieldIdx>) -> EarlyBinder<PolyFnSig> {
3036        self.as_ref().map(|poly_variant| {
3037            poly_variant.as_ref().map(|variant| {
3038                let ret = variant.ret().shift_in_escaping(1);
3039                let output = Binder::bind_with_vars(FnOutput::new(ret, vec![]), List::empty());
3040                let inputs = match field_idx {
3041                    None => variant.fields.clone(),
3042                    Some(i) => List::singleton(variant.fields[i.index()].clone()),
3043                };
3044                FnSig::new(
3045                    Safety::Safe,
3046                    rustc_abi::ExternAbi::Rust,
3047                    variant.requires.clone(),
3048                    inputs,
3049                    output,
3050                    Expr::tt(),
3051                    false,
3052                )
3053            })
3054        })
3055    }
3056}
3057
3058impl TyKind {
3059    fn intern(self) -> Ty {
3060        Ty(Interned::new(self))
3061    }
3062}
3063
3064/// All slices have 0 <= len <= usize::MAX, with the upper bound subject to overflow checking.
3065///
3066/// Also subject to overflow checking, slices have len * T::size_of() <=
3067/// isize::MAX (see [`std::slice::from_raw_parts`]).
3068///
3069/// While this holds for all slices, the above condition reduces to true for ZST
3070/// slices, so we omit it. Additionally, for ZST slices, the usize::MAX upper
3071/// bound is redundant, so we omit it.
3072///
3073/// [`std::slice::from_raw_parts`]:
3074/// https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html
3075fn slice_invariants(genv: GlobalEnv, elem_ty: &Ty, overflow_mode: OverflowMode) -> Vec<Invariant> {
3076    let mut invariants = vec![Invariant {
3077        pred: Binder::bind_with_sort(Expr::ge(Expr::nu(), Expr::zero()), Sort::Int),
3078    }];
3079    if !matches!(
3080        overflow_mode,
3081        OverflowMode::Strict | OverflowMode::Lazy | OverflowMode::StrictUnder
3082    ) {
3083        return invariants;
3084    }
3085
3086    let sized_id = genv.tcx().require_lang_item(LangItem::Sized, DUMMY_SP);
3087    let size_of = Expr::alias(
3088        AliasReft {
3089            assoc_id: genv.require_builtin_assoc_reft(sized_id, sym::size_of),
3090            args: List::from_arr([GenericArg::Base(
3091                elem_ty
3092                    .with_holes()
3093                    .replace_holes(|_, _| Expr::tt())
3094                    .as_bty_skipping_existentials()
3095                    .expect("slice element type must have a base type")
3096                    .to_subset_ty_ctor(),
3097            )]),
3098        },
3099        List::empty(),
3100    );
3101    // T::size_of() * len <= isize::MAX
3102    invariants.push(Invariant {
3103        pred: Binder::bind_with_sort(
3104            Expr::le(
3105                Expr::binary_op(BinOp::Mul(Sort::Int), Expr::nu(), size_of),
3106                Expr::int_max(IntTy::Isize),
3107            ),
3108            Sort::Int,
3109        ),
3110    });
3111    // len <= usize::MAX (only relevant for ZSTs)
3112    invariants.push(Invariant {
3113        pred: Binder::bind_with_sort(
3114            Expr::le(Expr::nu(), Expr::uint_max(UintTy::Usize)),
3115            Sort::Int,
3116        ),
3117    });
3118    invariants
3119}
3120
3121fn uint_invariants(uint_ty: UintTy, overflow_mode: OverflowMode) -> &'static [Invariant] {
3122    static DEFAULT: LazyLock<[Invariant; 1]> = LazyLock::new(|| {
3123        [Invariant { pred: Binder::bind_with_sort(Expr::ge(Expr::nu(), Expr::zero()), Sort::Int) }]
3124    });
3125
3126    static OVERFLOW: LazyLock<UnordMap<UintTy, [Invariant; 2]>> = LazyLock::new(|| {
3127        UINT_TYS
3128            .into_iter()
3129            .map(|uint_ty| {
3130                let invariants = [
3131                    Invariant {
3132                        pred: Binder::bind_with_sort(Expr::ge(Expr::nu(), Expr::zero()), Sort::Int),
3133                    },
3134                    Invariant {
3135                        pred: Binder::bind_with_sort(
3136                            Expr::le(Expr::nu(), Expr::uint_max(uint_ty)),
3137                            Sort::Int,
3138                        ),
3139                    },
3140                ];
3141                (uint_ty, invariants)
3142            })
3143            .collect()
3144    });
3145    if matches!(
3146        overflow_mode,
3147        OverflowMode::Strict | OverflowMode::Lazy | OverflowMode::StrictUnder
3148    ) {
3149        &OVERFLOW[&uint_ty]
3150    } else {
3151        &*DEFAULT
3152    }
3153}
3154
3155fn raw_ptr_invariants() -> &'static [Invariant] {
3156    fn field(field: RawPtrField) -> Expr {
3157        Expr::nu().proj_and_reduce(FieldProj::RawPtr { field })
3158    }
3159
3160    static INVARIANTS: LazyLock<[Invariant; 4]> = LazyLock::new(|| {
3161        let base = field(RawPtrField::Base);
3162        let addr = field(RawPtrField::Addr);
3163        let size = field(RawPtrField::Size);
3164        let max = Expr::uint_max(UintTy::Usize);
3165        [
3166            Expr::ge(base, Expr::zero()),
3167            Expr::ge(&addr, Expr::zero()),
3168            Expr::le(&addr, &max),
3169            Expr::le(addr + size, max),
3170        ]
3171        .map(|pred| Invariant { pred: Binder::bind_with_sort(pred, Sort::RawPtr) })
3172    });
3173    &*INVARIANTS
3174}
3175
3176fn char_invariants() -> &'static [Invariant] {
3177    static INVARIANTS: LazyLock<[Invariant; 2]> = LazyLock::new(|| {
3178        [
3179            Invariant {
3180                pred: Binder::bind_with_sort(
3181                    Expr::le(
3182                        Expr::cast(Sort::Char, Sort::Int, Expr::nu()),
3183                        Expr::constant((char::MAX as u32).into()),
3184                    ),
3185                    Sort::Int,
3186                ),
3187            },
3188            Invariant {
3189                pred: Binder::bind_with_sort(
3190                    Expr::le(Expr::zero(), Expr::cast(Sort::Char, Sort::Int, Expr::nu())),
3191                    Sort::Int,
3192                ),
3193            },
3194        ]
3195    });
3196    &*INVARIANTS
3197}
3198
3199fn int_invariants(int_ty: IntTy, overflow_mode: OverflowMode) -> &'static [Invariant] {
3200    static DEFAULT: [Invariant; 0] = [];
3201
3202    static OVERFLOW: LazyLock<UnordMap<IntTy, [Invariant; 2]>> = LazyLock::new(|| {
3203        INT_TYS
3204            .into_iter()
3205            .map(|int_ty| {
3206                let invariants = [
3207                    Invariant {
3208                        pred: Binder::bind_with_sort(
3209                            Expr::ge(Expr::nu(), Expr::int_min(int_ty)),
3210                            Sort::Int,
3211                        ),
3212                    },
3213                    Invariant {
3214                        pred: Binder::bind_with_sort(
3215                            Expr::le(Expr::nu(), Expr::int_max(int_ty)),
3216                            Sort::Int,
3217                        ),
3218                    },
3219                ];
3220                (int_ty, invariants)
3221            })
3222            .collect()
3223    });
3224    if matches!(
3225        overflow_mode,
3226        OverflowMode::Strict | OverflowMode::Lazy | OverflowMode::StrictUnder
3227    ) {
3228        &OVERFLOW[&int_ty]
3229    } else {
3230        &DEFAULT
3231    }
3232}
3233
3234impl_internable!(AdtDefData, AdtSortDefData, TyKind);
3235impl_slice_internable!(
3236    Ty,
3237    GenericArg,
3238    Ensures,
3239    InferMode,
3240    Sort,
3241    SortArg,
3242    GenericParamDef,
3243    TraitRef,
3244    Binder<ExistentialPredicate>,
3245    Clause,
3246    PolyVariant,
3247    Invariant,
3248    RefineParam,
3249    FluxDefId,
3250    SortParamKind,
3251    AssocReft
3252);
3253
3254#[macro_export]
3255macro_rules! _Int {
3256    ($int_ty:pat, $idxs:pat) => {
3257        TyKind::Indexed(BaseTy::Int($int_ty), $idxs)
3258    };
3259}
3260pub use crate::_Int as Int;
3261
3262#[macro_export]
3263macro_rules! _Uint {
3264    ($uint_ty:pat, $idxs:pat) => {
3265        TyKind::Indexed(BaseTy::Uint($uint_ty), $idxs)
3266    };
3267}
3268pub use crate::_Uint as Uint;
3269
3270#[macro_export]
3271macro_rules! _Bool {
3272    ($idxs:pat) => {
3273        TyKind::Indexed(BaseTy::Bool, $idxs)
3274    };
3275}
3276pub use crate::_Bool as Bool;
3277
3278#[macro_export]
3279macro_rules! _Char {
3280    ($idxs:pat) => {
3281        TyKind::Indexed(BaseTy::Char, $idxs)
3282    };
3283}
3284pub use crate::_Char as Char;
3285
3286#[macro_export]
3287macro_rules! _Ref {
3288    ($($pats:pat),+ $(,)?) => {
3289        $crate::rty::TyKind::Indexed($crate::rty::BaseTy::Ref($($pats),+), _)
3290    };
3291}
3292pub use crate::_Ref as Ref;
3293
3294pub struct WfckResults {
3295    pub owner: FluxOwnerId,
3296    param_sorts: UnordMap<fhir::ParamId, Sort>,
3297    bin_op_sorts: ItemLocalMap<Sort>,
3298    fn_app_sorts: ItemLocalMap<List<SortArg>>,
3299    coercions: ItemLocalMap<Vec<Coercion>>,
3300    field_projs: ItemLocalMap<FieldProj>,
3301    node_sorts: ItemLocalMap<Sort>,
3302    record_ctors: ItemLocalMap<RecordCtor>,
3303}
3304
3305#[derive(Clone, Copy, Debug)]
3306pub enum Coercion {
3307    Inject(DefId),
3308    Project(DefId),
3309}
3310
3311#[derive(Clone, Copy, Debug)]
3312pub enum RecordCtor {
3313    Struct(DefId),
3314    RawPtr,
3315}
3316
3317pub type ItemLocalMap<T> = UnordMap<fhir::ItemLocalId, T>;
3318
3319#[derive(Debug)]
3320pub struct LocalTableInContext<'a, T> {
3321    owner: FluxOwnerId,
3322    data: &'a ItemLocalMap<T>,
3323}
3324
3325pub struct LocalTableInContextMut<'a, T> {
3326    owner: FluxOwnerId,
3327    data: &'a mut ItemLocalMap<T>,
3328}
3329
3330impl WfckResults {
3331    pub fn new(owner: impl Into<FluxOwnerId>) -> Self {
3332        Self {
3333            owner: owner.into(),
3334            param_sorts: UnordMap::default(),
3335            bin_op_sorts: ItemLocalMap::default(),
3336            coercions: ItemLocalMap::default(),
3337            field_projs: ItemLocalMap::default(),
3338            node_sorts: ItemLocalMap::default(),
3339            record_ctors: ItemLocalMap::default(),
3340            fn_app_sorts: ItemLocalMap::default(),
3341        }
3342    }
3343
3344    pub fn param_sorts_mut(&mut self) -> &mut UnordMap<fhir::ParamId, Sort> {
3345        &mut self.param_sorts
3346    }
3347
3348    pub fn param_sorts(&self) -> &UnordMap<fhir::ParamId, Sort> {
3349        &self.param_sorts
3350    }
3351
3352    pub fn bin_op_sorts_mut(&mut self) -> LocalTableInContextMut<'_, Sort> {
3353        LocalTableInContextMut { owner: self.owner, data: &mut self.bin_op_sorts }
3354    }
3355
3356    pub fn fn_app_sorts_mut(&mut self) -> LocalTableInContextMut<'_, List<SortArg>> {
3357        LocalTableInContextMut { owner: self.owner, data: &mut self.fn_app_sorts }
3358    }
3359
3360    pub fn fn_app_sorts(&self) -> LocalTableInContext<'_, List<SortArg>> {
3361        LocalTableInContext { owner: self.owner, data: &self.fn_app_sorts }
3362    }
3363
3364    pub fn bin_op_sorts(&self) -> LocalTableInContext<'_, Sort> {
3365        LocalTableInContext { owner: self.owner, data: &self.bin_op_sorts }
3366    }
3367
3368    pub fn coercions_mut(&mut self) -> LocalTableInContextMut<'_, Vec<Coercion>> {
3369        LocalTableInContextMut { owner: self.owner, data: &mut self.coercions }
3370    }
3371
3372    pub fn coercions(&self) -> LocalTableInContext<'_, Vec<Coercion>> {
3373        LocalTableInContext { owner: self.owner, data: &self.coercions }
3374    }
3375
3376    pub fn field_projs_mut(&mut self) -> LocalTableInContextMut<'_, FieldProj> {
3377        LocalTableInContextMut { owner: self.owner, data: &mut self.field_projs }
3378    }
3379
3380    pub fn field_projs(&self) -> LocalTableInContext<'_, FieldProj> {
3381        LocalTableInContext { owner: self.owner, data: &self.field_projs }
3382    }
3383
3384    pub fn node_sorts_mut(&mut self) -> LocalTableInContextMut<'_, Sort> {
3385        LocalTableInContextMut { owner: self.owner, data: &mut self.node_sorts }
3386    }
3387
3388    pub fn node_sorts(&self) -> LocalTableInContext<'_, Sort> {
3389        LocalTableInContext { owner: self.owner, data: &self.node_sorts }
3390    }
3391
3392    pub fn record_ctors_mut(&mut self) -> LocalTableInContextMut<'_, RecordCtor> {
3393        LocalTableInContextMut { owner: self.owner, data: &mut self.record_ctors }
3394    }
3395
3396    pub fn record_ctors(&self) -> LocalTableInContext<'_, RecordCtor> {
3397        LocalTableInContext { owner: self.owner, data: &self.record_ctors }
3398    }
3399}
3400
3401impl<T> LocalTableInContextMut<'_, T> {
3402    pub fn insert(&mut self, fhir_id: FhirId, value: T) {
3403        tracked_span_assert_eq!(self.owner, fhir_id.owner);
3404        self.data.insert(fhir_id.local_id, value);
3405    }
3406}
3407
3408impl<'a, T> LocalTableInContext<'a, T> {
3409    pub fn get(&self, fhir_id: FhirId) -> Option<&'a T> {
3410        tracked_span_assert_eq!(self.owner, fhir_id.owner);
3411        self.data.get(&fhir_id.local_id)
3412    }
3413}
3414
3415fn can_auto_strong(fn_sig: &PolyFnSig) -> bool {
3416    struct RegionDetector {
3417        has_region: bool,
3418    }
3419
3420    impl fold::TypeFolder for RegionDetector {
3421        fn fold_region(&mut self, re: &Region) -> Region {
3422            self.has_region = true;
3423            *re
3424        }
3425    }
3426    let mut detector = RegionDetector { has_region: false };
3427    fn_sig
3428        .skip_binder_ref()
3429        .output()
3430        .skip_binder_ref()
3431        .ret
3432        .fold_with(&mut detector);
3433
3434    !detector.has_region
3435}
3436/// The [`auto_strong`] function transforms function signatures by automatically converting
3437/// mutable reference parameters into strong references with associated ensures clauses. This
3438/// transformation is applied only when the function signature does not already contain region
3439/// variables in its return type.
3440///
3441/// Specifically, given a source function of type
3442///
3443///    fn (x: &mut InnerTy) -> bool
3444///
3445/// By default the above gives us an `rty::FnSig`
3446///
3447///    forall<>. fn (x: &mut InnerTy) -> bool
3448///
3449/// Which this function then transforms to
3450///
3451///     forall<l0: Loc>. fn (x: &strg<l0:InnerTy>) -> bool ensures l0:InnerTy
3452pub fn auto_strong(
3453    genv: GlobalEnv,
3454    def_id: impl IntoQueryKey<DefId>,
3455    fn_sig: PolyFnSig,
3456) -> PolyFnSig {
3457    // TODO(auto-strong): we only *really* need the first check `can_auto_strong` here.
3458    // The other two skip `auto-strong` as doing it breaks various downstream things
3459    // that should be fixed.
3460    if !can_auto_strong(&fn_sig)
3461        || matches!(genv.def_kind(def_id), rustc_hir::def::DefKind::Closure)
3462        || !fn_sig.skip_binder_ref().lifted
3463    {
3464        return fn_sig;
3465    }
3466    let kind = BoundReftKind::Anon;
3467    let mut vars = fn_sig.vars().to_vec();
3468    let fn_sig = fn_sig.skip_binder();
3469    // new list of (bound_var, inner_ty)
3470    let mut strg_bvars = vec![];
3471    // new list of input types
3472    let mut strg_inputs = vec![];
3473    // 1. Traverse inputs collecting strong locations
3474    for ty in &fn_sig.inputs {
3475        let strg_ty = if let TyKind::Indexed(BaseTy::Ref(re, inner_ty, Mutability::Mut), _) =
3476            ty.kind()
3477            && !inner_ty.is_slice()
3478        // TODO(auto-strong): including `slice` breaks `tock` for some reason we should replicate in our own tests...
3479        {
3480            // if input is &mut InnerTy create a new bound var `loc` for the strong location
3481            let var = {
3482                let idx = vars.len() + strg_bvars.len();
3483                BoundVar::from_usize(idx)
3484            };
3485            strg_bvars.push((var, inner_ty.clone()));
3486            let loc = Loc::Var(Var::Bound(INNERMOST, BoundReft { var, kind }));
3487            // and transform to &strg<loc:InnerTy>
3488            Ty::strg_ref(*re, Path::new(loc, List::empty()), inner_ty.clone())
3489        } else {
3490            // else leave input type unchanged
3491            ty.clone()
3492        };
3493        strg_inputs.push(strg_ty);
3494    }
3495    // 2. Add bound vars for strong locations
3496    for _ in 0..strg_bvars.len() {
3497        vars.push(BoundVariableKind::Refine(Sort::Loc, InferMode::EVar, kind));
3498    }
3499    // 3. Add ensures for strong locations
3500    let output = fn_sig.output.map(|out| {
3501        let mut ens = out.ensures.to_vec();
3502        for (var, inner_ty) in strg_bvars {
3503            let loc = Loc::Var(Var::Bound(INNERMOST.shifted_in(1), BoundReft { var, kind }));
3504            let path = Path::new(loc, List::empty());
3505            ens.push(Ensures::Type(path, inner_ty.shift_in_escaping(1)));
3506        }
3507        FnOutput { ensures: List::from_vec(ens), ..out }
3508    });
3509
3510    // 4. Reconstruct fn sig with new inputs and output and vars
3511    let fn_sig = FnSig { inputs: List::from_vec(strg_inputs), output, ..fn_sig };
3512    Binder::bind_with_vars(fn_sig, vars.into())
3513}