Skip to main content

flux_syntax/parser/
mod.rs

1pub(crate) mod lookahead;
2mod utils;
3use std::{collections::HashSet, str::FromStr, vec};
4
5use lookahead::{AnyLit, LAngle, NonReserved, RAngle};
6use rustc_ast::token::Lit;
7use rustc_data_structures::unord::UnordSet;
8use rustc_span::{Symbol, sym::Output};
9use utils::{
10    angle, braces, brackets, delimited, opt_angle, parens, punctuated_until,
11    punctuated_with_trailing, repeat_while, sep1, until,
12};
13
14use crate::{
15    ParseCtxt, ParseError, ParseResult,
16    parser::lookahead::{AnyOf, Expected, PeekExpected},
17    surface::{
18        self, Async,
19        Attr::{self},
20        Axiom, BareFnTy, BaseSort, BaseTy, BaseTyKind, BinOp, BindKind, ConstArg, ConstArgKind,
21        ConstructorArg, DetachedInherentImpl, DetachedItem, DetachedItemKind, DetachedSpecs,
22        DetachedTrait, DetachedTraitImpl, Ensures, EnumDef, Expr, ExprKind, ExprPath,
23        ExprPathSegment, FieldExpr, FluxItem, FnInput, FnOutput, FnRetTy, FnSig, GenericArg,
24        GenericArgKind, GenericBounds, GenericParam, Generics, HintKind, Ident, ImplAssocReft,
25        Indices, LetDecl, LitKind, Mutability, ParamMode, Path, PathSegment, PrimOpProp, Qualifier,
26        QuantKind, RefineArg, RefineParam, RefineParams, Requires, Sort, SortDecl, SortPath,
27        SpecFunc, Spread, StaticInfo, StructDef, TraitAssocReft, TraitRef, Trusted, Ty, TyAlias,
28        TyKind, UnOp, UseTree, UseTreeKind, VariantDef, VariantRet, WhereBoundPredicate,
29    },
30    symbols::{kw, sym},
31    token::{self, Comma, Delimiter::*, IdentKind, Or, Token, TokenKind},
32};
33
34/// An attribute that's considered part of the *syntax* of an item.
35///
36/// This is in contrast to a [`surface::Attr`] which changes the behavior of an item. For example,
37/// a `#[refined_by(...)]` is part of the syntax of an adt: we could think of a different syntax
38/// that doesn't use an attribute. The existence of a syntax attribute in the token stream can be
39/// used to decide how to keep parsing, for example, if we see a `#[reft]` we know that the next
40/// item must be an associated refinement and not a method inside an impl or trait.
41enum SyntaxAttr {
42    /// A `#[reft]` attribute
43    Reft,
44    /// A `#[invariant]` attribute
45    Invariant(Expr),
46    /// A `#[refined_by(...)]` attribute
47    RefinedBy(RefineParams),
48    /// A `#[hide]` attribute
49    ///
50    /// NOTE(nilehmann) This should be considered a normal attribute, but we haven't implemented
51    /// attributes for flux items. If we start seeing more of these we should consider implementing
52    /// the infrastructure necesary to keep a list of attributes inside the flux item like we do
53    /// for rust items.
54    Hide,
55    /// a `#[opaque]` attribute
56    Opaque,
57    /// A `#[no_panic_if(...)]` attribute
58    NoPanicIf(Expr),
59}
60
61#[derive(Default)]
62struct ParsedAttrs {
63    normal: Vec<Attr>,
64    syntax: Vec<SyntaxAttr>,
65}
66
67impl ParsedAttrs {
68    fn is_reft(&self) -> bool {
69        self.syntax
70            .iter()
71            .any(|attr| matches!(attr, SyntaxAttr::Reft))
72    }
73
74    fn is_hide(&self) -> bool {
75        self.syntax
76            .iter()
77            .any(|attr| matches!(attr, SyntaxAttr::Hide))
78    }
79
80    fn is_opaque(&self) -> bool {
81        self.syntax
82            .iter()
83            .any(|attr| matches!(attr, SyntaxAttr::Opaque))
84    }
85
86    fn refined_by(&mut self) -> Option<RefineParams> {
87        let pos = self
88            .syntax
89            .iter()
90            .position(|x| matches!(x, SyntaxAttr::RefinedBy(_)))?;
91        if let SyntaxAttr::RefinedBy(params) = self.syntax.remove(pos) {
92            Some(params)
93        } else {
94            None
95        }
96    }
97
98    fn no_panic_if(&mut self) -> Option<Expr> {
99        let pos = self
100            .syntax
101            .iter()
102            .position(|x| matches!(x, SyntaxAttr::NoPanicIf(_)))?;
103        if let SyntaxAttr::NoPanicIf(expr) = self.syntax.remove(pos) { Some(expr) } else { None }
104    }
105
106    fn invariant(&mut self) -> Option<Expr> {
107        let pos = self
108            .syntax
109            .iter()
110            .position(|x| matches!(x, SyntaxAttr::Invariant(_)))?;
111        if let SyntaxAttr::Invariant(exp) = self.syntax.remove(pos) { Some(exp) } else { None }
112    }
113}
114
115/// ```text
116///   yes ⟨ , reason = ⟨literal⟩ ⟩?
117/// | no ⟨ , reason = ⟨literal⟩ ⟩?
118/// | reason = ⟨literal⟩
119/// ```
120pub(crate) fn parse_yes_or_no_with_reason(cx: &mut ParseCtxt) -> ParseResult<bool> {
121    let mut lookahead = cx.lookahead1();
122    if lookahead.advance_if(sym::yes) {
123        if cx.advance_if(token::Comma) {
124            parse_reason(cx)?;
125        }
126        Ok(true)
127    } else if lookahead.advance_if(sym::no) {
128        if cx.advance_if(token::Comma) {
129            parse_reason(cx)?;
130        }
131        Ok(false)
132    } else if lookahead.peek(sym::reason) {
133        parse_reason(cx)?;
134        Ok(true)
135    } else {
136        Err(lookahead.into_error())
137    }
138}
139
140/// ```text
141/// ⟨reason⟩ := reason = ⟨literal⟩
142/// ```
143fn parse_reason(cx: &mut ParseCtxt) -> ParseResult {
144    cx.expect(sym::reason)?;
145    cx.expect(token::Eq)?;
146    cx.expect(AnyLit)
147}
148
149/// ```text
150/// ⟨ident_list⟩ := ⟨ident⟩,*
151/// ```
152pub(crate) fn parse_ident_list(cx: &mut ParseCtxt) -> ParseResult<Vec<Ident>> {
153    punctuated_until(cx, Comma, token::Eof, parse_ident)
154}
155
156/// ```text
157/// ⟨path_list⟩ := ⟨path⟩,*
158/// ⟨path⟩      := ⟨ident⟩ ⟨ :: ⟨ident⟩ ⟩*
159/// ```
160pub(crate) fn parse_path_list(cx: &mut ParseCtxt) -> ParseResult<Vec<ExprPath>> {
161    punctuated_until(cx, Comma, token::Eof, parse_simple_path)
162}
163
164fn parse_simple_path(cx: &mut ParseCtxt) -> ParseResult<ExprPath> {
165    let lo = cx.lo();
166    let mut segments = vec![parse_expr_path_segment(cx)?];
167    while cx.advance_if(token::PathSep) {
168        segments.push(parse_expr_path_segment(cx)?);
169    }
170    let hi = cx.hi();
171    Ok(ExprPath { segments, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
172}
173
174/// ```text
175/// ⟨flux_items⟩ := ⟨flux_item⟩*
176/// ```
177pub(crate) fn parse_flux_items(cx: &mut ParseCtxt) -> ParseResult<Vec<FluxItem>> {
178    until(cx, token::Eof, parse_flux_item)
179}
180
181/// ```text
182/// ⟨flux_item⟩ := ⟨func_def⟩
183///              | ⟨qualifier⟩
184///              | ⟨sort_decl⟩
185///              | ⟨primop_prop⟩
186///              | ⟨axiom⟩
187///              | ⟨use_item⟩
188/// ```
189fn parse_flux_item(cx: &mut ParseCtxt) -> ParseResult<FluxItem> {
190    // `local` can start a qualifier, an axiom or a property, so we need to look at the next token
191    if cx.peek2(kw::Local, kw::Axiom) {
192        return parse_axiom(cx).map(FluxItem::Axiom);
193    }
194    if cx.peek2(kw::Local, kw::Property) {
195        return parse_primop_property(cx).map(FluxItem::PrimOpProp);
196    }
197    let mut lookahead = cx.lookahead1();
198    if lookahead.peek(token::Pound) || lookahead.peek(kw::Fn) {
199        parse_reft_func(cx).map(FluxItem::FuncDef)
200    } else if lookahead.peek(kw::Axiom) {
201        parse_axiom(cx).map(FluxItem::Axiom)
202    } else if lookahead.peek(kw::Local)
203        || lookahead.peek(kw::Invariant)
204        || lookahead.peek(kw::Qualifier)
205    {
206        parse_qualifier(cx).map(FluxItem::Qualifier)
207    } else if lookahead.peek(kw::Opaque) {
208        parse_sort_decl(cx).map(FluxItem::SortDecl)
209    } else if lookahead.peek(kw::Property) {
210        parse_primop_property(cx).map(FluxItem::PrimOpProp)
211    } else if lookahead.peek(kw::Use) {
212        parse_use_item(cx).map(FluxItem::Use)
213    } else {
214        Err(lookahead.into_error())
215    }
216}
217
218///```text
219/// ⟨specs⟩ ::= ⟨specs⟩*
220/// ```
221pub(crate) fn parse_detached_specs(cx: &mut ParseCtxt) -> ParseResult<surface::DetachedSpecs> {
222    let items = until(cx, token::Eof, parse_detached_item)?;
223    Ok(surface::DetachedSpecs { items })
224}
225
226///```text
227/// ⟨specs⟩ ::= ⟨fn-spec⟩
228///           | ⟨struct-spec⟩
229///           | ⟨enum-spec⟩
230///           | ⟨mod⟩
231///           | ⟨impl⟩
232/// ```
233pub(crate) fn parse_detached_item(cx: &mut ParseCtxt) -> ParseResult<DetachedItem> {
234    let attrs = parse_attrs(cx)?;
235    let mut lookahead = cx.lookahead1();
236    if lookahead.peek(kw::Fn) {
237        Ok(parse_detached_fn_sig(cx, attrs)?.map_kind(DetachedItemKind::FnSig))
238    } else if lookahead.peek(kw::Mod) {
239        parse_detached_mod(cx)
240    } else if lookahead.peek(kw::Struct) {
241        parse_detached_struct(cx, attrs)
242    } else if lookahead.peek(kw::Enum) {
243        parse_detached_enum(cx, attrs)
244    } else if lookahead.peek(kw::Impl) {
245        parse_detached_impl(cx, attrs)
246    } else if lookahead.peek(kw::Trait) {
247        parse_detached_trait(cx, attrs)
248    } else if lookahead.peek(kw::Static) {
249        parse_detached_static(cx, attrs)
250    } else {
251        Err(lookahead.into_error())
252    }
253}
254
255///```text
256/// ⟨field⟩ ::= ⟨ident⟩ : ⟨type⟩
257/// ```
258fn parse_detached_field(cx: &mut ParseCtxt) -> ParseResult<(Ident, Ty)> {
259    let ident = parse_ident(cx)?;
260    cx.expect(token::Colon)?;
261    let ty = parse_type(cx)?;
262    Ok((ident, ty))
263}
264
265///```text
266/// ⟨enum⟩ := enum Ident ⟨refine_info⟩ { ⟨variant⟩* }
267/// ```
268fn parse_detached_enum(cx: &mut ParseCtxt, mut attrs: ParsedAttrs) -> ParseResult<DetachedItem> {
269    cx.expect(kw::Enum)?;
270    let path = parse_expr_path(cx)?;
271    let generics = Some(parse_opt_generics(cx)?);
272    let refined_by = attrs.refined_by();
273    let invariants = attrs.invariant().into_iter().collect();
274    let variants = braces(cx, Comma, |cx| parse_variant(cx, true))?
275        .into_iter()
276        .map(Some)
277        .collect();
278    let enum_def = EnumDef { generics, refined_by, variants, invariants, reflected: false };
279    Ok(DetachedItem {
280        attrs: attrs.normal,
281        path,
282        kind: DetachedItemKind::Enum(enum_def),
283        node_id: cx.next_node_id(),
284    })
285}
286
287fn parse_detached_struct(cx: &mut ParseCtxt, mut attrs: ParsedAttrs) -> ParseResult<DetachedItem> {
288    cx.expect(kw::Struct)?;
289    let path = parse_expr_path(cx)?;
290    let generics = Some(parse_opt_generics(cx)?);
291    let refined_by = attrs.refined_by();
292    let opaque = attrs.is_opaque();
293    let invariants = attrs.invariant().into_iter().collect();
294    let fields = if cx.peek(token::OpenBrace) {
295        braces(cx, Comma, parse_detached_field)?
296            .into_iter()
297            .map(|(_, ty)| Some(ty))
298            .collect()
299    } else if cx.peek(token::OpenParen) {
300        parens(cx, Comma, parse_type)?
301            .into_iter()
302            .map(Some)
303            .collect()
304    } else {
305        cx.expect(token::Semi)?;
306        vec![]
307    };
308    let struct_def = StructDef { generics, opaque, refined_by, invariants, fields };
309    Ok(DetachedItem {
310        attrs: attrs.normal,
311        path,
312        kind: DetachedItemKind::Struct(struct_def),
313        node_id: cx.next_node_id(),
314    })
315}
316
317fn ident_path(cx: &mut ParseCtxt, ident: Ident) -> ExprPath {
318    let span = ident.span;
319    let segments = vec![ExprPathSegment { ident, node_id: cx.next_node_id() }];
320    ExprPath { segments, span, node_id: cx.next_node_id() }
321}
322
323fn parse_detached_fn_sig(
324    cx: &mut ParseCtxt,
325    mut attrs: ParsedAttrs,
326) -> ParseResult<DetachedItem<FnSig>> {
327    let mut fn_sig = parse_fn_sig(cx, token::Semi)?;
328    fn_sig.no_panic = attrs.no_panic_if();
329    let span = fn_sig.span;
330    let ident = fn_sig
331        .ident
332        .ok_or(ParseError { kind: crate::ParseErrorKind::InvalidDetachedSpec, span })?;
333    let path = ident_path(cx, ident);
334    Ok(DetachedItem { attrs: attrs.normal, path, kind: fn_sig, node_id: cx.next_node_id() })
335}
336
337///```text
338/// ⟨static-spec⟩ ::= static ⟨ident⟩ : ⟨type⟩ ;
339/// ```
340fn parse_detached_static(cx: &mut ParseCtxt, attrs: ParsedAttrs) -> ParseResult<DetachedItem> {
341    cx.expect(kw::Static)?;
342    let path = parse_expr_path(cx)?;
343    cx.expect(token::Colon)?;
344    let ty = parse_type(cx)?;
345    cx.expect(token::Semi)?;
346    Ok(DetachedItem {
347        attrs: attrs.normal,
348        path,
349        kind: DetachedItemKind::Static(StaticInfo { ty }),
350        node_id: cx.next_node_id(),
351    })
352}
353
354///```text
355/// ⟨mod⟩ ::= mod ⟨ident⟩ { ⟨specs⟩ }
356/// ```
357fn parse_detached_mod(cx: &mut ParseCtxt) -> ParseResult<DetachedItem> {
358    cx.expect(kw::Mod)?;
359    let path = parse_expr_path(cx)?;
360    cx.expect(TokenKind::open_delim(Brace))?;
361    let items = until(cx, TokenKind::close_delim(Brace), parse_detached_item)?;
362    cx.expect(TokenKind::close_delim(Brace))?;
363    Ok(DetachedItem {
364        attrs: vec![],
365        path,
366        kind: DetachedItemKind::Mod(DetachedSpecs { items }),
367        node_id: cx.next_node_id(),
368    })
369}
370
371///```text
372/// ⟨trait-spec⟩ ::= trait Ident { ⟨fn-spec⟩* }
373/// ```
374fn parse_detached_trait(cx: &mut ParseCtxt, attrs: ParsedAttrs) -> ParseResult<DetachedItem> {
375    cx.expect(kw::Trait)?;
376    let path = parse_expr_path(cx)?;
377    let _generics = parse_opt_generics(cx)?;
378    cx.expect(TokenKind::open_delim(Brace))?;
379
380    let mut items = vec![];
381    let mut refts = vec![];
382    while !cx.peek(TokenKind::close_delim(Brace)) {
383        let assoc_item_attrs = parse_attrs(cx)?;
384        if assoc_item_attrs.is_reft() {
385            refts.push(parse_trait_assoc_reft(cx)?);
386        } else {
387            items.push(parse_detached_fn_sig(cx, assoc_item_attrs)?);
388        }
389    }
390    cx.expect(TokenKind::close_delim(Brace))?;
391    Ok(DetachedItem {
392        attrs: attrs.normal,
393        path,
394        kind: DetachedItemKind::Trait(DetachedTrait { items, refts }),
395        node_id: cx.next_node_id(),
396    })
397}
398
399///```text
400/// ⟨impl-spec⟩ ::= impl Ident (for Ident)? { ⟨#[assoc] impl_assoc_reft⟩* ⟨fn-spec⟩* }
401/// ```
402fn parse_detached_impl(cx: &mut ParseCtxt, attrs: ParsedAttrs) -> ParseResult<DetachedItem> {
403    let lo = cx.lo();
404    cx.expect(kw::Impl)?;
405    let hi = cx.hi();
406    let span = cx.mk_span(lo, hi);
407    let outer_path = parse_expr_path(cx)?;
408    let _generics = parse_opt_generics(cx)?;
409    let inner_path = if cx.advance_if(kw::For) {
410        let path = parse_expr_path(cx)?;
411        let _generics = parse_opt_generics(cx)?;
412        Some(path)
413    } else {
414        None
415    };
416    cx.expect(TokenKind::open_delim(Brace))?;
417
418    let mut items = vec![];
419    let mut refts = vec![];
420    while !cx.peek(TokenKind::close_delim(Brace)) {
421        // if inner_path.is_none, we are parsing an inherent impl with no associated-refts
422        let assoc_item_attrs = parse_attrs(cx)?;
423        if assoc_item_attrs.is_reft() && inner_path.is_some() {
424            refts.push(parse_impl_assoc_reft(cx)?);
425        } else {
426            items.push(parse_detached_fn_sig(cx, assoc_item_attrs)?);
427        }
428    }
429    cx.expect(TokenKind::close_delim(Brace))?;
430    if let Some(path) = inner_path {
431        Ok(DetachedItem {
432            attrs: attrs.normal,
433            path,
434            kind: DetachedItemKind::TraitImpl(DetachedTraitImpl {
435                trait_: outer_path,
436                items,
437                refts,
438                span,
439            }),
440            node_id: cx.next_node_id(),
441        })
442    } else {
443        Ok(DetachedItem {
444            attrs: attrs.normal,
445            path: outer_path,
446            kind: DetachedItemKind::InherentImpl(DetachedInherentImpl { items, span }),
447            node_id: cx.next_node_id(),
448        })
449    }
450}
451
452fn parse_attr(cx: &mut ParseCtxt, attrs: &mut ParsedAttrs) -> ParseResult {
453    cx.expect(token::Pound)?;
454    cx.expect(token::OpenBracket)?;
455    let mut lookahead = cx.lookahead1();
456    if lookahead.advance_if(kw::Trusted) {
457        if cx.advance_if(token::OpenParen) {
458            parse_reason(cx)?;
459            cx.expect(token::CloseParen)?;
460        }
461        attrs.normal.push(Attr::Trusted(Trusted::Yes));
462    } else if lookahead.advance_if(sym::hide) {
463        attrs.syntax.push(SyntaxAttr::Hide);
464    } else if lookahead.advance_if(kw::Opaque) {
465        attrs.syntax.push(SyntaxAttr::Opaque);
466    } else if lookahead.advance_if(kw::Reft) {
467        attrs.syntax.push(SyntaxAttr::Reft);
468    } else if lookahead.advance_if(kw::RefinedBy) {
469        attrs
470            .syntax
471            .push(SyntaxAttr::RefinedBy(delimited(cx, Parenthesis, parse_refined_by)?));
472    } else if lookahead.advance_if(kw::Invariant) {
473        attrs
474            .syntax
475            .push(SyntaxAttr::Invariant(delimited(cx, Parenthesis, |cx| parse_expr(cx, true))?));
476    } else if lookahead.advance_if(sym::no_panic_if) {
477        attrs
478            .syntax
479            .push(SyntaxAttr::NoPanicIf(parse_expr(cx, true)?));
480    } else {
481        return Err(lookahead.into_error());
482    };
483    cx.expect(token::CloseBracket)
484}
485
486fn parse_attrs(cx: &mut ParseCtxt) -> ParseResult<ParsedAttrs> {
487    let mut attrs = ParsedAttrs::default();
488    repeat_while(cx, token::Pound, |cx| parse_attr(cx, &mut attrs))?;
489    Ok(attrs)
490}
491
492/// ```text
493/// ⟨func_def⟩ := ⟨ # [ hide ] ⟩?
494///               fn ⟨ident⟩ ⟨ < ⟨ident⟩,* > ⟩?
495///               ( ⟨refine_param⟩,* )
496///               ->
497///               ⟨sort⟩
498/// ```
499fn parse_reft_func(cx: &mut ParseCtxt) -> ParseResult<SpecFunc> {
500    let attrs = parse_attrs(cx)?;
501    let hide = attrs.is_hide();
502    cx.expect(kw::Fn)?;
503    let name = parse_ident(cx)?;
504    let sort_vars = opt_angle(cx, Comma, parse_ident)?;
505    let params = parens(cx, Comma, |cx| parse_refine_param(cx, RequireSort::Yes))?;
506    cx.expect(token::RArrow)?;
507    let output = parse_sort(cx)?;
508    let body = if cx.peek(token::OpenBrace) {
509        Some(parse_block(cx)?)
510    } else {
511        cx.expect(token::Semi)?;
512        None
513    };
514    Ok(SpecFunc { name, sort_vars, params, output, body, hide })
515}
516
517/// ```text
518/// ⟨qualifier_kind⟩ :=  local
519///                   |  invariant
520/// ```
521fn parse_qualifier_kind(cx: &mut ParseCtxt) -> ParseResult<HintKind> {
522    let mut lookahead = cx.lookahead1();
523    if lookahead.advance_if(kw::Local) {
524        Ok(HintKind::Local)
525    } else if lookahead.advance_if(kw::Invariant) {
526        Ok(HintKind::Enclosing)
527    } else {
528        Ok(HintKind::Global)
529    }
530}
531
532/// ```text
533/// ⟨qualifier⟩ :=  ⟨ qualifier_kind ⟩?
534///                 qualifier ⟨ident⟩ ( ⟨qualifier_param⟩,* )
535///                 ⟨block⟩
536/// ```
537fn parse_qualifier(cx: &mut ParseCtxt) -> ParseResult<Qualifier> {
538    let lo = cx.lo();
539    let kind = parse_qualifier_kind(cx)?;
540    cx.expect(kw::Qualifier)?;
541    let mut name = parse_ident(cx)?;
542    let (mut params, mut wildcards): (RefineParams, Vec<bool>) =
543        parens(cx, Comma, parse_qualifier_param)?
544            .into_iter()
545            .unzip();
546    let expr = parse_block(cx)?;
547    let hi = cx.hi();
548
549    if let HintKind::Enclosing = kind {
550        // Append the body's free variables that weren't given an explicit sort, keeping the
551        // order in which they appear in the body.
552        let explicit: UnordSet<_> = params.iter().map(|param| param.ident).collect();
553        params.extend(
554            expr.free_vars()
555                .into_iter()
556                .filter(|ident| !explicit.contains(ident))
557                .map(|ident| {
558                    RefineParam {
559                        ident,
560                        sort: Sort::Infer,
561                        mode: None,
562                        span: ident.span,
563                        node_id: cx.next_node_id(),
564                    }
565                }),
566        );
567        // Params synthesized from the body's free variables are bound to values in the enclosing
568        // function, so they are never wildcards.
569        wildcards.resize(params.len(), false);
570
571        // Uniquify the name so hints don't collide with each other (qualifier names are
572        // crate-global). The span alone is not enough: every expansion of a macro like
573        // `qualifier!` transcribes the same `name` token, so all of them share a span. The
574        // node id is a session-global counter, so it distinguishes them.
575        let span = name.span;
576        let str = format!(
577            "{}_{}_{}_{}",
578            name.name.to_ident_string(),
579            span.lo().0,
580            span.hi().0,
581            cx.next_node_id().as_usize()
582        );
583        name = Ident { name: Symbol::intern(&str), ..name };
584    }
585
586    debug_assert_eq!(params.len(), wildcards.len());
587    Ok(Qualifier { name, params, wildcards, expr, span: cx.mk_span(lo, hi), kind })
588}
589
590/// ```text
591/// ⟨sort_decl⟩ := opaque sort ⟨ident⟩ ;
592/// ```
593fn parse_sort_decl(cx: &mut ParseCtxt) -> ParseResult<SortDecl> {
594    cx.expect(kw::Opaque)?;
595    cx.expect(kw::Sort)?;
596    let name = parse_ident(cx)?;
597    let sort_vars = opt_angle(cx, Comma, parse_ident)?;
598    cx.expect(token::Semi)?;
599    Ok(SortDecl { name, sort_vars })
600}
601
602/// `⟨bin_op⟩ := ⟨ a binary operator ⟩
603fn parse_binop(cx: &mut ParseCtxt) -> ParseResult<BinOp> {
604    let (op, ntokens) = cx
605        .peek_binop()
606        .ok_or_else(|| cx.unexpected_token(vec![Expected::Str("binary operator")]))?;
607    cx.advance_by(ntokens);
608    Ok(op)
609}
610
611/// ```text
612/// ⟨primop_prop⟩ := local? property ⟨ident⟩ [ ⟨bin_op⟩ ] ( ⟨refine_param⟩,* ) ⟨block⟩
613/// ```
614fn parse_primop_property(cx: &mut ParseCtxt) -> ParseResult<PrimOpProp> {
615    let lo = cx.lo();
616    let kind = if cx.advance_if(kw::Local) { HintKind::Local } else { HintKind::Global };
617    cx.expect(kw::Property)?;
618
619    // Parse the name
620    let name = parse_ident(cx)?;
621
622    // Parse the operator
623    cx.expect(token::OpenBracket)?;
624    let op = parse_binop(cx)?;
625    cx.expect(token::CloseBracket)?;
626
627    // Parse the args
628    let params = parens(cx, Comma, |cx| parse_refine_param(cx, RequireSort::No))?;
629
630    let body = parse_block(cx)?;
631    let hi = cx.hi();
632
633    Ok(PrimOpProp { name, kind, op, params, body, span: cx.mk_span(lo, hi) })
634}
635
636/// ```text
637/// ⟨axiom⟩ := ⟨ local ⟩? axiom ⟨ident⟩ ( ⟨refine_param⟩,* ) ⟨block⟩
638/// ```
639fn parse_axiom(cx: &mut ParseCtxt) -> ParseResult<Axiom> {
640    let lo = cx.lo();
641    let kind = if cx.advance_if(kw::Local) { HintKind::Local } else { HintKind::Global };
642    cx.expect(kw::Axiom)?;
643    let name = parse_ident(cx)?;
644    let params = parens(cx, Comma, |cx| parse_refine_param(cx, RequireSort::Yes))?;
645    let body = parse_block(cx)?;
646    let hi = cx.hi();
647    Ok(Axiom { name, params, body, span: cx.mk_span(lo, hi), kind })
648}
649
650/// ```text
651/// ⟨use_item⟩ := use ⟨use_tree⟩ ;
652/// ```
653fn parse_use_item(cx: &mut ParseCtxt) -> ParseResult<UseTree> {
654    cx.expect(kw::Use)?;
655    let tree = parse_use_tree(cx)?;
656    cx.expect(token::Semi)?;
657    Ok(tree)
658}
659
660/// ```text
661/// ⟨use_tree⟩ := ⟨ident⟩ ( :: ⟨ident⟩ )* ( :: { ⟨use_tree⟩,* } )?
662/// ```
663fn parse_use_tree(cx: &mut ParseCtxt) -> ParseResult<UseTree> {
664    let lo = cx.lo();
665    let mut segments = vec![parse_expr_path_segment(cx)?];
666    let mut hi = cx.hi();
667    let kind = loop {
668        if !cx.advance_if(token::PathSep) {
669            break UseTreeKind::Simple;
670        }
671        if cx.advance_if(token::OpenBrace) {
672            let items = punctuated_until(cx, token::Comma, token::CloseBrace, parse_use_tree)?;
673            cx.expect(token::CloseBrace)?;
674            break UseTreeKind::Nested(items);
675        }
676        segments.push(parse_expr_path_segment(cx)?);
677        hi = cx.hi();
678    };
679    let prefix = ExprPath { segments, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) };
680    Ok(UseTree { prefix, kind })
681}
682
683pub(crate) fn parse_trait_assoc_refts(cx: &mut ParseCtxt) -> ParseResult<Vec<TraitAssocReft>> {
684    until(cx, token::Eof, parse_trait_assoc_reft)
685}
686
687/// ```text
688/// ⟨trait_assoc_reft⟩ := fn ⟨ident⟩ ( ⟨refine_param⟩,* ) -> ⟨base_sort⟩ ;?
689///                     | fn ⟨ident⟩ ( ⟨refine_param⟩,* ) -> ⟨base_sort⟩ ⟨block⟩
690///                     | final fn ⟨ident⟩ ( ⟨refine_param⟩,* ) -> ⟨base_sort⟩ ⟨block⟩
691/// ```
692fn parse_trait_assoc_reft(cx: &mut ParseCtxt) -> ParseResult<TraitAssocReft> {
693    let lo = cx.lo();
694    let final_ = cx.advance_if(kw::Final);
695    cx.expect(kw::Fn)?;
696    let name = parse_ident(cx)?;
697    let params = parens(cx, Comma, |cx| parse_refine_param(cx, RequireSort::Yes))?;
698    cx.expect(token::RArrow)?;
699    let output = parse_base_sort(cx)?;
700    let body = if cx.peek(token::OpenBrace) {
701        Some(parse_block(cx)?)
702    } else {
703        cx.advance_if(token::Semi);
704        None
705    };
706    let hi = cx.hi();
707    Ok(TraitAssocReft { name, params, output, body, span: cx.mk_span(lo, hi), final_ })
708}
709
710pub(crate) fn parse_impl_assoc_refts(cx: &mut ParseCtxt) -> ParseResult<Vec<ImplAssocReft>> {
711    until(cx, token::Eof, parse_impl_assoc_reft)
712}
713
714/// ```text
715/// ⟨impl_assoc_reft⟩ := fn ⟨ident⟩ ( ⟨refine_param⟩,* ) -> ⟨base_sort⟩ ⟨block⟩
716/// ```
717fn parse_impl_assoc_reft(cx: &mut ParseCtxt) -> ParseResult<ImplAssocReft> {
718    let lo = cx.lo();
719    cx.expect(kw::Fn)?;
720    let name = parse_ident(cx)?;
721    let params = parens(cx, Comma, |cx| parse_refine_param(cx, RequireSort::Yes))?;
722    cx.expect(token::RArrow)?;
723    let output = parse_base_sort(cx)?;
724    let body = parse_block(cx)?;
725    let hi = cx.hi();
726    Ok(ImplAssocReft { name, params, output, body, span: cx.mk_span(lo, hi) })
727}
728
729/// ```text
730/// ⟨refined_by⟩ := ⟨refine_param⟩,*
731/// ```
732pub(crate) fn parse_refined_by(cx: &mut ParseCtxt) -> ParseResult<RefineParams> {
733    punctuated_until(cx, Comma, token::Eof, |cx| parse_refine_param(cx, RequireSort::Yes))
734}
735
736/// ```text
737/// ⟨variant⟩ := ⟨fields⟩ -> ⟨variant_ret⟩
738///            | ⟨fields⟩
739///            | ⟨variant_ret⟩
740/// ```
741pub(crate) fn parse_variant(cx: &mut ParseCtxt, ret_arrow: bool) -> ParseResult<VariantDef> {
742    let lo = cx.lo();
743    let mut fields = vec![];
744    let mut ret = None;
745    let ident = if ret_arrow || cx.peek2(NonReserved, token::OpenParen) {
746        Some(parse_ident(cx)?)
747    } else {
748        None
749    };
750    if cx.peek(token::OpenParen) || cx.peek(token::OpenBrace) {
751        fields = parse_fields(cx)?;
752        if cx.advance_if(token::RArrow) {
753            ret = Some(parse_variant_ret(cx)?);
754        }
755    } else {
756        if ret_arrow {
757            cx.expect(token::RArrow)?;
758        }
759        ret = Some(parse_variant_ret(cx)?);
760    };
761    let hi = cx.hi();
762    Ok(VariantDef { ident, fields, ret, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
763}
764
765/// ```text
766/// ⟨fields⟩ := ( ⟨ty⟩,* ) | { ⟨ty⟩,* }
767/// ```
768fn parse_fields(cx: &mut ParseCtxt) -> ParseResult<Vec<Ty>> {
769    let mut lookahead = cx.lookahead1();
770    if lookahead.peek(token::OpenParen) {
771        parens(cx, Comma, parse_type)
772    } else if lookahead.peek(token::OpenBrace) {
773        braces(cx, Comma, parse_type)
774    } else {
775        Err(lookahead.into_error())
776    }
777}
778
779/// ```text
780/// ⟨variant_ret⟩ := ⟨path⟩ ⟨ [ ⟨refine_arg⟩,? ] ⟩?
781/// ```
782fn parse_variant_ret(cx: &mut ParseCtxt) -> ParseResult<VariantRet> {
783    let path = parse_path(cx)?;
784    let indices = if cx.peek(token::OpenBracket) {
785        parse_indices(cx)?
786    } else {
787        let hi = cx.hi();
788        Indices { indices: vec![], span: cx.mk_span(hi, hi) }
789    };
790    Ok(VariantRet { path, indices })
791}
792
793pub(crate) fn parse_type_alias(cx: &mut ParseCtxt) -> ParseResult<TyAlias> {
794    let lo = cx.lo();
795    cx.expect(kw::Type)?;
796    let ident = parse_ident(cx)?;
797    let generics = parse_opt_generics(cx)?;
798    let params = if cx.peek(token::OpenParen) {
799        parens(cx, Comma, |cx| parse_refine_param(cx, RequireSort::Yes))?
800    } else {
801        vec![]
802    };
803    let index = if cx.peek(token::OpenBracket) {
804        Some(delimited(cx, Bracket, |cx| parse_refine_param(cx, RequireSort::Yes))?)
805    } else {
806        None
807    };
808    cx.expect(token::Eq)?;
809    let ty = parse_type(cx)?;
810    let hi = cx.hi();
811    Ok(TyAlias {
812        ident,
813        generics,
814        params,
815        index,
816        ty,
817        node_id: cx.next_node_id(),
818        span: cx.mk_span(lo, hi),
819    })
820}
821
822fn parse_opt_generics(cx: &mut ParseCtxt) -> ParseResult<Generics> {
823    if !cx.peek(LAngle) {
824        let hi = cx.hi();
825        return Ok(Generics { params: vec![], predicates: None, span: cx.mk_span(hi, hi) });
826    }
827    let lo = cx.lo();
828    let params = angle(cx, Comma, parse_generic_param)?;
829    let hi = cx.hi();
830    Ok(Generics { params, predicates: None, span: cx.mk_span(lo, hi) })
831}
832
833fn parse_generic_param(cx: &mut ParseCtxt) -> ParseResult<GenericParam> {
834    let name = parse_ident(cx)?;
835    Ok(GenericParam { name, node_id: cx.next_node_id() })
836}
837
838fn invalid_ident_err(ident: &Ident) -> ParseError {
839    ParseError { kind: crate::ParseErrorKind::InvalidBinding, span: ident.span }
840}
841
842fn mut_as_strg(inputs: Vec<FnInput>, ensures: &[Ensures]) -> ParseResult<Vec<FnInput>> {
843    // 1. Gather ensures
844    let locs = ensures
845        .iter()
846        .filter_map(|ens| if let Ensures::Type(ident, _, _) = ens { Some(ident) } else { None })
847        .collect::<HashSet<_>>();
848    // 2. Walk over inputs and transform references mentioned in ensures
849    let mut res = vec![];
850    for input in inputs {
851        if let FnInput::Ty(Some(ident), _, _) = &input
852            && locs.contains(&ident)
853        {
854            // a known location: better be a mut or else, error!
855            let FnInput::Ty(Some(ident), ty, id) = input else {
856                return Err(invalid_ident_err(ident));
857            };
858            let TyKind::Ref(Mutability::Mut, inner_ty) = ty.kind else {
859                return Err(invalid_ident_err(&ident));
860            };
861            res.push(FnInput::StrgRef(ident, *inner_ty, id));
862        } else {
863            // not a known location, leave unchanged
864            res.push(input);
865        }
866    }
867    Ok(res)
868}
869
870/// ```text
871/// ⟨fn_sig⟩ := ⟨asyncness⟩ fn ⟨ident⟩?
872///             ⟨ [ ⟨refine_param⟩,* ] ⟩?
873///             ( ⟨fn_inputs⟩,* )
874///             ⟨-> ⟨ty⟩⟩?
875///             ⟨requires⟩ ⟨ensures⟩ ⟨where⟩
876/// ```
877pub(crate) fn parse_fn_sig<T: PeekExpected>(cx: &mut ParseCtxt, end: T) -> ParseResult<FnSig> {
878    let lo = cx.lo();
879    let asyncness = parse_asyncness(cx);
880    cx.expect(kw::Fn)?;
881    let ident = if cx.peek(NonReserved) { Some(parse_ident(cx)?) } else { None };
882    let mut generics = parse_opt_generics(cx)?;
883    let params = if cx.peek(token::OpenBracket) {
884        brackets(cx, Comma, |cx| parse_refine_param(cx, RequireSort::Maybe))?
885    } else {
886        vec![]
887    };
888    let inputs = parens(cx, Comma, parse_fn_input)?;
889    let returns = parse_fn_ret(cx)?;
890    let requires = parse_opt_requires(cx)?;
891    let ensures = parse_opt_ensures(cx)?;
892    let inputs = mut_as_strg(inputs, &ensures)?;
893    generics.predicates = parse_opt_where(cx)?;
894    cx.expect(end)?;
895    let hi = cx.hi();
896    Ok(FnSig {
897        asyncness,
898        generics,
899        params,
900        ident,
901        inputs,
902        requires,
903        output: FnOutput { returns, ensures, node_id: cx.next_node_id() },
904        node_id: cx.next_node_id(),
905        span: cx.mk_span(lo, hi),
906        no_panic: None, // We attach the `no_panic` expr later
907    })
908}
909
910/// ```text
911/// ⟨requires⟩ := ⟨ requires ⟨requires_clause⟩,* ⟩?
912/// ```
913fn parse_opt_requires(cx: &mut ParseCtxt) -> ParseResult<Vec<Requires>> {
914    if !cx.advance_if(kw::Requires) {
915        return Ok(vec![]);
916    }
917    punctuated_until(
918        cx,
919        Comma,
920        |t: TokenKind| t.is_keyword(kw::Ensures) || t.is_keyword(kw::Where) || t.is_eof(),
921        parse_requires_clause,
922    )
923}
924
925/// ```text
926/// ⟨requires_clause⟩ := ⟨ forall ⟨refine_param⟩,+ . ⟩? ⟨expr⟩
927/// ```
928fn parse_requires_clause(cx: &mut ParseCtxt) -> ParseResult<Requires> {
929    let mut params = vec![];
930    if cx.advance_if(kw::Forall) {
931        params = sep1(cx, Comma, |cx| parse_refine_param(cx, RequireSort::Maybe))?;
932        cx.expect(token::Dot)?;
933    }
934    let pred = parse_expr(cx, true)?;
935    Ok(Requires { params, pred })
936}
937
938/// ```text
939/// ⟨ensures⟩ := ⟨ensures ⟨ensures_clause⟩,*⟩?
940/// ```
941fn parse_opt_ensures(cx: &mut ParseCtxt) -> ParseResult<Vec<Ensures>> {
942    if !cx.advance_if(kw::Ensures) {
943        return Ok(vec![]);
944    }
945    punctuated_until(
946        cx,
947        Comma,
948        |t: TokenKind| t.is_keyword(kw::Where) || t.is_eof(),
949        parse_ensures_clause,
950    )
951}
952
953/// ```text
954/// ⟨ensures_clause⟩ :=  ⟨ident⟩ : ⟨ty⟩
955///                   |  ⟨expr⟩
956/// ```
957fn parse_ensures_clause(cx: &mut ParseCtxt) -> ParseResult<Ensures> {
958    if cx.peek2(NonReserved, token::Colon) {
959        // ⟨ident⟩ : ⟨ty⟩
960        let ident = parse_ident(cx)?;
961        cx.expect(token::Colon)?;
962        let ty = parse_type(cx)?;
963        Ok(Ensures::Type(ident, ty, cx.next_node_id()))
964    } else {
965        // ⟨expr⟩
966        Ok(Ensures::Pred(parse_expr(cx, true)?))
967    }
968}
969
970fn parse_opt_where(cx: &mut ParseCtxt) -> ParseResult<Option<Vec<WhereBoundPredicate>>> {
971    if !cx.advance_if(kw::Where) {
972        return Ok(None);
973    }
974    Ok(Some(punctuated_until(cx, Comma, token::Eof, parse_where_bound)?))
975}
976
977fn parse_where_bound(cx: &mut ParseCtxt) -> ParseResult<WhereBoundPredicate> {
978    let lo = cx.lo();
979    let bounded_ty = parse_type(cx)?;
980    cx.expect(token::Colon)?;
981    let bounds = parse_generic_bounds(cx)?;
982    let hi = cx.hi();
983    Ok(WhereBoundPredicate { span: cx.mk_span(lo, hi), bounded_ty, bounds })
984}
985
986/// ```text
987/// ⟨fn_ret⟩ := ⟨ -> ⟨ty⟩ ⟩?
988/// ```
989fn parse_fn_ret(cx: &mut ParseCtxt) -> ParseResult<FnRetTy> {
990    if cx.advance_if(token::RArrow) {
991        Ok(FnRetTy::Ty(Box::new(parse_type(cx)?)))
992    } else {
993        let hi = cx.hi();
994        Ok(FnRetTy::Default(cx.mk_span(hi, hi)))
995    }
996}
997
998/// ```text
999/// ⟨fn_input⟩ := ⟨ident⟩ : &strg ⟨ty⟩
1000///             | ⟨ident⟩ : ⟨path⟩ { ⟨expr⟩ }
1001///             | ⟨ident⟩ : ⟨ty⟩
1002///             | ⟨ty⟩
1003/// ```
1004fn parse_fn_input(cx: &mut ParseCtxt) -> ParseResult<FnInput> {
1005    if cx.peek2(NonReserved, token::Colon) {
1006        let bind = parse_ident(cx)?;
1007        cx.expect(token::Colon)?;
1008        if cx.advance_if2(token::And, kw::Strg) {
1009            // ⟨ident⟩ : &strg ⟨ty⟩
1010            Ok(FnInput::StrgRef(bind, parse_type(cx)?, cx.next_node_id()))
1011        } else if cx.peek(NonReserved) {
1012            let path = parse_path(cx)?;
1013            if cx.peek3(token::OpenBrace, NonReserved, token::Colon) {
1014                // ⟨ident⟩ : ⟨path⟩ { ⟨ident⟩ : ⟨expr⟩ }
1015                let bty = path_to_bty(path);
1016                let ty = parse_bty_exists(cx, bty)?;
1017                Ok(FnInput::Ty(Some(bind), ty, cx.next_node_id()))
1018            } else if cx.peek(token::OpenBrace) {
1019                // ⟨ident⟩ : ⟨path⟩ { ⟨expr⟩ }
1020                let pred = delimited(cx, Brace, |cx| parse_expr(cx, true))?;
1021                Ok(FnInput::Constr(bind, path, pred, cx.next_node_id()))
1022            } else {
1023                // ⟨ident⟩ : ⟨ty⟩
1024                let bty = path_to_bty(path);
1025                let ty = parse_bty_rhs(cx, bty)?;
1026                Ok(FnInput::Ty(Some(bind), ty, cx.next_node_id()))
1027            }
1028        } else {
1029            // ⟨ident⟩ : ⟨ty⟩
1030            Ok(FnInput::Ty(Some(bind), parse_type(cx)?, cx.next_node_id()))
1031        }
1032    } else {
1033        // ⟨ty⟩
1034        Ok(FnInput::Ty(None, parse_type(cx)?, cx.next_node_id()))
1035    }
1036}
1037
1038/// ```text
1039/// ⟨asyncness⟩ := async?
1040/// ```
1041fn parse_asyncness(cx: &mut ParseCtxt) -> Async {
1042    let lo = cx.lo();
1043    if cx.advance_if(kw::Async) {
1044        Async::Yes { node_id: cx.next_node_id(), span: cx.mk_span(lo, cx.hi()) }
1045    } else {
1046        Async::No
1047    }
1048}
1049
1050enum Reft {
1051    Exi(Ident, Expr),
1052    Idx(Indices),
1053    None,
1054}
1055
1056fn parse_reft(cx: &mut ParseCtxt) -> ParseResult<Reft> {
1057    if cx.peek(token::OpenBrace) {
1058        let (bind, pred) = delimited(cx, Brace, |cx| {
1059            let bind = parse_ident(cx)?;
1060            cx.expect(token::Colon)?;
1061            let pred = parse_block_expr(cx)?;
1062            Ok((bind, pred))
1063        })?;
1064        Ok(Reft::Exi(bind, pred))
1065    } else if cx.peek(token::OpenBracket) {
1066        let indices = parse_indices(cx)?;
1067        Ok(Reft::Idx(indices))
1068    } else {
1069        Ok(Reft::None)
1070    }
1071}
1072
1073/// ```text
1074/// ⟨ty⟩ := _
1075///       | { ⟨ident⟩ ⟨,⟨ident⟩⟩* . ⟨ty⟩ | ⟨block_expr⟩ }
1076///       | ( ⟨ty⟩,* )
1077///       | { ⟨ty⟩ | ⟨block_expr⟩ }
1078///       | { ⟨refine_param⟩ ⟨,⟨refine_param⟩⟩* . ⟨ty⟩ | ⟨block_expr⟩ }
1079///       | & mut? ⟨ty⟩
1080///       | * const ⟨ { ⟨ident⟩ : ⟨expr⟩ } ⟩? ⟨ty⟩
1081///       | * mut ⟨ { ⟨ident⟩ : ⟨expr⟩ } ⟩? ⟨ty⟩
1082///       | [ ⟨ty⟩ ; ⟨const_arg⟩ ]
1083///       | impl ⟨path⟩
1084///       | unsafe? ⟨extern ⟨string⟩?⟩? fn ( ⟨ty⟩,* ) ⟨fn_ret⟩
1085///       | ⟨bty⟩
1086///       | ⟨bty⟩ [ ⟨refine_arg⟩,* ]
1087///       | ⟨bty⟩ { ⟨ident⟩ : ⟨block_expr⟩ }
1088///
1089/// ⟨bty⟩ := ⟨path⟩ | ⟨qpath⟩ | [ ⟨ty⟩ ]
1090/// ```
1091pub(crate) fn parse_type(cx: &mut ParseCtxt) -> ParseResult<Ty> {
1092    let lo = cx.lo();
1093    let mut lookahead = cx.lookahead1();
1094    let kind = if lookahead.advance_if(kw::Underscore) {
1095        TyKind::Hole
1096    } else if lookahead.advance_if(token::OpenParen) {
1097        // ( ⟨ty⟩,* )
1098        let (mut tys, trailing) =
1099            punctuated_with_trailing(cx, Comma, token::CloseParen, parse_type)?;
1100        cx.expect(token::CloseParen)?;
1101        if tys.len() == 1 && !trailing {
1102            return Ok(tys.remove(0));
1103        } else {
1104            TyKind::Tuple(tys)
1105        }
1106    } else if lookahead.peek(token::OpenBrace) {
1107        delimited(cx, Brace, |cx| {
1108            if cx.peek2(NonReserved, AnyOf([token::Comma, token::Dot, token::Colon])) {
1109                // { ⟨refine_param⟩ ⟨,⟨refine_param⟩⟩* . ⟨ty⟩ | ⟨block_expr⟩ }
1110                parse_general_exists(cx)
1111            } else {
1112                // { ⟨ty⟩ | ⟨block_expr⟩ }
1113                let ty = parse_type(cx)?;
1114                cx.expect(token::Or)?;
1115                let pred = parse_block_expr(cx)?;
1116                Ok(TyKind::Constr(pred, Box::new(ty)))
1117            }
1118        })?
1119    } else if lookahead.advance_if(token::And) {
1120        //  & mut? ⟨ty⟩
1121        let mutbl = if cx.advance_if(kw::Mut) { Mutability::Mut } else { Mutability::Not };
1122        TyKind::Ref(mutbl, Box::new(parse_type(cx)?))
1123    } else if lookahead.advance_if(token::Star) {
1124        //  * const ⟨ { ⟨ident⟩ : ⟨expr⟩ } ⟩? ⟨ty⟩ | * mut ⟨ { ⟨ident⟩ : ⟨expr⟩ } ⟩? ⟨ty⟩
1125        let mutbl = if cx.advance_if(kw::Mut) {
1126            Mutability::Mut
1127        } else {
1128            cx.expect(kw::Const)?;
1129            Mutability::Not
1130        };
1131        // Parse optional refinement on the pointer value: {v: pred}
1132        let reft = parse_reft(cx)?;
1133        let inner_ty = parse_type(cx)?;
1134        let bty = BaseTy {
1135            kind: BaseTyKind::Ptr(mutbl, Box::new(inner_ty)),
1136            span: cx.mk_span(lo, cx.hi()),
1137        };
1138        match reft {
1139            Reft::Exi(bind, pred) => TyKind::Exists { bind, bty, pred },
1140            Reft::Idx(indices) => TyKind::Indexed { bty, indices },
1141            Reft::None => TyKind::Base(bty),
1142        }
1143    } else if lookahead.advance_if(token::OpenBracket) {
1144        let ty = parse_type(cx)?;
1145        if cx.advance_if(token::Semi) {
1146            // [ ⟨ty⟩ ; ⟨const_arg⟩ ]
1147            let len = parse_const_arg(cx)?;
1148            cx.expect(token::CloseBracket)?;
1149            TyKind::Array(Box::new(ty), len)
1150        } else {
1151            // [ ⟨ty⟩ ] ...
1152            cx.expect(token::CloseBracket)?;
1153            let span = cx.mk_span(lo, cx.hi());
1154            let kind = BaseTyKind::Slice(Box::new(ty));
1155            return parse_bty_rhs(cx, BaseTy { kind, span });
1156        }
1157    } else if lookahead.advance_if(kw::Impl) {
1158        // impl ⟨bounds⟩
1159        TyKind::ImplTrait(cx.next_node_id(), parse_generic_bounds(cx)?)
1160    } else if lookahead.peek(kw::Fn) || lookahead.peek(kw::Unsafe) || lookahead.peek(kw::Extern) {
1161        // unsafe? ⟨extern ⟨string⟩?⟩? fn ( ⟨ty⟩,* ) ⟨fn_ret⟩
1162        let safety =
1163            if cx.advance_if(kw::Unsafe) { surface::Safety::Unsafe } else { surface::Safety::Safe };
1164        let abi = if cx.peek(kw::Extern) {
1165            let extern_lo = cx.lo();
1166            cx.advance();
1167            if let Token { kind: token::Literal(Lit { kind: LitKind::Str, symbol, .. }), lo, hi } =
1168                cx.at(0)
1169            {
1170                cx.advance();
1171                Some(Ident { name: symbol, span: cx.mk_span(lo, hi) })
1172            } else {
1173                // `extern fn` is `extern "C" fn`
1174                Some(Ident { name: sym::C, span: cx.mk_span(extern_lo, cx.hi()) })
1175            }
1176        } else {
1177            None
1178        };
1179        cx.expect(kw::Fn)?;
1180        let inputs = parens(cx, Comma, parse_type)?;
1181        let output = parse_fn_ret(cx)?;
1182        let span = cx.mk_span(lo, cx.hi());
1183        TyKind::BareFn(Box::new(BareFnTy {
1184            safety,
1185            abi,
1186            inputs,
1187            output,
1188            node_id: cx.next_node_id(),
1189            span,
1190        }))
1191    } else if lookahead.peek(NonReserved) {
1192        // ⟨path⟩ ...
1193        let path = parse_path(cx)?;
1194        let bty = path_to_bty(path);
1195        return parse_bty_rhs(cx, bty);
1196    } else if lookahead.peek(LAngle) {
1197        // ⟨qpath⟩ ...
1198        let bty = parse_qpath(cx)?;
1199        return parse_bty_rhs(cx, bty);
1200    } else {
1201        return Err(lookahead.into_error());
1202    };
1203    let hi = cx.hi();
1204    Ok(Ty { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1205}
1206
1207/// ```text
1208/// ⟨qpath⟩ := < ⟨ty⟩ as ⟨segments⟩> :: ⟨segments⟩
1209/// ```
1210fn parse_qpath(cx: &mut ParseCtxt) -> ParseResult<BaseTy> {
1211    let lo = cx.lo();
1212    cx.expect(LAngle)?;
1213    let qself = parse_type(cx)?;
1214    cx.expect(kw::As)?;
1215    let mut segments = parse_segments(cx)?;
1216    cx.expect(RAngle)?;
1217    cx.expect(token::PathSep)?;
1218    segments.extend(parse_segments(cx)?);
1219    let hi = cx.hi();
1220
1221    let span = cx.mk_span(lo, hi);
1222    let path = Path { segments, refine: vec![], node_id: cx.next_node_id(), span };
1223    let kind = BaseTyKind::Path(Some(Box::new(qself)), path);
1224    Ok(BaseTy { kind, span })
1225}
1226
1227/// ```text
1228/// { ⟨refine_param⟩ ⟨,⟨refine_param⟩⟩* . ⟨ty⟩ | ⟨block_expr⟩ }
1229/// ```
1230fn parse_general_exists(cx: &mut ParseCtxt) -> ParseResult<TyKind> {
1231    let params = sep1(cx, Comma, |cx| parse_refine_param(cx, RequireSort::Maybe))?;
1232    cx.expect(token::Dot)?;
1233    let ty = parse_type(cx)?;
1234    let pred = if cx.advance_if(token::Or) { Some(parse_block_expr(cx)?) } else { None };
1235    Ok(TyKind::GeneralExists { params, ty: Box::new(ty), pred })
1236}
1237
1238/// ```text
1239///    ⟨bty⟩ [ ⟨refine_arg⟩,* ]
1240/// |  ⟨bty⟩ { ⟨ident⟩ : ⟨block_expr⟩ }
1241/// |  ⟨bty⟩
1242/// ```
1243fn parse_bty_rhs(cx: &mut ParseCtxt, bty: BaseTy) -> ParseResult<Ty> {
1244    let lo = bty.span.lo();
1245    if cx.peek(token::OpenBracket) {
1246        // ⟨bty⟩ [ ⟨refine_arg⟩,* ]
1247        let indices = parse_indices(cx)?;
1248        let hi = cx.hi();
1249        let kind = TyKind::Indexed { bty, indices };
1250        Ok(Ty { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1251    } else if cx.peek(token::OpenBrace) {
1252        // ⟨bty⟩ { ⟨ident⟩ : ⟨block_expr⟩ }
1253        parse_bty_exists(cx, bty)
1254    } else {
1255        // ⟨bty⟩
1256        let hi = cx.hi();
1257        let kind = TyKind::Base(bty);
1258        Ok(Ty { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1259    }
1260}
1261
1262/// ```text
1263/// ⟨bty⟩ { ⟨ident⟩ : ⟨block_expr⟩ }
1264/// ```
1265fn parse_bty_exists(cx: &mut ParseCtxt, bty: BaseTy) -> ParseResult<Ty> {
1266    let lo = bty.span.lo();
1267    delimited(cx, Brace, |cx| {
1268        let bind = parse_ident(cx)?;
1269        cx.expect(token::Colon)?;
1270        let pred = parse_block_expr(cx)?;
1271        let hi = cx.hi();
1272        let kind = TyKind::Exists { bind, bty, pred };
1273        Ok(Ty { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1274    })
1275}
1276
1277fn path_to_bty(path: Path) -> BaseTy {
1278    let span = path.span;
1279    BaseTy { kind: BaseTyKind::Path(None, path), span }
1280}
1281
1282fn parse_indices(cx: &mut ParseCtxt) -> ParseResult<Indices> {
1283    let lo = cx.lo();
1284    let indices = brackets(cx, Comma, parse_refine_arg)?;
1285    let hi = cx.hi();
1286    Ok(Indices { indices, span: cx.mk_span(lo, hi) })
1287}
1288
1289fn parse_fn_bound_input(cx: &mut ParseCtxt) -> ParseResult<GenericArg> {
1290    let lo = cx.lo();
1291    let tys = parens(cx, Comma, parse_type)?;
1292    let hi = cx.hi();
1293    let kind = TyKind::Tuple(tys);
1294    let span = cx.mk_span(lo, hi);
1295    let in_ty = Ty { kind, node_id: cx.next_node_id(), span };
1296    Ok(GenericArg { kind: GenericArgKind::Type(in_ty), node_id: cx.next_node_id() })
1297}
1298
1299fn parse_fn_bound_output(cx: &mut ParseCtxt) -> ParseResult<GenericArg> {
1300    let lo = cx.lo();
1301
1302    let ty = if cx.advance_if(token::RArrow) {
1303        parse_type(cx)?
1304    } else {
1305        Ty { kind: TyKind::Tuple(vec![]), node_id: cx.next_node_id(), span: cx.mk_span(lo, lo) }
1306    };
1307    let hi = cx.hi();
1308    let ident = Ident { name: Output, span: cx.mk_span(lo, hi) };
1309    Ok(GenericArg { kind: GenericArgKind::Constraint(ident, ty), node_id: cx.next_node_id() })
1310}
1311
1312fn parse_fn_bound_path(cx: &mut ParseCtxt) -> ParseResult<Path> {
1313    let lo = cx.lo();
1314    let ident = parse_ident(cx)?;
1315    let in_arg = parse_fn_bound_input(cx)?;
1316    let out_arg = parse_fn_bound_output(cx)?;
1317    let args = vec![in_arg, out_arg];
1318    let segment = PathSegment { ident, args, node_id: cx.next_node_id() };
1319    let hi = cx.hi();
1320    Ok(Path {
1321        segments: vec![segment],
1322        refine: vec![],
1323        node_id: cx.next_node_id(),
1324        span: cx.mk_span(lo, hi),
1325    })
1326}
1327
1328fn parse_generic_bounds(cx: &mut ParseCtxt) -> ParseResult<GenericBounds> {
1329    let path = if cx.peek(sym::FnOnce) || cx.peek(sym::FnMut) || cx.peek(sym::Fn) {
1330        parse_fn_bound_path(cx)?
1331    } else {
1332        parse_path(cx)?
1333    };
1334    Ok(vec![TraitRef { path, node_id: cx.next_node_id() }])
1335}
1336
1337fn parse_const_arg(cx: &mut ParseCtxt) -> ParseResult<ConstArg> {
1338    let lo = cx.lo();
1339    let mut lookahead = cx.lookahead1();
1340    let kind = if lookahead.peek(AnyLit) {
1341        let len = parse_int(cx)?;
1342        ConstArgKind::Lit(len)
1343    } else if lookahead.peek(NonReserved) {
1344        ConstArgKind::Path(parse_path(cx)?)
1345    } else if lookahead.advance_if(kw::Underscore) {
1346        ConstArgKind::Infer
1347    } else {
1348        return Err(lookahead.into_error());
1349    };
1350    let hi = cx.hi();
1351    Ok(ConstArg { kind, span: cx.mk_span(lo, hi) })
1352}
1353
1354/// ```text
1355/// ⟨path⟩ := ⟨segments⟩ ⟨ ( ⟨refine_arg⟩,* ) ⟩?
1356/// ```
1357fn parse_path(cx: &mut ParseCtxt) -> ParseResult<Path> {
1358    let lo = cx.lo();
1359    let segments = parse_segments(cx)?;
1360    let refine =
1361        if cx.peek(token::OpenParen) { parens(cx, Comma, parse_refine_arg)? } else { vec![] };
1362    let hi = cx.hi();
1363    Ok(Path { segments, refine, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1364}
1365
1366/// ```text
1367/// ⟨segments⟩ := ⟨segment⟩ ⟨:: ⟨segment⟩ ⟩*
1368/// ```
1369fn parse_segments(cx: &mut ParseCtxt) -> ParseResult<Vec<PathSegment>> {
1370    sep1(cx, token::PathSep, parse_segment)
1371}
1372
1373/// ```text
1374/// ⟨segment⟩ := ⟨ident⟩ ⟨ < ⟨generic_arg⟩,* > ⟩?
1375/// ```
1376fn parse_segment(cx: &mut ParseCtxt) -> ParseResult<PathSegment> {
1377    let ident = parse_ident(cx)?;
1378    let args = opt_angle(cx, Comma, parse_generic_arg)?;
1379    Ok(PathSegment { ident, node_id: cx.next_node_id(), args })
1380}
1381
1382/// ```text
1383/// ⟨generic_arg⟩ := ⟨ty⟩ | ⟨ident⟩ = ⟨ty⟩
1384/// ```
1385fn parse_generic_arg(cx: &mut ParseCtxt) -> ParseResult<GenericArg> {
1386    let kind = if cx.peek2(NonReserved, token::Eq) {
1387        let ident = parse_ident(cx)?;
1388        cx.expect(token::Eq)?;
1389        let ty = parse_type(cx)?;
1390        GenericArgKind::Constraint(ident, ty)
1391    } else {
1392        GenericArgKind::Type(parse_type(cx)?)
1393    };
1394    Ok(GenericArg { kind, node_id: cx.next_node_id() })
1395}
1396
1397/// ```text
1398/// ⟨refine_arg⟩ :=  @ ⟨ident⟩
1399///               |  # ⟨ident⟩
1400///               |  |⟨⟨refine_parm⟩,*| ⟨expr⟩
1401///               |  ⟨expr⟩
1402/// ```
1403fn parse_refine_arg(cx: &mut ParseCtxt) -> ParseResult<RefineArg> {
1404    let lo = cx.lo();
1405    let arg = if cx.advance_if(token::At) {
1406        // @ ⟨ident⟩
1407        let bind = parse_ident(cx)?;
1408        let hi = cx.hi();
1409        RefineArg::Bind(bind, BindKind::At, cx.mk_span(lo, hi), cx.next_node_id())
1410    } else if cx.peek2(token::Pound, NonReserved) {
1411        // # ⟨ident⟩
1412        cx.expect(token::Pound)?;
1413        let bind = parse_ident(cx)?;
1414        let hi = cx.hi();
1415        RefineArg::Bind(bind, BindKind::Pound, cx.mk_span(lo, hi), cx.next_node_id())
1416    } else if cx.advance_if(Or) {
1417        let params =
1418            punctuated_until(cx, Comma, Or, |cx| parse_refine_param(cx, RequireSort::Maybe))?;
1419        cx.expect(Or)?;
1420        let body = parse_expr(cx, true)?;
1421        let hi = cx.hi();
1422        RefineArg::Abs(params, body, cx.mk_span(lo, hi), cx.next_node_id())
1423    } else {
1424        // ⟨expr⟩
1425        RefineArg::Expr(parse_expr(cx, true)?)
1426    };
1427    Ok(arg)
1428}
1429
1430/// Whether a sort is required in a refinement parameter declaration.
1431enum RequireSort {
1432    /// Definitely require a sort
1433    Yes,
1434    /// Optional sort. Use [`Sort::Infer`] if not present
1435    Maybe,
1436    /// Definitely do not not require a sort. Always use [`Sort::Infer`]
1437    No,
1438}
1439
1440fn parse_sort_if_required(cx: &mut ParseCtxt, require_sort: RequireSort) -> ParseResult<Sort> {
1441    match require_sort {
1442        RequireSort::No => Ok(Sort::Infer),
1443        RequireSort::Maybe => {
1444            if cx.advance_if(token::Colon) {
1445                parse_sort(cx)
1446            } else {
1447                Ok(Sort::Infer)
1448            }
1449        }
1450        RequireSort::Yes => {
1451            cx.expect(token::Colon)?;
1452            parse_sort(cx)
1453        }
1454    }
1455}
1456
1457/// ```text
1458/// ⟨refine_param⟩ := ⟨mode⟩? ⟨ident⟩ ⟨ : ⟨sort⟩ ⟩?    if require_sort is Maybe
1459///                 | ⟨mode⟩? ⟨ident⟩ : ⟨sort⟩         if require_sort is Yes
1460///                 | ⟨mode⟩? ⟨ident⟩                  if require_sort is No
1461/// ```
1462fn parse_refine_param(cx: &mut ParseCtxt, require_sort: RequireSort) -> ParseResult<RefineParam> {
1463    let lo = cx.lo();
1464    let mode = parse_opt_param_mode(cx);
1465    let ident = parse_ident(cx)?;
1466    let sort = parse_sort_if_required(cx, require_sort)?;
1467    let hi = cx.hi();
1468    Ok(RefineParam { mode, ident, sort, span: cx.mk_span(lo, hi), node_id: cx.next_node_id() })
1469}
1470
1471/// ```text
1472/// ⟨qualifier_param⟩ := #? ⟨refine_param⟩
1473/// ```
1474///
1475/// `#a: int` rather than fixpoint's `a#: int` because rustc lexes the enclosing attribute first and
1476/// rejects `a#` as a reserved prefix.
1477fn parse_qualifier_param(cx: &mut ParseCtxt) -> ParseResult<(RefineParam, bool)> {
1478    let is_wildcard = cx.advance_if(token::Pound);
1479    let param = parse_refine_param(cx, RequireSort::Yes)?;
1480    Ok((param, is_wildcard))
1481}
1482
1483/// ```text
1484/// ⟨mode⟩ := ⟨ hrn | hdl ⟩?
1485/// ```
1486fn parse_opt_param_mode(cx: &mut ParseCtxt) -> Option<ParamMode> {
1487    if cx.advance_if(kw::Hrn) {
1488        Some(ParamMode::Horn)
1489    } else if cx.advance_if(kw::Hdl) {
1490        Some(ParamMode::Hindley)
1491    } else {
1492        None
1493    }
1494}
1495
1496pub(crate) fn parse_expr(cx: &mut ParseCtxt, allow_struct: bool) -> ParseResult<Expr> {
1497    parse_binops(cx, Precedence::MIN, allow_struct)
1498}
1499
1500fn parse_binops(cx: &mut ParseCtxt, base: Precedence, allow_struct: bool) -> ParseResult<Expr> {
1501    let mut lhs = unary_expr(cx, allow_struct)?;
1502    loop {
1503        let lo = cx.lo();
1504        let Some((op, ntokens)) = cx.peek_binop() else { break };
1505        let precedence = Precedence::of_binop(&op);
1506        if precedence < base {
1507            break;
1508        }
1509        cx.advance_by(ntokens);
1510        let next = match precedence.associativity() {
1511            Associativity::Right => precedence,
1512            Associativity::Left => precedence.next(),
1513            Associativity::None => {
1514                if let ExprKind::BinaryOp(op, ..) = &lhs.kind
1515                    && Precedence::of_binop(op) == precedence
1516                {
1517                    return Err(cx.cannot_be_chained(lo, cx.hi()));
1518                }
1519                precedence.next()
1520            }
1521        };
1522        let rhs = parse_binops(cx, next, allow_struct)?;
1523        let span = lhs.span.to(rhs.span);
1524        lhs = Expr {
1525            kind: ExprKind::BinaryOp(op, Box::new([lhs, rhs])),
1526            node_id: cx.next_node_id(),
1527            span,
1528        }
1529    }
1530    Ok(lhs)
1531}
1532
1533/// ```text
1534/// ⟨unary_expr⟩ := - ⟨unary_expr⟩ | ! ⟨unary_expr⟩ | ⟨trailer_expr⟩
1535/// ```
1536fn unary_expr(cx: &mut ParseCtxt, allow_struct: bool) -> ParseResult<Expr> {
1537    let lo = cx.lo();
1538    let kind = if cx.advance_if(token::Minus) {
1539        ExprKind::UnaryOp(UnOp::Neg, Box::new(unary_expr(cx, allow_struct)?))
1540    } else if cx.advance_if(token::Bang) {
1541        ExprKind::UnaryOp(UnOp::Not, Box::new(unary_expr(cx, allow_struct)?))
1542    } else {
1543        return parse_trailer_expr(cx, allow_struct);
1544    };
1545    let hi = cx.hi();
1546    Ok(Expr { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1547}
1548
1549/// ```text
1550/// ⟨trailer_expr⟩ :=  ⟨trailer_expr⟩ . ⟨ident⟩
1551///                 |  ⟨trailer_expr⟩ . ⟨integer⟩
1552///                 |  ⟨trailer_expr⟩ ( ⟨expr⟩,* )
1553///                 |  ⟨atom⟩
1554/// ```
1555fn parse_trailer_expr(cx: &mut ParseCtxt, allow_struct: bool) -> ParseResult<Expr> {
1556    let lo = cx.lo();
1557    let mut e = parse_atom(cx, allow_struct)?;
1558    loop {
1559        let kind = if cx.advance_if(token::Dot) {
1560            if let Token { kind: token::Literal(lit), lo, hi } = cx.at(0)
1561                && let Lit { kind: LitKind::Integer, symbol: name, suffix: None, .. } = lit
1562            {
1563                // ⟨trailer_expr⟩ . ⟨integer⟩
1564                cx.advance();
1565                ExprKind::Dot(Box::new(e), Ident { name, span: cx.mk_span(lo, hi) })
1566            } else {
1567                // ⟨trailer_expr⟩ . ⟨ident⟩
1568                let field = parse_ident(cx)?;
1569                ExprKind::Dot(Box::new(e), field)
1570            }
1571        } else if cx.peek(token::OpenParen) {
1572            // ⟨trailer_expr⟩ ( ⟨expr⟩,* )
1573            let args = parens(cx, Comma, |cx| parse_expr(cx, true))?;
1574            ExprKind::Call(Box::new(e), args)
1575        } else {
1576            break;
1577        };
1578        let hi = cx.hi();
1579        e = Expr { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) };
1580    }
1581    Ok(e)
1582}
1583
1584/// ```text
1585/// ⟨atom⟩ := ⟨if_expr⟩
1586///         | ⟨lit⟩
1587///         | ( ⟨expr⟩ )
1588///         | ( ⟨expr⟩,* )
1589///         | ⟨epath⟩
1590///         | ⟨bounded_quant⟩
1591///         |  <⟨ty⟩ as ⟨path⟩> :: ⟨ident⟩
1592///         | [binop]
1593///         | ⟨epath⟩ { ⟨constructor_arg⟩,* }    if allow_struct
1594///         | { ⟨constructor_arg⟩,* }            if allow_struct
1595///         | #{ ⟨expr⟩,* }
1596/// ```
1597fn parse_atom(cx: &mut ParseCtxt, allow_struct: bool) -> ParseResult<Expr> {
1598    let lo = cx.lo();
1599    let mut lookahead = cx.lookahead1();
1600    if lookahead.peek(kw::If) {
1601        // ⟨if_expr⟩
1602        parse_if_expr(cx)
1603    } else if lookahead.peek(AnyLit) {
1604        // ⟨lit⟩
1605        parse_lit(cx)
1606    } else if lookahead.advance_if(token::OpenParen) {
1607        // ( ⟨expr⟩ ) | ( ⟨expr⟩,* )
1608        let (mut exprs, trailing) =
1609            punctuated_with_trailing(cx, Comma, token::CloseParen, |cx| parse_expr(cx, true))?;
1610        cx.expect(token::CloseParen)?;
1611        if exprs.len() == 1 && !trailing {
1612            Ok(exprs.remove(0))
1613        } else {
1614            Ok(Expr {
1615                kind: ExprKind::Tuple(exprs),
1616                node_id: cx.next_node_id(),
1617                span: cx.mk_span(lo, cx.hi()),
1618            })
1619        }
1620    } else if lookahead.advance_if(token::Pound) {
1621        // #{ ⟨expr⟩,* }
1622        let lo = cx.lo();
1623        let exprs = braces(cx, Comma, |cx| parse_expr(cx, true))?;
1624        let hi = cx.hi();
1625        let kind = ExprKind::SetLiteral(exprs);
1626        Ok(Expr { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1627    } else if lookahead.peek(NonReserved) {
1628        let path = parse_expr_path(cx)?;
1629        let kind = if allow_struct && cx.peek(token::OpenBrace) {
1630            // ⟨epath⟩ { ⟨constructor_arg⟩,* }
1631            let args = braces(cx, Comma, parse_constructor_arg)?;
1632            ExprKind::Constructor(Some(path), args)
1633        } else {
1634            // ⟨epath⟩
1635            ExprKind::Path(path)
1636        };
1637        let hi = cx.hi();
1638        Ok(Expr { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1639    } else if allow_struct && lookahead.peek(token::OpenBrace) {
1640        // { ⟨constructor_arg⟩,* }
1641        let args = braces(cx, Comma, parse_constructor_arg)?;
1642        let hi = cx.hi();
1643        Ok(Expr {
1644            kind: ExprKind::Constructor(None, args),
1645            node_id: cx.next_node_id(),
1646            span: cx.mk_span(lo, hi),
1647        })
1648    } else if lookahead.advance_if(LAngle) {
1649        // <⟨ty⟩ as ⟨path⟩> :: ⟨ident⟩
1650        let lo = cx.lo();
1651        let qself = parse_type(cx)?;
1652        cx.expect(kw::As)?;
1653        let path = parse_path(cx)?;
1654        cx.expect(RAngle)?;
1655        cx.expect(token::PathSep)?;
1656        let name = parse_ident(cx)?;
1657        let hi = cx.hi();
1658        let kind = ExprKind::AssocReft(Box::new(qself), path, name);
1659        Ok(Expr { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1660    } else if lookahead.peek(token::OpenBracket) {
1661        parse_prim_uif(cx)
1662    } else if lookahead.peek(kw::Exists) || lookahead.peek(kw::Forall) {
1663        parse_quantifier(cx)
1664    } else {
1665        Err(lookahead.into_error())
1666    }
1667}
1668
1669fn parse_prim_uif(cx: &mut ParseCtxt) -> ParseResult<Expr> {
1670    let lo = cx.lo();
1671    cx.expect(token::OpenBracket)?;
1672    let op = parse_binop(cx)?;
1673    cx.expect(token::CloseBracket)?;
1674    let hi = cx.hi();
1675    Ok(Expr { kind: ExprKind::PrimUIF(op), node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1676}
1677
1678/// ```text
1679/// ⟨quant⟩ := forall ⟨refine_param⟩ in ⟨int⟩..⟨int⟩ ⟨block⟩
1680///          | exists ⟨refine_param⟩ in ⟨int⟩..⟨int⟩ ⟨block⟩
1681///          | forall ⟨refine_param⟩                 ⟨block⟩
1682///          | exists ⟨refine_param⟩                 ⟨block⟩
1683/// ```
1684fn parse_quantifier(cx: &mut ParseCtxt) -> ParseResult<Expr> {
1685    let lo = cx.lo();
1686    let mut lookahead = cx.lookahead1();
1687    let quant = if lookahead.advance_if(kw::Forall) {
1688        QuantKind::Forall
1689    } else if lookahead.advance_if(kw::Exists) {
1690        QuantKind::Exists
1691    } else {
1692        return Err(lookahead.into_error());
1693    };
1694    let param = parse_refine_param(cx, RequireSort::Maybe)?;
1695
1696    let mut lookahead = cx.lookahead1();
1697    let dom = if lookahead.peek(kw::In) {
1698        cx.expect(kw::In)?;
1699        let start = parse_int(cx)?;
1700        cx.expect(token::DotDot)?;
1701        let end = parse_int(cx)?;
1702        Some(start..end)
1703    } else {
1704        None
1705    };
1706    let body = parse_block(cx)?;
1707    let hi = cx.hi();
1708    let kind = ExprKind::Quant(quant, param, dom, Box::new(body));
1709    Ok(Expr { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1710}
1711
1712/// ```text
1713/// ⟨constructor_arg⟩ :=  ⟨ident⟩ : ⟨expr⟩ |  ..
1714/// ```
1715fn parse_constructor_arg(cx: &mut ParseCtxt) -> ParseResult<ConstructorArg> {
1716    let lo = cx.lo();
1717    let mut lookahead = cx.lookahead1();
1718    if lookahead.peek(NonReserved) {
1719        let ident = parse_ident(cx)?;
1720        cx.expect(token::Colon)?;
1721        let expr = parse_refine_arg(cx)?;
1722        let hi = cx.hi();
1723        Ok(ConstructorArg::FieldExpr(FieldExpr {
1724            ident,
1725            expr,
1726            node_id: cx.next_node_id(),
1727            span: cx.mk_span(lo, hi),
1728        }))
1729    } else if lookahead.advance_if(token::DotDot) {
1730        let spread = parse_expr(cx, true)?;
1731        let hi = cx.hi();
1732        Ok(ConstructorArg::Spread(Spread {
1733            expr: spread,
1734            node_id: cx.next_node_id(),
1735            span: cx.mk_span(lo, hi),
1736        }))
1737    } else {
1738        Err(lookahead.into_error())
1739    }
1740}
1741
1742/// `⟨epath⟩ := ⟨ident⟩ ⟨ :: ⟨ident⟩ ⟩*`
1743fn parse_expr_path(cx: &mut ParseCtxt) -> ParseResult<ExprPath> {
1744    let lo = cx.lo();
1745    let segments = sep1(cx, token::PathSep, parse_expr_path_segment)?;
1746    let hi = cx.hi();
1747    Ok(ExprPath { segments, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1748}
1749
1750fn parse_expr_path_segment(cx: &mut ParseCtxt) -> ParseResult<ExprPathSegment> {
1751    Ok(ExprPathSegment { ident: parse_ident(cx)?, node_id: cx.next_node_id() })
1752}
1753
1754/// `⟨if_expr⟩ := if ⟨expr⟩ ⟨block⟩ ⟨ else if ⟨expr⟩ ⟨block⟩ ⟩* else ⟨block⟩`
1755///
1756/// The `⟨expr⟩` in conditions is parsed with `allow_struct = false`
1757fn parse_if_expr(cx: &mut ParseCtxt) -> ParseResult<Expr> {
1758    let mut branches = vec![];
1759
1760    loop {
1761        let lo = cx.lo();
1762        cx.expect(kw::If)?;
1763        let cond = parse_expr(cx, false)?;
1764        let then_ = parse_block(cx)?;
1765        branches.push((lo, cond, then_));
1766        cx.expect(kw::Else)?;
1767
1768        if !cx.peek(kw::If) {
1769            break;
1770        }
1771    }
1772    let mut else_ = parse_block(cx)?;
1773
1774    let hi = cx.hi();
1775    while let Some((lo, cond, then_)) = branches.pop() {
1776        else_ = Expr {
1777            kind: ExprKind::IfThenElse(Box::new([cond, then_, else_])),
1778            node_id: cx.next_node_id(),
1779            span: cx.mk_span(lo, hi),
1780        };
1781    }
1782    Ok(else_)
1783}
1784
1785/// `⟨block⟩ := { ⟨block_expr⟩ }`
1786fn parse_block(cx: &mut ParseCtxt) -> ParseResult<Expr> {
1787    delimited(cx, Brace, parse_block_expr)
1788}
1789
1790/// `⟨block_expr⟩ = ⟨let_decl⟩* ⟨expr⟩`
1791fn parse_block_expr(cx: &mut ParseCtxt) -> ParseResult<Expr> {
1792    let lo = cx.lo();
1793    let decls = repeat_while(cx, kw::Let, parse_let_decl)?;
1794    let body = parse_expr(cx, true)?;
1795    let hi = cx.hi();
1796
1797    if decls.is_empty() {
1798        Ok(body)
1799    } else {
1800        let kind = ExprKind::Block(decls, Box::new(body));
1801        Ok(Expr { kind, node_id: cx.next_node_id(), span: cx.mk_span(lo, hi) })
1802    }
1803}
1804
1805/// `⟨let_decl⟩ := let ⟨refine_param⟩ = ⟨expr⟩ ;`
1806fn parse_let_decl(cx: &mut ParseCtxt) -> ParseResult<LetDecl> {
1807    cx.expect(kw::Let)?;
1808    let param = parse_refine_param(cx, RequireSort::Maybe)?;
1809    cx.expect(token::Eq)?;
1810    let init = parse_expr(cx, true)?;
1811    cx.expect(token::Semi)?;
1812    Ok(LetDecl { param, init })
1813}
1814
1815/// ```text
1816/// ⟨lit⟩ := ⟨a Rust literal like an integer or a boolean⟩
1817/// ```
1818fn parse_lit(cx: &mut ParseCtxt) -> ParseResult<Expr> {
1819    if let Token { kind: token::Literal(lit), lo, hi } = cx.at(0) {
1820        cx.advance();
1821        Ok(Expr {
1822            kind: ExprKind::Literal(lit),
1823            node_id: cx.next_node_id(),
1824            span: cx.mk_span(lo, hi),
1825        })
1826    } else {
1827        Err(cx.unexpected_token(vec![AnyLit.expected()]))
1828    }
1829}
1830
1831fn parse_ident(cx: &mut ParseCtxt) -> ParseResult<Ident> {
1832    if let Token { kind: token::Ident(name, is_raw), lo, hi } = cx.at(0)
1833        && (!cx.is_reserved(name) || is_raw == IdentKind::Raw)
1834    {
1835        cx.advance();
1836        return Ok(Ident { name, span: cx.mk_span(lo, hi) });
1837    }
1838    Err(cx.unexpected_token(vec![NonReserved.expected()]))
1839}
1840
1841fn parse_int<T: FromStr>(cx: &mut ParseCtxt) -> ParseResult<T> {
1842    if let token::Literal(lit) = cx.at(0).kind
1843        && let Lit { kind: LitKind::Integer, symbol, suffix: None, .. } = lit
1844        && let Ok(value) = symbol.as_str().parse::<T>()
1845    {
1846        cx.advance();
1847        return Ok(value);
1848    }
1849
1850    Err(cx.unexpected_token(vec![Expected::Str(std::any::type_name::<T>())]))
1851}
1852
1853/// ```text
1854/// ⟨sort⟩ :=  ⟨base_sort⟩
1855///         |  ( ⟨base_sort⟩,* ) -> ⟨base_sort⟩
1856///         |  ⟨base_sort⟩ -> ⟨base_sort⟩
1857/// ```
1858fn parse_sort(cx: &mut ParseCtxt) -> ParseResult<Sort> {
1859    if cx.peek(token::OpenParen) {
1860        // ( ⟨base_sort⟩,* ) -> ⟨base_sort⟩ | ( ⟨base_sort⟩,* )
1861        let inputs = parens(cx, Comma, parse_base_sort)?;
1862        if cx.advance_if(token::RArrow) {
1863            // ( ⟨base_sort⟩,* ) -> ⟨base_sort⟩
1864            let output = parse_base_sort(cx)?;
1865            Ok(Sort::Func { inputs, output })
1866        } else {
1867            // ( ⟨base_sort⟩,* )
1868            Ok(Sort::Base(BaseSort::Tuple(inputs)))
1869        }
1870    } else {
1871        let bsort = parse_base_sort(cx)?;
1872        if cx.advance_if(token::RArrow) {
1873            // ⟨base_sort⟩ -> ⟨base_sort⟩
1874            let output = parse_base_sort(cx)?;
1875            Ok(Sort::Func { inputs: vec![bsort], output })
1876        } else {
1877            // ⟨base_sort⟩
1878            Ok(Sort::Base(bsort))
1879        }
1880    }
1881}
1882
1883/// ```text
1884/// ⟨base_sort⟩ := bitvec < ⟨u32⟩ >
1885///              | ( ⟨base_sort⟩,* )
1886///              | ⟨sort_path⟩ < ⟨base_sort⟩,* >
1887///              | < ⟨ty⟩ as ⟨path⟩ > :: ⟨segment⟩
1888/// ⟨sort_path⟩ := ⟨ident⟩ ⟨ :: ⟨ident⟩ ⟩* < (⟨base_sort⟩,*) >
1889/// ```
1890fn parse_base_sort(cx: &mut ParseCtxt) -> ParseResult<BaseSort> {
1891    if cx.advance_if(kw::Bitvec) {
1892        // bitvec < ⟨u32⟩ >
1893        cx.expect(LAngle)?;
1894        let len = parse_int(cx)?;
1895        cx.expect(RAngle)?;
1896        Ok(BaseSort::BitVec(len))
1897    } else if cx.peek(token::OpenParen) {
1898        // ( ⟨base_sort⟩,* )
1899        let sorts = parens(cx, Comma, parse_base_sort)?;
1900        Ok(BaseSort::Tuple(sorts))
1901    } else if cx.advance_if(LAngle) {
1902        // < ⟨ty⟩ as ⟨path⟩ > :: ⟨segment⟩
1903        let qself = parse_type(cx)?;
1904        cx.expect(kw::As)?;
1905        let mut path = parse_path(cx)?;
1906        cx.expect(RAngle)?;
1907        cx.expect(token::PathSep)?;
1908        path.segments.push(parse_segment(cx)?);
1909        Ok(BaseSort::SortOf(Box::new(qself), path))
1910    } else {
1911        // ⟨sort_path⟩ < ⟨base_sort⟩,* >
1912        let segments = sep1(cx, token::PathSep, parse_ident)?;
1913        let args = opt_angle(cx, Comma, parse_base_sort)?;
1914        let path = SortPath { segments, args, node_id: cx.next_node_id() };
1915        Ok(BaseSort::Path(path))
1916    }
1917}
1918
1919// Reference: https://doc.rust-lang.org/reference/expressions.html#expression-precedence
1920#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
1921enum Precedence {
1922    /// <=>
1923    Iff,
1924    /// =>
1925    Implies,
1926    /// ||
1927    Or,
1928    /// &&
1929    And,
1930    /// == != < > <= >=
1931    Compare,
1932    /// |
1933    BitOr,
1934    /// ^
1935    BitXor,
1936    /// &
1937    BitAnd,
1938    /// << >>
1939    Shift,
1940    /// + -
1941    Sum,
1942    /// * / %
1943    Product,
1944    /// unary - and !
1945    Prefix,
1946}
1947
1948enum Associativity {
1949    Right,
1950    Left,
1951    None,
1952}
1953
1954impl Precedence {
1955    const MIN: Self = Precedence::Iff;
1956
1957    fn of_binop(op: &BinOp) -> Precedence {
1958        match op {
1959            BinOp::Iff => Precedence::Iff,
1960            BinOp::Imp => Precedence::Implies,
1961            BinOp::Or => Precedence::Or,
1962            BinOp::And => Precedence::And,
1963            BinOp::Eq | BinOp::Ne | BinOp::Gt | BinOp::Ge | BinOp::Lt | BinOp::Le => {
1964                Precedence::Compare
1965            }
1966            BinOp::BitOr => Precedence::BitOr,
1967            BinOp::BitXor => Precedence::BitXor,
1968            BinOp::BitAnd => Precedence::BitAnd,
1969            BinOp::BitShl | BinOp::BitShr => Precedence::Shift,
1970            BinOp::Add | BinOp::Sub => Precedence::Sum,
1971            BinOp::Mul | BinOp::Div | BinOp::Mod => Precedence::Product,
1972        }
1973    }
1974
1975    fn next(self) -> Precedence {
1976        match self {
1977            Precedence::Iff => Precedence::Implies,
1978            Precedence::Implies => Precedence::Or,
1979            Precedence::Or => Precedence::And,
1980            Precedence::And => Precedence::Compare,
1981            Precedence::Compare => Precedence::BitOr,
1982            Precedence::BitOr => Precedence::BitXor,
1983            Precedence::BitXor => Precedence::BitAnd,
1984            Precedence::BitAnd => Precedence::Shift,
1985            Precedence::Shift => Precedence::Sum,
1986            Precedence::Sum => Precedence::Product,
1987            Precedence::Product => Precedence::Prefix,
1988            Precedence::Prefix => Precedence::Prefix,
1989        }
1990    }
1991
1992    fn associativity(self) -> Associativity {
1993        match self {
1994            Precedence::Or
1995            | Precedence::And
1996            | Precedence::BitOr
1997            | Precedence::BitXor
1998            | Precedence::BitAnd
1999            | Precedence::Shift
2000            | Precedence::Sum
2001            | Precedence::Product => Associativity::Left,
2002            Precedence::Compare | Precedence::Iff => Associativity::None,
2003            Precedence::Implies | Precedence::Prefix => Associativity::Right,
2004        }
2005    }
2006}