Skip to main content

flux_middle/
fhir.rs

1//! Flux High-Level Intermediate Representation
2//!
3//! The fhir corresponds to the desugared version of source level flux annotations. The main
4//! difference with the surface syntax is that the list of refinement parameters is explicit
5//! in fhir. For example, the following signature
6//!
7//! `fn(x: &strg i32[@n]) ensures x: i32[n + 1]`
8//!
9//! desugars to
10//!
11//! `for<n: int, l: loc> fn(&strg<l: i32[n]>) ensures l: i32[n + 1]`.
12//!
13//! The name fhir is borrowed (pun intended) from rustc's hir to refer to something a bit lower
14//! than the surface syntax.
15
16pub mod visit;
17
18use std::{borrow::Cow, fmt, iter};
19
20use flux_common::{bug, span_bug};
21use flux_config::PartialInferOpts;
22pub use flux_syntax::surface::{BinOp, UnOp};
23use flux_syntax::{
24    surface::{self, Ignored, Trusted},
25    symbols::sym,
26};
27use itertools::Itertools;
28use rustc_abi;
29pub use rustc_abi::VariantIdx;
30use rustc_ast::TraitObjectSyntax;
31use rustc_data_structures::{
32    fx::{FxIndexMap, FxIndexSet},
33    unord::UnordMap,
34};
35pub use rustc_hir::PrimTy;
36use rustc_hir::{
37    FnHeader, OwnerId, ParamName, Safety,
38    def::DefKind,
39    def_id::{DefId, LocalDefId},
40};
41use rustc_index::newtype_index;
42use rustc_macros::{Decodable, Encodable};
43pub use rustc_middle::mir::Mutability;
44use rustc_middle::ty::TyCtxt;
45use rustc_span::{ErrorGuaranteed, Span, Symbol, symbol::Ident};
46
47use crate::{
48    def_id::{FluxDefId, FluxLocalDefId, MaybeExternId},
49    global_env::GlobalEnv,
50    rty::HintKind,
51};
52
53pub enum Attr {
54    Trusted(Trusted),
55    TrustedImpl(Trusted),
56    TrustedDerive(Trusted),
57    Ignore(Ignored),
58    ProvenExternally(Span),
59    ShouldFail,
60    InferOpts(PartialInferOpts),
61    NoPanic,
62    NoSuggestions,
63}
64
65#[derive(Clone, Copy, Default)]
66pub struct AttrMap<'fhir> {
67    pub attrs: &'fhir [Attr],
68    pub qualifiers: &'fhir [FluxDefId],
69    /// The local axioms listed in `#[axioms(...)]`
70    pub axioms: &'fhir [FluxDefId],
71    /// The local primop properties listed in `#[properties(...)]`
72    pub properties: &'fhir [FluxDefId],
73    /// The definitions listed in `#[reveal(...)]` together with the span where they are named.
74    pub reveals: &'fhir [(FluxDefId, Span)],
75    /// The definitions listed in `#[hide(...)]` together with the span where they are named.
76    pub hides: &'fhir [(FluxDefId, Span)],
77    /// The `DefId`s of type params listed in `#[assume_parametric(...)]`. They match
78    /// the `DefId` entries in `generics_of(callee_id)`. These are `DefId`s and not
79    /// `LocalDefId`s such that they are correct for extern specs as well.
80    pub parametric_params: &'fhir [DefId],
81}
82
83impl AttrMap<'_> {
84    pub(crate) fn proven_externally(&self) -> Option<Span> {
85        self.attrs.iter().find_map(|attr| {
86            if let Attr::ProvenExternally(span) = *attr { Some(span) } else { None }
87        })
88    }
89
90    pub(crate) fn ignored(&self) -> Option<Ignored> {
91        self.attrs
92            .iter()
93            .find_map(|attr| if let Attr::Ignore(ignored) = *attr { Some(ignored) } else { None })
94    }
95
96    pub(crate) fn trusted(&self) -> Option<Trusted> {
97        self.attrs
98            .iter()
99            .find_map(|attr| if let Attr::Trusted(trusted) = *attr { Some(trusted) } else { None })
100    }
101
102    pub(crate) fn trusted_impl(&self) -> Option<Trusted> {
103        self.attrs.iter().find_map(|attr| {
104            if let Attr::TrustedImpl(trusted) = *attr { Some(trusted) } else { None }
105        })
106    }
107
108    pub(crate) fn trusted_derive(&self) -> Option<Trusted> {
109        self.attrs.iter().find_map(|attr| {
110            if let Attr::TrustedDerive(trusted) = *attr { Some(trusted) } else { None }
111        })
112    }
113
114    pub(crate) fn should_fail(&self) -> bool {
115        self.attrs
116            .iter()
117            .any(|attr| matches!(attr, Attr::ShouldFail))
118    }
119
120    pub(crate) fn infer_opts(&self) -> Option<PartialInferOpts> {
121        self.attrs
122            .iter()
123            .find_map(|attr| if let Attr::InferOpts(opts) = *attr { Some(opts) } else { None })
124    }
125
126    pub(crate) fn no_panic(&self) -> bool {
127        self.attrs.iter().any(|attr| matches!(attr, Attr::NoPanic))
128    }
129
130    pub(crate) fn parametric_params(&self) -> &[DefId] {
131        self.parametric_params
132    }
133
134    pub(crate) fn no_suggestions(&self) -> bool {
135        self.attrs
136            .iter()
137            .any(|attr| matches!(attr, Attr::NoSuggestions))
138    }
139}
140
141#[derive(Debug, Clone, Copy)]
142pub struct Generics<'fhir> {
143    pub params: &'fhir [GenericParam<'fhir>],
144    pub refinement_params: &'fhir [RefineParam<'fhir>],
145    pub predicates: Option<&'fhir [WhereBoundPredicate<'fhir>]>,
146}
147
148#[derive(Debug, Clone, Copy)]
149pub struct GenericParam<'fhir> {
150    pub def_id: MaybeExternId,
151    pub name: ParamName,
152    pub kind: GenericParamKind<'fhir>,
153}
154
155#[derive(Debug, Clone, Copy)]
156pub enum GenericParamKind<'fhir> {
157    Type { default: Option<Ty<'fhir>> },
158    Lifetime,
159    Const { ty: Ty<'fhir>, has_default: bool },
160}
161
162#[derive(Debug)]
163pub struct Qualifier<'fhir> {
164    pub def_id: FluxLocalDefId,
165    pub args: &'fhir [RefineParam<'fhir>],
166    pub wildcards: &'fhir [bool],
167    pub expr: Expr<'fhir>,
168    pub kind: HintKind,
169}
170
171#[derive(Clone, Copy, Debug)]
172pub enum Node<'fhir> {
173    Item(&'fhir Item<'fhir>),
174    TraitItem(&'fhir TraitItem<'fhir>),
175    ImplItem(&'fhir ImplItem<'fhir>),
176    OpaqueTy(&'fhir OpaqueTy<'fhir>),
177    ForeignItem(&'fhir ForeignItem<'fhir>),
178    Ctor,
179    AnonConst,
180    Expr,
181}
182
183impl<'fhir> Node<'fhir> {
184    pub fn as_owner(self) -> Option<OwnerNode<'fhir>> {
185        match self {
186            Node::Item(item) => Some(OwnerNode::Item(item)),
187            Node::TraitItem(trait_item) => Some(OwnerNode::TraitItem(trait_item)),
188            Node::ImplItem(impl_item) => Some(OwnerNode::ImplItem(impl_item)),
189            Node::ForeignItem(foreign_item) => Some(OwnerNode::ForeignItem(foreign_item)),
190            Node::OpaqueTy(_) | Node::AnonConst | Node::Expr | Node::Ctor => None,
191        }
192    }
193
194    pub fn expect_opaque_ty(&self) -> &'fhir OpaqueTy<'fhir> {
195        if let Node::OpaqueTy(opaque_ty) = &self { opaque_ty } else { bug!("expected opaque type") }
196    }
197}
198
199#[derive(Clone, Copy, Debug)]
200pub enum OwnerNode<'fhir> {
201    Item(&'fhir Item<'fhir>),
202    TraitItem(&'fhir TraitItem<'fhir>),
203    ImplItem(&'fhir ImplItem<'fhir>),
204    ForeignItem(&'fhir ForeignItem<'fhir>),
205}
206
207impl<'fhir> OwnerNode<'fhir> {
208    pub fn fn_sig(&self) -> Option<&'fhir FnSig<'fhir>> {
209        match self {
210            OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, ..), .. })
211            | OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig), .. })
212            | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig), .. })
213            | OwnerNode::ForeignItem(ForeignItem {
214                kind: ForeignItemKind::Fn(fn_sig, ..), ..
215            }) => Some(fn_sig),
216            _ => None,
217        }
218    }
219
220    pub fn generics(self) -> &'fhir Generics<'fhir> {
221        match self {
222            OwnerNode::Item(item) => &item.generics,
223            OwnerNode::TraitItem(trait_item) => &trait_item.generics,
224            OwnerNode::ImplItem(impl_item) => &impl_item.generics,
225            OwnerNode::ForeignItem(foreign_item) => {
226                match foreign_item.kind {
227                    ForeignItemKind::Fn(.., generics) | ForeignItemKind::Static(.., generics) => {
228                        generics
229                    }
230                }
231            }
232        }
233    }
234
235    pub fn owner_id(&self) -> MaybeExternId<OwnerId> {
236        match self {
237            OwnerNode::Item(item) => item.owner_id,
238            OwnerNode::TraitItem(trait_item) => trait_item.owner_id,
239            OwnerNode::ImplItem(impl_item) => impl_item.owner_id,
240            OwnerNode::ForeignItem(foreign_item) => foreign_item.owner_id,
241        }
242    }
243}
244
245#[derive(Debug)]
246pub struct Item<'fhir> {
247    pub owner_id: MaybeExternId<OwnerId>,
248    pub generics: Generics<'fhir>,
249    pub kind: ItemKind<'fhir>,
250}
251
252impl<'fhir> Item<'fhir> {
253    pub fn expect_enum(&self) -> &EnumDef<'fhir> {
254        if let ItemKind::Enum(enum_def) = &self.kind { enum_def } else { bug!("expected enum") }
255    }
256
257    pub fn expect_struct(&self) -> &StructDef<'fhir> {
258        if let ItemKind::Struct(struct_def) = &self.kind {
259            struct_def
260        } else {
261            bug!("expected struct")
262        }
263    }
264
265    pub fn expect_type_alias(&self) -> &TyAlias<'fhir> {
266        if let ItemKind::TyAlias(ty_alias) = &self.kind {
267            ty_alias
268        } else {
269            bug!("expected type alias")
270        }
271    }
272
273    pub fn expect_impl(&self) -> &Impl<'fhir> {
274        if let ItemKind::Impl(impl_) = &self.kind { impl_ } else { bug!("expected impl") }
275    }
276
277    pub fn expect_trait(&self) -> &Trait<'fhir> {
278        if let ItemKind::Trait(trait_) = &self.kind { trait_ } else { bug!("expected trait") }
279    }
280}
281
282#[derive(Debug)]
283pub enum ItemKind<'fhir> {
284    Enum(EnumDef<'fhir>),
285    Struct(StructDef<'fhir>),
286    TyAlias(&'fhir TyAlias<'fhir>),
287    Trait(Trait<'fhir>),
288    Impl(Impl<'fhir>),
289    Fn(FnSig<'fhir>),
290    Const(Option<Expr<'fhir>>),
291    Static(Option<Ty<'fhir>>),
292}
293
294#[derive(Debug)]
295pub struct TraitItem<'fhir> {
296    pub owner_id: MaybeExternId<OwnerId>,
297    pub generics: Generics<'fhir>,
298    pub kind: TraitItemKind<'fhir>,
299}
300
301#[derive(Debug)]
302pub enum TraitItemKind<'fhir> {
303    Fn(FnSig<'fhir>),
304    Const,
305    Type,
306}
307
308#[derive(Debug)]
309pub struct ImplItem<'fhir> {
310    pub owner_id: MaybeExternId<OwnerId>,
311    pub kind: ImplItemKind<'fhir>,
312    pub generics: Generics<'fhir>,
313}
314
315#[derive(Debug)]
316pub enum ImplItemKind<'fhir> {
317    Fn(FnSig<'fhir>),
318    Const,
319    Type,
320}
321
322#[derive(Copy, Clone, Debug)]
323pub enum FluxItem<'fhir> {
324    Qualifier(&'fhir Qualifier<'fhir>),
325    Func(&'fhir SpecFunc<'fhir>),
326    PrimOpProp(&'fhir PrimOpProp<'fhir>),
327    Axiom(&'fhir Axiom<'fhir>),
328    SortDecl(&'fhir SortDecl),
329}
330
331impl FluxItem<'_> {
332    pub fn def_id(self) -> FluxLocalDefId {
333        match self {
334            FluxItem::Qualifier(qualifier) => qualifier.def_id,
335            FluxItem::Func(func) => func.def_id,
336            FluxItem::PrimOpProp(prop) => prop.def_id,
337            FluxItem::Axiom(axiom) => axiom.def_id,
338            FluxItem::SortDecl(sort_decl) => sort_decl.def_id,
339        }
340    }
341}
342
343#[derive(Debug)]
344pub struct ForeignItem<'fhir> {
345    pub ident: Ident,
346    pub kind: ForeignItemKind<'fhir>,
347    pub owner_id: MaybeExternId<OwnerId>,
348    pub span: Span,
349}
350
351#[derive(Debug)]
352pub enum ForeignItemKind<'fhir> {
353    Fn(FnSig<'fhir>, &'fhir Generics<'fhir>),
354    Static(Ty<'fhir>, Mutability, Safety, &'fhir Generics<'fhir>),
355}
356
357#[derive(Debug, Clone, Copy)]
358pub struct SortDecl {
359    pub def_id: FluxLocalDefId,
360    pub params: usize,
361    pub span: Span,
362}
363
364pub type SortDecls = UnordMap<Symbol, SortDecl>;
365
366#[derive(Debug, Clone, Copy)]
367pub struct WhereBoundPredicate<'fhir> {
368    pub span: Span,
369    pub bounded_ty: Ty<'fhir>,
370    pub bounds: GenericBounds<'fhir>,
371}
372
373pub type GenericBounds<'fhir> = &'fhir [GenericBound<'fhir>];
374
375#[derive(Debug, Clone, Copy)]
376pub enum GenericBound<'fhir> {
377    Trait(PolyTraitRef<'fhir>),
378    Outlives,
379}
380
381#[derive(Debug, Clone, Copy)]
382pub struct PolyTraitRef<'fhir> {
383    pub bound_generic_params: &'fhir [GenericParam<'fhir>],
384    /// To represent binders for closures i.e. in Fn* traits; see tests/pos/surface/closure{07,08,09,10}.rs
385    pub refine_params: &'fhir [RefineParam<'fhir>],
386    pub modifiers: TraitBoundModifier,
387    pub trait_ref: Path<'fhir>,
388    pub span: Span,
389}
390
391#[derive(Debug, Copy, Clone)]
392pub enum TraitBoundModifier {
393    None,
394    Maybe,
395}
396
397#[derive(Debug)]
398pub struct Trait<'fhir> {
399    pub assoc_refinements: &'fhir [TraitAssocReft<'fhir>],
400}
401
402impl<'fhir> Trait<'fhir> {
403    pub fn find_assoc_reft(&self, name: Symbol) -> Option<&'fhir TraitAssocReft<'fhir>> {
404        self.assoc_refinements
405            .iter()
406            .find(|assoc_reft| assoc_reft.name == name)
407    }
408}
409
410#[derive(Debug, Clone, Copy)]
411pub struct TraitAssocReft<'fhir> {
412    pub name: Symbol,
413    pub params: &'fhir [RefineParam<'fhir>],
414    pub output: Sort<'fhir>,
415    pub body: Option<Expr<'fhir>>,
416    pub span: Span,
417    pub final_: bool,
418}
419
420#[derive(Debug)]
421pub struct Impl<'fhir> {
422    pub assoc_refinements: &'fhir [ImplAssocReft<'fhir>],
423}
424
425impl<'fhir> Impl<'fhir> {
426    pub fn find_assoc_reft(&self, name: Symbol) -> Option<&'fhir ImplAssocReft<'fhir>> {
427        self.assoc_refinements
428            .iter()
429            .find(|assoc_reft| assoc_reft.name == name)
430    }
431}
432
433#[derive(Clone, Copy, Debug)]
434pub struct ImplAssocReft<'fhir> {
435    pub name: Symbol,
436    pub params: &'fhir [RefineParam<'fhir>],
437    pub output: Sort<'fhir>,
438    pub body: Expr<'fhir>,
439    pub span: Span,
440}
441
442#[derive(Debug)]
443pub struct OpaqueTy<'fhir> {
444    pub def_id: MaybeExternId,
445    pub bounds: GenericBounds<'fhir>,
446}
447
448pub type Arena = bumpalo::Bump;
449
450/// A map between rust definitions and flux annotations in their desugared `fhir` form.
451///
452/// note: most items in this struct have been moved out into their own query or method in genv.
453/// We should eventually get rid of this or change its name.
454#[derive(Default)]
455pub struct FluxItems<'fhir> {
456    pub items: FxIndexMap<FluxLocalDefId, FluxItem<'fhir>>,
457}
458
459impl FluxItems<'_> {
460    pub fn new() -> Self {
461        Self { items: Default::default() }
462    }
463}
464
465#[derive(Debug)]
466pub struct TyAlias<'fhir> {
467    pub index: Option<RefineParam<'fhir>>,
468    pub ty: Ty<'fhir>,
469    pub span: Span,
470    /// Whether this alias was lifted from a `hir` alias
471    pub lifted: bool,
472}
473
474#[derive(Debug, Clone, Copy)]
475pub struct StructDef<'fhir> {
476    pub refinement: &'fhir RefinementKind<'fhir>,
477    pub params: &'fhir [RefineParam<'fhir>],
478    pub kind: StructKind<'fhir>,
479    pub invariants: &'fhir [Expr<'fhir>],
480}
481
482#[derive(Debug, Clone, Copy)]
483pub enum StructKind<'fhir> {
484    Transparent { fields: &'fhir [FieldDef<'fhir>] },
485    Opaque,
486}
487
488#[derive(Debug, Clone, Copy)]
489pub struct FieldDef<'fhir> {
490    pub ty: Ty<'fhir>,
491    /// Whether this field was lifted from a `hir` field
492    pub lifted: bool,
493}
494
495#[derive(Debug)]
496pub enum RefinementKind<'fhir> {
497    /// User specified indices (e.g. length, elems, etc.)
498    Refined(RefinedBy<'fhir>),
499    /// Singleton refinements e.g. `State[On]`, `State[Off]`
500    Reflected,
501}
502
503impl RefinementKind<'_> {
504    pub fn is_reflected(&self) -> bool {
505        matches!(self, RefinementKind::Reflected)
506    }
507}
508
509#[derive(Debug)]
510pub struct EnumDef<'fhir> {
511    pub refinement: &'fhir RefinementKind<'fhir>,
512    pub params: &'fhir [RefineParam<'fhir>],
513    pub variants: &'fhir [VariantDef<'fhir>],
514    pub invariants: &'fhir [Expr<'fhir>],
515}
516
517#[derive(Debug, Clone, Copy)]
518pub struct VariantDef<'fhir> {
519    pub def_id: LocalDefId,
520    pub params: &'fhir [RefineParam<'fhir>],
521    pub fields: &'fhir [FieldDef<'fhir>],
522    pub ret: VariantRet<'fhir>,
523    pub span: Span,
524    /// Whether this variant was lifted from a hir variant
525    pub lifted: bool,
526}
527
528#[derive(Debug, Clone, Copy)]
529pub struct VariantRet<'fhir> {
530    pub enum_id: DefId,
531    pub idx: Expr<'fhir>,
532}
533
534#[derive(Clone, Copy)]
535pub struct FnDecl<'fhir> {
536    pub requires: &'fhir [Requires<'fhir>],
537    pub inputs: &'fhir [Ty<'fhir>],
538    pub output: FnOutput<'fhir>,
539    pub span: Span,
540    /// Whether the sig was lifted from a hir signature
541    pub lifted: bool,
542}
543
544/// A predicate required to hold before calling a function.
545#[derive(Clone, Copy)]
546pub struct Requires<'fhir> {
547    /// An (optional) list of universally quantified parameters
548    pub params: &'fhir [RefineParam<'fhir>],
549    pub pred: Expr<'fhir>,
550}
551
552#[derive(Clone, Copy)]
553pub struct FnSig<'fhir> {
554    pub header: FnHeader,
555    pub decl: &'fhir FnDecl<'fhir>,
556    pub no_panic_if: Option<Expr<'fhir>>,
557}
558
559#[derive(Clone, Copy)]
560pub struct FnOutput<'fhir> {
561    pub params: &'fhir [RefineParam<'fhir>],
562    pub ret: Ty<'fhir>,
563    pub ensures: &'fhir [Ensures<'fhir>],
564}
565
566#[derive(Clone, Copy)]
567pub enum Ensures<'fhir> {
568    /// A type constraint on a location
569    Type(PathExpr<'fhir>, &'fhir Ty<'fhir>),
570    /// A predicate that needs to hold on function exit
571    Pred(Expr<'fhir>),
572}
573
574#[derive(Clone, Copy)]
575pub struct Ty<'fhir> {
576    pub kind: TyKind<'fhir>,
577    pub span: Span,
578}
579
580#[derive(Clone, Copy)]
581pub enum TyKind<'fhir> {
582    /// A type that parses as a [`BaseTy`] but was written without refinements. Most types in
583    /// this category are base types and will be converted into an [existential], e.g., `i32` is
584    /// converted into `∃v:int. i32[v]`. However, this category also contains generic variables
585    /// of kind [type]. We cannot distinguish these syntactially so we resolve them later in the
586    /// analysis.
587    ///
588    /// [existential]: crate::rty::TyKind::Exists
589    /// [type]: GenericParamKind::Type
590    BaseTy(BaseTy<'fhir>),
591    Indexed(BaseTy<'fhir>, Expr<'fhir>),
592    Exists(&'fhir [RefineParam<'fhir>], &'fhir Ty<'fhir>),
593    /// Constrained types `{T | p}` are like existentials but without binders, and are useful
594    /// for specifying constraints on indexed values e.g. `{i32[@a] | 0 <= a}`
595    Constr(Expr<'fhir>, &'fhir Ty<'fhir>),
596    StrgRef(&'fhir PathExpr<'fhir>, &'fhir Ty<'fhir>),
597    Ref(&'fhir Ty<'fhir>, Mutability),
598    BareFn(&'fhir BareFnTy<'fhir>),
599    Tuple(&'fhir [Ty<'fhir>]),
600    Array(&'fhir Ty<'fhir>, ConstArg),
601    OpaqueDef(&'fhir OpaqueTy<'fhir>),
602    TraitObject(&'fhir [PolyTraitRef<'fhir>], TraitObjectSyntax),
603    Never,
604    Infer,
605    Err(ErrorGuaranteed),
606}
607
608pub struct BareFnTy<'fhir> {
609    /// Refinement params bound by the fn pointer type, e.g., `n` in `fn(i32[@n]) -> i32[n]`
610    pub params: &'fhir [RefineParam<'fhir>],
611    pub safety: Safety,
612    pub abi: rustc_abi::ExternAbi,
613    pub generic_params: &'fhir [GenericParam<'fhir>],
614    pub decl: &'fhir FnDecl<'fhir>,
615    pub param_idents: &'fhir [Option<Ident>],
616}
617
618/// Owner version of [`FluxLocalDefId`]
619#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Encodable, Decodable)]
620pub enum FluxOwnerId {
621    Flux(FluxLocalDefId),
622    Rust(MaybeExternId<OwnerId>),
623}
624
625impl FluxOwnerId {
626    pub fn as_rust(self) -> Option<MaybeExternId<OwnerId>> {
627        match self {
628            FluxOwnerId::Flux(_) => None,
629            FluxOwnerId::Rust(owner_id) => Some(owner_id),
630        }
631    }
632
633    pub fn resolved_id(self) -> Option<DefId> {
634        self.as_rust().map(MaybeExternId::resolved_id)
635    }
636}
637
638/// A unique identifier for a node in the AST. Like [`HirId`] it is composed of an `owner` and a
639/// `local_id`. We don't generate ids for all nodes, but only for those we need to remember
640/// information elaborated during well-formedness checking to later be used during conversion into
641/// [`rty`].
642///
643/// [`rty`]: crate::rty
644/// [`HirId`]: rustc_hir::HirId
645#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, Encodable, Decodable)]
646pub struct FhirId {
647    pub owner: FluxOwnerId,
648    pub local_id: ItemLocalId,
649}
650
651newtype_index! {
652    /// An `ItemLocalId` uniquely identifies something within a given "item-like".
653    #[encodable]
654    pub struct ItemLocalId {}
655}
656
657/// These are types of things that may be refined with indices or existentials
658#[derive(Clone, Copy)]
659pub struct BaseTy<'fhir> {
660    pub kind: BaseTyKind<'fhir>,
661    pub fhir_id: FhirId,
662    pub span: Span,
663}
664
665impl<'fhir> BaseTy<'fhir> {
666    pub fn from_qpath(qpath: QPath<'fhir>, fhir_id: FhirId) -> Self {
667        let span = qpath.span();
668        Self { kind: BaseTyKind::Path(qpath), fhir_id, span }
669    }
670
671    fn as_path(&self) -> Option<Path<'fhir>> {
672        match self.kind {
673            BaseTyKind::Path(QPath::Resolved(None, path)) => Some(path),
674            _ => None,
675        }
676    }
677}
678
679#[derive(Clone, Copy)]
680pub enum BaseTyKind<'fhir> {
681    Path(QPath<'fhir>),
682    Slice(&'fhir Ty<'fhir>),
683    RawPtr(&'fhir Ty<'fhir>, Mutability),
684    Err(ErrorGuaranteed),
685}
686
687#[derive(Clone, Copy)]
688pub enum QPath<'fhir> {
689    Resolved(Option<&'fhir Ty<'fhir>>, Path<'fhir>),
690    TypeRelative(&'fhir Ty<'fhir>, &'fhir PathSegment<'fhir>),
691}
692
693#[derive(Clone, Copy)]
694pub struct Path<'fhir> {
695    pub res: Res,
696    pub fhir_id: FhirId,
697    pub segments: &'fhir [PathSegment<'fhir>],
698    pub refine: &'fhir [Expr<'fhir>],
699    pub span: Span,
700}
701
702impl<'fhir> Path<'fhir> {
703    pub fn last_segment(&self) -> &'fhir PathSegment<'fhir> {
704        self.segments.last().unwrap()
705    }
706}
707
708#[derive(Clone, Copy)]
709pub struct PathSegment<'fhir> {
710    pub ident: Ident,
711    pub res: Res,
712    pub args: &'fhir [GenericArg<'fhir>],
713    pub constraints: &'fhir [AssocItemConstraint<'fhir>],
714}
715
716#[derive(Clone, Copy)]
717pub struct AssocItemConstraint<'fhir> {
718    pub ident: Ident,
719    pub kind: AssocItemConstraintKind<'fhir>,
720}
721
722#[derive(Clone, Copy)]
723pub enum AssocItemConstraintKind<'fhir> {
724    Equality { term: Ty<'fhir> },
725}
726
727#[derive(Clone, Copy)]
728pub enum GenericArg<'fhir> {
729    Type(&'fhir Ty<'fhir>),
730    Const(ConstArg),
731    Infer,
732}
733
734impl<'fhir> GenericArg<'fhir> {
735    pub fn expect_type(&self) -> &'fhir Ty<'fhir> {
736        if let GenericArg::Type(ty) = self { ty } else { bug!("expected `GenericArg::Type`") }
737    }
738}
739
740#[derive(PartialEq, Eq, Clone, Copy)]
741pub struct ConstArg {
742    pub kind: ConstArgKind,
743    pub span: Span,
744}
745
746#[derive(PartialEq, Eq, Clone, Copy)]
747pub enum ConstArgKind {
748    Lit(usize),
749    Param(DefId),
750    Infer,
751}
752
753/// Different kinds of symbols can coexist even if they share the same textual name.
754/// Therefore, they each have a separate universe (known as a "namespace").
755#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
756pub enum Namespace {
757    /// We also put sorts in this namespace.
758    ///
759    /// See [`rustc_hir::def::Namespace::TypeNS`]
760    TypeNS,
761    /// See [`rustc_hir::def::Namespace::ValueNS`]
762    ValueNS,
763    /// See [`rustc_hir::def::Namespace::MacroNS`]
764    MacroNS,
765    /// The refinement namespace includes refinement functions, theory function,
766    /// refinement parameters, ...
767    ReftNS,
768    /// The namespace of solver hints, i.e., qualifiers, axioms and primop properties. These are only
769    /// ever named in attributes like `#[qualifiers(...)]`, `#[axioms(...)]` or `#[properties(...)]`,
770    /// so they get their own namespace
771    /// to avoid clashing with refinement functions and parameters.
772    HintNS,
773}
774
775impl Namespace {
776    /// A human-readable description, used in diagnostics.
777    pub fn descr(self) -> &'static str {
778        match self {
779            Namespace::TypeNS => "type",
780            Namespace::ValueNS => "value",
781            Namespace::MacroNS => "macro",
782            Namespace::ReftNS => "value",
783            Namespace::HintNS => "qualifier, axiom or property",
784        }
785    }
786
787    /// The corresponding [`rustc_hir::def::Namespace`], or `None` for the flux-only namespaces.
788    pub fn to_rustc(self) -> Option<rustc_hir::def::Namespace> {
789        match self {
790            Namespace::TypeNS => Some(rustc_hir::def::Namespace::TypeNS),
791            Namespace::ValueNS => Some(rustc_hir::def::Namespace::ValueNS),
792            Namespace::MacroNS => Some(rustc_hir::def::Namespace::MacroNS),
793            Namespace::ReftNS | Namespace::HintNS => None,
794        }
795    }
796}
797
798impl From<rustc_hir::def::Namespace> for Namespace {
799    fn from(ns: rustc_hir::def::Namespace) -> Self {
800        match ns {
801            rustc_hir::def::Namespace::TypeNS => Namespace::TypeNS,
802            rustc_hir::def::Namespace::ValueNS => Namespace::ValueNS,
803            rustc_hir::def::Namespace::MacroNS => Namespace::MacroNS,
804        }
805    }
806}
807
808/// Flux's analogue of [`rustc_hir::def::PerNS`], carrying one `T` per [`Namespace`] (including the
809/// flux-specific ones), indexable by [`Namespace`].
810#[derive(Debug, Clone)]
811pub struct PerNS<T> {
812    pub type_ns: T,
813    pub value_ns: T,
814    pub macro_ns: T,
815    pub flux_fn_ns: T,
816    pub hint_ns: T,
817}
818
819impl<T> std::ops::Index<Namespace> for PerNS<T> {
820    type Output = T;
821
822    fn index(&self, ns: Namespace) -> &T {
823        match ns {
824            Namespace::TypeNS => &self.type_ns,
825            Namespace::ValueNS => &self.value_ns,
826            Namespace::MacroNS => &self.macro_ns,
827            Namespace::ReftNS => &self.flux_fn_ns,
828            Namespace::HintNS => &self.hint_ns,
829        }
830    }
831}
832
833impl<T> std::ops::IndexMut<Namespace> for PerNS<T> {
834    fn index_mut(&mut self, ns: Namespace) -> &mut T {
835        match ns {
836            Namespace::TypeNS => &mut self.type_ns,
837            Namespace::ValueNS => &mut self.value_ns,
838            Namespace::MacroNS => &mut self.macro_ns,
839            Namespace::ReftNS => &mut self.flux_fn_ns,
840            Namespace::HintNS => &mut self.hint_ns,
841        }
842    }
843}
844
845/// The resolution of a path
846///
847/// The enum contains a subset of the variants in [`rustc_hir::def::Res`] plus some extra variants
848/// for stuff refinements resolve to.
849#[derive(Eq, PartialEq, Debug, Copy, Clone, Encodable, Decodable)]
850pub enum Res<Id = ParamId> {
851    /// See [`rustc_hir::def::Res::Def`]
852    Def(DefKind, DefId),
853    /// See [`rustc_hir::def::Res::PrimTy`]
854    PrimTy(PrimTy),
855    /// See [`rustc_hir::def::Res::SelfTyAlias`]
856    SelfTyAlias {
857        alias_to: DefId,
858        is_trait_impl: bool,
859    },
860    /// See [`rustc_hir::def::Res::SelfTyParam`]
861    SelfTyParam {
862        trait_: DefId,
863    },
864    /// A refinement parameter, e.g., declared with `@n` syntax
865    Param(ParamKind, Id),
866    /// A refinement function defined with `flux::defs! { ... }`
867    GlobalFunc(SpecFuncKind),
868    /// A primitive sort, e.g., `int`, `bool`, `Set`, `Map`.
869    PrimSort(PrimSort),
870    /// A sort parameter inside a polymorphic function or data sort.
871    SortParam(usize),
872    /// A user declared sort.
873    UserSort(FluxDefId),
874    /// A qualifier declared with `flux::defs! { ... }`
875    Qualifier(FluxDefId),
876    /// An axiom declared with `flux::defs! { ... }`
877    Axiom(FluxDefId),
878    /// A primop property declared with `flux::defs! { ... }`
879    Property(FluxDefId),
880    Err,
881}
882
883/// Akin to `rustc_middle::middle::resolve::ModChild` but for flux items defined in a module
884#[derive(Debug, Clone, Copy, Encodable, Decodable)]
885pub struct FluxModChild {
886    pub ident: Ident,
887    pub res: Res<!>,
888}
889
890/// See [`rustc_hir::def::PartialRes`]
891#[derive(Copy, Clone, Debug)]
892pub struct PartialRes<Id = ParamId> {
893    base_res: Res<Id>,
894    unresolved_segments: usize,
895}
896
897impl<Id: Copy> PartialRes<Id> {
898    pub fn new(base_res: Res<Id>) -> Self {
899        Self { base_res, unresolved_segments: 0 }
900    }
901
902    pub fn with_unresolved_segments(base_res: Res<Id>, unresolved_segments: usize) -> Self {
903        Self { base_res, unresolved_segments }
904    }
905
906    #[inline]
907    pub fn base_res(&self) -> Res<Id> {
908        self.base_res
909    }
910
911    pub fn unresolved_segments(&self) -> usize {
912        self.unresolved_segments
913    }
914
915    #[inline]
916    pub fn full_res(&self) -> Option<Res<Id>> {
917        (self.unresolved_segments == 0).then_some(self.base_res)
918    }
919
920    #[inline]
921    pub fn expect_full_res(&self) -> Res<Id> {
922        self.full_res().unwrap_or_else(|| bug!("expected full res"))
923    }
924
925    pub fn is_box(&self, tcx: TyCtxt) -> bool {
926        self.full_res().is_some_and(|res| res.is_box(tcx))
927    }
928
929    pub fn map_param_id<R>(&self, f: impl FnOnce(Id) -> R) -> PartialRes<R> {
930        PartialRes {
931            base_res: self.base_res.map_param_id(f),
932            unresolved_segments: self.unresolved_segments,
933        }
934    }
935}
936
937#[derive(Debug, Clone, Copy)]
938pub struct RefineParam<'fhir> {
939    pub id: ParamId,
940    pub name: Symbol,
941    pub span: Span,
942    pub sort: Sort<'fhir>,
943    pub kind: ParamKind,
944    pub fhir_id: FhirId,
945}
946
947#[derive(Clone, Copy, Debug, PartialEq, Eq, Encodable, Decodable)]
948pub enum ParamMode {
949    Horn,
950    Hindley,
951}
952
953impl From<surface::ParamMode> for ParamMode {
954    fn from(value: surface::ParamMode) -> Self {
955        match value {
956            surface::ParamMode::Horn => Self::Horn,
957            surface::ParamMode::Hindley => Self::Hindley,
958        }
959    }
960}
961
962/// How a parameter was declared in the surface syntax.
963#[derive(PartialEq, Eq, Debug, Clone, Copy, Encodable, Decodable)]
964pub enum ParamKind {
965    /// A parameter declared in an explicit scope, e.g., `fn foo[hdl n: int](x: i32[n])`
966    Explicit(Option<ParamMode>),
967    /// An implicitly scoped parameter declared with `@a` syntax
968    At,
969    /// An implicitly scoped parameter declared with `#a` syntax
970    Pound,
971    /// An implicitly scoped parameter declared with `x: T` syntax.
972    Colon,
973    /// A location declared with `x: &strg T` syntax.
974    Loc,
975    /// A parameter introduced with `x: T` syntax that we know *syntactically* is always and error
976    /// to use inside a refinement. For example, consider the following:
977    /// ```ignore
978    /// fn(x: {v. i32[v] | v > 0}) -> i32[x]
979    /// ```
980    /// In this definition, we know syntactically that `x` binds to a non-base type so it's an error
981    /// to use `x` as an index in the return type.
982    ///
983    /// These parameters should not appear in a desugared item and we only track them during name
984    /// resolution to report errors at the use site.
985    Error,
986}
987
988impl ParamKind {
989    pub fn is_loc(&self) -> bool {
990        matches!(self, ParamKind::Loc)
991    }
992}
993
994/// *Infer*ence *mode* for a parameter.
995#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable)]
996pub enum InferMode {
997    /// Generate a fresh evar for the parameter and solve it via syntactic unification. The parameter
998    /// must appear at least once as an index for unification to succeed, but otherwise it can appear
999    /// (mostly) freely.
1000    EVar,
1001    /// Generate a fresh kvar and let fixpoint infer it. This mode can only be used with abstract
1002    /// refinement predicates. If the parameter is marked as kvar then it can only appear in
1003    /// positions that will result in a _horn_ constraint as required by fixpoint.
1004    KVar,
1005}
1006
1007impl InferMode {
1008    pub fn from_param_kind(kind: ParamKind) -> InferMode {
1009        if let ParamKind::Explicit(Some(ParamMode::Horn)) = kind {
1010            InferMode::KVar
1011        } else {
1012            InferMode::EVar
1013        }
1014    }
1015
1016    pub fn prefix_str(self) -> &'static str {
1017        match self {
1018            InferMode::EVar => "?",
1019            InferMode::KVar => "$",
1020        }
1021    }
1022}
1023
1024/// `bool`, `char`, and `str` are primitive sorts, but because sorts and types are in the same
1025/// namespace we resolve them to [`Res::PrimTy`] and then make them into a sort during `conv`
1026/// they share their name with the
1027#[derive(Debug, Eq, PartialEq, Clone, Copy, Encodable, Decodable)]
1028pub enum PrimSort {
1029    Int,
1030    Real,
1031    Set,
1032    Map,
1033    RawPtr,
1034    Bool,
1035    Char,
1036    Str,
1037}
1038
1039impl PrimSort {
1040    pub const ALL: [Self; 8] = [
1041        Self::Int,
1042        Self::Real,
1043        Self::Set,
1044        Self::Map,
1045        Self::RawPtr,
1046        Self::Bool,
1047        Self::Char,
1048        Self::Str,
1049    ];
1050
1051    pub fn name(self) -> Symbol {
1052        match self {
1053            PrimSort::Int => sym::int,
1054            PrimSort::Real => sym::real,
1055            PrimSort::Set => sym::Set,
1056            PrimSort::Map => sym::Map,
1057            PrimSort::RawPtr => sym::ptr,
1058            PrimSort::Bool => sym::bool,
1059            PrimSort::Char => sym::char,
1060            PrimSort::Str => sym::str,
1061        }
1062    }
1063    pub fn name_str(self) -> &'static str {
1064        match self {
1065            PrimSort::Int => "int",
1066            PrimSort::Real => "real",
1067            PrimSort::Set => "Set",
1068            PrimSort::Map => "Map",
1069            PrimSort::RawPtr => "ptr",
1070            PrimSort::Bool => "bool",
1071            PrimSort::Char => "char",
1072            PrimSort::Str => "str",
1073        }
1074    }
1075
1076    /// Number of generics expected by this primitive sort
1077    pub fn generics(self) -> usize {
1078        match self {
1079            PrimSort::Bool
1080            | PrimSort::Char
1081            | PrimSort::Str
1082            | PrimSort::Int
1083            | PrimSort::Real
1084            | PrimSort::RawPtr => 0,
1085            PrimSort::Set => 1,
1086            PrimSort::Map => 2,
1087        }
1088    }
1089}
1090
1091#[derive(Clone, Copy)]
1092pub enum Sort<'fhir> {
1093    Path(SortPath<'fhir>),
1094    /// The sort of a location parameter introduced with the `x: &strg T` syntax.
1095    Loc,
1096    /// A bit vector with the given width.
1097    BitVec(u32),
1098    /// A polymorphic sort function.
1099    Func(PolyFuncSort<'fhir>),
1100    /// The sort associated with a base type. This is normalized into a concrete sort during
1101    /// conversion
1102    SortOf(BaseTy<'fhir>),
1103    /// A tuple sort, e.g., (int, bool)
1104    Tuple(&'fhir [Sort<'fhir>]),
1105    /// A sort that needs to be inferred.
1106    Infer,
1107    Err(ErrorGuaranteed),
1108}
1109
1110/// See [`flux_syntax::surface::SortPath`]
1111#[derive(Clone, Copy)]
1112pub struct SortPath<'fhir> {
1113    pub res: PartialRes,
1114    pub segments: &'fhir [Ident],
1115    pub args: &'fhir [Sort<'fhir>],
1116}
1117
1118#[derive(Clone, Copy)]
1119pub struct FuncSort<'fhir> {
1120    /// inputs and output in order
1121    pub inputs_and_output: &'fhir [Sort<'fhir>],
1122}
1123
1124#[derive(Clone, Copy)]
1125pub struct PolyFuncSort<'fhir> {
1126    pub params: usize,
1127    pub fsort: FuncSort<'fhir>,
1128}
1129
1130impl<'fhir> PolyFuncSort<'fhir> {
1131    pub fn new(params: usize, inputs_and_output: &'fhir [Sort]) -> Self {
1132        let fsort = FuncSort { inputs_and_output };
1133        Self { params, fsort }
1134    }
1135}
1136
1137/// `<qself as path>::name`
1138#[derive(Clone, Copy)]
1139pub enum AliasReft<'fhir> {
1140    /// A fully qualified associated refinement `<qself as trait_>::name`
1141    Qualified { qself: &'fhir Ty<'fhir>, trait_: Path<'fhir>, name: Ident },
1142    /// A type-relative associated refinement, e.g., `Self::name`. Note that
1143    /// we can only resolve this when `ty` is a parameter, similar to how
1144    /// type-relative associated types are resolved.
1145    TypeRelative { qself: &'fhir Ty<'fhir>, name: Ident },
1146}
1147
1148#[derive(Debug, Clone, Copy)]
1149pub struct FieldExpr<'fhir> {
1150    pub ident: Ident,
1151    pub expr: Expr<'fhir>,
1152    pub fhir_id: FhirId,
1153    pub span: Span,
1154}
1155
1156#[derive(Debug, Clone, Copy)]
1157pub struct Spread<'fhir> {
1158    pub expr: Expr<'fhir>,
1159    pub span: Span,
1160    pub fhir_id: FhirId,
1161}
1162
1163#[derive(Clone, Copy)]
1164pub struct Expr<'fhir> {
1165    pub kind: ExprKind<'fhir>,
1166    pub fhir_id: FhirId,
1167    pub span: Span,
1168}
1169
1170#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable)]
1171pub enum QuantKind {
1172    Forall,
1173    Exists,
1174}
1175
1176#[derive(Clone, Copy)]
1177pub enum QuantDom {
1178    Bounded { start: usize, end: usize },
1179    Unbounded,
1180}
1181
1182#[derive(Clone, Copy)]
1183pub enum ExprKind<'fhir> {
1184    Var(QPathExpr<'fhir>),
1185    Dot(&'fhir Expr<'fhir>, Ident),
1186    Literal(Lit),
1187    BinaryOp(BinOp, &'fhir Expr<'fhir>, &'fhir Expr<'fhir>),
1188    UnaryOp(UnOp, &'fhir Expr<'fhir>),
1189    App(PathExpr<'fhir>, &'fhir [Expr<'fhir>]),
1190    /// UIF application representing a primitive operation, e.g. `[<<](x, y)`
1191    PrimApp(BinOp, &'fhir Expr<'fhir>, &'fhir Expr<'fhir>),
1192    Alias(AliasReft<'fhir>, &'fhir [Expr<'fhir>]),
1193    IfThenElse(&'fhir Expr<'fhir>, &'fhir Expr<'fhir>, &'fhir Expr<'fhir>),
1194    Abs(&'fhir [RefineParam<'fhir>], &'fhir Expr<'fhir>),
1195    Quant(QuantKind, RefineParam<'fhir>, QuantDom, &'fhir Expr<'fhir>),
1196    Record(&'fhir [Expr<'fhir>]),
1197    SetLiteral(&'fhir [Expr<'fhir>]),
1198    Constructor(Option<PathExpr<'fhir>>, &'fhir [FieldExpr<'fhir>], Option<&'fhir Spread<'fhir>>),
1199    Block(&'fhir [LetDecl<'fhir>], &'fhir Expr<'fhir>),
1200    Tuple(&'fhir [Expr<'fhir>]),
1201    Err(ErrorGuaranteed),
1202}
1203
1204#[derive(Clone, Copy)]
1205pub enum QPathExpr<'fhir> {
1206    Resolved(PathExpr<'fhir>, Option<ParamKind>),
1207    TypeRelative(&'fhir Ty<'fhir>, Ident),
1208}
1209
1210#[derive(Clone, Copy)]
1211pub struct LetDecl<'fhir> {
1212    pub param: RefineParam<'fhir>,
1213    pub init: Expr<'fhir>,
1214}
1215
1216#[derive(Clone, Copy)]
1217pub enum Lit {
1218    Int(u128),
1219    Real(Symbol),
1220    Bool(bool),
1221    Str(Symbol),
1222    Char(char),
1223}
1224
1225#[derive(Clone, Copy)]
1226pub struct PathExpr<'fhir> {
1227    pub segments: &'fhir [Ident],
1228    pub res: Res,
1229    pub fhir_id: FhirId,
1230    pub span: Span,
1231}
1232
1233impl<'fhir> PathExpr<'fhir> {
1234    pub fn name(&self) -> Option<Symbol> {
1235        self.segments.last().map(|ident| ident.name)
1236    }
1237}
1238
1239newtype_index! {
1240    #[debug_format = "a{}"]
1241    #[encodable]
1242    pub struct ParamId {}
1243}
1244
1245impl PolyTraitRef<'_> {
1246    pub fn trait_def_id(&self) -> DefId {
1247        let path = &self.trait_ref;
1248        if let Res::Def(DefKind::Trait, did) = path.res {
1249            did
1250        } else {
1251            span_bug!(path.span, "unexpected resolution {:?}", path.res);
1252        }
1253    }
1254}
1255
1256impl From<MaybeExternId<OwnerId>> for FluxOwnerId {
1257    fn from(owner_id: MaybeExternId<OwnerId>) -> Self {
1258        FluxOwnerId::Rust(owner_id)
1259    }
1260}
1261
1262impl<'fhir> Ty<'fhir> {
1263    pub fn as_path(&self) -> Option<Path<'fhir>> {
1264        match &self.kind {
1265            TyKind::BaseTy(bty) => bty.as_path(),
1266            _ => None,
1267        }
1268    }
1269}
1270
1271impl<Id> Res<Id> {
1272    pub fn descr(&self) -> &'static str {
1273        match self {
1274            Res::PrimTy(_) => "builtin type",
1275            Res::Def(kind, def_id) => kind.descr(*def_id),
1276            Res::SelfTyAlias { .. } | Res::SelfTyParam { .. } => "self type",
1277            Res::Param(..) => "refinement parameter",
1278            Res::GlobalFunc(..) => "refinement function",
1279            Res::PrimSort(..) => "primitive sort",
1280            Res::SortParam(..) => "sort parameter",
1281            Res::UserSort(..) => "user-defined sort",
1282            Res::Qualifier(..) => "qualifier",
1283            Res::Axiom(..) => "axiom",
1284            Res::Property(..) => "property",
1285            Res::Err => "unresolved item",
1286        }
1287    }
1288
1289    pub fn is_box(&self, tcx: TyCtxt) -> bool {
1290        if let Res::Def(DefKind::Struct, def_id) = self {
1291            tcx.adt_def(*def_id).is_box()
1292        } else {
1293            false
1294        }
1295    }
1296
1297    /// Returns `None` if this is `Res::Err`
1298    pub fn ns(&self) -> Option<Namespace> {
1299        match self {
1300            Res::Def(kind, ..) => kind.ns().map(Namespace::from),
1301            Res::PrimTy(..) | Res::SelfTyAlias { .. } | Res::SelfTyParam { .. } => {
1302                Some(Namespace::TypeNS)
1303            }
1304            Res::Param(..) | Res::GlobalFunc(..) => Some(Namespace::ReftNS),
1305            // Sorts share the type namespace: primitive sorts live in the type prelude and
1306            // sort parameters in the type ribs, so they resolve through `TypeNS` alongside types.
1307            Res::PrimSort(..) | Res::SortParam(..) | Res::UserSort(..) => Some(Namespace::TypeNS),
1308            Res::Qualifier(..) | Res::Axiom(..) | Res::Property(..) => Some(Namespace::HintNS),
1309            Res::Err => None,
1310        }
1311    }
1312
1313    /// Always returns `true` if `self` is `Res::Err`
1314    pub fn matches_ns(&self, ns: Namespace) -> bool {
1315        self.ns().is_none_or(|actual_ns| actual_ns == ns)
1316    }
1317
1318    pub fn map_param_id<R>(self, f: impl FnOnce(Id) -> R) -> Res<R> {
1319        match self {
1320            Res::Param(kind, param_id) => Res::Param(kind, f(param_id)),
1321            Res::Def(def_kind, def_id) => Res::Def(def_kind, def_id),
1322            Res::PrimTy(prim_ty) => Res::PrimTy(prim_ty),
1323            Res::SelfTyAlias { alias_to, is_trait_impl } => {
1324                Res::SelfTyAlias { alias_to, is_trait_impl }
1325            }
1326            Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
1327            Res::GlobalFunc(spec_func_kind) => Res::GlobalFunc(spec_func_kind),
1328            Res::PrimSort(prim_sort) => Res::PrimSort(prim_sort),
1329            Res::SortParam(n) => Res::SortParam(n),
1330            Res::UserSort(def_id) => Res::UserSort(def_id),
1331            Res::Qualifier(def_id) => Res::Qualifier(def_id),
1332            Res::Axiom(def_id) => Res::Axiom(def_id),
1333            Res::Property(def_id) => Res::Property(def_id),
1334            Res::Err => Res::Err,
1335        }
1336    }
1337
1338    pub fn expect_param(self) -> (ParamKind, Id) {
1339        if let Res::Param(kind, id) = self { (kind, id) } else { bug!("expected param") }
1340    }
1341}
1342
1343impl<Id1, Id2> TryFrom<rustc_hir::def::Res<Id1>> for Res<Id2> {
1344    type Error = ();
1345
1346    fn try_from(res: rustc_hir::def::Res<Id1>) -> Result<Self, Self::Error> {
1347        match res {
1348            rustc_hir::def::Res::Def(kind, did) => Ok(Res::Def(kind, did)),
1349            rustc_hir::def::Res::PrimTy(prim_ty) => Ok(Res::PrimTy(prim_ty)),
1350            rustc_hir::def::Res::SelfTyAlias { alias_to, is_trait_impl } => {
1351                Ok(Res::SelfTyAlias { alias_to, is_trait_impl })
1352            }
1353            rustc_hir::def::Res::SelfTyParam { trait_ } => Ok(Res::SelfTyParam { trait_ }),
1354            rustc_hir::def::Res::Err => Ok(Res::Err),
1355            _ => Err(()),
1356        }
1357    }
1358}
1359
1360impl QPath<'_> {
1361    pub fn span(&self) -> Span {
1362        match self {
1363            QPath::Resolved(_, path) => path.span,
1364            QPath::TypeRelative(qself, assoc) => qself.span.to(assoc.ident.span),
1365        }
1366    }
1367}
1368
1369impl Lit {
1370    pub const TRUE: Lit = Lit::Bool(true);
1371}
1372
1373/// Information about the refinement parameters associated with an adt (struct/enum).
1374#[derive(Clone, Debug)]
1375pub struct RefinedBy<'fhir> {
1376    /// When a `#[flux::refined_by(..)]` annotation mentions generic type parameters we implicitly
1377    /// generate a *polymorphic* data sort.
1378    ///
1379    /// For example, if we have:
1380    /// ```ignore
1381    /// #[refined_by(keys: Set<K>)]
1382    /// RMap<K, V> { ... }
1383    /// ```
1384    /// we implicitly create a data sort of the form `forall #0. { keys: Set<#0> }`, where `#0` is a
1385    /// *sort variable*.
1386    ///
1387    /// This [`FxIndexSet`] is used to track a mapping between sort variables and their corresponding
1388    /// type parameter. The [`DefId`] is the id of the type parameter and its index in the set is the
1389    /// position of the sort variable.
1390    pub sort_params: FxIndexSet<DefId>,
1391    /// Fields indexed by their name in the same order they appear in the `#[refined_by(..)]` annotation.
1392    pub fields: FxIndexMap<Symbol, Sort<'fhir>>,
1393}
1394
1395#[derive(Debug)]
1396pub struct SpecFunc<'fhir> {
1397    pub def_id: FluxLocalDefId,
1398    pub params: usize,
1399    pub args: &'fhir [RefineParam<'fhir>],
1400    pub sort: Sort<'fhir>,
1401    pub body: Option<Expr<'fhir>>,
1402    pub hide: bool,
1403    pub ident_span: Span,
1404}
1405#[derive(Debug)]
1406pub struct PrimOpProp<'fhir> {
1407    pub def_id: FluxLocalDefId,
1408    pub kind: HintKind,
1409    pub op: BinOp,
1410    pub args: &'fhir [RefineParam<'fhir>],
1411    pub body: Expr<'fhir>,
1412    pub span: Span,
1413}
1414
1415/// A (global) axiom: `body` is assumed to hold for all values of `args`.
1416#[derive(Debug)]
1417pub struct Axiom<'fhir> {
1418    pub def_id: FluxLocalDefId,
1419    pub args: &'fhir [RefineParam<'fhir>],
1420    pub body: Expr<'fhir>,
1421    pub span: Span,
1422    pub kind: HintKind,
1423}
1424
1425#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable)]
1426pub enum SpecFuncKind {
1427    /// Theory symbols *interpreted* by the SMT solver
1428    Thy(liquid_fixpoint::ThyFunc),
1429    /// User-defined function. This can be either a function with a body or a UIF.
1430    Def(FluxDefId),
1431    /// Casts between sorts: id for char, int; if-then-else for bool-int; uninterpreted otherwise.
1432    Cast,
1433}
1434
1435impl SpecFuncKind {
1436    pub fn def_id(&self) -> Option<FluxDefId> {
1437        match self {
1438            SpecFuncKind::Def(flux_id) => Some(*flux_id),
1439            _ => None,
1440        }
1441    }
1442}
1443
1444impl<'fhir> Generics<'fhir> {
1445    pub fn get_param(&self, def_id: LocalDefId) -> &'fhir GenericParam<'fhir> {
1446        self.params
1447            .iter()
1448            .find(|p| p.def_id.local_id() == def_id)
1449            .unwrap()
1450    }
1451
1452    pub fn empty(genv: GlobalEnv<'fhir, '_>) -> Self {
1453        let params = genv.alloc_slice_fill_iter(iter::empty());
1454        Self { params, refinement_params: &[], predicates: None }
1455    }
1456}
1457
1458impl<'fhir> RefinedBy<'fhir> {
1459    pub fn new(fields: FxIndexMap<Symbol, Sort<'fhir>>, sort_params: FxIndexSet<DefId>) -> Self {
1460        RefinedBy { sort_params, fields }
1461    }
1462
1463    pub fn trivial() -> Self {
1464        RefinedBy { sort_params: Default::default(), fields: Default::default() }
1465    }
1466}
1467
1468impl<'fhir> From<PolyFuncSort<'fhir>> for Sort<'fhir> {
1469    fn from(fsort: PolyFuncSort<'fhir>) -> Self {
1470        Self::Func(fsort)
1471    }
1472}
1473
1474impl FuncSort<'_> {
1475    pub fn inputs(&self) -> &[Sort<'_>] {
1476        &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1477    }
1478
1479    pub fn output(&self) -> &Sort<'_> {
1480        &self.inputs_and_output[self.inputs_and_output.len() - 1]
1481    }
1482}
1483
1484impl rustc_errors::IntoDiagArg for Ty<'_> {
1485    fn into_diag_arg(self, _path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
1486        rustc_errors::DiagArgValue::Str(Cow::Owned(format!("{self:?}")))
1487    }
1488}
1489
1490impl rustc_errors::IntoDiagArg for Path<'_> {
1491    fn into_diag_arg(self, _path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
1492        rustc_errors::DiagArgValue::Str(Cow::Owned(format!("{self:?}")))
1493    }
1494}
1495
1496impl StructDef<'_> {
1497    pub fn is_opaque(&self) -> bool {
1498        matches!(self.kind, StructKind::Opaque)
1499    }
1500}
1501
1502impl fmt::Debug for FnSig<'_> {
1503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1504        write!(f, "{:?}", self.decl)
1505    }
1506}
1507
1508impl fmt::Debug for FnDecl<'_> {
1509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1510        if !self.requires.is_empty() {
1511            write!(f, "[{:?}] ", self.requires.iter().format(", "))?;
1512        }
1513        write!(f, "fn({:?}) -> {:?}", self.inputs.iter().format(", "), self.output)
1514    }
1515}
1516
1517impl fmt::Debug for FnOutput<'_> {
1518    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1519        if !self.params.is_empty() {
1520            write!(
1521                f,
1522                "exists<{}> ",
1523                self.params.iter().format_with(", ", |param, f| {
1524                    f(&format_args!("{}: {:?}", param.name, param.sort))
1525                })
1526            )?;
1527        }
1528        write!(f, "{:?}", self.ret)?;
1529        if !self.ensures.is_empty() {
1530            write!(f, "; [{:?}]", self.ensures.iter().format(", "))?;
1531        }
1532
1533        Ok(())
1534    }
1535}
1536
1537impl fmt::Debug for Requires<'_> {
1538    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1539        if !self.params.is_empty() {
1540            write!(
1541                f,
1542                "forall {}.",
1543                self.params.iter().format_with(",", |param, f| {
1544                    f(&format_args!("{}:{:?}", param.name, param.sort))
1545                })
1546            )?;
1547        }
1548        write!(f, "{:?}", self.pred)
1549    }
1550}
1551
1552impl fmt::Debug for Ensures<'_> {
1553    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1554        match self {
1555            Ensures::Type(loc, ty) => write!(f, "{loc:?}: {ty:?}"),
1556            Ensures::Pred(e) => write!(f, "{e:?}"),
1557        }
1558    }
1559}
1560
1561impl fmt::Debug for Ty<'_> {
1562    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1563        match &self.kind {
1564            TyKind::BaseTy(bty) => write!(f, "{bty:?}"),
1565            TyKind::Indexed(bty, idx) => write!(f, "{bty:?}[{idx:?}]"),
1566            TyKind::Exists(params, ty) => {
1567                write!(f, "{{")?;
1568                write!(
1569                    f,
1570                    "{}",
1571                    params.iter().format_with(",", |param, f| {
1572                        f(&format_args!("{}:{:?}", param.name, param.sort))
1573                    })
1574                )?;
1575                if let TyKind::Constr(pred, ty) = &ty.kind {
1576                    write!(f, ". {ty:?} | {pred:?}}}")
1577                } else {
1578                    write!(f, ". {ty:?}}}")
1579                }
1580            }
1581            TyKind::StrgRef(loc, ty) => write!(f, "&strg <{loc:?}: {ty:?}>"),
1582            TyKind::Ref(ty, mutbl) => {
1583                write!(f, "&{}{:?}", mutbl.prefix_str(), ty)
1584            }
1585            TyKind::BareFn(bare_fn_ty) => {
1586                write!(f, "{bare_fn_ty:?}")
1587            }
1588            TyKind::Tuple(tys) => write!(f, "({:?})", tys.iter().format(", ")),
1589            TyKind::Array(ty, len) => write!(f, "[{ty:?}; {len:?}]"),
1590            TyKind::Never => write!(f, "!"),
1591            TyKind::Constr(pred, ty) => write!(f, "{{{ty:?} | {pred:?}}}"),
1592            TyKind::Infer => write!(f, "_"),
1593            TyKind::OpaqueDef(opaque_ty) => {
1594                write!(f, "impl trait <def_id = {:?}>", opaque_ty.def_id.resolved_id(),)
1595            }
1596            TyKind::TraitObject(poly_traits, _syntax) => {
1597                write!(f, "dyn {poly_traits:?}")
1598            }
1599            TyKind::Err(_) => write!(f, "err"),
1600        }
1601    }
1602}
1603
1604impl fmt::Debug for BareFnTy<'_> {
1605    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1606        if !self.generic_params.is_empty() {
1607            write!(
1608                f,
1609                "for<{}>",
1610                self.generic_params
1611                    .iter()
1612                    .map(|param| param.name.ident())
1613                    .format(",")
1614            )?;
1615        }
1616        write!(f, "{:?}", self.decl)
1617    }
1618}
1619
1620impl fmt::Debug for ConstArg {
1621    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1622        write!(f, "{:?}", self.kind)
1623    }
1624}
1625
1626impl fmt::Debug for ConstArgKind {
1627    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1628        match self {
1629            ConstArgKind::Lit(n) => write!(f, "{n}"),
1630            ConstArgKind::Param(p) => write!(f, "{p:?}"),
1631            ConstArgKind::Infer => write!(f, "_"),
1632        }
1633    }
1634}
1635
1636impl fmt::Debug for BaseTy<'_> {
1637    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1638        match &self.kind {
1639            BaseTyKind::Path(qpath) => write!(f, "{qpath:?}"),
1640            BaseTyKind::Slice(ty) => write!(f, "[{ty:?}]"),
1641            BaseTyKind::RawPtr(ty, Mutability::Not) => write!(f, "*const {ty:?}"),
1642            BaseTyKind::RawPtr(ty, Mutability::Mut) => write!(f, "*mut {ty:?}"),
1643            BaseTyKind::Err(_) => write!(f, "err"),
1644        }
1645    }
1646}
1647
1648impl fmt::Debug for QPath<'_> {
1649    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1650        match self {
1651            QPath::Resolved(_, path) => write!(f, "{path:?}"),
1652            QPath::TypeRelative(qself, assoc) => write!(f, "<{qself:?}>::{assoc:?}"),
1653        }
1654    }
1655}
1656
1657impl fmt::Debug for Path<'_> {
1658    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1659        write!(f, "{:?}", self.segments.iter().format("::"))?;
1660        if !self.refine.is_empty() {
1661            write!(f, "({:?})", self.refine.iter().format(", "))?;
1662        }
1663        Ok(())
1664    }
1665}
1666
1667impl fmt::Debug for PathSegment<'_> {
1668    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1669        write!(f, "{}", self.ident)?;
1670        let args: Vec<_> = self
1671            .args
1672            .iter()
1673            .map(|a| a as &dyn std::fmt::Debug)
1674            .chain(self.constraints.iter().map(|b| b as &dyn std::fmt::Debug))
1675            .collect();
1676        if !args.is_empty() {
1677            write!(f, "<{:?}>", args.iter().format(", "))?;
1678        }
1679        Ok(())
1680    }
1681}
1682
1683impl fmt::Debug for GenericArg<'_> {
1684    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1685        match self {
1686            GenericArg::Type(ty) => write!(f, "{ty:?}"),
1687            GenericArg::Const(cst) => write!(f, "{cst:?}"),
1688            GenericArg::Infer => write!(f, "_"),
1689        }
1690    }
1691}
1692
1693impl fmt::Debug for AssocItemConstraint<'_> {
1694    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1695        match &self.kind {
1696            AssocItemConstraintKind::Equality { term } => {
1697                write!(f, "{:?} = {:?}", self.ident, term)
1698            }
1699        }
1700    }
1701}
1702
1703impl fmt::Debug for AliasReft<'_> {
1704    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1705        match self {
1706            AliasReft::Qualified { qself, trait_, name } => {
1707                write!(f, "<{qself:?} as {trait_:?}>::{name}")
1708            }
1709            AliasReft::TypeRelative { qself, name } => {
1710                write!(f, "{qself:?}::{name}")
1711            }
1712        }
1713    }
1714}
1715
1716impl fmt::Debug for QuantKind {
1717    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1718        match self {
1719            QuantKind::Forall => write!(f, "∀"),
1720            QuantKind::Exists => write!(f, "∃"),
1721        }
1722    }
1723}
1724
1725impl fmt::Debug for QuantDom {
1726    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1727        match self {
1728            QuantDom::Bounded { start, end } => write!(f, "in {start:?} .. {end:?}"),
1729            QuantDom::Unbounded => Ok(()),
1730        }
1731    }
1732}
1733
1734impl fmt::Debug for Expr<'_> {
1735    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1736        match self.kind {
1737            ExprKind::Var(QPathExpr::Resolved(path, ..)) => write!(f, "{path:?}"),
1738            ExprKind::Var(QPathExpr::TypeRelative(qself, assoc)) => {
1739                write!(f, "<{qself:?}>::{assoc}")
1740            }
1741            ExprKind::BinaryOp(op, e1, e2) => write!(f, "({e1:?} {op:?} {e2:?})"),
1742            ExprKind::PrimApp(op, e1, e2) => write!(f, "[{op:?}]({e1:?}, {e2:?})"),
1743            ExprKind::UnaryOp(op, e) => write!(f, "{op:?}{e:?}"),
1744            ExprKind::Literal(lit) => write!(f, "{lit:?}"),
1745            ExprKind::App(uf, es) => write!(f, "{uf:?}({:?})", es.iter().format(", ")),
1746            ExprKind::Alias(alias, refine_args) => {
1747                write!(f, "{alias:?}({:?})", refine_args.iter().format(", "))
1748            }
1749            ExprKind::IfThenElse(p, e1, e2) => {
1750                write!(f, "(if {p:?} {{ {e1:?} }} else {{ {e2:?} }})")
1751            }
1752            ExprKind::Dot(var, fld) => write!(f, "{var:?}.{fld}"),
1753            ExprKind::Abs(params, body) => {
1754                write!(
1755                    f,
1756                    "|{}| {body:?}",
1757                    params.iter().format_with(", ", |param, f| {
1758                        f(&format_args!("{}: {:?}", param.name, param.sort))
1759                    })
1760                )
1761            }
1762            ExprKind::Record(flds) => {
1763                write!(f, "{{ {:?} }}", flds.iter().format(", "))
1764            }
1765            ExprKind::SetLiteral(elems) => {
1766                write!(f, "#{{ {:?} }}", elems.iter().format(", "))
1767            }
1768            ExprKind::Constructor(path, exprs, spread) => {
1769                if let Some(path) = path
1770                    && let Some(s) = spread
1771                {
1772                    write!(f, "{:?} {{ {:?}, ..{:?} }}", path, exprs.iter().format(", "), s)
1773                } else if let Some(path) = path {
1774                    write!(f, "{:?} {{ {:?} }}", path, exprs.iter().format(", "))
1775                } else if let Some(s) = spread {
1776                    write!(f, "{{ {:?} ..{:?} }}", exprs.iter().format(", "), s)
1777                } else {
1778                    write!(f, "{{ {:?} }}", exprs.iter().format(", "))
1779                }
1780            }
1781            ExprKind::Quant(kind, refine_param, dom, expr) => {
1782                write!(f, "{kind:?} {refine_param:?} {dom:?} {{ {expr:?} }}")
1783            }
1784            ExprKind::Err(_) => write!(f, "err"),
1785            ExprKind::Block(decls, body) => {
1786                for decl in decls {
1787                    write!(f, "let {:?} = {:?};", decl.param, decl.init)?;
1788                }
1789                write!(f, "{body:?}")
1790            }
1791            ExprKind::Tuple(exprs) => {
1792                write!(f, "({:?})", exprs.iter().format(", "))
1793            }
1794        }
1795    }
1796}
1797
1798impl fmt::Debug for PathExpr<'_> {
1799    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1800        write!(f, "{}", self.segments.iter().format("::"))
1801    }
1802}
1803
1804impl fmt::Debug for Lit {
1805    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1806        match self {
1807            Lit::Int(i) => write!(f, "{i}"),
1808            Lit::Real(s) => write!(f, "{s}"),
1809            Lit::Bool(b) => write!(f, "{b}"),
1810            Lit::Str(s) => write!(f, "\"{s:?}\""),
1811            Lit::Char(c) => write!(f, "\'{c}\'"),
1812        }
1813    }
1814}
1815
1816impl fmt::Debug for Sort<'_> {
1817    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1818        match self {
1819            Sort::Path(path) => write!(f, "{path:?}"),
1820            Sort::BitVec(w) => write!(f, "bitvec({w})"),
1821            Sort::Loc => write!(f, "loc"),
1822            Sort::Func(fsort) => write!(f, "{fsort:?}"),
1823            Sort::SortOf(bty) => write!(f, "<{bty:?}>::sort"),
1824            Sort::Tuple(sorts) => write!(f, "({:?})", sorts.iter().format(", ")),
1825            Sort::Infer => write!(f, "_"),
1826            Sort::Err(_) => write!(f, "err"),
1827        }
1828    }
1829}
1830
1831impl fmt::Debug for SortPath<'_> {
1832    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1833        write!(f, "{:?}", self.res)?;
1834        if !self.args.is_empty() {
1835            write!(f, "<{:?}>", self.args.iter().format(", "))?;
1836        }
1837        Ok(())
1838    }
1839}
1840
1841impl fmt::Debug for PolyFuncSort<'_> {
1842    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1843        if self.params > 0 {
1844            write!(f, "for<{}>{:?}", self.params, self.fsort)
1845        } else {
1846            write!(f, "{:?}", self.fsort)
1847        }
1848    }
1849}
1850
1851impl fmt::Debug for FuncSort<'_> {
1852    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1853        match self.inputs() {
1854            [input] => {
1855                write!(f, "{:?} -> {:?}", input, self.output())
1856            }
1857            inputs => {
1858                write!(f, "({:?}) -> {:?}", inputs.iter().format(", "), self.output())
1859            }
1860        }
1861    }
1862}