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
34enum SyntaxAttr {
42 Reft,
44 Invariant(Expr),
46 RefinedBy(RefineParams),
48 Hide,
55 Opaque,
57 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
115pub(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
140fn parse_reason(cx: &mut ParseCtxt) -> ParseResult {
144 cx.expect(sym::reason)?;
145 cx.expect(token::Eq)?;
146 cx.expect(AnyLit)
147}
148
149pub(crate) fn parse_ident_list(cx: &mut ParseCtxt) -> ParseResult<Vec<Ident>> {
153 punctuated_until(cx, Comma, token::Eof, parse_ident)
154}
155
156pub(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
174pub(crate) fn parse_flux_items(cx: &mut ParseCtxt) -> ParseResult<Vec<FluxItem>> {
178 until(cx, token::Eof, parse_flux_item)
179}
180
181fn parse_flux_item(cx: &mut ParseCtxt) -> ParseResult<FluxItem> {
190 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
218pub(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
226pub(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
255fn 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
265fn 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
337fn 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
354fn 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
371fn 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
399fn 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 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
492fn 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
517fn 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
532fn 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 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 wildcards.resize(params.len(), false);
570
571 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
590fn 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
602fn 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
611fn 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 let name = parse_ident(cx)?;
621
622 cx.expect(token::OpenBracket)?;
624 let op = parse_binop(cx)?;
625 cx.expect(token::CloseBracket)?;
626
627 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
636fn 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
650fn 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
660fn 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
687fn 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
714fn 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
729pub(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
736pub(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
765fn 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
779fn 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 let locs = ensures
845 .iter()
846 .filter_map(|ens| if let Ensures::Type(ident, _, _) = ens { Some(ident) } else { None })
847 .collect::<HashSet<_>>();
848 let mut res = vec![];
850 for input in inputs {
851 if let FnInput::Ty(Some(ident), _, _) = &input
852 && locs.contains(&ident)
853 {
854 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 res.push(input);
865 }
866 }
867 Ok(res)
868}
869
870pub(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, })
908}
909
910fn 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
925fn 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
938fn 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
953fn parse_ensures_clause(cx: &mut ParseCtxt) -> ParseResult<Ensures> {
958 if cx.peek2(NonReserved, token::Colon) {
959 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 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
986fn 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
998fn 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 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 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 let pred = delimited(cx, Brace, |cx| parse_expr(cx, true))?;
1021 Ok(FnInput::Constr(bind, path, pred, cx.next_node_id()))
1022 } else {
1023 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 Ok(FnInput::Ty(Some(bind), parse_type(cx)?, cx.next_node_id()))
1031 }
1032 } else {
1033 Ok(FnInput::Ty(None, parse_type(cx)?, cx.next_node_id()))
1035 }
1036}
1037
1038fn 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
1073pub(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 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 parse_general_exists(cx)
1111 } else {
1112 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 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 let mutbl = if cx.advance_if(kw::Mut) {
1126 Mutability::Mut
1127 } else {
1128 cx.expect(kw::Const)?;
1129 Mutability::Not
1130 };
1131 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 let len = parse_const_arg(cx)?;
1148 cx.expect(token::CloseBracket)?;
1149 TyKind::Array(Box::new(ty), len)
1150 } else {
1151 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 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 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 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 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 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
1207fn 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
1227fn 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
1238fn parse_bty_rhs(cx: &mut ParseCtxt, bty: BaseTy) -> ParseResult<Ty> {
1244 let lo = bty.span.lo();
1245 if cx.peek(token::OpenBracket) {
1246 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 parse_bty_exists(cx, bty)
1254 } else {
1255 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
1262fn 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
1354fn 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
1366fn parse_segments(cx: &mut ParseCtxt) -> ParseResult<Vec<PathSegment>> {
1370 sep1(cx, token::PathSep, parse_segment)
1371}
1372
1373fn 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
1382fn 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
1397fn parse_refine_arg(cx: &mut ParseCtxt) -> ParseResult<RefineArg> {
1404 let lo = cx.lo();
1405 let arg = if cx.advance_if(token::At) {
1406 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 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 RefineArg::Expr(parse_expr(cx, true)?)
1426 };
1427 Ok(arg)
1428}
1429
1430enum RequireSort {
1432 Yes,
1434 Maybe,
1436 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
1457fn 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
1471fn 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
1483fn 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
1533fn 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
1549fn 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 cx.advance();
1565 ExprKind::Dot(Box::new(e), Ident { name, span: cx.mk_span(lo, hi) })
1566 } else {
1567 let field = parse_ident(cx)?;
1569 ExprKind::Dot(Box::new(e), field)
1570 }
1571 } else if cx.peek(token::OpenParen) {
1572 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
1584fn 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 parse_if_expr(cx)
1603 } else if lookahead.peek(AnyLit) {
1604 parse_lit(cx)
1606 } else if lookahead.advance_if(token::OpenParen) {
1607 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 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 let args = braces(cx, Comma, parse_constructor_arg)?;
1632 ExprKind::Constructor(Some(path), args)
1633 } else {
1634 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 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 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
1678fn 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
1712fn 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
1742fn 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
1754fn 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
1785fn parse_block(cx: &mut ParseCtxt) -> ParseResult<Expr> {
1787 delimited(cx, Brace, parse_block_expr)
1788}
1789
1790fn 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
1805fn 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
1815fn 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
1853fn parse_sort(cx: &mut ParseCtxt) -> ParseResult<Sort> {
1859 if cx.peek(token::OpenParen) {
1860 let inputs = parens(cx, Comma, parse_base_sort)?;
1862 if cx.advance_if(token::RArrow) {
1863 let output = parse_base_sort(cx)?;
1865 Ok(Sort::Func { inputs, output })
1866 } else {
1867 Ok(Sort::Base(BaseSort::Tuple(inputs)))
1869 }
1870 } else {
1871 let bsort = parse_base_sort(cx)?;
1872 if cx.advance_if(token::RArrow) {
1873 let output = parse_base_sort(cx)?;
1875 Ok(Sort::Func { inputs: vec![bsort], output })
1876 } else {
1877 Ok(Sort::Base(bsort))
1879 }
1880 }
1881}
1882
1883fn parse_base_sort(cx: &mut ParseCtxt) -> ParseResult<BaseSort> {
1891 if cx.advance_if(kw::Bitvec) {
1892 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 let sorts = parens(cx, Comma, parse_base_sort)?;
1900 Ok(BaseSort::Tuple(sorts))
1901 } else if cx.advance_if(LAngle) {
1902 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 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#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
1921enum Precedence {
1922 Iff,
1924 Implies,
1926 Or,
1928 And,
1930 Compare,
1932 BitOr,
1934 BitXor,
1936 BitAnd,
1938 Shift,
1940 Sum,
1942 Product,
1944 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}