Skip to main content

flux_syntax/
surface.rs

1pub mod visit;
2
3use std::{borrow::Cow, fmt, ops::Range};
4
5use flux_config::PartialInferOpts;
6pub use rustc_ast::{
7    Mutability,
8    token::{Lit, LitKind},
9};
10use rustc_data_structures::fx::FxIndexSet;
11pub use rustc_span::{Span, symbol::Ident};
12use rustc_span::{Symbol, symbol::sym};
13
14use crate::surface::visit::Visitor;
15
16/// A [`NodeId`] is a unique identifier we assign to some AST nodes to be able to attach information
17/// to them. For example, to assign a resolution to a [`Path`]. The [`NodeId`] is unique within a crate.
18#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
19pub struct NodeId(pub(super) usize);
20
21impl NodeId {
22    pub fn as_usize(&self) -> usize {
23        self.0
24    }
25}
26
27#[derive(Debug)]
28pub struct SortDecl {
29    pub name: Ident,
30    pub sort_vars: Vec<Ident>,
31}
32
33#[derive(Debug)]
34pub enum FluxItem {
35    Qualifier(Qualifier),
36    FuncDef(SpecFunc),
37    SortDecl(SortDecl),
38    PrimOpProp(PrimOpProp),
39    Axiom(Axiom),
40    Use(UseTree),
41}
42
43impl FluxItem {
44    pub fn name(&self) -> Option<Ident> {
45        match self {
46            FluxItem::Qualifier(qualifier) => Some(qualifier.name),
47            FluxItem::FuncDef(spec_func) => Some(spec_func.name),
48            FluxItem::SortDecl(sort_decl) => Some(sort_decl.name),
49            FluxItem::PrimOpProp(primop_prop) => Some(primop_prop.name),
50            FluxItem::Axiom(axiom) => Some(axiom.name),
51            FluxItem::Use(_) => None,
52        }
53    }
54
55    pub fn sort_vars(&self) -> &[Ident] {
56        match self {
57            FluxItem::FuncDef(defn) => &defn.sort_vars[..],
58            FluxItem::SortDecl(sort_decl) => &sort_decl.sort_vars[..],
59            FluxItem::Qualifier(_)
60            | FluxItem::PrimOpProp(_)
61            | FluxItem::Axiom(_)
62            | FluxItem::Use(_) => &[],
63        }
64    }
65}
66
67#[derive(Debug)]
68pub struct UseTree {
69    pub prefix: ExprPath,
70    pub kind: UseTreeKind,
71}
72
73#[derive(Debug)]
74pub enum UseTreeKind {
75    /// `use a::b::c`
76    Simple,
77    /// `use a::b::{...}`
78    Nested(Vec<UseTree>),
79}
80
81#[derive(Debug)]
82pub struct Qualifier {
83    pub name: Ident,
84    pub params: RefineParams,
85    pub wildcards: Vec<bool>,
86    pub expr: Expr,
87    pub span: Span,
88    pub kind: HintKind,
89}
90
91/// Determines which functions a hint to the solver (a qualifier or an axiom) is used for
92#[derive(Debug, Clone, Copy)]
93pub enum HintKind {
94    /// Used when checking every function in the crate
95    Global,
96    /// Used only when checking functions that name it in `#[qualifiers(...)]` / `#[axioms(...)]`
97    Local,
98    /// Used only when checking the item enclosing its declaration (e.g., a qualifier declared
99    /// with `invariant qualifier`)
100    Enclosing,
101}
102
103/// A global function definition. It can be either an uninterpreted function or a *syntactic abstraction*,
104/// i.e., a function with a body.
105#[derive(Debug)]
106pub struct SpecFunc {
107    pub name: Ident,
108    pub sort_vars: Vec<Ident>,
109    pub params: RefineParams,
110    pub output: Sort,
111    /// Body of the function. If not present this definition corresponds to an uninterpreted function.
112    pub body: Option<Expr>,
113    /// Is this function "hidden" i.e. to be considered
114    /// as uninterpreted by default (only makes sense if `body` is_some ...)
115    /// as otherwise it is *always* uninterpreted.
116    pub hide: bool,
117}
118
119/// A *primop property*; see tests/tests/pos/surface/
120#[derive(Debug)]
121pub struct PrimOpProp {
122    /// The name of the property
123    pub name: Ident,
124    /// Whether the property is global or `local`, i.e., only used by the functions that
125    /// request it with `#[properties(...)]`
126    pub kind: HintKind,
127    /// The binop it is attached to
128    pub op: BinOp,
129    /// The sort _at_ which the primop is defined,
130    /// The binders for the inputs of the primop; the output sort is always `Bool`
131    pub params: RefineParams,
132    /// The actual definition of the property
133    pub body: Expr,
134    pub span: Span,
135}
136
137/// A (global) *axiom*, i.e., a fact (typically about uninterpreted functions) that is assumed to
138/// hold for all values of its parameters; see tests/tests/pos/surface/axiom00.rs
139#[derive(Debug)]
140pub struct Axiom {
141    /// The name of the axiom
142    pub name: Ident,
143    /// The (universally quantified) binders of the axiom
144    pub params: RefineParams,
145    /// The actual definition of the axiom, which must have sort `bool`
146    pub body: Expr,
147    pub span: Span,
148    /// Whether the axiom is used when checking every function or only those that explicitly
149    /// request it with `#[axioms(...)]`
150    pub kind: HintKind,
151}
152
153#[derive(Debug)]
154pub struct Generics {
155    pub params: Vec<GenericParam>,
156    pub predicates: Option<Vec<WhereBoundPredicate>>,
157    pub span: Span,
158}
159
160#[derive(Debug)]
161pub struct GenericParam {
162    pub name: Ident,
163    pub node_id: NodeId,
164}
165
166#[derive(Debug)]
167pub struct TyAlias {
168    pub ident: Ident,
169    pub generics: Generics,
170    pub params: RefineParams,
171    pub index: Option<RefineParam>,
172    pub ty: Ty,
173    pub node_id: NodeId,
174    pub span: Span,
175}
176
177pub struct Item {
178    pub attrs: Vec<Attr>,
179    pub kind: ItemKind,
180    pub node_id: NodeId,
181}
182
183pub enum ItemKind {
184    Fn(Option<FnSig>),
185    Struct(StructDef),
186    Enum(EnumDef),
187    Trait(Trait),
188    Impl(Impl),
189    Const(ConstantInfo),
190    TyAlias(Box<TyAlias>),
191    Static(StaticInfo),
192    /// Modules can't be refined but we collect attributes for them, e.g., `#[trusted]`
193    /// This kind is also used for the crate root, for which we also collect attributes.
194    Mod,
195}
196
197pub struct TraitItemFn {
198    pub attrs: Vec<Attr>,
199    pub sig: Option<FnSig>,
200    pub node_id: NodeId,
201}
202
203pub struct ImplItemFn {
204    pub attrs: Vec<Attr>,
205    pub sig: Option<FnSig>,
206    pub node_id: NodeId,
207}
208
209#[derive(Debug)]
210pub struct DetachedSpecs {
211    pub items: Vec<DetachedItem>,
212}
213
214#[derive(Debug)]
215pub struct DetachedTraitImpl {
216    pub trait_: ExprPath,
217    pub items: Vec<DetachedItem<FnSig>>,
218    pub refts: Vec<ImplAssocReft>,
219    pub span: Span,
220}
221
222#[derive(Debug, Default)]
223pub struct DetachedTrait {
224    pub items: Vec<DetachedItem<FnSig>>,
225    pub refts: Vec<TraitAssocReft>,
226}
227
228#[derive(Debug)]
229pub struct DetachedInherentImpl {
230    pub items: Vec<DetachedItem<FnSig>>,
231    pub span: Span,
232}
233
234impl DetachedInherentImpl {
235    pub fn extend(&mut self, other: DetachedInherentImpl) {
236        self.items.extend(other.items);
237    }
238}
239
240#[derive(Debug)]
241pub struct DetachedItem<K = DetachedItemKind> {
242    pub attrs: Vec<Attr>,
243    pub path: ExprPath,
244    pub kind: K,
245    pub node_id: NodeId,
246}
247
248impl<K> DetachedItem<K> {
249    pub fn map_kind<R>(self, f: impl FnOnce(K) -> R) -> DetachedItem<R> {
250        DetachedItem {
251            attrs: self.attrs,
252            path: self.path,
253            kind: f(self.kind),
254            node_id: self.node_id,
255        }
256    }
257}
258
259impl DetachedItem<DetachedItemKind> {
260    pub fn span(&self) -> Span {
261        match &self.kind {
262            DetachedItemKind::InherentImpl(impl_) => impl_.span,
263            DetachedItemKind::TraitImpl(trait_impl) => trait_impl.span,
264            _ => self.path.span,
265        }
266    }
267}
268
269#[derive(Debug)]
270pub enum DetachedItemKind {
271    FnSig(FnSig),
272    Mod(DetachedSpecs),
273    Struct(StructDef),
274    Enum(EnumDef),
275    InherentImpl(DetachedInherentImpl),
276    TraitImpl(DetachedTraitImpl),
277    Trait(DetachedTrait),
278    Static(StaticInfo),
279}
280
281#[derive(Debug)]
282pub struct ConstantInfo {
283    pub expr: Option<Expr>,
284}
285
286#[derive(Debug)]
287pub struct StaticInfo {
288    pub ty: Ty,
289}
290
291#[derive(Debug)]
292pub struct StructDef {
293    pub generics: Option<Generics>,
294    pub refined_by: Option<RefineParams>,
295    pub fields: Vec<Option<Ty>>,
296    pub opaque: bool,
297    pub invariants: Vec<Expr>,
298}
299
300#[derive(Debug)]
301pub struct EnumDef {
302    pub generics: Option<Generics>,
303    pub refined_by: Option<RefineParams>,
304    pub variants: Vec<Option<VariantDef>>,
305    pub invariants: Vec<Expr>,
306    pub reflected: bool,
307}
308
309#[derive(Debug)]
310pub struct VariantDef {
311    pub ident: Option<Ident>,
312    pub fields: Vec<Ty>,
313    pub ret: Option<VariantRet>,
314    pub node_id: NodeId,
315    pub span: Span,
316}
317
318#[derive(Debug)]
319pub struct VariantRet {
320    pub path: Path,
321    /// Binders are not allowed at this position, but we parse this as a list of indices
322    /// for better error reporting.
323    pub indices: Indices,
324}
325
326pub type RefineParams = Vec<RefineParam>;
327
328#[derive(Debug)]
329pub struct RefineParam {
330    pub ident: Ident,
331    pub sort: Sort,
332    pub mode: Option<ParamMode>,
333    pub span: Span,
334    pub node_id: NodeId,
335}
336
337#[derive(Clone, Copy, Debug, PartialEq, Eq)]
338pub enum ParamMode {
339    Horn,
340    Hindley,
341}
342
343#[derive(Debug)]
344pub enum Sort {
345    /// A _base_ sort, e.g., `int` or `bool`.
346    Base(BaseSort),
347    /// A _function_ sort of the form `(bi,...) -> bo` where `bi..` and `bo`
348    /// are all base sorts.
349    Func { inputs: Vec<BaseSort>, output: BaseSort },
350    /// A sort that needs to be inferred.
351    Infer,
352}
353
354#[derive(Debug)]
355pub enum BaseSort {
356    /// a bitvector sort, e.g., bitvec<32>
357    BitVec(u32),
358    SortOf(Box<Ty>, Path),
359    Path(SortPath),
360    /// a tuple sort, e.g., (int, bool)
361    Tuple(Vec<BaseSort>),
362}
363
364/// A [`Path`] but for sorts.
365#[derive(Debug)]
366pub struct SortPath {
367    /// The segments in the path
368    pub segments: Vec<Ident>,
369    /// The sort arguments, i.e., the list `[int, bool]` in `Map<int, bool>`.
370    pub args: Vec<BaseSort>,
371    pub node_id: NodeId,
372}
373
374impl SortPath {
375    pub fn span(&self) -> Span {
376        self.segments
377            .iter()
378            .map(|ident| ident.span)
379            .reduce(Span::to)
380            .unwrap_or_default()
381    }
382}
383
384#[derive(Debug)]
385pub struct Impl {
386    pub generics: Option<Generics>,
387    pub assoc_refinements: Vec<ImplAssocReft>,
388}
389
390#[derive(Debug)]
391pub struct ImplAssocReft {
392    pub name: Ident,
393    pub params: RefineParams,
394    pub output: BaseSort,
395    pub body: Expr,
396    pub span: Span,
397}
398
399#[derive(Debug)]
400pub struct Trait {
401    pub generics: Option<Generics>,
402    pub assoc_refinements: Vec<TraitAssocReft>,
403}
404
405#[derive(Debug)]
406pub struct TraitAssocReft {
407    pub name: Ident,
408    pub params: RefineParams,
409    pub output: BaseSort,
410    pub body: Option<Expr>,
411    pub span: Span,
412    pub final_: bool,
413}
414
415#[derive(Debug)]
416pub struct FnSig {
417    pub asyncness: Async,
418    pub ident: Option<Ident>,
419    pub generics: Generics,
420    pub params: RefineParams,
421    /// example: `requires n > 0`
422    pub requires: Vec<Requires>,
423    /// example: `i32<@n>`
424    pub inputs: Vec<FnInput>,
425    pub output: FnOutput,
426    /// source span
427    pub span: Span,
428    pub node_id: NodeId,
429    pub no_panic: Option<Expr>,
430}
431
432#[derive(Debug)]
433pub struct Requires {
434    /// Optional list of universally quantified parameters
435    pub params: RefineParams,
436    pub pred: Expr,
437}
438
439#[derive(Debug)]
440pub struct FnOutput {
441    /// example `i32{v:v >= 0}`
442    pub returns: FnRetTy,
443    /// example: `*x: i32{v. v = n+1}` or just `x > 10`
444    pub ensures: Vec<Ensures>,
445    pub node_id: NodeId,
446}
447
448#[derive(Debug)]
449pub enum Ensures {
450    /// A type constraint on a location
451    Type(Ident, Ty, NodeId),
452    /// A predicate that needs to hold
453    Pred(Expr),
454}
455
456#[derive(Debug)]
457pub enum FnRetTy {
458    Default(Span),
459    Ty(Box<Ty>),
460}
461
462#[derive(Debug, Copy, Clone)]
463pub enum Async {
464    Yes { node_id: NodeId, span: Span },
465    No,
466}
467
468#[derive(Debug)]
469pub struct WhereBoundPredicate {
470    pub span: Span,
471    pub bounded_ty: Ty,
472    pub bounds: GenericBounds,
473}
474
475pub type GenericBounds = Vec<TraitRef>;
476
477#[derive(Debug)]
478pub struct TraitRef {
479    pub path: Path,
480    pub node_id: NodeId,
481}
482
483impl TraitRef {
484    fn is_fn_trait_name(name: Symbol) -> bool {
485        name == sym::FnOnce || name == sym::FnMut || name == sym::Fn
486    }
487
488    pub fn as_fn_trait_ref(&self) -> Option<(&GenericArg, &GenericArg)> {
489        if let [segment] = self.path.segments.as_slice()
490            && Self::is_fn_trait_name(segment.ident.name)
491            && let [in_arg, out_arg] = segment.args.as_slice()
492        {
493            return Some((in_arg, out_arg));
494        }
495        None
496    }
497}
498
499#[derive(Debug)]
500pub enum FnInput {
501    /// example `a: i32{a > 0}`
502    Constr(Ident, Path, Expr, NodeId),
503    /// example `v: &strg i32`
504    StrgRef(Ident, Ty, NodeId),
505    /// A type with an optional binder, e.g, `i32`, `x: i32` or `x: i32{v: v > 0}`.
506    /// The binder has a different meaning depending on the type.
507    Ty(Option<Ident>, Ty, NodeId),
508}
509
510#[derive(Debug)]
511pub struct Ty {
512    pub kind: TyKind,
513    pub node_id: NodeId,
514    pub span: Span,
515}
516
517#[derive(Debug)]
518pub enum TyKind {
519    /// ty
520    Base(BaseTy),
521    /// `B[r]`
522    Indexed {
523        bty: BaseTy,
524        indices: Indices,
525    },
526    /// B{v: r}
527    Exists {
528        bind: Ident,
529        bty: BaseTy,
530        pred: Expr,
531    },
532    GeneralExists {
533        params: RefineParams,
534        ty: Box<Ty>,
535        pred: Option<Expr>,
536    },
537    /// Mutable or shared reference
538    Ref(Mutability, Box<Ty>),
539    /// Constrained type: an exists without binder
540    Constr(Expr, Box<Ty>),
541    Tuple(Vec<Ty>),
542    Array(Box<Ty>, ConstArg),
543    /// A function pointer type, e.g., `fn(i32) -> i32{v: v > 0}`
544    BareFn(Box<BareFnTy>),
545    /// The `NodeId` is used to resolve the type to a corresponding `OpaqueTy`
546    ImplTrait(NodeId, GenericBounds),
547    Hole,
548}
549
550#[derive(Debug, Clone, Copy, PartialEq, Eq)]
551pub enum Safety {
552    Safe,
553    Unsafe,
554}
555
556#[derive(Debug)]
557pub struct BareFnTy {
558    /// Whether the fn pointer is `unsafe`
559    pub safety: Safety,
560    /// The abi of an `extern "abi" fn` pointer (`extern fn` is `extern "C" fn`), or `None` for the
561    /// default (rust) abi.
562    pub abi: Option<Ident>,
563    /// example `&T[@n]`. `@` binders in the inputs are bound by the fn pointer type itself
564    pub inputs: Vec<Ty>,
565    pub output: FnRetTy,
566    pub node_id: NodeId,
567    pub span: Span,
568}
569
570impl Ty {
571    pub fn is_refined(&self) -> bool {
572        struct IsRefinedVisitor {
573            is_refined: bool,
574        }
575        let mut vis = IsRefinedVisitor { is_refined: false };
576        impl visit::Visitor<'_> for IsRefinedVisitor {
577            fn visit_ty(&mut self, ty: &Ty) {
578                match &ty.kind {
579                    TyKind::Tuple(_)
580                    | TyKind::Ref(..)
581                    | TyKind::Array(..)
582                    | TyKind::BareFn(..)
583                    | TyKind::ImplTrait(..)
584                    | TyKind::Hole
585                    | TyKind::Base(_) => {
586                        visit::walk_ty(self, ty);
587                    }
588                    TyKind::Indexed { .. }
589                    | TyKind::Exists { .. }
590                    | TyKind::GeneralExists { .. }
591                    | TyKind::Constr(..) => {
592                        self.is_refined = true;
593                    }
594                }
595            }
596        }
597        vis.visit_ty(self);
598        vis.is_refined
599    }
600
601    pub fn is_potential_const_arg(&self) -> Option<&Path> {
602        if let TyKind::Base(bty) = &self.kind
603            && let BaseTyKind::Path(None, path) = &bty.kind
604            && let [segment] = &path.segments[..]
605            && segment.args.is_empty()
606        {
607            Some(path)
608        } else {
609            None
610        }
611    }
612}
613#[derive(Debug)]
614pub struct BaseTy {
615    pub kind: BaseTyKind,
616    pub span: Span,
617}
618
619#[derive(Debug)]
620pub enum BaseTyKind {
621    Path(Option<Box<Ty>>, Path),
622    Slice(Box<Ty>),
623    /// Raw pointer (*const T or *mut T), optionally with refinement on pointer value
624    Ptr(Mutability, Box<Ty>),
625}
626
627#[derive(Debug)]
628pub struct ConstArg {
629    pub kind: ConstArgKind,
630    pub span: Span,
631}
632
633#[derive(Debug)]
634pub enum ConstArgKind {
635    Lit(usize),
636    Path(Path),
637    Infer,
638}
639
640#[derive(Debug)]
641pub struct Indices {
642    pub indices: Vec<RefineArg>,
643    pub span: Span,
644}
645
646#[derive(Debug)]
647pub enum RefineArg {
648    /// `@n` or `#n`, the span corresponds to the span of the identifier plus the binder token (`@` or `#`)
649    Bind(Ident, BindKind, Span, NodeId),
650    Expr(Expr),
651    Abs(RefineParams, Expr, Span, NodeId),
652}
653
654#[derive(Debug, Clone, Copy)]
655pub enum BindKind {
656    At,
657    Pound,
658}
659
660/// A boolean-like enum used to mark whether some code should be trusted.
661#[derive(Debug, Eq, PartialEq, Copy, Clone)]
662pub enum Trusted {
663    Yes,
664    No,
665}
666
667impl Trusted {
668    pub fn to_bool(self) -> bool {
669        match self {
670            Trusted::Yes => true,
671            Trusted::No => false,
672        }
673    }
674}
675
676impl From<bool> for Trusted {
677    fn from(value: bool) -> Self {
678        if value { Trusted::Yes } else { Trusted::No }
679    }
680}
681
682/// A boolean-like enum used to mark whether a piece of code is ignored.
683#[derive(Debug, Eq, PartialEq, Copy, Clone)]
684pub enum Ignored {
685    Yes,
686    No,
687}
688
689impl Ignored {
690    pub fn to_bool(self) -> bool {
691        match self {
692            Ignored::Yes => true,
693            Ignored::No => false,
694        }
695    }
696}
697
698impl From<bool> for Ignored {
699    fn from(value: bool) -> Self {
700        if value { Ignored::Yes } else { Ignored::No }
701    }
702}
703
704/// An attribute attaches metadata to an item.
705///
706/// Note that some of these attributes correspond to a Rust attribute, but some don't. For example,
707/// when annotating a function, a `#[flux::trusted]` is mapped to [`Attr::Trusted`] because it
708/// corresponds to metadata associated to the function, however, a `#[flux::spec(...)]` doesn't
709/// map to any [`Attr`] because that's considered to be part of the *refined syntax* of the item.
710///
711/// Note that these attributes can also originate from detached specs.
712#[derive(Debug)]
713pub enum Attr {
714    /// A `#[trusted(...)]` attribute
715    Trusted(Trusted),
716    /// A `#[trusted_impl(...)]` attribute
717    TrustedImpl(Trusted),
718    /// A `#[trusted_derive(...)]` attribute
719    TrustedDerive(Trusted),
720    /// A `#[ignore(...)]` attribute
721    Ignore(Ignored),
722    /// A `#[proven_externally]` attribute
723    ProvenExternally(Span),
724    /// A `#[should_fail]` attribute
725    ShouldFail,
726    /// A `#[qualifiers(...)]` attribute
727    Qualifiers(Vec<ExprPath>),
728    /// A `#[axioms(...)]` attribute
729    Axioms(Vec<ExprPath>),
730    /// A `#[properties(...)]` attribute
731    Properties(Vec<ExprPath>),
732    /// A `#[reveal(...)]` attribute
733    Reveal(Vec<ExprPath>),
734    /// A `#[hide(...)]` attribute
735    Hide(Vec<ExprPath>),
736    /// A `#[opts(...)]` attribute
737    InferOpts(PartialInferOpts),
738    /// A `#[no_panic]` attribute
739    NoPanic,
740    /// A `#[assume_parametric(...)]` attribute
741    AssumeParametric(Vec<Ident>),
742    /// A `#[no_suggestions]` attribute
743    NoSuggestions,
744}
745
746#[derive(Debug)]
747pub struct Path {
748    pub segments: Vec<PathSegment>,
749    pub refine: Vec<RefineArg>,
750    pub node_id: NodeId,
751    pub span: Span,
752}
753
754impl Path {
755    pub fn last(&self) -> &PathSegment {
756        self.segments
757            .last()
758            .expect("path must have at least one segment")
759    }
760}
761
762#[derive(Debug)]
763pub struct PathSegment {
764    pub ident: Ident,
765    pub args: Vec<GenericArg>,
766    pub node_id: NodeId,
767}
768
769#[derive(Debug)]
770pub struct GenericArg {
771    pub kind: GenericArgKind,
772    pub node_id: NodeId,
773}
774
775#[derive(Debug)]
776pub enum GenericArgKind {
777    Type(Ty),
778    Constraint(Ident, Ty),
779}
780
781#[derive(Debug)]
782pub struct FieldExpr {
783    pub ident: Ident,
784    pub expr: RefineArg,
785    pub span: Span,
786    pub node_id: NodeId,
787}
788
789#[derive(Debug)]
790pub struct Spread {
791    pub expr: Expr,
792    pub span: Span,
793    pub node_id: NodeId,
794}
795
796#[derive(Debug)]
797pub enum ConstructorArg {
798    FieldExpr(FieldExpr),
799    Spread(Spread),
800}
801
802#[derive(Debug)]
803pub struct Expr {
804    pub kind: ExprKind,
805    pub node_id: NodeId,
806    pub span: Span,
807}
808
809#[derive(Debug)]
810pub enum QuantKind {
811    Forall,
812    Exists,
813}
814
815#[derive(Debug)]
816pub enum ExprKind {
817    Path(ExprPath),
818    Dot(Box<Expr>, Ident),
819    Literal(Lit),
820    BinaryOp(BinOp, Box<[Expr; 2]>),
821    UnaryOp(UnOp, Box<Expr>),
822    Call(Box<Expr>, Vec<Expr>),
823    /// A UIF representing a PrimOp expression, e.g. `[<<](x, y)`
824    PrimUIF(BinOp),
825    /// `<qself as path>::name`
826    AssocReft(Box<Ty>, Path, Ident),
827    IfThenElse(Box<[Expr; 3]>),
828    Constructor(Option<ExprPath>, Vec<ConstructorArg>),
829    Quant(QuantKind, RefineParam, Option<Range<usize>>, Box<Expr>),
830    Block(Vec<LetDecl>, Box<Expr>),
831    /// Set expression `#{ e1, e2, ..., en }`
832    SetLiteral(Vec<Expr>),
833    /// Tuple expression `(e1, e2, ..., en)`
834    Tuple(Vec<Expr>),
835}
836
837#[derive(Debug)]
838pub struct LetDecl {
839    pub param: RefineParam,
840    pub init: Expr,
841}
842
843/// A [`Path`] but for refinement expressions
844#[derive(Debug, Clone)]
845pub struct ExprPath {
846    pub segments: Vec<ExprPathSegment>,
847    pub node_id: NodeId,
848    pub span: Span,
849}
850
851#[derive(Debug, Clone)]
852pub struct ExprPathSegment {
853    pub ident: Ident,
854    pub node_id: NodeId,
855}
856#[derive(Copy, Clone, Hash, Eq, PartialEq)]
857pub enum BinOp {
858    Iff,
859    Imp,
860    Or,
861    And,
862    Eq,
863    Ne,
864    Gt,
865    Ge,
866    Lt,
867    Le,
868    Add,
869    Sub,
870    Mul,
871    Div,
872    Mod,
873    BitOr,
874    BitXor,
875    BitAnd,
876    BitShl,
877    BitShr,
878}
879
880impl fmt::Debug for BinOp {
881    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882        match self {
883            BinOp::Iff => write!(f, "<=>"),
884            BinOp::Imp => write!(f, "=>"),
885            BinOp::Or => write!(f, "||"),
886            BinOp::And => write!(f, "&&"),
887            BinOp::Eq => write!(f, "=="),
888            BinOp::Ne => write!(f, "!="),
889            BinOp::Lt => write!(f, "<"),
890            BinOp::Le => write!(f, "<="),
891            BinOp::Gt => write!(f, ">"),
892            BinOp::Ge => write!(f, ">="),
893            BinOp::Add => write!(f, "+"),
894            BinOp::Sub => write!(f, "-"),
895            BinOp::Mod => write!(f, "mod"),
896            BinOp::Mul => write!(f, "*"),
897            BinOp::Div => write!(f, "/"),
898            BinOp::BitOr => write!(f, "|"),
899            BinOp::BitXor => write!(f, "^"),
900            BinOp::BitAnd => write!(f, "&"),
901            BinOp::BitShl => write!(f, "<<"),
902            BinOp::BitShr => write!(f, ">>"),
903        }
904    }
905}
906
907impl rustc_errors::IntoDiagArg for BinOp {
908    fn into_diag_arg(self, _path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
909        rustc_errors::DiagArgValue::Str(Cow::Owned(format!("{self:?}")))
910    }
911}
912
913#[derive(Copy, Clone)]
914pub enum UnOp {
915    Not,
916    Neg,
917}
918
919impl fmt::Debug for UnOp {
920    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
921        match self {
922            Self::Not => write!(f, "!"),
923            Self::Neg => write!(f, "-"),
924        }
925    }
926}
927
928impl BindKind {
929    pub fn token_str(&self) -> &'static str {
930        match self {
931            BindKind::At => "@",
932            BindKind::Pound => "#",
933        }
934    }
935}
936
937/// A punctuated sequence of values of type `T` separated by punctuation of type `P`
938pub struct Punctuated<T, P> {
939    inner: Vec<(T, P)>,
940    last: Option<Box<T>>,
941}
942
943impl<T, P> From<Vec<(T, P)>> for Punctuated<T, P> {
944    fn from(inner: Vec<(T, P)>) -> Self {
945        Self { inner, last: None }
946    }
947}
948
949impl<T, P> Punctuated<T, P> {
950    pub fn len(&self) -> usize {
951        self.inner.len() + self.last.is_some() as usize
952    }
953
954    /// Determines whether this punctuated sequence is empty, meaning it
955    /// contains no syntax tree nodes or punctuation.
956    pub fn is_empty(&self) -> bool {
957        self.inner.len() == 0 && self.last.is_none()
958    }
959
960    /// Appends a syntax tree node onto the end of this punctuated sequence. The
961    /// sequence must already have a trailing punctuation, or be empty.
962    ///
963    /// # Panics
964    ///
965    /// Panics if the sequence is nonempty and does not already have a trailing
966    /// punctuation.
967    pub fn push_value(&mut self, value: T) {
968        assert!(
969            self.empty_or_trailing(),
970            "Punctuated::push_value: cannot push value if Punctuated is missing trailing punctuation",
971        );
972
973        self.last = Some(Box::new(value));
974    }
975
976    /// Returns true if either this `Punctuated` is empty, or it has a trailing
977    /// punctuation.
978    ///
979    /// Equivalent to `punctuated.is_empty() || punctuated.trailing_punct()`.
980    pub fn empty_or_trailing(&self) -> bool {
981        self.last.is_none()
982    }
983
984    /// Determines whether this punctuated sequence ends with a trailing
985    /// punctuation.
986    pub fn trailing_punct(&self) -> bool {
987        self.last.is_none() && !self.is_empty()
988    }
989
990    pub fn into_values(self) -> Vec<T> {
991        let mut v: Vec<T> = self.inner.into_iter().map(|(v, _)| v).collect();
992        if let Some(last) = self.last {
993            v.push(*last);
994        }
995        v
996    }
997}
998
999impl Expr {
1000    /// Collects all free variables in an expression.
1001    /// A free variable is an `ExprKind::Path` with a single identifier segment.
1002    ///
1003    /// Variables are returned in the order they first appear in the expression.
1004    pub fn free_vars(&self) -> FxIndexSet<Ident> {
1005        struct FreeVarsVisitor {
1006            vars: FxIndexSet<Ident>,
1007        }
1008
1009        impl visit::Visitor<'_> for FreeVarsVisitor {
1010            fn visit_expr(&mut self, expr: &Expr) {
1011                match &expr.kind {
1012                    ExprKind::Path(path) => {
1013                        // Only collect paths with a single segment
1014                        if let [segment] = path.segments.as_slice() {
1015                            self.vars.insert(segment.ident);
1016                        }
1017                    }
1018                    ExprKind::Call(callee, args) => {
1019                        // The callee of a call is a refinement function, not a variable, so
1020                        // don't collect it. Anything that's not a path may contain free
1021                        // variables, so visit it normally.
1022                        if !matches!(&callee.kind, ExprKind::Path(_)) {
1023                            self.visit_expr(callee);
1024                        }
1025                        for arg in args {
1026                            self.visit_expr(arg);
1027                        }
1028                    }
1029                    // Continue visiting child expressions
1030                    _ => visit::walk_expr(self, expr),
1031                }
1032            }
1033        }
1034
1035        let mut visitor = FreeVarsVisitor { vars: FxIndexSet::default() };
1036        visitor.visit_expr(self);
1037        visitor.vars
1038    }
1039}