1 // ignore-tidy-filelength
3 use crate::ast::{AngleBracketedArgs, ParenthesizedArgs, AttrStyle, BareFnTy};
4 use crate::ast::{GenericBound, TraitBoundModifier};
5 use crate::ast::Unsafety;
6 use crate::ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind};
8 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
9 use crate::ast::{Constness, Crate};
10 use crate::ast::Defaultness;
11 use crate::ast::EnumDef;
12 use crate::ast::{Expr, ExprKind, RangeLimits};
13 use crate::ast::{Field, FnDecl, FnHeader};
14 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
15 use crate::ast::{GenericParam, GenericParamKind};
16 use crate::ast::GenericArg;
17 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
18 use crate::ast::{Label, Lifetime};
19 use crate::ast::Local;
20 use crate::ast::MacStmtStyle;
21 use crate::ast::{Mac, Mac_, MacDelimiter};
22 use crate::ast::{MutTy, Mutability};
23 use crate::ast::{Pat, PatKind, PathSegment};
24 use crate::ast::{PolyTraitRef, QSelf};
25 use crate::ast::{Stmt, StmtKind};
26 use crate::ast::{VariantData, StructField};
27 use crate::ast::StrStyle;
28 use crate::ast::SelfKind;
29 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
30 use crate::ast::{Ty, TyKind, AssocTyConstraint, AssocTyConstraintKind, GenericBounds};
31 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
32 use crate::ast::{UseTree, UseTreeKind};
33 use crate::ast::{BinOpKind, UnOp};
34 use crate::ast::{RangeEnd, RangeSyntax};
35 use crate::{ast, attr};
36 use crate::ext::base::DummyResult;
37 use crate::ext::hygiene::SyntaxContext;
38 use crate::source_map::{self, SourceMap, Spanned, respan};
39 use crate::parse::{SeqSep, classify, literal, token};
40 use crate::parse::lexer::UnmatchedBrace;
41 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
42 use crate::parse::token::{Token, TokenKind, DelimToken};
43 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
44 use crate::util::parser::{AssocOp, Fixity, prec_let_scrutinee_needs_par};
45 use crate::print::pprust;
47 use crate::parse::PResult;
49 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
50 use crate::symbol::{kw, sym, Symbol};
51 use crate::parse::diagnostics::{Error, dummy_arg};
53 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
54 use rustc_target::spec::abi::{self, Abi};
55 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
61 use std::path::{self, Path, PathBuf};
65 /// Whether the type alias or associated type is a concrete type or an opaque type
67 /// Just a new name for the same type
69 /// Only trait impls of the type will be usable, not the actual type itself
70 OpaqueTy(GenericBounds),
74 struct Restrictions: u8 {
75 const STMT_EXPR = 1 << 0;
76 const NO_STRUCT_LITERAL = 1 << 1;
80 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
82 /// Specifies how to parse a path.
83 #[derive(Copy, Clone, PartialEq)]
85 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
86 /// with something else. For example, in expressions `segment < ....` can be interpreted
87 /// as a comparison and `segment ( ....` can be interpreted as a function call.
88 /// In all such contexts the non-path interpretation is preferred by default for practical
89 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
90 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
92 /// In other contexts, notably in types, no ambiguity exists and paths can be written
93 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
94 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
96 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
97 /// visibilities or attributes.
98 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
99 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
100 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
101 /// tokens when something goes wrong.
105 #[derive(Clone, Copy, PartialEq, Debug)]
106 crate enum SemiColonMode {
112 #[derive(Clone, Copy, PartialEq, Debug)]
113 crate enum BlockMode {
118 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
119 /// dropped into the token stream, which happens while parsing the result of
120 /// macro expansion). Placement of these is not as complex as I feared it would
121 /// be. The important thing is to make sure that lookahead doesn't balk at
122 /// `token::Interpolated` tokens.
123 macro_rules! maybe_whole_expr {
125 if let token::Interpolated(nt) = &$p.token.kind {
127 token::NtExpr(e) | token::NtLiteral(e) => {
132 token::NtPath(path) => {
133 let path = path.clone();
135 return Ok($p.mk_expr(
136 $p.token.span, ExprKind::Path(None, path), ThinVec::new()
139 token::NtBlock(block) => {
140 let block = block.clone();
142 return Ok($p.mk_expr(
143 $p.token.span, ExprKind::Block(block, None), ThinVec::new()
146 // N.B: `NtIdent(ident)` is normalized to `Ident` in `fn bump`.
153 /// As maybe_whole_expr, but for things other than expressions
154 macro_rules! maybe_whole {
155 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
156 if let token::Interpolated(nt) = &$p.token.kind {
157 if let token::$constructor(x) = &**nt {
166 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
167 macro_rules! maybe_recover_from_interpolated_ty_qpath {
168 ($self: expr, $allow_qpath_recovery: expr) => {
169 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
170 if let token::Interpolated(nt) = &$self.token.kind {
171 if let token::NtTy(ty) = &**nt {
174 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
181 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
182 if let Some(ref mut rhs) = rhs {
188 #[derive(Debug, Clone, Copy, PartialEq)]
200 // NOTE: `Ident`s are handled by `common.rs`.
203 pub struct Parser<'a> {
204 pub sess: &'a ParseSess,
205 /// The current normalized token.
206 /// "Normalized" means that some interpolated tokens
207 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
208 /// with non-interpolated identifier and lifetime tokens they refer to.
209 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
211 /// Span of the current non-normalized token.
212 meta_var_span: Option<Span>,
213 /// Span of the previous non-normalized token.
215 /// Kind of the previous normalized token (in simplified form).
216 prev_token_kind: PrevTokenKind,
217 restrictions: Restrictions,
218 /// Used to determine the path to externally loaded source files.
219 crate directory: Directory<'a>,
220 /// `true` to parse sub-modules in other files.
221 pub recurse_into_file_modules: bool,
222 /// Name of the root module this parser originated from. If `None`, then the
223 /// name is not known. This does not change while the parser is descending
224 /// into modules, and sub-parsers have new values for this name.
225 pub root_module_name: Option<String>,
226 crate expected_tokens: Vec<TokenType>,
227 crate token_cursor: TokenCursor,
228 desugar_doc_comments: bool,
229 /// `true` we should configure out of line modules as we parse.
231 /// This field is used to keep track of how many left angle brackets we have seen. This is
232 /// required in order to detect extra leading left angle brackets (`<` characters) and error
235 /// See the comments in the `parse_path_segment` function for more details.
236 crate unmatched_angle_bracket_count: u32,
237 crate max_angle_bracket_count: u32,
238 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
239 /// it gets removed from here. Every entry left at the end gets emitted as an independent
241 crate unclosed_delims: Vec<UnmatchedBrace>,
242 crate last_unexpected_token_span: Option<Span>,
243 crate last_type_ascription: Option<(Span, bool /* likely path typo */)>,
244 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
245 crate subparser_name: Option<&'static str>,
248 impl<'a> Drop for Parser<'a> {
250 let diag = self.diagnostic();
251 emit_unclosed_delims(&mut self.unclosed_delims, diag);
256 crate struct TokenCursor {
257 crate frame: TokenCursorFrame,
258 crate stack: Vec<TokenCursorFrame>,
262 crate struct TokenCursorFrame {
263 crate delim: token::DelimToken,
264 crate span: DelimSpan,
265 crate open_delim: bool,
266 crate tree_cursor: tokenstream::Cursor,
267 crate close_delim: bool,
268 crate last_token: LastToken,
271 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
272 /// by the parser, and then that's transitively used to record the tokens that
273 /// each parse AST item is created with.
275 /// Right now this has two states, either collecting tokens or not collecting
276 /// tokens. If we're collecting tokens we just save everything off into a local
277 /// `Vec`. This should eventually though likely save tokens from the original
278 /// token stream and just use slicing of token streams to avoid creation of a
279 /// whole new vector.
281 /// The second state is where we're passively not recording tokens, but the last
282 /// token is still tracked for when we want to start recording tokens. This
283 /// "last token" means that when we start recording tokens we'll want to ensure
284 /// that this, the first token, is included in the output.
286 /// You can find some more example usage of this in the `collect_tokens` method
289 crate enum LastToken {
290 Collecting(Vec<TreeAndJoint>),
291 Was(Option<TreeAndJoint>),
294 impl TokenCursorFrame {
295 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
299 open_delim: delim == token::NoDelim,
300 tree_cursor: tts.clone().into_trees(),
301 close_delim: delim == token::NoDelim,
302 last_token: LastToken::Was(None),
308 fn next(&mut self) -> Token {
310 let tree = if !self.frame.open_delim {
311 self.frame.open_delim = true;
312 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
313 } else if let Some(tree) = self.frame.tree_cursor.next() {
315 } else if !self.frame.close_delim {
316 self.frame.close_delim = true;
317 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
318 } else if let Some(frame) = self.stack.pop() {
322 return Token::new(token::Eof, DUMMY_SP);
325 match self.frame.last_token {
326 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
327 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
331 TokenTree::Token(token) => return token,
332 TokenTree::Delimited(sp, delim, tts) => {
333 let frame = TokenCursorFrame::new(sp, delim, &tts);
334 self.stack.push(mem::replace(&mut self.frame, frame));
340 fn next_desugared(&mut self) -> Token {
341 let (name, sp) = match self.next() {
342 Token { kind: token::DocComment(name), span } => (name, span),
346 let stripped = strip_doc_comment_decoration(&name.as_str());
348 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
349 // required to wrap the text.
350 let mut num_of_hashes = 0;
352 for ch in stripped.chars() {
355 '#' if count > 0 => count + 1,
358 num_of_hashes = cmp::max(num_of_hashes, count);
361 let delim_span = DelimSpan::from_single(sp);
362 let body = TokenTree::Delimited(
366 TokenTree::token(token::Ident(sym::doc, false), sp),
367 TokenTree::token(token::Eq, sp),
368 TokenTree::token(TokenKind::lit(
369 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
372 .iter().cloned().collect::<TokenStream>().into(),
375 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
378 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
379 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
380 .iter().cloned().collect::<TokenStream>().into()
382 [TokenTree::token(token::Pound, sp), body]
383 .iter().cloned().collect::<TokenStream>().into()
391 #[derive(Clone, PartialEq)]
392 crate enum TokenType {
404 crate fn to_string(&self) -> String {
406 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
407 TokenType::Keyword(kw) => format!("`{}`", kw),
408 TokenType::Operator => "an operator".to_string(),
409 TokenType::Lifetime => "lifetime".to_string(),
410 TokenType::Ident => "identifier".to_string(),
411 TokenType::Path => "path".to_string(),
412 TokenType::Type => "type".to_string(),
413 TokenType::Const => "const".to_string(),
418 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
419 /// `IDENT<<u8 as Trait>::AssocTy>`.
421 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
422 /// that `IDENT` is not the ident of a fn trait.
423 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
424 t == &token::ModSep || t == &token::Lt ||
425 t == &token::BinOp(token::Shl)
428 /// Information about the path to a module.
429 pub struct ModulePath {
432 pub result: Result<ModulePathSuccess, Error>,
435 pub struct ModulePathSuccess {
437 pub directory_ownership: DirectoryOwnership,
444 AttributesParsed(ThinVec<Attribute>),
445 AlreadyParsed(P<Expr>),
448 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
449 fn from(o: Option<ThinVec<Attribute>>) -> Self {
450 if let Some(attrs) = o {
451 LhsExpr::AttributesParsed(attrs)
453 LhsExpr::NotYetParsed
458 impl From<P<Expr>> for LhsExpr {
459 fn from(expr: P<Expr>) -> Self {
460 LhsExpr::AlreadyParsed(expr)
464 #[derive(Copy, Clone, Debug)]
465 crate enum TokenExpectType {
470 impl<'a> Parser<'a> {
474 directory: Option<Directory<'a>>,
475 recurse_into_file_modules: bool,
476 desugar_doc_comments: bool,
477 subparser_name: Option<&'static str>,
479 let mut parser = Parser {
481 token: Token::dummy(),
484 prev_token_kind: PrevTokenKind::Other,
485 restrictions: Restrictions::empty(),
486 recurse_into_file_modules,
487 directory: Directory {
488 path: Cow::from(PathBuf::new()),
489 ownership: DirectoryOwnership::Owned { relative: None }
491 root_module_name: None,
492 expected_tokens: Vec::new(),
493 token_cursor: TokenCursor {
494 frame: TokenCursorFrame::new(
501 desugar_doc_comments,
503 unmatched_angle_bracket_count: 0,
504 max_angle_bracket_count: 0,
505 unclosed_delims: Vec::new(),
506 last_unexpected_token_span: None,
507 last_type_ascription: None,
511 parser.token = parser.next_tok();
513 if let Some(directory) = directory {
514 parser.directory = directory;
515 } else if !parser.token.span.is_dummy() {
516 if let FileName::Real(mut path) =
517 sess.source_map().span_to_unmapped_path(parser.token.span) {
519 parser.directory.path = Cow::from(path);
523 parser.process_potential_macro_variable();
527 fn next_tok(&mut self) -> Token {
528 let mut next = if self.desugar_doc_comments {
529 self.token_cursor.next_desugared()
531 self.token_cursor.next()
533 if next.span.is_dummy() {
534 // Tweak the location for better diagnostics, but keep syntactic context intact.
535 next.span = self.prev_span.with_ctxt(next.span.ctxt());
540 /// Converts the current token to a string using `self`'s reader.
541 pub fn this_token_to_string(&self) -> String {
542 pprust::token_to_string(&self.token)
545 crate fn token_descr(&self) -> Option<&'static str> {
546 Some(match &self.token.kind {
547 _ if self.token.is_special_ident() => "reserved identifier",
548 _ if self.token.is_used_keyword() => "keyword",
549 _ if self.token.is_unused_keyword() => "reserved keyword",
550 token::DocComment(..) => "doc comment",
555 crate fn this_token_descr(&self) -> String {
556 if let Some(prefix) = self.token_descr() {
557 format!("{} `{}`", prefix, self.this_token_to_string())
559 format!("`{}`", self.this_token_to_string())
563 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
564 match self.expect_one_of(&[], &[]) {
566 Ok(_) => unreachable!(),
570 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
571 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
572 if self.expected_tokens.is_empty() {
573 if self.token == *t {
577 self.unexpected_try_recover(t)
580 self.expect_one_of(slice::from_ref(t), &[])
584 /// Expect next token to be edible or inedible token. If edible,
585 /// then consume it; if inedible, then return without consuming
586 /// anything. Signal a fatal error if next token is unexpected.
587 pub fn expect_one_of(
589 edible: &[TokenKind],
590 inedible: &[TokenKind],
591 ) -> PResult<'a, bool /* recovered */> {
592 if edible.contains(&self.token.kind) {
595 } else if inedible.contains(&self.token.kind) {
596 // leave it in the input
598 } else if self.last_unexpected_token_span == Some(self.token.span) {
601 self.expected_one_of_not_found(edible, inedible)
605 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
606 fn interpolated_or_expr_span(
608 expr: PResult<'a, P<Expr>>,
609 ) -> PResult<'a, (Span, P<Expr>)> {
611 if self.prev_token_kind == PrevTokenKind::Interpolated {
619 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
620 self.parse_ident_common(true)
623 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
624 match self.token.kind {
625 token::Ident(name, _) => {
626 if self.token.is_reserved_ident() {
627 let mut err = self.expected_ident_found();
634 let span = self.token.span;
636 Ok(Ident::new(name, span))
639 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
640 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
642 self.expected_ident_found()
648 /// Checks if the next token is `tok`, and returns `true` if so.
650 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
652 crate fn check(&mut self, tok: &TokenKind) -> bool {
653 let is_present = self.token == *tok;
654 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
658 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
659 pub fn eat(&mut self, tok: &TokenKind) -> bool {
660 let is_present = self.check(tok);
661 if is_present { self.bump() }
665 fn check_keyword(&mut self, kw: Symbol) -> bool {
666 self.expected_tokens.push(TokenType::Keyword(kw));
667 self.token.is_keyword(kw)
670 /// If the next token is the given keyword, eats it and returns
671 /// `true`. Otherwise, returns `false`.
672 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
673 if self.check_keyword(kw) {
681 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
682 if self.token.is_keyword(kw) {
690 /// If the given word is not a keyword, signals an error.
691 /// If the next token is not the given word, signals an error.
692 /// Otherwise, eats it.
693 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
694 if !self.eat_keyword(kw) {
701 crate fn check_ident(&mut self) -> bool {
702 if self.token.is_ident() {
705 self.expected_tokens.push(TokenType::Ident);
710 fn check_path(&mut self) -> bool {
711 if self.token.is_path_start() {
714 self.expected_tokens.push(TokenType::Path);
719 fn check_type(&mut self) -> bool {
720 if self.token.can_begin_type() {
723 self.expected_tokens.push(TokenType::Type);
728 fn check_const_arg(&mut self) -> bool {
729 if self.token.can_begin_const_arg() {
732 self.expected_tokens.push(TokenType::Const);
737 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
738 /// and continues. If a `+` is not seen, returns `false`.
740 /// This is used when token-splitting `+=` into `+`.
741 /// See issue #47856 for an example of when this may occur.
742 fn eat_plus(&mut self) -> bool {
743 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
744 match self.token.kind {
745 token::BinOp(token::Plus) => {
749 token::BinOpEq(token::Plus) => {
750 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
751 self.bump_with(token::Eq, span);
759 /// Checks to see if the next token is either `+` or `+=`.
760 /// Otherwise returns `false`.
761 fn check_plus(&mut self) -> bool {
762 if self.token.is_like_plus() {
766 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
771 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
772 /// `&` and continues. If an `&` is not seen, signals an error.
773 fn expect_and(&mut self) -> PResult<'a, ()> {
774 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
775 match self.token.kind {
776 token::BinOp(token::And) => {
781 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
782 Ok(self.bump_with(token::BinOp(token::And), span))
784 _ => self.unexpected()
788 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
789 /// `|` and continues. If an `|` is not seen, signals an error.
790 fn expect_or(&mut self) -> PResult<'a, ()> {
791 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
792 match self.token.kind {
793 token::BinOp(token::Or) => {
798 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
799 Ok(self.bump_with(token::BinOp(token::Or), span))
801 _ => self.unexpected()
805 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
806 literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
809 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
810 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
811 /// and continue. If a `<` is not seen, returns false.
813 /// This is meant to be used when parsing generics on a path to get the
815 fn eat_lt(&mut self) -> bool {
816 self.expected_tokens.push(TokenType::Token(token::Lt));
817 let ate = match self.token.kind {
822 token::BinOp(token::Shl) => {
823 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
824 self.bump_with(token::Lt, span);
828 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
829 self.bump_with(token::BinOp(token::Minus), span);
836 // See doc comment for `unmatched_angle_bracket_count`.
837 self.unmatched_angle_bracket_count += 1;
838 self.max_angle_bracket_count += 1;
839 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
845 fn expect_lt(&mut self) -> PResult<'a, ()> {
853 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
854 /// with a single `>` and continues. If a `>` is not seen, signals an error.
855 fn expect_gt(&mut self) -> PResult<'a, ()> {
856 self.expected_tokens.push(TokenType::Token(token::Gt));
857 let ate = match self.token.kind {
862 token::BinOp(token::Shr) => {
863 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
864 Some(self.bump_with(token::Gt, span))
866 token::BinOpEq(token::Shr) => {
867 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
868 Some(self.bump_with(token::Ge, span))
871 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
872 Some(self.bump_with(token::Eq, span))
879 // See doc comment for `unmatched_angle_bracket_count`.
880 if self.unmatched_angle_bracket_count > 0 {
881 self.unmatched_angle_bracket_count -= 1;
882 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
887 None => self.unexpected(),
891 /// Parses a sequence, including the closing delimiter. The function
892 /// `f` must consume tokens until reaching the next separator or
894 pub fn parse_seq_to_end<T>(
898 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
899 ) -> PResult<'a, Vec<T>> {
900 let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
907 /// Parses a sequence, not including the closing delimiter. The function
908 /// `f` must consume tokens until reaching the next separator or
910 pub fn parse_seq_to_before_end<T>(
914 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
915 ) -> PResult<'a, (Vec<T>, bool, bool)> {
916 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
919 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
920 kets.iter().any(|k| {
922 TokenExpectType::Expect => self.check(k),
923 TokenExpectType::NoExpect => self.token == **k,
928 crate fn parse_seq_to_before_tokens<T>(
932 expect: TokenExpectType,
933 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
934 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
935 let mut first = true;
936 let mut recovered = false;
937 let mut trailing = false;
939 while !self.expect_any_with_type(kets, expect) {
940 if let token::CloseDelim(..) | token::Eof = self.token.kind {
943 if let Some(ref t) = sep.sep {
947 match self.expect(t) {
954 // Attempt to keep parsing if it was a similar separator
955 if let Some(ref tokens) = t.similar_tokens() {
956 if tokens.contains(&self.token.kind) {
961 // Attempt to keep parsing if it was an omitted separator
976 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
985 Ok((v, trailing, recovered))
988 /// Parses a sequence, including the closing delimiter. The function
989 /// `f` must consume tokens until reaching the next separator or
991 fn parse_unspanned_seq<T>(
996 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
997 ) -> PResult<'a, (Vec<T>, bool)> {
999 let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1003 Ok((result, trailing))
1006 fn parse_delim_comma_seq<T>(
1009 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1010 ) -> PResult<'a, (Vec<T>, bool)> {
1011 self.parse_unspanned_seq(
1012 &token::OpenDelim(delim),
1013 &token::CloseDelim(delim),
1014 SeqSep::trailing_allowed(token::Comma),
1019 fn parse_paren_comma_seq<T>(
1021 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1022 ) -> PResult<'a, (Vec<T>, bool)> {
1023 self.parse_delim_comma_seq(token::Paren, f)
1026 /// Advance the parser by one token
1027 pub fn bump(&mut self) {
1028 if self.prev_token_kind == PrevTokenKind::Eof {
1029 // Bumping after EOF is a bad sign, usually an infinite loop.
1030 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1033 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
1035 // Record last token kind for possible error recovery.
1036 self.prev_token_kind = match self.token.kind {
1037 token::DocComment(..) => PrevTokenKind::DocComment,
1038 token::Comma => PrevTokenKind::Comma,
1039 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1040 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1041 token::Interpolated(..) => PrevTokenKind::Interpolated,
1042 token::Eof => PrevTokenKind::Eof,
1043 token::Ident(..) => PrevTokenKind::Ident,
1044 _ => PrevTokenKind::Other,
1047 self.token = self.next_tok();
1048 self.expected_tokens.clear();
1049 // check after each token
1050 self.process_potential_macro_variable();
1053 /// Advance the parser using provided token as a next one. Use this when
1054 /// consuming a part of a token. For example a single `<` from `<<`.
1055 fn bump_with(&mut self, next: TokenKind, span: Span) {
1056 self.prev_span = self.token.span.with_hi(span.lo());
1057 // It would be incorrect to record the kind of the current token, but
1058 // fortunately for tokens currently using `bump_with`, the
1059 // prev_token_kind will be of no use anyway.
1060 self.prev_token_kind = PrevTokenKind::Other;
1061 self.token = Token::new(next, span);
1062 self.expected_tokens.clear();
1065 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1066 F: FnOnce(&Token) -> R,
1069 return f(&self.token);
1072 let frame = &self.token_cursor.frame;
1073 f(&match frame.tree_cursor.look_ahead(dist - 1) {
1074 Some(tree) => match tree {
1075 TokenTree::Token(token) => token,
1076 TokenTree::Delimited(dspan, delim, _) =>
1077 Token::new(token::OpenDelim(delim), dspan.open),
1079 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
1083 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1084 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1085 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1088 /// Is the current token one of the keywords that signals a bare function type?
1089 fn token_is_bare_fn_keyword(&mut self) -> bool {
1090 self.check_keyword(kw::Fn) ||
1091 self.check_keyword(kw::Unsafe) ||
1092 self.check_keyword(kw::Extern)
1095 /// Parses a `TyKind::BareFn` type.
1096 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1099 [unsafe] [extern "ABI"] fn (S) -> T
1109 let unsafety = self.parse_unsafety();
1110 let abi = if self.eat_keyword(kw::Extern) {
1111 self.parse_opt_abi()?.unwrap_or(Abi::C)
1116 self.expect_keyword(kw::Fn)?;
1117 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1118 let ret_ty = self.parse_ret_ty(false)?;
1119 let decl = P(FnDecl {
1124 Ok(TyKind::BareFn(P(BareFnTy {
1132 /// Parses asyncness: `async` or nothing.
1133 fn parse_asyncness(&mut self) -> IsAsync {
1134 if self.eat_keyword(kw::Async) {
1136 closure_id: ast::DUMMY_NODE_ID,
1137 return_impl_trait_id: ast::DUMMY_NODE_ID,
1144 /// Parses unsafety: `unsafe` or nothing.
1145 fn parse_unsafety(&mut self) -> Unsafety {
1146 if self.eat_keyword(kw::Unsafe) {
1153 /// Parses the items in a trait declaration.
1154 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1155 maybe_whole!(self, NtTraitItem, |x| x);
1156 let attrs = self.parse_outer_attributes()?;
1157 let mut unclosed_delims = vec![];
1158 let (mut item, tokens) = self.collect_tokens(|this| {
1159 let item = this.parse_trait_item_(at_end, attrs);
1160 unclosed_delims.append(&mut this.unclosed_delims);
1163 self.unclosed_delims.append(&mut unclosed_delims);
1164 // See `parse_item` for why this clause is here.
1165 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1166 item.tokens = Some(tokens);
1171 fn parse_trait_item_(&mut self,
1173 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1174 let lo = self.token.span;
1176 let (name, node, generics) = if self.eat_keyword(kw::Type) {
1177 self.parse_trait_item_assoc_ty()?
1178 } else if self.is_const_item() {
1179 self.expect_keyword(kw::Const)?;
1180 let ident = self.parse_ident()?;
1181 self.expect(&token::Colon)?;
1182 let ty = self.parse_ty()?;
1183 let default = if self.eat(&token::Eq) {
1184 let expr = self.parse_expr()?;
1185 self.expect(&token::Semi)?;
1188 self.expect(&token::Semi)?;
1191 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1192 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1193 // trait item macro.
1194 (Ident::invalid(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1196 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1198 let ident = self.parse_ident()?;
1199 let mut generics = self.parse_generics()?;
1201 let decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1202 // This is somewhat dubious; We don't want to allow
1203 // argument names to be left off if there is a
1206 // We don't allow argument names to be left off in edition 2018.
1207 let is_name_required = p.token.span.rust_2018();
1208 p.parse_arg_general(true, false, |_| is_name_required)
1210 generics.where_clause = self.parse_where_clause()?;
1212 let sig = ast::MethodSig {
1222 let body = match self.token.kind {
1226 debug!("parse_trait_methods(): parsing required method");
1229 token::OpenDelim(token::Brace) => {
1230 debug!("parse_trait_methods(): parsing provided method");
1232 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1233 attrs.extend(inner_attrs.iter().cloned());
1236 token::Interpolated(ref nt) => {
1238 token::NtBlock(..) => {
1240 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1241 attrs.extend(inner_attrs.iter().cloned());
1245 return self.expected_semi_or_open_brace();
1250 return self.expected_semi_or_open_brace();
1253 (ident, ast::TraitItemKind::Method(sig, body), generics)
1257 id: ast::DUMMY_NODE_ID,
1262 span: lo.to(self.prev_span),
1267 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1268 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1269 if self.eat(&token::RArrow) {
1270 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1272 Ok(FunctionRetTy::Default(self.token.span.shrink_to_lo()))
1277 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1278 self.parse_ty_common(true, true, false)
1281 /// Parses a type in restricted contexts where `+` is not permitted.
1283 /// Example 1: `&'a TYPE`
1284 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1285 /// Example 2: `value1 as TYPE + value2`
1286 /// `+` is prohibited to avoid interactions with expression grammar.
1287 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1288 self.parse_ty_common(false, true, false)
1291 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1292 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1293 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1294 maybe_whole!(self, NtTy, |x| x);
1296 let lo = self.token.span;
1297 let mut impl_dyn_multi = false;
1298 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1299 // `(TYPE)` is a parenthesized type.
1300 // `(TYPE,)` is a tuple with a single field of type TYPE.
1301 let mut ts = vec![];
1302 let mut last_comma = false;
1303 while self.token != token::CloseDelim(token::Paren) {
1304 ts.push(self.parse_ty()?);
1305 if self.eat(&token::Comma) {
1312 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1313 self.expect(&token::CloseDelim(token::Paren))?;
1315 if ts.len() == 1 && !last_comma {
1316 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1317 let maybe_bounds = allow_plus && self.token.is_like_plus();
1319 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1320 TyKind::Path(None, ref path) if maybe_bounds => {
1321 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1323 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1324 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1325 let path = match bounds[0] {
1326 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1327 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1329 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1332 _ => TyKind::Paren(P(ty))
1337 } else if self.eat(&token::Not) {
1340 } else if self.eat(&token::BinOp(token::Star)) {
1342 TyKind::Ptr(self.parse_ptr()?)
1343 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1345 let t = self.parse_ty()?;
1346 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1347 let t = match self.maybe_parse_fixed_length_of_vec()? {
1348 None => TyKind::Slice(t),
1349 Some(length) => TyKind::Array(t, AnonConst {
1350 id: ast::DUMMY_NODE_ID,
1354 self.expect(&token::CloseDelim(token::Bracket))?;
1356 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1359 self.parse_borrowed_pointee()?
1360 } else if self.eat_keyword_noexpect(kw::Typeof) {
1362 // In order to not be ambiguous, the type must be surrounded by parens.
1363 self.expect(&token::OpenDelim(token::Paren))?;
1365 id: ast::DUMMY_NODE_ID,
1366 value: self.parse_expr()?,
1368 self.expect(&token::CloseDelim(token::Paren))?;
1370 } else if self.eat_keyword(kw::Underscore) {
1371 // A type to be inferred `_`
1373 } else if self.token_is_bare_fn_keyword() {
1374 // Function pointer type
1375 self.parse_ty_bare_fn(Vec::new())?
1376 } else if self.check_keyword(kw::For) {
1377 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1378 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1379 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1380 let lo = self.token.span;
1381 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1382 if self.token_is_bare_fn_keyword() {
1383 self.parse_ty_bare_fn(lifetime_defs)?
1385 let path = self.parse_path(PathStyle::Type)?;
1386 let parse_plus = allow_plus && self.check_plus();
1387 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1389 } else if self.eat_keyword(kw::Impl) {
1390 // Always parse bounds greedily for better error recovery.
1391 let bounds = self.parse_generic_bounds(None)?;
1392 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1393 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1394 } else if self.check_keyword(kw::Dyn) &&
1395 (self.token.span.rust_2018() ||
1396 self.look_ahead(1, |t| t.can_begin_bound() &&
1397 !can_continue_type_after_non_fn_ident(t))) {
1398 self.bump(); // `dyn`
1399 // Always parse bounds greedily for better error recovery.
1400 let bounds = self.parse_generic_bounds(None)?;
1401 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1402 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1403 } else if self.check(&token::Question) ||
1404 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1405 // Bound list (trait object type)
1406 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1407 TraitObjectSyntax::None)
1408 } else if self.eat_lt() {
1410 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1411 TyKind::Path(Some(qself), path)
1412 } else if self.token.is_path_start() {
1414 let path = self.parse_path(PathStyle::Type)?;
1415 if self.eat(&token::Not) {
1416 // Macro invocation in type position
1417 let (delim, tts) = self.expect_delimited_token_tree()?;
1418 let node = Mac_ { path, tts, delim };
1419 TyKind::Mac(respan(lo.to(self.prev_span), node))
1421 // Just a type path or bound list (trait object type) starting with a trait.
1423 // `Trait1 + Trait2 + 'a`
1424 if allow_plus && self.check_plus() {
1425 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1427 TyKind::Path(None, path)
1430 } else if self.check(&token::DotDotDot) {
1431 if allow_c_variadic {
1432 self.eat(&token::DotDotDot);
1435 return Err(self.fatal(
1436 "only foreign functions are allowed to be C-variadic"
1440 let msg = format!("expected type, found {}", self.this_token_descr());
1441 let mut err = self.fatal(&msg);
1442 err.span_label(self.token.span, "expected type");
1443 self.maybe_annotate_with_ascription(&mut err, true);
1447 let span = lo.to(self.prev_span);
1448 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1450 // Try to recover from use of `+` with incorrect priority.
1451 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1452 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1453 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1456 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1457 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1458 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1459 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1461 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1462 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1464 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1467 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1468 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1469 let mutbl = self.parse_mutability();
1470 let ty = self.parse_ty_no_plus()?;
1471 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }));
1474 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1475 let mutbl = if self.eat_keyword(kw::Mut) {
1477 } else if self.eat_keyword(kw::Const) {
1478 Mutability::Immutable
1480 let span = self.prev_span;
1481 let msg = "expected mut or const in raw pointer type";
1482 self.struct_span_err(span, msg)
1483 .span_label(span, msg)
1484 .help("use `*mut T` or `*const T` as appropriate")
1486 Mutability::Immutable
1488 let t = self.parse_ty_no_plus()?;
1489 Ok(MutTy { ty: t, mutbl })
1492 fn is_named_argument(&self) -> bool {
1493 let offset = match self.token.kind {
1494 token::Interpolated(ref nt) => match **nt {
1495 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1498 token::BinOp(token::And) | token::AndAnd => 1,
1499 _ if self.token.is_keyword(kw::Mut) => 1,
1503 self.look_ahead(offset, |t| t.is_ident()) &&
1504 self.look_ahead(offset + 1, |t| t == &token::Colon)
1507 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1509 /// This version of parse arg doesn't necessarily require identifier names.
1510 fn parse_arg_general<F>(
1512 is_trait_item: bool,
1513 allow_c_variadic: bool,
1514 is_name_required: F,
1515 ) -> PResult<'a, Arg>
1517 F: Fn(&token::Token) -> bool
1519 let lo = self.token.span;
1520 let attrs = self.parse_arg_attributes()?;
1521 if let Some(mut arg) = self.parse_self_arg()? {
1522 arg.attrs = attrs.into();
1523 return self.recover_bad_self_arg(arg, is_trait_item);
1526 let is_name_required = is_name_required(&self.token);
1527 let (pat, ty) = if is_name_required || self.is_named_argument() {
1528 debug!("parse_arg_general parse_pat (is_name_required:{})", is_name_required);
1530 let pat = self.parse_pat(Some("argument name"))?;
1531 if let Err(mut err) = self.expect(&token::Colon) {
1532 if let Some(ident) = self.argument_without_type(
1539 return Ok(dummy_arg(ident));
1545 self.eat_incorrect_doc_comment_for_arg_type();
1546 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1548 debug!("parse_arg_general ident_to_pat");
1549 let parser_snapshot_before_ty = self.clone();
1550 self.eat_incorrect_doc_comment_for_arg_type();
1551 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1552 if ty.is_ok() && self.token != token::Comma &&
1553 self.token != token::CloseDelim(token::Paren) {
1554 // This wasn't actually a type, but a pattern looking like a type,
1555 // so we are going to rollback and re-parse for recovery.
1556 ty = self.unexpected();
1560 let ident = Ident::new(kw::Invalid, self.prev_span);
1562 id: ast::DUMMY_NODE_ID,
1563 node: PatKind::Ident(
1564 BindingMode::ByValue(Mutability::Immutable), ident, None),
1570 // If this is a C-variadic argument and we hit an error, return the
1572 if self.token == token::DotDotDot {
1575 // Recover from attempting to parse the argument as a type without pattern.
1577 mem::replace(self, parser_snapshot_before_ty);
1578 self.recover_arg_parse()?
1583 let span = lo.to(self.token.span);
1585 Ok(Arg { attrs: attrs.into(), id: ast::DUMMY_NODE_ID, pat, span, ty })
1588 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
1589 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1590 let lo = self.token.span;
1591 let attrs = self.parse_arg_attributes()?;
1592 let pat = self.parse_pat(Some("argument name"))?;
1593 let t = if self.eat(&token::Colon) {
1597 id: ast::DUMMY_NODE_ID,
1598 node: TyKind::Infer,
1599 span: self.prev_span,
1602 let span = lo.to(self.token.span);
1604 attrs: attrs.into(),
1608 id: ast::DUMMY_NODE_ID
1612 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1613 if self.eat(&token::Semi) {
1614 Ok(Some(self.parse_expr()?))
1620 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1621 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1622 maybe_whole_expr!(self);
1624 let minus_lo = self.token.span;
1625 let minus_present = self.eat(&token::BinOp(token::Minus));
1626 let lo = self.token.span;
1627 let literal = self.parse_lit()?;
1628 let hi = self.prev_span;
1629 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1632 let minus_hi = self.prev_span;
1633 let unary = self.mk_unary(UnOp::Neg, expr);
1634 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1640 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1641 match self.token.kind {
1642 token::Ident(name, _) if name.is_path_segment_keyword() => {
1643 let span = self.token.span;
1645 Ok(Ident::new(name, span))
1647 _ => self.parse_ident(),
1651 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
1652 match self.token.kind {
1653 token::Ident(name, false) if name == kw::Underscore => {
1654 let span = self.token.span;
1656 Ok(Ident::new(name, span))
1658 _ => self.parse_ident(),
1662 /// Parses a qualified path.
1663 /// Assumes that the leading `<` has been parsed already.
1665 /// `qualified_path = <type [as trait_ref]>::path`
1670 /// `<T as U>::F::a<S>` (without disambiguator)
1671 /// `<T as U>::F::a::<S>` (with disambiguator)
1672 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1673 let lo = self.prev_span;
1674 let ty = self.parse_ty()?;
1676 // `path` will contain the prefix of the path up to the `>`,
1677 // if any (e.g., `U` in the `<T as U>::*` examples
1678 // above). `path_span` has the span of that path, or an empty
1679 // span in the case of something like `<T>::Bar`.
1680 let (mut path, path_span);
1681 if self.eat_keyword(kw::As) {
1682 let path_lo = self.token.span;
1683 path = self.parse_path(PathStyle::Type)?;
1684 path_span = path_lo.to(self.prev_span);
1686 path_span = self.token.span.to(self.token.span);
1687 path = ast::Path { segments: Vec::new(), span: path_span };
1690 // See doc comment for `unmatched_angle_bracket_count`.
1691 self.expect(&token::Gt)?;
1692 if self.unmatched_angle_bracket_count > 0 {
1693 self.unmatched_angle_bracket_count -= 1;
1694 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1697 self.expect(&token::ModSep)?;
1699 let qself = QSelf { ty, path_span, position: path.segments.len() };
1700 self.parse_path_segments(&mut path.segments, style)?;
1702 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1705 /// Parses simple paths.
1707 /// `path = [::] segment+`
1708 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1711 /// `a::b::C<D>` (without disambiguator)
1712 /// `a::b::C::<D>` (with disambiguator)
1713 /// `Fn(Args)` (without disambiguator)
1714 /// `Fn::(Args)` (with disambiguator)
1715 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1716 maybe_whole!(self, NtPath, |path| {
1717 if style == PathStyle::Mod &&
1718 path.segments.iter().any(|segment| segment.args.is_some()) {
1719 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1724 let lo = self.meta_var_span.unwrap_or(self.token.span);
1725 let mut segments = Vec::new();
1726 let mod_sep_ctxt = self.token.span.ctxt();
1727 if self.eat(&token::ModSep) {
1728 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
1730 self.parse_path_segments(&mut segments, style)?;
1732 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1735 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
1736 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
1738 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1739 let meta_ident = match self.token.kind {
1740 token::Interpolated(ref nt) => match **nt {
1741 token::NtMeta(ref meta) => match meta.node {
1742 ast::MetaItemKind::Word => Some(meta.path.clone()),
1749 if let Some(path) = meta_ident {
1753 self.parse_path(style)
1756 crate fn parse_path_segments(&mut self,
1757 segments: &mut Vec<PathSegment>,
1759 -> PResult<'a, ()> {
1761 let segment = self.parse_path_segment(style)?;
1762 if style == PathStyle::Expr {
1763 // In order to check for trailing angle brackets, we must have finished
1764 // recursing (`parse_path_segment` can indirectly call this function),
1765 // that is, the next token must be the highlighted part of the below example:
1767 // `Foo::<Bar as Baz<T>>::Qux`
1770 // As opposed to the below highlight (if we had only finished the first
1773 // `Foo::<Bar as Baz<T>>::Qux`
1776 // `PathStyle::Expr` is only provided at the root invocation and never in
1777 // `parse_path_segment` to recurse and therefore can be checked to maintain
1779 self.check_trailing_angle_brackets(&segment, token::ModSep);
1781 segments.push(segment);
1783 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1789 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
1790 let ident = self.parse_path_segment_ident()?;
1792 let is_args_start = |token: &Token| match token.kind {
1793 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
1794 | token::LArrow => true,
1797 let check_args_start = |this: &mut Self| {
1798 this.expected_tokens.extend_from_slice(
1799 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1801 is_args_start(&this.token)
1804 Ok(if style == PathStyle::Type && check_args_start(self) ||
1805 style != PathStyle::Mod && self.check(&token::ModSep)
1806 && self.look_ahead(1, |t| is_args_start(t)) {
1807 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
1808 // it isn't, then we reset the unmatched angle bracket count as we're about to start
1809 // parsing a new path.
1810 if style == PathStyle::Expr {
1811 self.unmatched_angle_bracket_count = 0;
1812 self.max_angle_bracket_count = 0;
1815 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1816 self.eat(&token::ModSep);
1817 let lo = self.token.span;
1818 let args = if self.eat_lt() {
1820 let (args, constraints) =
1821 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
1823 let span = lo.to(self.prev_span);
1824 AngleBracketedArgs { args, constraints, span }.into()
1827 let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?;
1828 let span = lo.to(self.prev_span);
1829 let output = if self.eat(&token::RArrow) {
1830 Some(self.parse_ty_common(false, false, false)?)
1834 ParenthesizedArgs { inputs, output, span }.into()
1837 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
1839 // Generic arguments are not found.
1840 PathSegment::from_ident(ident)
1844 crate fn check_lifetime(&mut self) -> bool {
1845 self.expected_tokens.push(TokenType::Lifetime);
1846 self.token.is_lifetime()
1849 /// Parses a single lifetime `'a` or panics.
1850 crate fn expect_lifetime(&mut self) -> Lifetime {
1851 if let Some(ident) = self.token.lifetime() {
1852 let span = self.token.span;
1854 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
1856 self.span_bug(self.token.span, "not a lifetime")
1860 fn eat_label(&mut self) -> Option<Label> {
1861 if let Some(ident) = self.token.lifetime() {
1862 let span = self.token.span;
1864 Some(Label { ident: Ident::new(ident.name, span) })
1870 /// Parses mutability (`mut` or nothing).
1871 fn parse_mutability(&mut self) -> Mutability {
1872 if self.eat_keyword(kw::Mut) {
1875 Mutability::Immutable
1879 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1880 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1882 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1884 Ok(Ident::new(symbol, self.prev_span))
1886 self.parse_ident_common(false)
1890 /// Parse ident (COLON expr)?
1891 fn parse_field(&mut self) -> PResult<'a, Field> {
1892 let attrs = self.parse_outer_attributes()?;
1893 let lo = self.token.span;
1895 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1896 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1897 t == &token::Colon || t == &token::Eq
1899 let fieldname = self.parse_field_name()?;
1901 // Check for an equals token. This means the source incorrectly attempts to
1902 // initialize a field with an eq rather than a colon.
1903 if self.token == token::Eq {
1905 .struct_span_err(self.token.span, "expected `:`, found `=`")
1907 fieldname.span.shrink_to_hi().to(self.token.span),
1908 "replace equals symbol with a colon",
1910 Applicability::MachineApplicable,
1915 (fieldname, self.parse_expr()?, false)
1917 let fieldname = self.parse_ident_common(false)?;
1919 // Mimic `x: x` for the `x` field shorthand.
1920 let path = ast::Path::from_ident(fieldname);
1921 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1922 (fieldname, expr, true)
1926 span: lo.to(expr.span),
1929 attrs: attrs.into(),
1933 crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1934 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
1937 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1938 ExprKind::Unary(unop, expr)
1941 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1942 ExprKind::Binary(binop, lhs, rhs)
1945 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1946 ExprKind::Call(f, args)
1949 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1950 ExprKind::Index(expr, idx)
1954 start: Option<P<Expr>>,
1955 end: Option<P<Expr>>,
1956 limits: RangeLimits)
1957 -> PResult<'a, ast::ExprKind> {
1958 if end.is_none() && limits == RangeLimits::Closed {
1959 Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
1961 Ok(ExprKind::Range(start, end, limits))
1965 fn mk_assign_op(&self, binop: ast::BinOp,
1966 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1967 ExprKind::AssignOp(binop, lhs, rhs)
1970 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
1971 let delim = match self.token.kind {
1972 token::OpenDelim(delim) => delim,
1974 let msg = "expected open delimiter";
1975 let mut err = self.fatal(msg);
1976 err.span_label(self.token.span, msg);
1980 let tts = match self.parse_token_tree() {
1981 TokenTree::Delimited(_, _, tts) => tts,
1982 _ => unreachable!(),
1984 let delim = match delim {
1985 token::Paren => MacDelimiter::Parenthesis,
1986 token::Bracket => MacDelimiter::Bracket,
1987 token::Brace => MacDelimiter::Brace,
1988 token::NoDelim => self.bug("unexpected no delimiter"),
1990 Ok((delim, tts.into()))
1993 /// At the bottom (top?) of the precedence hierarchy,
1994 /// Parses things like parenthesized exprs, macros, `return`, etc.
1996 /// N.B., this does not parse outer attributes, and is private because it only works
1997 /// correctly if called from `parse_dot_or_call_expr()`.
1998 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1999 maybe_recover_from_interpolated_ty_qpath!(self, true);
2000 maybe_whole_expr!(self);
2002 // Outer attributes are already parsed and will be
2003 // added to the return value after the fact.
2005 // Therefore, prevent sub-parser from parsing
2006 // attributes by giving them a empty "already parsed" list.
2007 let mut attrs = ThinVec::new();
2009 let lo = self.token.span;
2010 let mut hi = self.token.span;
2014 macro_rules! parse_lit {
2016 match self.parse_lit() {
2018 hi = self.prev_span;
2019 ex = ExprKind::Lit(literal);
2022 self.cancel(&mut err);
2023 return Err(self.expected_expression_found());
2029 // Note: when adding new syntax here, don't forget to adjust TokenKind::can_begin_expr().
2030 match self.token.kind {
2031 // This match arm is a special-case of the `_` match arm below and
2032 // could be removed without changing functionality, but it's faster
2033 // to have it here, especially for programs with large constants.
2034 token::Literal(_) => {
2037 token::OpenDelim(token::Paren) => {
2040 attrs.extend(self.parse_inner_attributes()?);
2042 // (e) is parenthesized e
2043 // (e,) is a tuple with only one field, e
2044 let mut es = vec![];
2045 let mut trailing_comma = false;
2046 let mut recovered = false;
2047 while self.token != token::CloseDelim(token::Paren) {
2048 es.push(match self.parse_expr() {
2051 // recover from parse error in tuple list
2052 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2055 recovered = self.expect_one_of(
2057 &[token::Comma, token::CloseDelim(token::Paren)],
2059 if self.eat(&token::Comma) {
2060 trailing_comma = true;
2062 trailing_comma = false;
2070 hi = self.prev_span;
2071 ex = if es.len() == 1 && !trailing_comma {
2072 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2077 token::OpenDelim(token::Brace) => {
2078 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2080 token::BinOp(token::Or) | token::OrOr => {
2081 return self.parse_lambda_expr(attrs);
2083 token::OpenDelim(token::Bracket) => {
2086 attrs.extend(self.parse_inner_attributes()?);
2088 if self.eat(&token::CloseDelim(token::Bracket)) {
2090 ex = ExprKind::Array(Vec::new());
2093 let first_expr = self.parse_expr()?;
2094 if self.eat(&token::Semi) {
2095 // Repeating array syntax: [ 0; 512 ]
2096 let count = AnonConst {
2097 id: ast::DUMMY_NODE_ID,
2098 value: self.parse_expr()?,
2100 self.expect(&token::CloseDelim(token::Bracket))?;
2101 ex = ExprKind::Repeat(first_expr, count);
2102 } else if self.eat(&token::Comma) {
2103 // Vector with two or more elements.
2104 let remaining_exprs = self.parse_seq_to_end(
2105 &token::CloseDelim(token::Bracket),
2106 SeqSep::trailing_allowed(token::Comma),
2107 |p| Ok(p.parse_expr()?)
2109 let mut exprs = vec![first_expr];
2110 exprs.extend(remaining_exprs);
2111 ex = ExprKind::Array(exprs);
2113 // Vector with one element.
2114 self.expect(&token::CloseDelim(token::Bracket))?;
2115 ex = ExprKind::Array(vec![first_expr]);
2118 hi = self.prev_span;
2122 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2124 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2126 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
2127 return self.parse_lambda_expr(attrs);
2129 if self.eat_keyword(kw::If) {
2130 return self.parse_if_expr(attrs);
2132 if self.eat_keyword(kw::For) {
2133 let lo = self.prev_span;
2134 return self.parse_for_expr(None, lo, attrs);
2136 if self.eat_keyword(kw::While) {
2137 let lo = self.prev_span;
2138 return self.parse_while_expr(None, lo, attrs);
2140 if let Some(label) = self.eat_label() {
2141 let lo = label.ident.span;
2142 self.expect(&token::Colon)?;
2143 if self.eat_keyword(kw::While) {
2144 return self.parse_while_expr(Some(label), lo, attrs)
2146 if self.eat_keyword(kw::For) {
2147 return self.parse_for_expr(Some(label), lo, attrs)
2149 if self.eat_keyword(kw::Loop) {
2150 return self.parse_loop_expr(Some(label), lo, attrs)
2152 if self.token == token::OpenDelim(token::Brace) {
2153 return self.parse_block_expr(Some(label),
2155 BlockCheckMode::Default,
2158 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2159 let mut err = self.fatal(msg);
2160 err.span_label(self.token.span, msg);
2163 if self.eat_keyword(kw::Loop) {
2164 let lo = self.prev_span;
2165 return self.parse_loop_expr(None, lo, attrs);
2167 if self.eat_keyword(kw::Continue) {
2168 let label = self.eat_label();
2169 let ex = ExprKind::Continue(label);
2170 let hi = self.prev_span;
2171 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2173 if self.eat_keyword(kw::Match) {
2174 let match_sp = self.prev_span;
2175 return self.parse_match_expr(attrs).map_err(|mut err| {
2176 err.span_label(match_sp, "while parsing this match expression");
2180 if self.eat_keyword(kw::Unsafe) {
2181 return self.parse_block_expr(
2184 BlockCheckMode::Unsafe(ast::UserProvided),
2187 if self.is_do_catch_block() {
2188 let mut db = self.fatal("found removed `do catch` syntax");
2189 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2192 if self.is_try_block() {
2193 let lo = self.token.span;
2194 assert!(self.eat_keyword(kw::Try));
2195 return self.parse_try_block(lo, attrs);
2198 // Span::rust_2018() is somewhat expensive; don't get it repeatedly.
2199 let is_span_rust_2018 = self.token.span.rust_2018();
2200 if is_span_rust_2018 && self.check_keyword(kw::Async) {
2201 return if self.is_async_block() { // check for `async {` and `async move {`
2202 self.parse_async_block(attrs)
2204 self.parse_lambda_expr(attrs)
2207 if self.eat_keyword(kw::Return) {
2208 if self.token.can_begin_expr() {
2209 let e = self.parse_expr()?;
2211 ex = ExprKind::Ret(Some(e));
2213 ex = ExprKind::Ret(None);
2215 } else if self.eat_keyword(kw::Break) {
2216 let label = self.eat_label();
2217 let e = if self.token.can_begin_expr()
2218 && !(self.token == token::OpenDelim(token::Brace)
2219 && self.restrictions.contains(
2220 Restrictions::NO_STRUCT_LITERAL)) {
2221 Some(self.parse_expr()?)
2225 ex = ExprKind::Break(label, e);
2226 hi = self.prev_span;
2227 } else if self.eat_keyword(kw::Yield) {
2228 if self.token.can_begin_expr() {
2229 let e = self.parse_expr()?;
2231 ex = ExprKind::Yield(Some(e));
2233 ex = ExprKind::Yield(None);
2235 } else if self.eat_keyword(kw::Let) {
2236 return self.parse_let_expr(attrs);
2237 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
2238 let (await_hi, e_kind) = self.parse_incorrect_await_syntax(lo, self.prev_span)?;
2241 } else if self.token.is_path_start() {
2242 let path = self.parse_path(PathStyle::Expr)?;
2244 // `!`, as an operator, is prefix, so we know this isn't that
2245 if self.eat(&token::Not) {
2246 // MACRO INVOCATION expression
2247 let (delim, tts) = self.expect_delimited_token_tree()?;
2248 hi = self.prev_span;
2249 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2250 } else if self.check(&token::OpenDelim(token::Brace)) {
2251 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2255 ex = ExprKind::Path(None, path);
2259 ex = ExprKind::Path(None, path);
2262 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2263 // Don't complain about bare semicolons after unclosed braces
2264 // recovery in order to keep the error count down. Fixing the
2265 // delimiters will possibly also fix the bare semicolon found in
2266 // expression context. For example, silence the following error:
2268 // error: expected expression, found `;`
2272 // | ^ expected expression
2275 return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()));
2282 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2283 self.maybe_recover_from_bad_qpath(expr, true)
2286 fn maybe_parse_struct_expr(
2290 attrs: &ThinVec<Attribute>,
2291 ) -> Option<PResult<'a, P<Expr>>> {
2292 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2293 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2294 // `{ ident, ` cannot start a block
2295 self.look_ahead(2, |t| t == &token::Comma) ||
2296 self.look_ahead(2, |t| t == &token::Colon) && (
2297 // `{ ident: token, ` cannot start a block
2298 self.look_ahead(4, |t| t == &token::Comma) ||
2299 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2300 self.look_ahead(3, |t| !t.can_begin_type())
2304 if struct_allowed || certainly_not_a_block() {
2305 // This is a struct literal, but we don't can't accept them here
2306 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2307 if let (Ok(expr), false) = (&expr, struct_allowed) {
2308 self.struct_span_err(
2310 "struct literals are not allowed here",
2312 .multipart_suggestion(
2313 "surround the struct literal with parentheses",
2315 (lo.shrink_to_lo(), "(".to_string()),
2316 (expr.span.shrink_to_hi(), ")".to_string()),
2318 Applicability::MachineApplicable,
2327 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2328 -> PResult<'a, P<Expr>> {
2329 let struct_sp = lo.to(self.prev_span);
2331 let mut fields = Vec::new();
2332 let mut base = None;
2334 attrs.extend(self.parse_inner_attributes()?);
2336 while self.token != token::CloseDelim(token::Brace) {
2337 if self.eat(&token::DotDot) {
2338 let exp_span = self.prev_span;
2339 match self.parse_expr() {
2345 self.recover_stmt();
2348 if self.token == token::Comma {
2349 self.struct_span_err(
2350 exp_span.to(self.prev_span),
2351 "cannot use a comma after the base struct",
2353 .span_suggestion_short(
2355 "remove this comma",
2357 Applicability::MachineApplicable
2359 .note("the base struct must always be the last field")
2361 self.recover_stmt();
2366 let mut recovery_field = None;
2367 if let token::Ident(name, _) = self.token.kind {
2368 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2369 // Use in case of error after field-looking code: `S { foo: () with a }`
2370 recovery_field = Some(ast::Field {
2371 ident: Ident::new(name, self.token.span),
2372 span: self.token.span,
2373 expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
2374 is_shorthand: false,
2375 attrs: ThinVec::new(),
2379 let mut parsed_field = None;
2380 match self.parse_field() {
2381 Ok(f) => parsed_field = Some(f),
2383 e.span_label(struct_sp, "while parsing this struct");
2386 // If the next token is a comma, then try to parse
2387 // what comes next as additional fields, rather than
2388 // bailing out until next `}`.
2389 if self.token != token::Comma {
2390 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2391 if self.token != token::Comma {
2398 match self.expect_one_of(&[token::Comma],
2399 &[token::CloseDelim(token::Brace)]) {
2400 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2401 // only include the field if there's no parse error for the field name
2405 if let Some(f) = recovery_field {
2408 e.span_label(struct_sp, "while parsing this struct");
2410 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2411 self.eat(&token::Comma);
2416 let span = lo.to(self.token.span);
2417 self.expect(&token::CloseDelim(token::Brace))?;
2418 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2421 fn parse_or_use_outer_attributes(&mut self,
2422 already_parsed_attrs: Option<ThinVec<Attribute>>)
2423 -> PResult<'a, ThinVec<Attribute>> {
2424 if let Some(attrs) = already_parsed_attrs {
2427 self.parse_outer_attributes().map(|a| a.into())
2431 /// Parses a block or unsafe block.
2432 crate fn parse_block_expr(
2434 opt_label: Option<Label>,
2436 blk_mode: BlockCheckMode,
2437 outer_attrs: ThinVec<Attribute>,
2438 ) -> PResult<'a, P<Expr>> {
2439 self.expect(&token::OpenDelim(token::Brace))?;
2441 let mut attrs = outer_attrs;
2442 attrs.extend(self.parse_inner_attributes()?);
2444 let blk = self.parse_block_tail(lo, blk_mode)?;
2445 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2448 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2449 fn parse_dot_or_call_expr(&mut self,
2450 already_parsed_attrs: Option<ThinVec<Attribute>>)
2451 -> PResult<'a, P<Expr>> {
2452 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2454 let b = self.parse_bottom_expr();
2455 let (span, b) = self.interpolated_or_expr_span(b)?;
2456 self.parse_dot_or_call_expr_with(b, span, attrs)
2459 fn parse_dot_or_call_expr_with(&mut self,
2462 mut attrs: ThinVec<Attribute>)
2463 -> PResult<'a, P<Expr>> {
2464 // Stitch the list of outer attributes onto the return value.
2465 // A little bit ugly, but the best way given the current code
2467 self.parse_dot_or_call_expr_with_(e0, lo)
2469 expr.map(|mut expr| {
2470 attrs.extend::<Vec<_>>(expr.attrs.into());
2473 ExprKind::If(..) if !expr.attrs.is_empty() => {
2474 // Just point to the first attribute in there...
2475 let span = expr.attrs[0].span;
2478 "attributes are not yet allowed on `if` \
2488 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2489 let span = lo.to(self.prev_span);
2490 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), ThinVec::new());
2491 self.recover_from_await_method_call();
2495 /// Assuming we have just parsed `.`, continue parsing into an expression.
2496 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2497 if self.token.span.rust_2018() && self.eat_keyword(kw::Await) {
2498 return self.mk_await_expr(self_arg, lo);
2501 let segment = self.parse_path_segment(PathStyle::Expr)?;
2502 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2504 Ok(match self.token.kind {
2505 token::OpenDelim(token::Paren) => {
2506 // Method call `expr.f()`
2507 let mut args = self.parse_paren_expr_seq()?;
2508 args.insert(0, self_arg);
2510 let span = lo.to(self.prev_span);
2511 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2514 // Field access `expr.f`
2515 if let Some(args) = segment.args {
2516 self.span_err(args.span(),
2517 "field expressions may not have generic arguments");
2520 let span = lo.to(self.prev_span);
2521 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2526 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2531 while self.eat(&token::Question) {
2532 let hi = self.prev_span;
2533 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2537 if self.eat(&token::Dot) {
2538 match self.token.kind {
2539 token::Ident(..) => {
2540 e = self.parse_dot_suffix(e, lo)?;
2542 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
2543 let span = self.token.span;
2545 let field = ExprKind::Field(e, Ident::new(symbol, span));
2546 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2548 self.expect_no_suffix(span, "a tuple index", suffix);
2550 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
2552 let fstr = symbol.as_str();
2553 let msg = format!("unexpected token: `{}`", symbol);
2554 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
2555 err.span_label(self.prev_span, "unexpected token");
2556 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2557 let float = match fstr.parse::<f64>().ok() {
2561 let sugg = pprust::to_string(|s| {
2565 s.print_usize(float.trunc() as usize);
2568 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2570 err.span_suggestion(
2571 lo.to(self.prev_span),
2572 "try parenthesizing the first index",
2574 Applicability::MachineApplicable
2581 // FIXME Could factor this out into non_fatal_unexpected or something.
2582 let actual = self.this_token_to_string();
2583 self.span_err(self.token.span, &format!("unexpected token: `{}`", actual));
2588 if self.expr_is_complete(&e) { break; }
2589 match self.token.kind {
2591 token::OpenDelim(token::Paren) => {
2592 let seq = self.parse_paren_expr_seq().map(|es| {
2593 let nd = self.mk_call(e, es);
2594 let hi = self.prev_span;
2595 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2597 e = self.recover_seq_parse_error(token::Paren, lo, seq);
2601 // Could be either an index expression or a slicing expression.
2602 token::OpenDelim(token::Bracket) => {
2604 let ix = self.parse_expr()?;
2605 hi = self.token.span;
2606 self.expect(&token::CloseDelim(token::Bracket))?;
2607 let index = self.mk_index(e, ix);
2608 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2616 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
2617 self.parse_paren_comma_seq(|p| p.parse_expr()).map(|(r, _)| r)
2620 crate fn process_potential_macro_variable(&mut self) {
2621 self.token = match self.token.kind {
2622 token::Dollar if self.token.span.ctxt() != SyntaxContext::empty() &&
2623 self.look_ahead(1, |t| t.is_ident()) => {
2625 let name = match self.token.kind {
2626 token::Ident(name, _) => name,
2629 let span = self.prev_span.to(self.token.span);
2631 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
2632 .span_label(span, "unknown macro variable")
2637 token::Interpolated(ref nt) => {
2638 self.meta_var_span = Some(self.token.span);
2639 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2640 // and lifetime tokens, so the former are never encountered during normal parsing.
2642 token::NtIdent(ident, is_raw) =>
2643 Token::new(token::Ident(ident.name, is_raw), ident.span),
2644 token::NtLifetime(ident) =>
2645 Token::new(token::Lifetime(ident.name), ident.span),
2653 /// Parses a single token tree from the input.
2654 crate fn parse_token_tree(&mut self) -> TokenTree {
2655 match self.token.kind {
2656 token::OpenDelim(..) => {
2657 let frame = mem::replace(&mut self.token_cursor.frame,
2658 self.token_cursor.stack.pop().unwrap());
2659 self.token.span = frame.span.entire();
2661 TokenTree::Delimited(
2664 frame.tree_cursor.stream.into(),
2667 token::CloseDelim(_) | token::Eof => unreachable!(),
2669 let token = self.token.take();
2671 TokenTree::Token(token)
2676 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
2677 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2678 let mut tts = Vec::new();
2679 while self.token != token::Eof {
2680 tts.push(self.parse_token_tree());
2685 pub fn parse_tokens(&mut self) -> TokenStream {
2686 let mut result = Vec::new();
2688 match self.token.kind {
2689 token::Eof | token::CloseDelim(..) => break,
2690 _ => result.push(self.parse_token_tree().into()),
2693 TokenStream::new(result)
2696 /// Parse a prefix-unary-operator expr
2697 fn parse_prefix_expr(&mut self,
2698 already_parsed_attrs: Option<ThinVec<Attribute>>)
2699 -> PResult<'a, P<Expr>> {
2700 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2701 let lo = self.token.span;
2702 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
2703 let (hi, ex) = match self.token.kind {
2706 let e = self.parse_prefix_expr(None);
2707 let (span, e) = self.interpolated_or_expr_span(e)?;
2708 (lo.to(span), self.mk_unary(UnOp::Not, e))
2710 // Suggest `!` for bitwise negation when encountering a `~`
2713 let e = self.parse_prefix_expr(None);
2714 let (span, e) = self.interpolated_or_expr_span(e)?;
2715 let span_of_tilde = lo;
2716 self.struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator")
2717 .span_suggestion_short(
2719 "use `!` to perform bitwise negation",
2721 Applicability::MachineApplicable
2724 (lo.to(span), self.mk_unary(UnOp::Not, e))
2726 token::BinOp(token::Minus) => {
2728 let e = self.parse_prefix_expr(None);
2729 let (span, e) = self.interpolated_or_expr_span(e)?;
2730 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2732 token::BinOp(token::Star) => {
2734 let e = self.parse_prefix_expr(None);
2735 let (span, e) = self.interpolated_or_expr_span(e)?;
2736 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2738 token::BinOp(token::And) | token::AndAnd => {
2740 let m = self.parse_mutability();
2741 let e = self.parse_prefix_expr(None);
2742 let (span, e) = self.interpolated_or_expr_span(e)?;
2743 (lo.to(span), ExprKind::AddrOf(m, e))
2745 token::Ident(..) if self.token.is_keyword(kw::Box) => {
2747 let e = self.parse_prefix_expr(None);
2748 let (span, e) = self.interpolated_or_expr_span(e)?;
2749 (lo.to(span), ExprKind::Box(e))
2751 token::Ident(..) if self.token.is_ident_named(sym::not) => {
2752 // `not` is just an ordinary identifier in Rust-the-language,
2753 // but as `rustc`-the-compiler, we can issue clever diagnostics
2754 // for confused users who really want to say `!`
2755 let token_cannot_continue_expr = |t: &Token| match t.kind {
2756 // These tokens can start an expression after `!`, but
2757 // can't continue an expression after an ident
2758 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
2759 token::Literal(..) | token::Pound => true,
2760 _ => t.is_whole_expr(),
2762 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2763 if cannot_continue_expr {
2765 // Emit the error ...
2766 self.struct_span_err(
2768 &format!("unexpected {} after identifier",self.this_token_descr())
2770 .span_suggestion_short(
2771 // Span the `not` plus trailing whitespace to avoid
2772 // trailing whitespace after the `!` in our suggestion
2773 self.sess.source_map()
2774 .span_until_non_whitespace(lo.to(self.token.span)),
2775 "use `!` to perform logical negation",
2777 Applicability::MachineApplicable
2780 // —and recover! (just as if we were in the block
2781 // for the `token::Not` arm)
2782 let e = self.parse_prefix_expr(None);
2783 let (span, e) = self.interpolated_or_expr_span(e)?;
2784 (lo.to(span), self.mk_unary(UnOp::Not, e))
2786 return self.parse_dot_or_call_expr(Some(attrs));
2789 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2791 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2794 /// Parses an associative expression.
2796 /// This parses an expression accounting for associativity and precedence of the operators in
2799 fn parse_assoc_expr(&mut self,
2800 already_parsed_attrs: Option<ThinVec<Attribute>>)
2801 -> PResult<'a, P<Expr>> {
2802 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2805 /// Parses an associative expression with operators of at least `min_prec` precedence.
2806 fn parse_assoc_expr_with(
2810 ) -> PResult<'a, P<Expr>> {
2811 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2814 let attrs = match lhs {
2815 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2818 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
2819 return self.parse_prefix_range_expr(attrs);
2821 self.parse_prefix_expr(attrs)?
2824 let last_type_ascription_set = self.last_type_ascription.is_some();
2826 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
2828 self.last_type_ascription = None;
2829 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2832 (false, _) => {} // continue parsing the expression
2833 // An exhaustive check is done in the following block, but these are checked first
2834 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
2835 // want to keep their span info to improve diagnostics in these cases in a later stage.
2836 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
2837 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
2838 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
2839 (true, Some(AssocOp::Add)) // `{ 42 } + 42
2840 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
2841 // `if x { a } else { b } && if y { c } else { d }`
2842 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
2843 self.last_type_ascription = None;
2844 // These cases are ambiguous and can't be identified in the parser alone
2845 let sp = self.sess.source_map().start_point(self.token.span);
2846 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
2849 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
2850 self.last_type_ascription = None;
2853 (true, Some(_)) => {
2854 // We've found an expression that would be parsed as a statement, but the next
2855 // token implies this should be parsed as an expression.
2856 // For example: `if let Some(x) = x { x } else { 0 } / 2`
2857 let mut err = self.struct_span_err(self.token.span, &format!(
2858 "expected expression, found `{}`",
2859 pprust::token_to_string(&self.token),
2861 err.span_label(self.token.span, "expected expression");
2862 self.sess.expr_parentheses_needed(
2865 Some(pprust::expr_to_string(&lhs),
2870 self.expected_tokens.push(TokenType::Operator);
2871 while let Some(op) = AssocOp::from_token(&self.token) {
2873 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2874 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2875 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2876 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2877 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2878 (PrevTokenKind::Interpolated, _) => self.prev_span,
2879 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2880 if path.segments.len() == 1 => self.prev_span,
2884 let cur_op_span = self.token.span;
2885 let restrictions = if op.is_assign_like() {
2886 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2890 let prec = op.precedence();
2891 if prec < min_prec {
2894 // Check for deprecated `...` syntax
2895 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2896 self.err_dotdotdot_syntax(self.token.span);
2900 if op.is_comparison() {
2901 self.check_no_chained_comparison(&lhs, &op);
2904 if op == AssocOp::As {
2905 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2907 } else if op == AssocOp::Colon {
2908 let maybe_path = self.could_ascription_be_path(&lhs.node);
2909 self.last_type_ascription = Some((self.prev_span, maybe_path));
2911 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
2913 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2914 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2915 // generalise it to the Fixity::None code.
2917 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2918 // two variants are handled with `parse_prefix_range_expr` call above.
2919 let rhs = if self.is_at_start_of_range_notation_rhs() {
2920 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
2924 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2929 let limits = if op == AssocOp::DotDot {
2930 RangeLimits::HalfOpen
2935 let r = self.mk_range(Some(lhs), rhs, limits)?;
2936 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2940 let fixity = op.fixity();
2941 let prec_adjustment = match fixity {
2944 // We currently have no non-associative operators that are not handled above by
2945 // the special cases. The code is here only for future convenience.
2948 let rhs = self.with_res(
2949 restrictions - Restrictions::STMT_EXPR,
2950 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
2953 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
2954 // including the attributes.
2958 .filter(|a| a.style == AttrStyle::Outer)
2960 .map_or(lhs_span, |a| a.span);
2961 let span = lhs_span.to(rhs.span);
2963 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2964 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2965 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2966 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2967 AssocOp::Greater | AssocOp::GreaterEqual => {
2968 let ast_op = op.to_ast_binop().unwrap();
2969 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
2970 self.mk_expr(span, binary, ThinVec::new())
2972 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2973 AssocOp::AssignOp(k) => {
2975 token::Plus => BinOpKind::Add,
2976 token::Minus => BinOpKind::Sub,
2977 token::Star => BinOpKind::Mul,
2978 token::Slash => BinOpKind::Div,
2979 token::Percent => BinOpKind::Rem,
2980 token::Caret => BinOpKind::BitXor,
2981 token::And => BinOpKind::BitAnd,
2982 token::Or => BinOpKind::BitOr,
2983 token::Shl => BinOpKind::Shl,
2984 token::Shr => BinOpKind::Shr,
2986 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
2987 self.mk_expr(span, aopexpr, ThinVec::new())
2989 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
2990 self.bug("AssocOp should have been handled by special case")
2994 if let Fixity::None = fixity { break }
2996 if last_type_ascription_set {
2997 self.last_type_ascription = None;
3002 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3003 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3004 -> PResult<'a, P<Expr>> {
3005 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3006 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3009 // Save the state of the parser before parsing type normally, in case there is a
3010 // LessThan comparison after this cast.
3011 let parser_snapshot_before_type = self.clone();
3012 match self.parse_ty_no_plus() {
3014 Ok(mk_expr(self, rhs))
3016 Err(mut type_err) => {
3017 // Rewind to before attempting to parse the type with generics, to recover
3018 // from situations like `x as usize < y` in which we first tried to parse
3019 // `usize < y` as a type with generic arguments.
3020 let parser_snapshot_after_type = self.clone();
3021 mem::replace(self, parser_snapshot_before_type);
3023 match self.parse_path(PathStyle::Expr) {
3025 let (op_noun, op_verb) = match self.token.kind {
3026 token::Lt => ("comparison", "comparing"),
3027 token::BinOp(token::Shl) => ("shift", "shifting"),
3029 // We can end up here even without `<` being the next token, for
3030 // example because `parse_ty_no_plus` returns `Err` on keywords,
3031 // but `parse_path` returns `Ok` on them due to error recovery.
3032 // Return original error and parser state.
3033 mem::replace(self, parser_snapshot_after_type);
3034 return Err(type_err);
3038 // Successfully parsed the type path leaving a `<` yet to parse.
3041 // Report non-fatal diagnostics, keep `x as usize` as an expression
3042 // in AST and continue parsing.
3043 let msg = format!("`<` is interpreted as a start of generic \
3044 arguments for `{}`, not a {}", path, op_noun);
3045 let span_after_type = parser_snapshot_after_type.token.span;
3046 let expr = mk_expr(self, P(Ty {
3048 node: TyKind::Path(None, path),
3049 id: ast::DUMMY_NODE_ID
3052 let expr_str = self.span_to_snippet(expr.span)
3053 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3055 self.struct_span_err(self.token.span, &msg)
3057 self.look_ahead(1, |t| t.span).to(span_after_type),
3058 "interpreted as generic arguments"
3060 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
3063 &format!("try {} the cast value", op_verb),
3064 format!("({})", expr_str),
3065 Applicability::MachineApplicable
3071 Err(mut path_err) => {
3072 // Couldn't parse as a path, return original error and parser state.
3074 mem::replace(self, parser_snapshot_after_type);
3082 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3083 fn parse_prefix_range_expr(&mut self,
3084 already_parsed_attrs: Option<ThinVec<Attribute>>)
3085 -> PResult<'a, P<Expr>> {
3086 // Check for deprecated `...` syntax
3087 if self.token == token::DotDotDot {
3088 self.err_dotdotdot_syntax(self.token.span);
3091 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
3092 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3094 let tok = self.token.clone();
3095 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3096 let lo = self.token.span;
3097 let mut hi = self.token.span;
3099 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3100 // RHS must be parsed with more associativity than the dots.
3101 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3102 Some(self.parse_assoc_expr_with(next_prec,
3103 LhsExpr::NotYetParsed)
3111 let limits = if tok == token::DotDot {
3112 RangeLimits::HalfOpen
3117 let r = self.mk_range(None, opt_end, limits)?;
3118 Ok(self.mk_expr(lo.to(hi), r, attrs))
3121 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3122 if self.token.can_begin_expr() {
3123 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3124 if self.token == token::OpenDelim(token::Brace) {
3125 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3133 /// Parses an `if` expression (`if` token already eaten).
3134 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3135 let lo = self.prev_span;
3136 let cond = self.parse_cond_expr()?;
3138 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3139 // verify that the last statement is either an implicit return (no `;`) or an explicit
3140 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3141 // the dead code lint.
3142 if self.eat_keyword(kw::Else) || !cond.returns() {
3143 let sp = self.sess.source_map().next_point(lo);
3144 let mut err = self.diagnostic()
3145 .struct_span_err(sp, "missing condition for `if` statemement");
3146 err.span_label(sp, "expected if condition here");
3149 let not_block = self.token != token::OpenDelim(token::Brace);
3150 let thn = self.parse_block().map_err(|mut err| {
3152 err.span_label(lo, "this `if` statement has a condition, but no block");
3156 let mut els: Option<P<Expr>> = None;
3157 let mut hi = thn.span;
3158 if self.eat_keyword(kw::Else) {
3159 let elexpr = self.parse_else_expr()?;
3163 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3166 /// Parse the condition of a `if`- or `while`-expression
3167 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
3168 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3170 if let ExprKind::Let(..) = cond.node {
3171 // Remove the last feature gating of a `let` expression since it's stable.
3172 let last = self.sess.let_chains_spans.borrow_mut().pop();
3173 debug_assert_eq!(cond.span, last.unwrap());
3179 /// Parses a `let $pats = $expr` pseudo-expression.
3180 /// The `let` token has already been eaten.
3181 fn parse_let_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3182 let lo = self.prev_span;
3183 let pats = self.parse_pats()?;
3184 self.expect(&token::Eq)?;
3185 let expr = self.with_res(
3186 Restrictions::NO_STRUCT_LITERAL,
3187 |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
3189 let span = lo.to(expr.span);
3190 self.sess.let_chains_spans.borrow_mut().push(span);
3191 Ok(self.mk_expr(span, ExprKind::Let(pats, expr), attrs))
3194 /// Parses `move |args| expr`.
3195 fn parse_lambda_expr(&mut self,
3196 attrs: ThinVec<Attribute>)
3197 -> PResult<'a, P<Expr>>
3199 let lo = self.token.span;
3201 let movability = if self.eat_keyword(kw::Static) {
3207 let asyncness = if self.token.span.rust_2018() {
3208 self.parse_asyncness()
3212 if asyncness.is_async() {
3213 // Feature gate `async ||` closures.
3214 self.sess.async_closure_spans.borrow_mut().push(self.prev_span);
3217 let capture_clause = self.parse_capture_clause();
3218 let decl = self.parse_fn_block_decl()?;
3219 let decl_hi = self.prev_span;
3220 let body = match decl.output {
3221 FunctionRetTy::Default(_) => {
3222 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3223 self.parse_expr_res(restrictions, None)?
3226 // If an explicit return type is given, require a
3227 // block to appear (RFC 968).
3228 let body_lo = self.token.span;
3229 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3235 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3239 /// `else` token already eaten
3240 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3241 if self.eat_keyword(kw::If) {
3242 return self.parse_if_expr(ThinVec::new());
3244 let blk = self.parse_block()?;
3245 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3249 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3252 opt_label: Option<Label>,
3254 mut attrs: ThinVec<Attribute>
3255 ) -> PResult<'a, P<Expr>> {
3256 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3258 // Record whether we are about to parse `for (`.
3259 // This is used below for recovery in case of `for ( $stuff ) $block`
3260 // in which case we will suggest `for $stuff $block`.
3261 let begin_paren = match self.token.kind {
3262 token::OpenDelim(token::Paren) => Some(self.token.span),
3266 let pat = self.parse_top_level_pat()?;
3267 if !self.eat_keyword(kw::In) {
3268 let in_span = self.prev_span.between(self.token.span);
3269 self.struct_span_err(in_span, "missing `in` in `for` loop")
3270 .span_suggestion_short(
3272 "try adding `in` here", " in ".into(),
3273 // has been misleading, at least in the past (closed Issue #48492)
3274 Applicability::MaybeIncorrect
3278 let in_span = self.prev_span;
3279 self.check_for_for_in_in_typo(in_span);
3280 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3282 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
3284 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3285 attrs.extend(iattrs);
3287 let hi = self.prev_span;
3288 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3291 /// Parses a `while` or `while let` expression (`while` token already eaten).
3292 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3294 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3295 let cond = self.parse_cond_expr()?;
3296 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3297 attrs.extend(iattrs);
3298 let span = span_lo.to(body.span);
3299 Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs))
3302 /// Parse `loop {...}`, `loop` token already eaten.
3303 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3305 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3306 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3307 attrs.extend(iattrs);
3308 let span = span_lo.to(body.span);
3309 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3312 /// Parse an optional `move` prefix to a closure lke construct.
3313 fn parse_capture_clause(&mut self) -> CaptureBy {
3314 if self.eat_keyword(kw::Move) {
3321 /// Parses an `async move? {...}` expression.
3322 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3323 let span_lo = self.token.span;
3324 self.expect_keyword(kw::Async)?;
3325 let capture_clause = self.parse_capture_clause();
3326 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3327 attrs.extend(iattrs);
3329 span_lo.to(body.span),
3330 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3333 /// Parses a `try {...}` expression (`try` token already eaten).
3334 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3335 -> PResult<'a, P<Expr>>
3337 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3338 attrs.extend(iattrs);
3339 if self.eat_keyword(kw::Catch) {
3340 let mut error = self.struct_span_err(self.prev_span,
3341 "keyword `catch` cannot follow a `try` block");
3342 error.help("try using `match` on the result of the `try` block instead");
3346 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3350 // `match` token already eaten
3351 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3352 let match_span = self.prev_span;
3353 let lo = self.prev_span;
3354 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3356 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3357 if self.token == token::Semi {
3358 e.span_suggestion_short(
3360 "try removing this `match`",
3362 Applicability::MaybeIncorrect // speculative
3367 attrs.extend(self.parse_inner_attributes()?);
3369 let mut arms: Vec<Arm> = Vec::new();
3370 while self.token != token::CloseDelim(token::Brace) {
3371 match self.parse_arm() {
3372 Ok(arm) => arms.push(arm),
3374 // Recover by skipping to the end of the block.
3376 self.recover_stmt();
3377 let span = lo.to(self.token.span);
3378 if self.token == token::CloseDelim(token::Brace) {
3381 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3385 let hi = self.token.span;
3387 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3390 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3391 let attrs = self.parse_outer_attributes()?;
3392 let lo = self.token.span;
3393 let pats = self.parse_pats()?;
3394 let guard = if self.eat_keyword(kw::If) {
3395 Some(self.parse_expr()?)
3399 let arrow_span = self.token.span;
3400 self.expect(&token::FatArrow)?;
3401 let arm_start_span = self.token.span;
3403 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3404 .map_err(|mut err| {
3405 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3409 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3410 && self.token != token::CloseDelim(token::Brace);
3412 let hi = self.token.span;
3415 let cm = self.sess.source_map();
3416 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3417 .map_err(|mut err| {
3418 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3419 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3420 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3421 && expr_lines.lines.len() == 2
3422 && self.token == token::FatArrow => {
3423 // We check whether there's any trailing code in the parse span,
3424 // if there isn't, we very likely have the following:
3427 // | -- - missing comma
3431 // | - ^^ self.token.span
3433 // | parsed until here as `"y" & X`
3434 err.span_suggestion_short(
3435 cm.next_point(arm_start_span),
3436 "missing a comma here to end this `match` arm",
3438 Applicability::MachineApplicable
3442 err.span_label(arrow_span,
3443 "while parsing the `match` arm starting here");
3449 self.eat(&token::Comma);
3461 /// Parses an expression.
3463 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3464 self.parse_expr_res(Restrictions::empty(), None)
3467 /// Evaluates the closure with restrictions in place.
3469 /// Afters the closure is evaluated, restrictions are reset.
3470 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3471 where F: FnOnce(&mut Self) -> T
3473 let old = self.restrictions;
3474 self.restrictions = r;
3476 self.restrictions = old;
3481 /// Parses an expression, subject to the given restrictions.
3483 fn parse_expr_res(&mut self, r: Restrictions,
3484 already_parsed_attrs: Option<ThinVec<Attribute>>)
3485 -> PResult<'a, P<Expr>> {
3486 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3489 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
3490 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3491 if self.eat(&token::Eq) {
3492 Ok(Some(self.parse_expr()?))
3494 Ok(Some(self.parse_expr()?))
3500 /// Parses patterns, separated by '|' s.
3501 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3502 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
3503 self.eat(&token::BinOp(token::Or));
3505 let mut pats = Vec::new();
3507 pats.push(self.parse_top_level_pat()?);
3509 if self.token == token::OrOr {
3510 self.struct_span_err(self.token.span, "unexpected token `||` after pattern")
3513 "use a single `|` to specify multiple patterns",
3515 Applicability::MachineApplicable
3519 } else if self.eat(&token::BinOp(token::Or)) {
3520 // This is a No-op. Continue the loop to parse the next
3531 attrs: Vec<Attribute>
3532 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3533 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3535 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3536 // Parsing a pattern of the form "fieldname: pat"
3537 let fieldname = self.parse_field_name()?;
3539 let pat = self.parse_pat(None)?;
3541 (pat, fieldname, false)
3543 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3544 let is_box = self.eat_keyword(kw::Box);
3545 let boxed_span = self.token.span;
3546 let is_ref = self.eat_keyword(kw::Ref);
3547 let is_mut = self.eat_keyword(kw::Mut);
3548 let fieldname = self.parse_ident()?;
3549 hi = self.prev_span;
3551 let bind_type = match (is_ref, is_mut) {
3552 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3553 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3554 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3555 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3557 let fieldpat = P(Pat {
3558 id: ast::DUMMY_NODE_ID,
3559 node: PatKind::Ident(bind_type, fieldname, None),
3560 span: boxed_span.to(hi),
3563 let subpat = if is_box {
3565 id: ast::DUMMY_NODE_ID,
3566 node: PatKind::Box(fieldpat),
3572 (subpat, fieldname, true)
3575 Ok(source_map::Spanned {
3577 node: ast::FieldPat {
3581 attrs: attrs.into(),
3586 /// Parses the fields of a struct-like pattern.
3587 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3588 let mut fields = Vec::new();
3589 let mut etc = false;
3590 let mut ate_comma = true;
3591 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3592 let mut etc_span = None;
3594 while self.token != token::CloseDelim(token::Brace) {
3595 let attrs = match self.parse_outer_attributes() {
3598 if let Some(mut delayed) = delayed_err {
3604 let lo = self.token.span;
3606 // check that a comma comes after every field
3608 let err = self.struct_span_err(self.prev_span, "expected `,`");
3609 if let Some(mut delayed) = delayed_err {
3616 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3618 let mut etc_sp = self.token.span;
3620 if self.token == token::DotDotDot { // Issue #46718
3621 // Accept `...` as if it were `..` to avoid further errors
3622 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
3625 "to omit remaining fields, use one fewer `.`",
3627 Applicability::MachineApplicable
3631 self.bump(); // `..` || `...`
3633 if self.token == token::CloseDelim(token::Brace) {
3634 etc_span = Some(etc_sp);
3637 let token_str = self.this_token_descr();
3638 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3640 err.span_label(self.token.span, "expected `}`");
3641 let mut comma_sp = None;
3642 if self.token == token::Comma { // Issue #49257
3643 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
3644 etc_sp = etc_sp.to(nw_span);
3645 err.span_label(etc_sp,
3646 "`..` must be at the end and cannot have a trailing comma");
3647 comma_sp = Some(self.token.span);
3652 etc_span = Some(etc_sp.until(self.token.span));
3653 if self.token == token::CloseDelim(token::Brace) {
3654 // If the struct looks otherwise well formed, recover and continue.
3655 if let Some(sp) = comma_sp {
3656 err.span_suggestion_short(
3658 "remove this comma",
3660 Applicability::MachineApplicable,
3665 } else if self.token.is_ident() && ate_comma {
3666 // Accept fields coming after `..,`.
3667 // This way we avoid "pattern missing fields" errors afterwards.
3668 // We delay this error until the end in order to have a span for a
3670 if let Some(mut delayed_err) = delayed_err {
3674 delayed_err = Some(err);
3677 if let Some(mut err) = delayed_err {
3684 fields.push(match self.parse_pat_field(lo, attrs) {
3687 if let Some(mut delayed_err) = delayed_err {
3693 ate_comma = self.eat(&token::Comma);
3696 if let Some(mut err) = delayed_err {
3697 if let Some(etc_span) = etc_span {
3698 err.multipart_suggestion(
3699 "move the `..` to the end of the field list",
3701 (etc_span, String::new()),
3702 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3704 Applicability::MachineApplicable,
3709 return Ok((fields, etc));
3712 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3713 if self.token.is_path_start() {
3714 let lo = self.token.span;
3715 let (qself, path) = if self.eat_lt() {
3716 // Parse a qualified path
3717 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3720 // Parse an unqualified path
3721 (None, self.parse_path(PathStyle::Expr)?)
3723 let hi = self.prev_span;
3724 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3726 self.parse_literal_maybe_minus()
3730 /// Is the current token suitable as the start of a range patterns end?
3731 fn is_pat_range_end_start(&self) -> bool {
3732 self.token.is_path_start() // e.g. `MY_CONST`;
3733 || self.token == token::Dot // e.g. `.5` for recovery;
3734 || self.token.can_begin_literal_or_bool() // e.g. `42`.
3735 || self.token.is_whole_expr()
3738 // Helper function to decide whether to parse as ident binding
3739 // or to try to do something more complex like range patterns.
3740 fn parse_as_ident(&mut self) -> bool {
3741 self.look_ahead(1, |t| match t.kind {
3742 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3743 token::DotDotDot | token::DotDotEq | token::DotDot |
3744 token::ModSep | token::Not => false,
3749 /// Parse and throw away a parentesized comma separated
3750 /// sequence of patterns until `)` is reached.
3751 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
3752 while !self.check(&token::CloseDelim(token::Paren)) {
3753 self.parse_pat(None)?;
3754 if !self.eat(&token::Comma) {
3761 /// A wrapper around `parse_pat` with some special error handling for the
3762 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3763 /// to subpatterns within such).
3764 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3765 let pat = self.parse_pat(None)?;
3766 if self.token == token::Comma {
3767 // An unexpected comma after a top-level pattern is a clue that the
3768 // user (perhaps more accustomed to some other language) forgot the
3769 // parentheses in what should have been a tuple pattern; return a
3770 // suggestion-enhanced error here rather than choking on the comma
3772 let comma_span = self.token.span;
3774 if let Err(mut err) = self.skip_pat_list() {
3775 // We didn't expect this to work anyway; we just wanted
3776 // to advance to the end of the comma-sequence so we know
3777 // the span to suggest parenthesizing
3780 let seq_span = pat.span.to(self.prev_span);
3781 let mut err = self.struct_span_err(comma_span,
3782 "unexpected `,` in pattern");
3783 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
3784 err.span_suggestion(
3786 "try adding parentheses to match on a tuple..",
3787 format!("({})", seq_snippet),
3788 Applicability::MachineApplicable
3791 "..or a vertical bar to match on multiple alternatives",
3792 format!("{}", seq_snippet.replace(",", " |")),
3793 Applicability::MachineApplicable
3801 /// Parses a pattern.
3802 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
3803 self.parse_pat_with_range_pat(true, expected)
3806 /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
3807 fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
3808 let lo = self.prev_span;
3809 let end = self.parse_pat_range_end()?;
3810 let range_span = lo.to(end.span);
3811 let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
3814 .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
3817 "try using the minimum value for the type",
3818 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
3819 Applicability::HasPlaceholders,
3823 Ok(PatKind::Range(begin, end, respan(lo, re)))
3826 /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern or recover
3827 /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
3828 fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
3829 if self.is_pat_range_end_start() {
3830 // Parsing e.g. `X..=Y`.
3831 self.parse_pat_range_end()
3833 // Parsing e.g. `X..`.
3834 let range_span = begin.span.to(self.prev_span);
3839 &format!("`X{}` range patterns are not supported", form),
3843 "try using the maximum value for the type",
3844 format!("{}{}MAX", pprust::expr_to_string(&begin), form),
3845 Applicability::HasPlaceholders,
3849 Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
3853 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
3855 fn parse_pat_with_range_pat(
3857 allow_range_pat: bool,
3858 expected: Option<&'static str>,
3859 ) -> PResult<'a, P<Pat>> {
3860 maybe_recover_from_interpolated_ty_qpath!(self, true);
3861 maybe_whole!(self, NtPat, |x| x);
3863 let lo = self.token.span;
3865 match self.token.kind {
3866 token::BinOp(token::And) | token::AndAnd => {
3867 // Parse &pat / &mut pat
3869 let mutbl = self.parse_mutability();
3870 if let token::Lifetime(name) = self.token.kind {
3871 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
3872 err.span_label(self.token.span, "unexpected lifetime");
3875 let subpat = self.parse_pat_with_range_pat(false, expected)?;
3876 pat = PatKind::Ref(subpat, mutbl);
3878 token::OpenDelim(token::Paren) => {
3879 // Parse a tuple or parenthesis pattern.
3880 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| p.parse_pat(None))?;
3882 // Here, `(pat,)` is a tuple pattern.
3883 // For backward compatibility, `(..)` is a tuple pattern as well.
3884 pat = if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
3885 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3887 PatKind::Tuple(fields)
3890 token::OpenDelim(token::Bracket) => {
3891 // Parse `[pat, pat,...]` as a slice pattern.
3892 let (slice, _) = self.parse_delim_comma_seq(token::Bracket, |p| p.parse_pat(None))?;
3893 pat = PatKind::Slice(slice);
3897 pat = if self.is_pat_range_end_start() {
3898 // Parse `..42` for recovery.
3899 self.parse_pat_range_to(RangeEnd::Excluded, "..")?
3901 // A rest pattern `..`.
3905 token::DotDotEq => {
3906 // Parse `..=42` for recovery.
3908 pat = self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?;
3910 token::DotDotDot => {
3911 // Parse `...42` for recovery.
3913 pat = self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?;
3915 // At this point, token != &, &&, (, [
3916 _ => if self.eat_keyword(kw::Underscore) {
3918 pat = PatKind::Wild;
3919 } else if self.eat_keyword(kw::Mut) {
3920 // Parse mut ident @ pat / mut ref ident @ pat
3921 let mutref_span = self.prev_span.to(self.token.span);
3922 let binding_mode = if self.eat_keyword(kw::Ref) {
3924 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3927 "try switching the order",
3929 Applicability::MachineApplicable
3931 BindingMode::ByRef(Mutability::Mutable)
3933 BindingMode::ByValue(Mutability::Mutable)
3935 pat = self.parse_pat_ident(binding_mode)?;
3936 } else if self.eat_keyword(kw::Ref) {
3937 // Parse ref ident @ pat / ref mut ident @ pat
3938 let mutbl = self.parse_mutability();
3939 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3940 } else if self.eat_keyword(kw::Box) {
3942 let subpat = self.parse_pat_with_range_pat(false, None)?;
3943 pat = PatKind::Box(subpat);
3944 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3945 self.parse_as_ident() {
3946 // Parse ident @ pat
3947 // This can give false positives and parse nullary enums,
3948 // they are dealt with later in resolve
3949 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3950 pat = self.parse_pat_ident(binding_mode)?;
3951 } else if self.token.is_path_start() {
3952 // Parse pattern starting with a path
3953 let (qself, path) = if self.eat_lt() {
3954 // Parse a qualified path
3955 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3958 // Parse an unqualified path
3959 (None, self.parse_path(PathStyle::Expr)?)
3961 match self.token.kind {
3962 token::Not if qself.is_none() => {
3963 // Parse macro invocation
3965 let (delim, tts) = self.expect_delimited_token_tree()?;
3966 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
3967 pat = PatKind::Mac(mac);
3969 token::DotDotDot | token::DotDotEq | token::DotDot => {
3970 let (end_kind, form) = match self.token.kind {
3971 token::DotDot => (RangeEnd::Excluded, ".."),
3972 token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
3973 token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
3974 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3977 let op_span = self.token.span;
3979 let span = lo.to(self.prev_span);
3980 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3982 let end = self.parse_pat_range_end_opt(&begin, form)?;
3983 pat = PatKind::Range(begin, end, respan(op_span, end_kind));
3985 token::OpenDelim(token::Brace) => {
3986 if qself.is_some() {
3987 let msg = "unexpected `{` after qualified path";
3988 let mut err = self.fatal(msg);
3989 err.span_label(self.token.span, msg);
3992 // Parse struct pattern
3994 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3996 self.recover_stmt();
4000 pat = PatKind::Struct(path, fields, etc);
4002 token::OpenDelim(token::Paren) => {
4003 if qself.is_some() {
4004 let msg = "unexpected `(` after qualified path";
4005 let mut err = self.fatal(msg);
4006 err.span_label(self.token.span, msg);
4009 // Parse tuple struct or enum pattern
4010 let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat(None))?;
4011 pat = PatKind::TupleStruct(path, fields)
4013 _ => pat = PatKind::Path(qself, path),
4016 // Try to parse everything else as literal with optional minus
4017 match self.parse_literal_maybe_minus() {
4019 let op_span = self.token.span;
4020 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4021 self.check(&token::DotDotDot) {
4022 let (end_kind, form) = if self.eat(&token::DotDotDot) {
4023 (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
4024 } else if self.eat(&token::DotDotEq) {
4025 (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
4026 } else if self.eat(&token::DotDot) {
4027 (RangeEnd::Excluded, "..")
4029 panic!("impossible case: we already matched \
4030 on a range-operator token")
4032 let end = self.parse_pat_range_end_opt(&begin, form)?;
4033 pat = PatKind::Range(begin, end, respan(op_span, end_kind))
4035 pat = PatKind::Lit(begin);
4039 self.cancel(&mut err);
4040 let expected = expected.unwrap_or("pattern");
4042 "expected {}, found {}",
4044 self.this_token_descr(),
4046 let mut err = self.fatal(&msg);
4047 err.span_label(self.token.span, format!("expected {}", expected));
4048 let sp = self.sess.source_map().start_point(self.token.span);
4049 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4050 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4058 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4059 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4061 if !allow_range_pat {
4064 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4066 PatKind::Range(..) => {
4067 let mut err = self.struct_span_err(
4069 "the range pattern here has ambiguous interpretation",
4071 err.span_suggestion(
4073 "add parentheses to clarify the precedence",
4074 format!("({})", pprust::pat_to_string(&pat)),
4075 // "ambiguous interpretation" implies that we have to be guessing
4076 Applicability::MaybeIncorrect
4087 /// Parses `ident` or `ident @ pat`.
4088 /// used by the copy foo and ref foo patterns to give a good
4089 /// error message when parsing mistakes like `ref foo(a, b)`.
4090 fn parse_pat_ident(&mut self,
4091 binding_mode: ast::BindingMode)
4092 -> PResult<'a, PatKind> {
4093 let ident = self.parse_ident()?;
4094 let sub = if self.eat(&token::At) {
4095 Some(self.parse_pat(Some("binding pattern"))?)
4100 // just to be friendly, if they write something like
4102 // we end up here with ( as the current token. This shortly
4103 // leads to a parse error. Note that if there is no explicit
4104 // binding mode then we do not end up here, because the lookahead
4105 // will direct us over to parse_enum_variant()
4106 if self.token == token::OpenDelim(token::Paren) {
4107 return Err(self.span_fatal(
4109 "expected identifier, found enum pattern"))
4112 Ok(PatKind::Ident(binding_mode, ident, sub))
4115 /// Parses a local variable declaration.
4116 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4117 let lo = self.prev_span;
4118 let pat = self.parse_top_level_pat()?;
4120 let (err, ty) = if self.eat(&token::Colon) {
4121 // Save the state of the parser before parsing type normally, in case there is a `:`
4122 // instead of an `=` typo.
4123 let parser_snapshot_before_type = self.clone();
4124 let colon_sp = self.prev_span;
4125 match self.parse_ty() {
4126 Ok(ty) => (None, Some(ty)),
4128 // Rewind to before attempting to parse the type and continue parsing
4129 let parser_snapshot_after_type = self.clone();
4130 mem::replace(self, parser_snapshot_before_type);
4132 let snippet = self.span_to_snippet(pat.span).unwrap();
4133 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4134 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4140 let init = match (self.parse_initializer(err.is_some()), err) {
4141 (Ok(init), None) => { // init parsed, ty parsed
4144 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4145 // Could parse the type as if it were the initializer, it is likely there was a
4146 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4147 err.span_suggestion_short(
4149 "use `=` if you meant to assign",
4151 Applicability::MachineApplicable
4154 // As this was parsed successfully, continue as if the code has been fixed for the
4155 // rest of the file. It will still fail due to the emitted error, but we avoid
4159 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4161 // Couldn't parse the type nor the initializer, only raise the type error and
4162 // return to the parser state before parsing the type as the initializer.
4163 // let x: <parse_error>;
4164 mem::replace(self, snapshot);
4167 (Err(err), None) => { // init error, ty parsed
4168 // Couldn't parse the initializer and we're not attempting to recover a failed
4169 // parse of the type, return the error.
4173 let hi = if self.token == token::Semi {
4182 id: ast::DUMMY_NODE_ID,
4188 /// Parses a structure field.
4189 fn parse_name_and_ty(&mut self,
4192 attrs: Vec<Attribute>)
4193 -> PResult<'a, StructField> {
4194 let name = self.parse_ident()?;
4195 self.expect(&token::Colon)?;
4196 let ty = self.parse_ty()?;
4198 span: lo.to(self.prev_span),
4201 id: ast::DUMMY_NODE_ID,
4207 /// Emits an expected-item-after-attributes error.
4208 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4209 let message = match attrs.last() {
4210 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4211 _ => "expected item after attributes",
4214 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4215 if attrs.last().unwrap().is_sugared_doc {
4216 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4221 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4222 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4223 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4224 Ok(self.parse_stmt_(true))
4227 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4228 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4230 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4235 fn is_async_block(&self) -> bool {
4236 self.token.is_keyword(kw::Async) &&
4239 self.is_keyword_ahead(1, &[kw::Move]) &&
4240 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4242 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4247 fn is_async_fn(&self) -> bool {
4248 self.token.is_keyword(kw::Async) &&
4249 self.is_keyword_ahead(1, &[kw::Fn])
4252 fn is_do_catch_block(&self) -> bool {
4253 self.token.is_keyword(kw::Do) &&
4254 self.is_keyword_ahead(1, &[kw::Catch]) &&
4255 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4256 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4259 fn is_try_block(&self) -> bool {
4260 self.token.is_keyword(kw::Try) &&
4261 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4262 self.token.span.rust_2018() &&
4263 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4264 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4267 fn is_union_item(&self) -> bool {
4268 self.token.is_keyword(kw::Union) &&
4269 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4272 fn is_crate_vis(&self) -> bool {
4273 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4276 fn is_auto_trait_item(&self) -> bool {
4278 (self.token.is_keyword(kw::Auto) &&
4279 self.is_keyword_ahead(1, &[kw::Trait]))
4280 || // unsafe auto trait
4281 (self.token.is_keyword(kw::Unsafe) &&
4282 self.is_keyword_ahead(1, &[kw::Auto]) &&
4283 self.is_keyword_ahead(2, &[kw::Trait]))
4286 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4287 -> PResult<'a, Option<P<Item>>> {
4288 let token_lo = self.token.span;
4289 let (ident, def) = if self.eat_keyword(kw::Macro) {
4290 let ident = self.parse_ident()?;
4291 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4292 match self.parse_token_tree() {
4293 TokenTree::Delimited(_, _, tts) => tts,
4294 _ => unreachable!(),
4296 } else if self.check(&token::OpenDelim(token::Paren)) {
4297 let args = self.parse_token_tree();
4298 let body = if self.check(&token::OpenDelim(token::Brace)) {
4299 self.parse_token_tree()
4304 TokenStream::new(vec![
4306 TokenTree::token(token::FatArrow, token_lo.to(self.prev_span)).into(),
4314 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4315 } else if self.check_keyword(sym::macro_rules) &&
4316 self.look_ahead(1, |t| *t == token::Not) &&
4317 self.look_ahead(2, |t| t.is_ident()) {
4318 let prev_span = self.prev_span;
4319 self.complain_if_pub_macro(&vis.node, prev_span);
4323 let ident = self.parse_ident()?;
4324 let (delim, tokens) = self.expect_delimited_token_tree()?;
4325 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
4326 self.report_invalid_macro_expansion_item();
4329 (ident, ast::MacroDef { tokens, legacy: true })
4334 let span = lo.to(self.prev_span);
4335 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4338 fn parse_stmt_without_recovery(
4340 macro_legacy_warnings: bool,
4341 ) -> PResult<'a, Option<Stmt>> {
4342 maybe_whole!(self, NtStmt, |x| Some(x));
4344 let attrs = self.parse_outer_attributes()?;
4345 let lo = self.token.span;
4347 Ok(Some(if self.eat_keyword(kw::Let) {
4349 id: ast::DUMMY_NODE_ID,
4350 node: StmtKind::Local(self.parse_local(attrs.into())?),
4351 span: lo.to(self.prev_span),
4353 } else if let Some(macro_def) = self.eat_macro_def(
4355 &source_map::respan(lo, VisibilityKind::Inherited),
4359 id: ast::DUMMY_NODE_ID,
4360 node: StmtKind::Item(macro_def),
4361 span: lo.to(self.prev_span),
4363 // Starts like a simple path, being careful to avoid contextual keywords
4364 // such as a union items, item with `crate` visibility or auto trait items.
4365 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4366 // like a path (1 token), but it fact not a path.
4367 // `union::b::c` - path, `union U { ... }` - not a path.
4368 // `crate::b::c` - path, `crate struct S;` - not a path.
4369 } else if self.token.is_path_start() &&
4370 !self.token.is_qpath_start() &&
4371 !self.is_union_item() &&
4372 !self.is_crate_vis() &&
4373 !self.is_auto_trait_item() &&
4374 !self.is_async_fn() {
4375 let path = self.parse_path(PathStyle::Expr)?;
4377 if !self.eat(&token::Not) {
4378 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4379 self.parse_struct_expr(lo, path, ThinVec::new())?
4381 let hi = self.prev_span;
4382 self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new())
4385 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4386 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4387 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4390 return Ok(Some(Stmt {
4391 id: ast::DUMMY_NODE_ID,
4392 node: StmtKind::Expr(expr),
4393 span: lo.to(self.prev_span),
4397 let (delim, tts) = self.expect_delimited_token_tree()?;
4398 let hi = self.prev_span;
4400 let style = if delim == MacDelimiter::Brace {
4401 MacStmtStyle::Braces
4403 MacStmtStyle::NoBraces
4406 let mac = respan(lo.to(hi), Mac_ { path, tts, delim });
4407 let node = if delim == MacDelimiter::Brace ||
4408 self.token == token::Semi || self.token == token::Eof {
4409 StmtKind::Mac(P((mac, style, attrs.into())))
4411 // We used to incorrectly stop parsing macro-expanded statements here.
4412 // If the next token will be an error anyway but could have parsed with the
4413 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4414 else if macro_legacy_warnings &&
4415 self.token.can_begin_expr() &&
4416 match self.token.kind {
4417 // These can continue an expression, so we can't stop parsing and warn.
4418 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4419 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4420 token::BinOp(token::And) | token::BinOp(token::Or) |
4421 token::AndAnd | token::OrOr |
4422 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4425 self.warn_missing_semicolon();
4426 StmtKind::Mac(P((mac, style, attrs.into())))
4428 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
4429 let e = self.maybe_recover_from_bad_qpath(e, true)?;
4430 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4431 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4435 id: ast::DUMMY_NODE_ID,
4440 // FIXME: Bad copy of attrs
4441 let old_directory_ownership =
4442 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4443 let item = self.parse_item_(attrs.clone(), false, true)?;
4444 self.directory.ownership = old_directory_ownership;
4448 id: ast::DUMMY_NODE_ID,
4449 span: lo.to(i.span),
4450 node: StmtKind::Item(i),
4453 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4454 if !attrs.is_empty() {
4455 if s.prev_token_kind == PrevTokenKind::DocComment {
4456 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4457 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4459 s.token.span, "expected statement after outer attribute"
4465 // Do not attempt to parse an expression if we're done here.
4466 if self.token == token::Semi {
4467 unused_attrs(&attrs, self);
4472 if self.token == token::CloseDelim(token::Brace) {
4473 unused_attrs(&attrs, self);
4477 // Remainder are line-expr stmts.
4478 let e = self.parse_expr_res(
4479 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4481 id: ast::DUMMY_NODE_ID,
4482 span: lo.to(e.span),
4483 node: StmtKind::Expr(e),
4490 /// Checks if this expression is a successfully parsed statement.
4491 fn expr_is_complete(&self, e: &Expr) -> bool {
4492 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4493 !classify::expr_requires_semi_to_be_stmt(e)
4496 /// Parses a block. No inner attributes are allowed.
4497 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4498 maybe_whole!(self, NtBlock, |x| x);
4500 let lo = self.token.span;
4502 if !self.eat(&token::OpenDelim(token::Brace)) {
4503 let sp = self.token.span;
4504 let tok = self.this_token_descr();
4505 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4506 let do_not_suggest_help =
4507 self.token.is_keyword(kw::In) || self.token == token::Colon;
4509 if self.token.is_ident_named(sym::and) {
4510 e.span_suggestion_short(
4512 "use `&&` instead of `and` for the boolean operator",
4514 Applicability::MaybeIncorrect,
4517 if self.token.is_ident_named(sym::or) {
4518 e.span_suggestion_short(
4520 "use `||` instead of `or` for the boolean operator",
4522 Applicability::MaybeIncorrect,
4526 // Check to see if the user has written something like
4531 // Which is valid in other languages, but not Rust.
4532 match self.parse_stmt_without_recovery(false) {
4534 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4535 || do_not_suggest_help {
4536 // if the next token is an open brace (e.g., `if a b {`), the place-
4537 // inside-a-block suggestion would be more likely wrong than right
4538 e.span_label(sp, "expected `{`");
4541 let mut stmt_span = stmt.span;
4542 // expand the span to include the semicolon, if it exists
4543 if self.eat(&token::Semi) {
4544 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4546 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
4549 "try placing this code inside a block",
4550 format!("{{ {} }}", snippet),
4551 // speculative, has been misleading in the past (#46836)
4552 Applicability::MaybeIncorrect,
4557 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4558 self.cancel(&mut e);
4562 e.span_label(sp, "expected `{`");
4566 self.parse_block_tail(lo, BlockCheckMode::Default)
4569 /// Parses a block. Inner attributes are allowed.
4570 crate fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4571 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4573 let lo = self.token.span;
4574 self.expect(&token::OpenDelim(token::Brace))?;
4575 Ok((self.parse_inner_attributes()?,
4576 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4579 /// Parses the rest of a block expression or function body.
4580 /// Precondition: already parsed the '{'.
4581 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4582 let mut stmts = vec![];
4583 while !self.eat(&token::CloseDelim(token::Brace)) {
4584 if self.token == token::Eof {
4587 let stmt = match self.parse_full_stmt(false) {
4590 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4592 id: ast::DUMMY_NODE_ID,
4593 node: StmtKind::Expr(DummyResult::raw_expr(self.token.span, true)),
4594 span: self.token.span,
4599 if let Some(stmt) = stmt {
4602 // Found only `;` or `}`.
4608 id: ast::DUMMY_NODE_ID,
4610 span: lo.to(self.prev_span),
4614 /// Parses a statement, including the trailing semicolon.
4615 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4616 // skip looking for a trailing semicolon when we have an interpolated statement
4617 maybe_whole!(self, NtStmt, |x| Some(x));
4619 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4621 None => return Ok(None),
4625 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4626 // expression without semicolon
4627 if classify::expr_requires_semi_to_be_stmt(expr) {
4628 // Just check for errors and recover; do not eat semicolon yet.
4630 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4633 self.recover_stmt();
4634 // Don't complain about type errors in body tail after parse error (#57383).
4635 let sp = expr.span.to(self.prev_span);
4636 stmt.node = StmtKind::Expr(DummyResult::raw_expr(sp, true));
4640 StmtKind::Local(..) => {
4641 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4642 if macro_legacy_warnings && self.token != token::Semi {
4643 self.warn_missing_semicolon();
4645 self.expect_one_of(&[], &[token::Semi])?;
4651 if self.eat(&token::Semi) {
4652 stmt = stmt.add_trailing_semicolon();
4654 stmt.span = stmt.span.to(self.prev_span);
4658 fn warn_missing_semicolon(&self) {
4659 self.diagnostic().struct_span_warn(self.token.span, {
4660 &format!("expected `;`, found {}", self.this_token_descr())
4662 "This was erroneously allowed and will become a hard error in a future release"
4666 fn err_dotdotdot_syntax(&self, span: Span) {
4667 self.diagnostic().struct_span_err(span, {
4668 "unexpected token: `...`"
4670 span, "use `..` for an exclusive range", "..".to_owned(),
4671 Applicability::MaybeIncorrect
4673 span, "or `..=` for an inclusive range", "..=".to_owned(),
4674 Applicability::MaybeIncorrect
4678 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
4681 /// BOUND = TY_BOUND | LT_BOUND
4682 /// LT_BOUND = LIFETIME (e.g., `'a`)
4683 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4684 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
4686 fn parse_generic_bounds_common(&mut self,
4688 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4689 let mut bounds = Vec::new();
4690 let mut negative_bounds = Vec::new();
4691 let mut last_plus_span = None;
4692 let mut was_negative = false;
4694 // This needs to be synchronized with `TokenKind::can_begin_bound`.
4695 let is_bound_start = self.check_path() || self.check_lifetime() ||
4696 self.check(&token::Not) || // used for error reporting only
4697 self.check(&token::Question) ||
4698 self.check_keyword(kw::For) ||
4699 self.check(&token::OpenDelim(token::Paren));
4701 let lo = self.token.span;
4702 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4703 let inner_lo = self.token.span;
4704 let is_negative = self.eat(&token::Not);
4705 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4706 if self.token.is_lifetime() {
4707 if let Some(question_span) = question {
4708 self.span_err(question_span,
4709 "`?` may only modify trait bounds, not lifetime bounds");
4711 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4713 let inner_span = inner_lo.to(self.prev_span);
4714 self.expect(&token::CloseDelim(token::Paren))?;
4715 let mut err = self.struct_span_err(
4716 lo.to(self.prev_span),
4717 "parenthesized lifetime bounds are not supported"
4719 if let Ok(snippet) = self.span_to_snippet(inner_span) {
4720 err.span_suggestion_short(
4721 lo.to(self.prev_span),
4722 "remove the parentheses",
4724 Applicability::MachineApplicable
4730 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4731 let path = self.parse_path(PathStyle::Type)?;
4733 self.expect(&token::CloseDelim(token::Paren))?;
4735 let poly_span = lo.to(self.prev_span);
4737 was_negative = true;
4738 if let Some(sp) = last_plus_span.or(colon_span) {
4739 negative_bounds.push(sp.to(poly_span));
4742 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
4743 let modifier = if question.is_some() {
4744 TraitBoundModifier::Maybe
4746 TraitBoundModifier::None
4748 bounds.push(GenericBound::Trait(poly_trait, modifier));
4755 if !allow_plus || !self.eat_plus() {
4758 last_plus_span = Some(self.prev_span);
4762 if !negative_bounds.is_empty() || was_negative {
4763 let plural = negative_bounds.len() > 1;
4764 let last_span = negative_bounds.last().map(|sp| *sp);
4765 let mut err = self.struct_span_err(
4767 "negative trait bounds are not supported",
4769 if let Some(sp) = last_span {
4770 err.span_label(sp, "negative trait bounds are not supported");
4772 if let Some(bound_list) = colon_span {
4773 let bound_list = bound_list.to(self.prev_span);
4774 let mut new_bound_list = String::new();
4775 if !bounds.is_empty() {
4776 let mut snippets = bounds.iter().map(|bound| bound.span())
4777 .map(|span| self.span_to_snippet(span));
4778 while let Some(Ok(snippet)) = snippets.next() {
4779 new_bound_list.push_str(" + ");
4780 new_bound_list.push_str(&snippet);
4782 new_bound_list = new_bound_list.replacen(" +", ":", 1);
4784 err.span_suggestion_hidden(
4786 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
4788 Applicability::MachineApplicable,
4797 crate fn parse_generic_bounds(&mut self,
4798 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4799 self.parse_generic_bounds_common(true, colon_span)
4802 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4805 /// BOUND = LT_BOUND (e.g., `'a`)
4807 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4808 let mut lifetimes = Vec::new();
4809 while self.check_lifetime() {
4810 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4812 if !self.eat_plus() {
4819 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
4820 fn parse_ty_param(&mut self,
4821 preceding_attrs: Vec<Attribute>)
4822 -> PResult<'a, GenericParam> {
4823 let ident = self.parse_ident()?;
4825 // Parse optional colon and param bounds.
4826 let bounds = if self.eat(&token::Colon) {
4827 self.parse_generic_bounds(Some(self.prev_span))?
4832 let default = if self.eat(&token::Eq) {
4833 Some(self.parse_ty()?)
4840 id: ast::DUMMY_NODE_ID,
4841 attrs: preceding_attrs.into(),
4843 kind: GenericParamKind::Type {
4849 /// Parses the following grammar:
4851 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4852 fn parse_trait_item_assoc_ty(&mut self)
4853 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4854 let ident = self.parse_ident()?;
4855 let mut generics = self.parse_generics()?;
4857 // Parse optional colon and param bounds.
4858 let bounds = if self.eat(&token::Colon) {
4859 self.parse_generic_bounds(None)?
4863 generics.where_clause = self.parse_where_clause()?;
4865 let default = if self.eat(&token::Eq) {
4866 Some(self.parse_ty()?)
4870 self.expect(&token::Semi)?;
4872 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4875 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
4876 self.expect_keyword(kw::Const)?;
4877 let ident = self.parse_ident()?;
4878 self.expect(&token::Colon)?;
4879 let ty = self.parse_ty()?;
4883 id: ast::DUMMY_NODE_ID,
4884 attrs: preceding_attrs.into(),
4886 kind: GenericParamKind::Const {
4892 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
4893 /// a trailing comma and erroneous trailing attributes.
4894 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4895 let mut params = Vec::new();
4897 let attrs = self.parse_outer_attributes()?;
4898 if self.check_lifetime() {
4899 let lifetime = self.expect_lifetime();
4900 // Parse lifetime parameter.
4901 let bounds = if self.eat(&token::Colon) {
4902 self.parse_lt_param_bounds()
4906 params.push(ast::GenericParam {
4907 ident: lifetime.ident,
4909 attrs: attrs.into(),
4911 kind: ast::GenericParamKind::Lifetime,
4913 } else if self.check_keyword(kw::Const) {
4914 // Parse const parameter.
4915 params.push(self.parse_const_param(attrs)?);
4916 } else if self.check_ident() {
4917 // Parse type parameter.
4918 params.push(self.parse_ty_param(attrs)?);
4920 // Check for trailing attributes and stop parsing.
4921 if !attrs.is_empty() {
4922 if !params.is_empty() {
4923 self.struct_span_err(
4925 &format!("trailing attribute after generic parameter"),
4927 .span_label(attrs[0].span, "attributes must go before parameters")
4930 self.struct_span_err(
4932 &format!("attribute without generic parameters"),
4936 "attributes are only permitted when preceding parameters",
4944 if !self.eat(&token::Comma) {
4951 /// Parses a set of optional generic type parameter declarations. Where
4952 /// clauses are not parsed here, and must be added later via
4953 /// `parse_where_clause()`.
4955 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4956 /// | ( < lifetimes , typaramseq ( , )? > )
4957 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4958 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4959 let span_lo = self.token.span;
4960 let (params, span) = if self.eat_lt() {
4961 let params = self.parse_generic_params()?;
4963 (params, span_lo.to(self.prev_span))
4965 (vec![], self.prev_span.between(self.token.span))
4969 where_clause: WhereClause {
4970 predicates: Vec::new(),
4977 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
4978 /// For the purposes of understanding the parsing logic of generic arguments, this function
4979 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
4980 /// had the correct amount of leading angle brackets.
4982 /// ```ignore (diagnostics)
4983 /// bar::<<<<T as Foo>::Output>();
4984 /// ^^ help: remove extra angle brackets
4986 fn parse_generic_args_with_leaning_angle_bracket_recovery(
4990 ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
4991 // We need to detect whether there are extra leading left angle brackets and produce an
4992 // appropriate error and suggestion. This cannot be implemented by looking ahead at
4993 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
4994 // then there won't be matching `>` tokens to find.
4996 // To explain how this detection works, consider the following example:
4998 // ```ignore (diagnostics)
4999 // bar::<<<<T as Foo>::Output>();
5000 // ^^ help: remove extra angle brackets
5003 // Parsing of the left angle brackets starts in this function. We start by parsing the
5004 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5007 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5008 // *Unmatched count:* 1
5009 // *`parse_path_segment` calls deep:* 0
5011 // This has the effect of recursing as this function is called if a `<` character
5012 // is found within the expected generic arguments:
5014 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5015 // *Unmatched count:* 2
5016 // *`parse_path_segment` calls deep:* 1
5018 // Eventually we will have recursed until having consumed all of the `<` tokens and
5019 // this will be reflected in the count:
5021 // *Upcoming tokens:* `T as Foo>::Output>;`
5022 // *Unmatched count:* 4
5023 // `parse_path_segment` calls deep:* 3
5025 // The parser will continue until reaching the first `>` - this will decrement the
5026 // unmatched angle bracket count and return to the parent invocation of this function
5027 // having succeeded in parsing:
5029 // *Upcoming tokens:* `::Output>;`
5030 // *Unmatched count:* 3
5031 // *`parse_path_segment` calls deep:* 2
5033 // This will continue until the next `>` character which will also return successfully
5034 // to the parent invocation of this function and decrement the count:
5036 // *Upcoming tokens:* `;`
5037 // *Unmatched count:* 2
5038 // *`parse_path_segment` calls deep:* 1
5040 // At this point, this function will expect to find another matching `>` character but
5041 // won't be able to and will return an error. This will continue all the way up the
5042 // call stack until the first invocation:
5044 // *Upcoming tokens:* `;`
5045 // *Unmatched count:* 2
5046 // *`parse_path_segment` calls deep:* 0
5048 // In doing this, we have managed to work out how many unmatched leading left angle
5049 // brackets there are, but we cannot recover as the unmatched angle brackets have
5050 // already been consumed. To remedy this, we keep a snapshot of the parser state
5051 // before we do the above. We can then inspect whether we ended up with a parsing error
5052 // and unmatched left angle brackets and if so, restore the parser state before we
5053 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5054 // recover by attempting to parse again.
5056 // In practice, the recursion of this function is indirect and there will be other
5057 // locations that consume some `<` characters - as long as we update the count when
5058 // this happens, it isn't an issue.
5060 let is_first_invocation = style == PathStyle::Expr;
5061 // Take a snapshot before attempting to parse - we can restore this later.
5062 let snapshot = if is_first_invocation {
5068 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5069 match self.parse_generic_args() {
5070 Ok(value) => Ok(value),
5071 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5072 // Cancel error from being unable to find `>`. We know the error
5073 // must have been this due to a non-zero unmatched angle bracket
5077 // Swap `self` with our backup of the parser state before attempting to parse
5078 // generic arguments.
5079 let snapshot = mem::replace(self, snapshot.unwrap());
5082 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5083 snapshot.count={:?}",
5084 snapshot.unmatched_angle_bracket_count,
5087 // Eat the unmatched angle brackets.
5088 for _ in 0..snapshot.unmatched_angle_bracket_count {
5092 // Make a span over ${unmatched angle bracket count} characters.
5093 let span = lo.with_hi(
5094 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5096 let plural = snapshot.unmatched_angle_bracket_count > 1;
5101 "unmatched angle bracket{}",
5102 if plural { "s" } else { "" }
5108 "remove extra angle bracket{}",
5109 if plural { "s" } else { "" }
5112 Applicability::MachineApplicable,
5116 // Try again without unmatched angle bracket characters.
5117 self.parse_generic_args()
5123 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5124 /// possibly including trailing comma.
5125 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5126 let mut args = Vec::new();
5127 let mut constraints = Vec::new();
5128 let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new();
5129 let mut assoc_ty_constraints: Vec<Span> = Vec::new();
5131 let args_lo = self.token.span;
5134 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5135 // Parse lifetime argument.
5136 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5137 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5138 } else if self.check_ident() && self.look_ahead(1,
5139 |t| t == &token::Eq || t == &token::Colon) {
5140 // Parse associated type constraint.
5141 let lo = self.token.span;
5142 let ident = self.parse_ident()?;
5143 let kind = if self.eat(&token::Eq) {
5144 AssocTyConstraintKind::Equality {
5145 ty: self.parse_ty()?,
5147 } else if self.eat(&token::Colon) {
5148 AssocTyConstraintKind::Bound {
5149 bounds: self.parse_generic_bounds(Some(self.prev_span))?,
5154 let span = lo.to(self.prev_span);
5155 constraints.push(AssocTyConstraint {
5156 id: ast::DUMMY_NODE_ID,
5161 assoc_ty_constraints.push(span);
5162 } else if self.check_const_arg() {
5163 // Parse const argument.
5164 let expr = if let token::OpenDelim(token::Brace) = self.token.kind {
5165 self.parse_block_expr(
5166 None, self.token.span, BlockCheckMode::Default, ThinVec::new()
5168 } else if self.token.is_ident() {
5169 // FIXME(const_generics): to distinguish between idents for types and consts,
5170 // we should introduce a GenericArg::Ident in the AST and distinguish when
5171 // lowering to the HIR. For now, idents for const args are not permitted.
5172 if self.token.is_keyword(kw::True) || self.token.is_keyword(kw::False) {
5173 self.parse_literal_maybe_minus()?
5176 self.fatal("identifiers may currently not be used for const generics")
5180 self.parse_literal_maybe_minus()?
5182 let value = AnonConst {
5183 id: ast::DUMMY_NODE_ID,
5186 args.push(GenericArg::Const(value));
5187 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5188 } else if self.check_type() {
5189 // Parse type argument.
5190 args.push(GenericArg::Type(self.parse_ty()?));
5191 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5196 if !self.eat(&token::Comma) {
5201 // FIXME: we would like to report this in ast_validation instead, but we currently do not
5202 // preserve ordering of generic parameters with respect to associated type binding, so we
5203 // lose that information after parsing.
5204 if misplaced_assoc_ty_constraints.len() > 0 {
5205 let mut err = self.struct_span_err(
5206 args_lo.to(self.prev_span),
5207 "associated type bindings must be declared after generic parameters",
5209 for span in misplaced_assoc_ty_constraints {
5212 "this associated type binding should be moved after the generic parameters",
5218 Ok((args, constraints))
5221 /// Parses an optional where-clause and places it in `generics`.
5223 /// ```ignore (only-for-syntax-highlight)
5224 /// where T : Trait<U, V> + 'b, 'a : 'b
5226 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5227 let mut where_clause = WhereClause {
5228 predicates: Vec::new(),
5229 span: self.prev_span.to(self.prev_span),
5232 if !self.eat_keyword(kw::Where) {
5233 return Ok(where_clause);
5235 let lo = self.prev_span;
5237 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5238 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5239 // change we parse those generics now, but report an error.
5240 if self.choose_generics_over_qpath() {
5241 let generics = self.parse_generics()?;
5242 self.struct_span_err(
5244 "generic parameters on `where` clauses are reserved for future use",
5246 .span_label(generics.span, "currently unsupported")
5251 let lo = self.token.span;
5252 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5253 let lifetime = self.expect_lifetime();
5254 // Bounds starting with a colon are mandatory, but possibly empty.
5255 self.expect(&token::Colon)?;
5256 let bounds = self.parse_lt_param_bounds();
5257 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5258 ast::WhereRegionPredicate {
5259 span: lo.to(self.prev_span),
5264 } else if self.check_type() {
5265 // Parse optional `for<'a, 'b>`.
5266 // This `for` is parsed greedily and applies to the whole predicate,
5267 // the bounded type can have its own `for` applying only to it.
5269 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
5270 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
5271 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
5272 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5274 // Parse type with mandatory colon and (possibly empty) bounds,
5275 // or with mandatory equality sign and the second type.
5276 let ty = self.parse_ty()?;
5277 if self.eat(&token::Colon) {
5278 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
5279 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5280 ast::WhereBoundPredicate {
5281 span: lo.to(self.prev_span),
5282 bound_generic_params: lifetime_defs,
5287 // FIXME: Decide what should be used here, `=` or `==`.
5288 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5289 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5290 let rhs_ty = self.parse_ty()?;
5291 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5292 ast::WhereEqPredicate {
5293 span: lo.to(self.prev_span),
5296 id: ast::DUMMY_NODE_ID,
5300 return self.unexpected();
5306 if !self.eat(&token::Comma) {
5311 where_clause.span = lo.to(self.prev_span);
5315 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
5316 -> PResult<'a, (Vec<Arg> , bool)> {
5317 let sp = self.token.span;
5318 let mut c_variadic = false;
5319 let (args, _): (Vec<Option<Arg>>, _) = self.parse_paren_comma_seq(|p| {
5320 let do_not_enforce_named_arguments_for_c_variadic =
5321 |token: &token::Token| -> bool {
5322 if token == &token::DotDotDot {
5328 match p.parse_arg_general(
5331 do_not_enforce_named_arguments_for_c_variadic
5334 if let TyKind::CVarArgs = arg.ty.node {
5336 if p.token != token::CloseDelim(token::Paren) {
5337 let span = p.token.span;
5339 "`...` must be the last argument of a C-variadic function");
5350 let lo = p.prev_span;
5351 // Skip every token until next possible arg or end.
5352 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5353 // Create a placeholder argument for proper arg count (issue #34264).
5354 let span = lo.to(p.prev_span);
5355 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
5360 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5362 if c_variadic && args.is_empty() {
5364 "C-variadic function must be declared with at least one named argument");
5367 Ok((args, c_variadic))
5370 /// Parses the argument list and result type of a function declaration.
5371 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
5372 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
5373 let ret_ty = self.parse_ret_ty(true)?;
5382 /// Returns the parsed optional self argument and whether a self shortcut was used.
5384 /// See `parse_self_arg_with_attrs` to collect attributes.
5385 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5386 let expect_ident = |this: &mut Self| match this.token.kind {
5387 // Preserve hygienic context.
5388 token::Ident(name, _) =>
5389 { let span = this.token.span; this.bump(); Ident::new(name, span) }
5392 let isolated_self = |this: &mut Self, n| {
5393 this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
5394 this.look_ahead(n + 1, |t| t != &token::ModSep)
5397 // Parse optional `self` parameter of a method.
5398 // Only a limited set of initial token sequences is considered `self` parameters; anything
5399 // else is parsed as a normal function parameter list, so some lookahead is required.
5400 let eself_lo = self.token.span;
5401 let (eself, eself_ident, eself_hi) = match self.token.kind {
5402 token::BinOp(token::And) => {
5408 (if isolated_self(self, 1) {
5410 SelfKind::Region(None, Mutability::Immutable)
5411 } else if self.is_keyword_ahead(1, &[kw::Mut]) &&
5412 isolated_self(self, 2) {
5415 SelfKind::Region(None, Mutability::Mutable)
5416 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5417 isolated_self(self, 2) {
5419 let lt = self.expect_lifetime();
5420 SelfKind::Region(Some(lt), Mutability::Immutable)
5421 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5422 self.is_keyword_ahead(2, &[kw::Mut]) &&
5423 isolated_self(self, 3) {
5425 let lt = self.expect_lifetime();
5427 SelfKind::Region(Some(lt), Mutability::Mutable)
5430 }, expect_ident(self), self.prev_span)
5432 token::BinOp(token::Star) => {
5437 // Emit special error for `self` cases.
5438 let msg = "cannot pass `self` by raw pointer";
5439 (if isolated_self(self, 1) {
5441 self.struct_span_err(self.token.span, msg)
5442 .span_label(self.token.span, msg)
5444 SelfKind::Value(Mutability::Immutable)
5445 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5446 isolated_self(self, 2) {
5449 self.struct_span_err(self.token.span, msg)
5450 .span_label(self.token.span, msg)
5452 SelfKind::Value(Mutability::Immutable)
5455 }, expect_ident(self), self.prev_span)
5457 token::Ident(..) => {
5458 if isolated_self(self, 0) {
5461 let eself_ident = expect_ident(self);
5462 let eself_hi = self.prev_span;
5463 (if self.eat(&token::Colon) {
5464 let ty = self.parse_ty()?;
5465 SelfKind::Explicit(ty, Mutability::Immutable)
5467 SelfKind::Value(Mutability::Immutable)
5468 }, eself_ident, eself_hi)
5469 } else if self.token.is_keyword(kw::Mut) &&
5470 isolated_self(self, 1) {
5474 let eself_ident = expect_ident(self);
5475 let eself_hi = self.prev_span;
5476 (if self.eat(&token::Colon) {
5477 let ty = self.parse_ty()?;
5478 SelfKind::Explicit(ty, Mutability::Mutable)
5480 SelfKind::Value(Mutability::Mutable)
5481 }, eself_ident, eself_hi)
5486 _ => return Ok(None),
5489 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5490 Ok(Some(Arg::from_self(ThinVec::default(), eself, eself_ident)))
5493 /// Returns the parsed optional self argument with attributes and whether a self
5494 /// shortcut was used.
5495 fn parse_self_arg_with_attrs(&mut self) -> PResult<'a, Option<Arg>> {
5496 let attrs = self.parse_arg_attributes()?;
5497 let arg_opt = self.parse_self_arg()?;
5498 Ok(arg_opt.map(|mut arg| {
5499 arg.attrs = attrs.into();
5504 /// Parses the parameter list and result type of a function that may have a `self` parameter.
5505 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5506 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5508 self.expect(&token::OpenDelim(token::Paren))?;
5510 // Parse optional self argument.
5511 let self_arg = self.parse_self_arg_with_attrs()?;
5513 // Parse the rest of the function parameter list.
5514 let sep = SeqSep::trailing_allowed(token::Comma);
5515 let (mut fn_inputs, recovered) = if let Some(self_arg) = self_arg {
5516 if self.check(&token::CloseDelim(token::Paren)) {
5517 (vec![self_arg], false)
5518 } else if self.eat(&token::Comma) {
5519 let mut fn_inputs = vec![self_arg];
5520 let (mut input, _, recovered) = self.parse_seq_to_before_end(
5521 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
5522 fn_inputs.append(&mut input);
5523 (fn_inputs, recovered)
5525 match self.expect_one_of(&[], &[]) {
5526 Err(err) => return Err(err),
5527 Ok(recovered) => (vec![self_arg], recovered),
5531 let (input, _, recovered) =
5532 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
5537 // Parse closing paren and return type.
5538 self.expect(&token::CloseDelim(token::Paren))?;
5540 // Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
5541 self.deduplicate_recovered_arg_names(&mut fn_inputs);
5545 output: self.parse_ret_ty(true)?,
5550 /// Parses the `|arg, arg|` header of a closure.
5551 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5552 let inputs_captures = {
5553 if self.eat(&token::OrOr) {
5556 self.expect(&token::BinOp(token::Or))?;
5557 let args = self.parse_seq_to_before_tokens(
5558 &[&token::BinOp(token::Or), &token::OrOr],
5559 SeqSep::trailing_allowed(token::Comma),
5560 TokenExpectType::NoExpect,
5561 |p| p.parse_fn_block_arg()
5567 let output = self.parse_ret_ty(true)?;
5570 inputs: inputs_captures,
5576 /// Parses the name and optional generic types of a function header.
5577 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5578 let id = self.parse_ident()?;
5579 let generics = self.parse_generics()?;
5583 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5584 attrs: Vec<Attribute>) -> P<Item> {
5588 id: ast::DUMMY_NODE_ID,
5596 /// Parses an item-position function declaration.
5597 fn parse_item_fn(&mut self,
5599 asyncness: Spanned<IsAsync>,
5600 constness: Spanned<Constness>,
5602 -> PResult<'a, ItemInfo> {
5603 let (ident, mut generics) = self.parse_fn_header()?;
5604 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
5605 let decl = self.parse_fn_decl(allow_c_variadic)?;
5606 generics.where_clause = self.parse_where_clause()?;
5607 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5608 let header = FnHeader { unsafety, asyncness, constness, abi };
5609 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5612 /// Returns `true` if we are looking at `const ID`
5613 /// (returns `false` for things like `const fn`, etc.).
5614 fn is_const_item(&self) -> bool {
5615 self.token.is_keyword(kw::Const) &&
5616 !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
5619 /// Parses all the "front matter" for a `fn` declaration, up to
5620 /// and including the `fn` keyword:
5624 /// - `const unsafe fn`
5627 fn parse_fn_front_matter(&mut self)
5635 let is_const_fn = self.eat_keyword(kw::Const);
5636 let const_span = self.prev_span;
5637 let asyncness = self.parse_asyncness();
5638 if let IsAsync::Async { .. } = asyncness {
5639 self.ban_async_in_2015(self.prev_span);
5641 let asyncness = respan(self.prev_span, asyncness);
5642 let unsafety = self.parse_unsafety();
5643 let (constness, unsafety, abi) = if is_const_fn {
5644 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5646 let abi = if self.eat_keyword(kw::Extern) {
5647 self.parse_opt_abi()?.unwrap_or(Abi::C)
5651 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5653 if !self.eat_keyword(kw::Fn) {
5654 // It is possible for `expect_one_of` to recover given the contents of
5655 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
5656 // account for this.
5657 if !self.expect_one_of(&[], &[])? { unreachable!() }
5659 Ok((constness, unsafety, asyncness, abi))
5662 /// Parses an impl item.
5663 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5664 maybe_whole!(self, NtImplItem, |x| x);
5665 let attrs = self.parse_outer_attributes()?;
5666 let mut unclosed_delims = vec![];
5667 let (mut item, tokens) = self.collect_tokens(|this| {
5668 let item = this.parse_impl_item_(at_end, attrs);
5669 unclosed_delims.append(&mut this.unclosed_delims);
5672 self.unclosed_delims.append(&mut unclosed_delims);
5674 // See `parse_item` for why this clause is here.
5675 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5676 item.tokens = Some(tokens);
5681 fn parse_impl_item_(&mut self,
5683 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5684 let lo = self.token.span;
5685 let vis = self.parse_visibility(false)?;
5686 let defaultness = self.parse_defaultness();
5687 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5688 let (name, alias, generics) = type_?;
5689 let kind = match alias {
5690 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5691 AliasKind::OpaqueTy(bounds) => ast::ImplItemKind::OpaqueTy(bounds),
5693 (name, kind, generics)
5694 } else if self.is_const_item() {
5695 // This parses the grammar:
5696 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5697 self.expect_keyword(kw::Const)?;
5698 let name = self.parse_ident()?;
5699 self.expect(&token::Colon)?;
5700 let typ = self.parse_ty()?;
5701 self.expect(&token::Eq)?;
5702 let expr = self.parse_expr()?;
5703 self.expect(&token::Semi)?;
5704 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5706 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5707 attrs.extend(inner_attrs);
5708 (name, node, generics)
5712 id: ast::DUMMY_NODE_ID,
5713 span: lo.to(self.prev_span),
5724 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
5726 VisibilityKind::Inherited => {}
5728 let mut err = if self.token.is_keyword(sym::macro_rules) {
5729 let mut err = self.diagnostic()
5730 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5731 err.span_suggestion(
5733 "try exporting the macro",
5734 "#[macro_export]".to_owned(),
5735 Applicability::MaybeIncorrect // speculative
5739 let mut err = self.diagnostic()
5740 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5741 err.help("try adjusting the macro to put `pub` inside the invocation");
5749 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
5750 -> DiagnosticBuilder<'a>
5752 let expected_kinds = if item_type == "extern" {
5753 "missing `fn`, `type`, or `static`"
5755 "missing `fn`, `type`, or `const`"
5758 // Given this code `path(`, it seems like this is not
5759 // setting the visibility of a macro invocation, but rather
5760 // a mistyped method declaration.
5761 // Create a diagnostic pointing out that `fn` is missing.
5763 // x | pub path(&self) {
5764 // | ^ missing `fn`, `type`, or `const`
5766 // ^^ `sp` below will point to this
5767 let sp = prev_span.between(self.prev_span);
5768 let mut err = self.diagnostic().struct_span_err(
5770 &format!("{} for {}-item declaration",
5771 expected_kinds, item_type));
5772 err.span_label(sp, expected_kinds);
5776 /// Parse a method or a macro invocation in a trait impl.
5777 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5778 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5779 ast::ImplItemKind)> {
5780 // code copied from parse_macro_use_or_failure... abstraction!
5781 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5783 Ok((Ident::invalid(), vec![], ast::Generics::default(),
5784 ast::ImplItemKind::Macro(mac)))
5786 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5787 let ident = self.parse_ident()?;
5788 let mut generics = self.parse_generics()?;
5789 let decl = self.parse_fn_decl_with_self(|p| {
5790 p.parse_arg_general(true, false, |_| true)
5792 generics.where_clause = self.parse_where_clause()?;
5794 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5795 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5796 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5797 ast::MethodSig { header, decl },
5803 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
5804 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5805 let ident = self.parse_ident()?;
5806 let mut tps = self.parse_generics()?;
5808 // Parse optional colon and supertrait bounds.
5809 let bounds = if self.eat(&token::Colon) {
5810 self.parse_generic_bounds(Some(self.prev_span))?
5815 if self.eat(&token::Eq) {
5816 // it's a trait alias
5817 let bounds = self.parse_generic_bounds(None)?;
5818 tps.where_clause = self.parse_where_clause()?;
5819 self.expect(&token::Semi)?;
5820 if is_auto == IsAuto::Yes {
5821 let msg = "trait aliases cannot be `auto`";
5822 self.struct_span_err(self.prev_span, msg)
5823 .span_label(self.prev_span, msg)
5826 if unsafety != Unsafety::Normal {
5827 let msg = "trait aliases cannot be `unsafe`";
5828 self.struct_span_err(self.prev_span, msg)
5829 .span_label(self.prev_span, msg)
5832 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5834 // it's a normal trait
5835 tps.where_clause = self.parse_where_clause()?;
5836 self.expect(&token::OpenDelim(token::Brace))?;
5837 let mut trait_items = vec![];
5838 while !self.eat(&token::CloseDelim(token::Brace)) {
5839 if let token::DocComment(_) = self.token.kind {
5840 if self.look_ahead(1,
5841 |tok| tok == &token::CloseDelim(token::Brace)) {
5842 self.diagnostic().struct_span_err_with_code(
5844 "found a documentation comment that doesn't document anything",
5845 DiagnosticId::Error("E0584".into()),
5848 "doc comments must come before what they document, maybe a \
5849 comment was intended with `//`?",
5856 let mut at_end = false;
5857 match self.parse_trait_item(&mut at_end) {
5858 Ok(item) => trait_items.push(item),
5862 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5867 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5871 fn choose_generics_over_qpath(&self) -> bool {
5872 // There's an ambiguity between generic parameters and qualified paths in impls.
5873 // If we see `<` it may start both, so we have to inspect some following tokens.
5874 // The following combinations can only start generics,
5875 // but not qualified paths (with one exception):
5876 // `<` `>` - empty generic parameters
5877 // `<` `#` - generic parameters with attributes
5878 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5879 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5880 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5881 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5882 // `<` const - generic const parameter
5883 // The only truly ambiguous case is
5884 // `<` IDENT `>` `::` IDENT ...
5885 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5886 // because this is what almost always expected in practice, qualified paths in impls
5887 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5888 self.token == token::Lt &&
5889 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5890 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5891 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5892 t == &token::Colon || t == &token::Eq) ||
5893 self.is_keyword_ahead(1, &[kw::Const]))
5896 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5897 self.expect(&token::OpenDelim(token::Brace))?;
5898 let attrs = self.parse_inner_attributes()?;
5900 let mut impl_items = Vec::new();
5901 while !self.eat(&token::CloseDelim(token::Brace)) {
5902 let mut at_end = false;
5903 match self.parse_impl_item(&mut at_end) {
5904 Ok(impl_item) => impl_items.push(impl_item),
5908 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5913 Ok((impl_items, attrs))
5916 /// Parses an implementation item, `impl` keyword is already parsed.
5918 /// impl<'a, T> TYPE { /* impl items */ }
5919 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5920 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5922 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5923 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5924 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5925 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5926 -> PResult<'a, ItemInfo> {
5927 // First, parse generic parameters if necessary.
5928 let mut generics = if self.choose_generics_over_qpath() {
5929 self.parse_generics()?
5931 ast::Generics::default()
5934 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5935 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5937 ast::ImplPolarity::Negative
5939 ast::ImplPolarity::Positive
5942 // Parse both types and traits as a type, then reinterpret if necessary.
5943 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
5944 let ty_first = if self.token.is_keyword(kw::For) &&
5945 self.look_ahead(1, |t| t != &token::Lt) {
5946 let span = self.prev_span.between(self.token.span);
5947 self.struct_span_err(span, "missing trait in a trait impl").emit();
5948 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
5953 // If `for` is missing we try to recover.
5954 let has_for = self.eat_keyword(kw::For);
5955 let missing_for_span = self.prev_span.between(self.token.span);
5957 let ty_second = if self.token == token::DotDot {
5958 // We need to report this error after `cfg` expansion for compatibility reasons
5959 self.bump(); // `..`, do not add it to expected tokens
5960 Some(DummyResult::raw_ty(self.prev_span, true))
5961 } else if has_for || self.token.can_begin_type() {
5962 Some(self.parse_ty()?)
5967 generics.where_clause = self.parse_where_clause()?;
5969 let (impl_items, attrs) = self.parse_impl_body()?;
5971 let item_kind = match ty_second {
5972 Some(ty_second) => {
5973 // impl Trait for Type
5975 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
5976 .span_suggestion_short(
5979 " for ".to_string(),
5980 Applicability::MachineApplicable,
5984 let ty_first = ty_first.into_inner();
5985 let path = match ty_first.node {
5986 // This notably includes paths passed through `ty` macro fragments (#46438).
5987 TyKind::Path(None, path) => path,
5989 self.span_err(ty_first.span, "expected a trait, found type");
5990 err_path(ty_first.span)
5993 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5995 ItemKind::Impl(unsafety, polarity, defaultness,
5996 generics, Some(trait_ref), ty_second, impl_items)
6000 ItemKind::Impl(unsafety, polarity, defaultness,
6001 generics, None, ty_first, impl_items)
6005 Ok((Ident::invalid(), item_kind, Some(attrs)))
6008 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6009 if self.eat_keyword(kw::For) {
6011 let params = self.parse_generic_params()?;
6013 // We rely on AST validation to rule out invalid cases: There must not be type
6014 // parameters, and the lifetime parameters must not have bounds.
6021 /// Parses `struct Foo { ... }`.
6022 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6023 let class_name = self.parse_ident()?;
6025 let mut generics = self.parse_generics()?;
6027 // There is a special case worth noting here, as reported in issue #17904.
6028 // If we are parsing a tuple struct it is the case that the where clause
6029 // should follow the field list. Like so:
6031 // struct Foo<T>(T) where T: Copy;
6033 // If we are parsing a normal record-style struct it is the case
6034 // that the where clause comes before the body, and after the generics.
6035 // So if we look ahead and see a brace or a where-clause we begin
6036 // parsing a record style struct.
6038 // Otherwise if we look ahead and see a paren we parse a tuple-style
6041 let vdata = if self.token.is_keyword(kw::Where) {
6042 generics.where_clause = self.parse_where_clause()?;
6043 if self.eat(&token::Semi) {
6044 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6045 VariantData::Unit(ast::DUMMY_NODE_ID)
6047 // If we see: `struct Foo<T> where T: Copy { ... }`
6048 let (fields, recovered) = self.parse_record_struct_body()?;
6049 VariantData::Struct(fields, recovered)
6051 // No `where` so: `struct Foo<T>;`
6052 } else if self.eat(&token::Semi) {
6053 VariantData::Unit(ast::DUMMY_NODE_ID)
6054 // Record-style struct definition
6055 } else if self.token == token::OpenDelim(token::Brace) {
6056 let (fields, recovered) = self.parse_record_struct_body()?;
6057 VariantData::Struct(fields, recovered)
6058 // Tuple-style struct definition with optional where-clause.
6059 } else if self.token == token::OpenDelim(token::Paren) {
6060 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6061 generics.where_clause = self.parse_where_clause()?;
6062 self.expect(&token::Semi)?;
6065 let token_str = self.this_token_descr();
6066 let mut err = self.fatal(&format!(
6067 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6070 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
6074 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6077 /// Parses `union Foo { ... }`.
6078 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6079 let class_name = self.parse_ident()?;
6081 let mut generics = self.parse_generics()?;
6083 let vdata = if self.token.is_keyword(kw::Where) {
6084 generics.where_clause = self.parse_where_clause()?;
6085 let (fields, recovered) = self.parse_record_struct_body()?;
6086 VariantData::Struct(fields, recovered)
6087 } else if self.token == token::OpenDelim(token::Brace) {
6088 let (fields, recovered) = self.parse_record_struct_body()?;
6089 VariantData::Struct(fields, recovered)
6091 let token_str = self.this_token_descr();
6092 let mut err = self.fatal(&format!(
6093 "expected `where` or `{{` after union name, found {}", token_str));
6094 err.span_label(self.token.span, "expected `where` or `{` after union name");
6098 Ok((class_name, ItemKind::Union(vdata, generics), None))
6101 fn parse_record_struct_body(
6103 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6104 let mut fields = Vec::new();
6105 let mut recovered = false;
6106 if self.eat(&token::OpenDelim(token::Brace)) {
6107 while self.token != token::CloseDelim(token::Brace) {
6108 let field = self.parse_struct_decl_field().map_err(|e| {
6109 self.recover_stmt();
6114 Ok(field) => fields.push(field),
6120 self.eat(&token::CloseDelim(token::Brace));
6122 let token_str = self.this_token_descr();
6123 let mut err = self.fatal(&format!(
6124 "expected `where`, or `{{` after struct name, found {}", token_str));
6125 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
6129 Ok((fields, recovered))
6132 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6133 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6134 // Unit like structs are handled in parse_item_struct function
6135 self.parse_paren_comma_seq(|p| {
6136 let attrs = p.parse_outer_attributes()?;
6137 let lo = p.token.span;
6138 let vis = p.parse_visibility(true)?;
6139 let ty = p.parse_ty()?;
6141 span: lo.to(ty.span),
6144 id: ast::DUMMY_NODE_ID,
6151 /// Parses a structure field declaration.
6152 fn parse_single_struct_field(&mut self,
6155 attrs: Vec<Attribute> )
6156 -> PResult<'a, StructField> {
6157 let mut seen_comma: bool = false;
6158 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6159 if self.token == token::Comma {
6162 match self.token.kind {
6166 token::CloseDelim(token::Brace) => {}
6167 token::DocComment(_) => {
6168 let previous_span = self.prev_span;
6169 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
6170 self.bump(); // consume the doc comment
6171 let comma_after_doc_seen = self.eat(&token::Comma);
6172 // `seen_comma` is always false, because we are inside doc block
6173 // condition is here to make code more readable
6174 if seen_comma == false && comma_after_doc_seen == true {
6177 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6180 if seen_comma == false {
6181 let sp = self.sess.source_map().next_point(previous_span);
6182 err.span_suggestion(
6184 "missing comma here",
6186 Applicability::MachineApplicable
6193 let sp = self.sess.source_map().next_point(self.prev_span);
6194 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6195 self.this_token_descr()));
6196 if self.token.is_ident() {
6197 // This is likely another field; emit the diagnostic and keep going
6198 err.span_suggestion(
6200 "try adding a comma",
6202 Applicability::MachineApplicable,
6213 /// Parses an element of a struct declaration.
6214 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6215 let attrs = self.parse_outer_attributes()?;
6216 let lo = self.token.span;
6217 let vis = self.parse_visibility(false)?;
6218 self.parse_single_struct_field(lo, vis, attrs)
6221 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6222 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6223 /// If the following element can't be a tuple (i.e., it's a function definition), then
6224 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6225 /// so emit a proper diagnostic.
6226 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6227 maybe_whole!(self, NtVis, |x| x);
6229 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
6230 if self.is_crate_vis() {
6231 self.bump(); // `crate`
6232 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6235 if !self.eat_keyword(kw::Pub) {
6236 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6237 // keyword to grab a span from for inherited visibility; an empty span at the
6238 // beginning of the current token would seem to be the "Schelling span".
6239 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
6241 let lo = self.prev_span;
6243 if self.check(&token::OpenDelim(token::Paren)) {
6244 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6245 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6246 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6247 // by the following tokens.
6248 if self.is_keyword_ahead(1, &[kw::Crate]) &&
6249 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
6253 self.bump(); // `crate`
6254 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6256 lo.to(self.prev_span),
6257 VisibilityKind::Crate(CrateSugar::PubCrate),
6260 } else if self.is_keyword_ahead(1, &[kw::In]) {
6263 self.bump(); // `in`
6264 let path = self.parse_path(PathStyle::Mod)?; // `path`
6265 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6266 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6268 id: ast::DUMMY_NODE_ID,
6271 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6272 self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
6274 // `pub(self)` or `pub(super)`
6276 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6277 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6278 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6280 id: ast::DUMMY_NODE_ID,
6283 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6284 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6286 let msg = "incorrect visibility restriction";
6287 let suggestion = r##"some possible visibility restrictions are:
6288 `pub(crate)`: visible only on the current crate
6289 `pub(super)`: visible only in the current module's parent
6290 `pub(in path::to::module)`: visible only on the specified path"##;
6291 let path = self.parse_path(PathStyle::Mod)?;
6293 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6294 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6295 struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg)
6300 format!("in {}", path),
6301 Applicability::MachineApplicable,
6303 .emit(); // emit diagnostic, but continue with public visibility
6307 Ok(respan(lo, VisibilityKind::Public))
6310 /// Parses defaultness (i.e., `default` or nothing).
6311 fn parse_defaultness(&mut self) -> Defaultness {
6312 // `pub` is included for better error messages
6313 if self.check_keyword(kw::Default) &&
6314 self.is_keyword_ahead(1, &[
6324 self.bump(); // `default`
6325 Defaultness::Default
6331 /// Given a termination token, parses all of the items in a module.
6332 fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
6333 let mut items = vec![];
6334 while let Some(item) = self.parse_item()? {
6336 self.maybe_consume_incorrect_semicolon(&items);
6339 if !self.eat(term) {
6340 let token_str = self.this_token_descr();
6341 if !self.maybe_consume_incorrect_semicolon(&items) {
6342 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6343 err.span_label(self.token.span, "expected item");
6348 let hi = if self.token.span.is_dummy() {
6355 inner: inner_lo.to(hi),
6361 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6362 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6363 self.expect(&token::Colon)?;
6364 let ty = self.parse_ty()?;
6365 self.expect(&token::Eq)?;
6366 let e = self.parse_expr()?;
6367 self.expect(&token::Semi)?;
6368 let item = match m {
6369 Some(m) => ItemKind::Static(ty, m, e),
6370 None => ItemKind::Const(ty, e),
6372 Ok((id, item, None))
6375 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6376 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6377 let (in_cfg, outer_attrs) = {
6378 let mut strip_unconfigured = crate::config::StripUnconfigured {
6380 features: None, // don't perform gated feature checking
6382 let mut outer_attrs = outer_attrs.to_owned();
6383 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
6384 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6387 let id_span = self.token.span;
6388 let id = self.parse_ident()?;
6389 if self.eat(&token::Semi) {
6390 if in_cfg && self.recurse_into_file_modules {
6391 // This mod is in an external file. Let's go get it!
6392 let ModulePathSuccess { path, directory_ownership, warn } =
6393 self.submod_path(id, &outer_attrs, id_span)?;
6394 let (module, mut attrs) =
6395 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6396 // Record that we fetched the mod from an external file
6398 let attr = attr::mk_attr_outer(
6399 attr::mk_word_item(Ident::with_empty_ctxt(sym::warn_directory_ownership)));
6400 attr::mark_known(&attr);
6403 Ok((id, ItemKind::Mod(module), Some(attrs)))
6405 let placeholder = ast::Mod {
6410 Ok((id, ItemKind::Mod(placeholder), None))
6413 let old_directory = self.directory.clone();
6414 self.push_directory(id, &outer_attrs);
6416 self.expect(&token::OpenDelim(token::Brace))?;
6417 let mod_inner_lo = self.token.span;
6418 let attrs = self.parse_inner_attributes()?;
6419 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6421 self.directory = old_directory;
6422 Ok((id, ItemKind::Mod(module), Some(attrs)))
6426 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6427 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6428 self.directory.path.to_mut().push(&path.as_str());
6429 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6431 // We have to push on the current module name in the case of relative
6432 // paths in order to ensure that any additional module paths from inline
6433 // `mod x { ... }` come after the relative extension.
6435 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6436 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6437 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6438 if let Some(ident) = relative.take() { // remove the relative offset
6439 self.directory.path.to_mut().push(ident.as_str());
6442 self.directory.path.to_mut().push(&id.as_str());
6446 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6447 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6450 // On windows, the base path might have the form
6451 // `\\?\foo\bar` in which case it does not tolerate
6452 // mixed `/` and `\` separators, so canonicalize
6455 let s = s.replace("/", "\\");
6456 Some(dir_path.join(s))
6462 /// Returns a path to a module.
6463 pub fn default_submod_path(
6465 relative: Option<ast::Ident>,
6467 source_map: &SourceMap) -> ModulePath
6469 // If we're in a foo.rs file instead of a mod.rs file,
6470 // we need to look for submodules in
6471 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6472 // `./<id>.rs` and `./<id>/mod.rs`.
6473 let relative_prefix_string;
6474 let relative_prefix = if let Some(ident) = relative {
6475 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6476 &relative_prefix_string
6481 let mod_name = id.to_string();
6482 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6483 let secondary_path_str = format!("{}{}{}mod.rs",
6484 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6485 let default_path = dir_path.join(&default_path_str);
6486 let secondary_path = dir_path.join(&secondary_path_str);
6487 let default_exists = source_map.file_exists(&default_path);
6488 let secondary_exists = source_map.file_exists(&secondary_path);
6490 let result = match (default_exists, secondary_exists) {
6491 (true, false) => Ok(ModulePathSuccess {
6493 directory_ownership: DirectoryOwnership::Owned {
6498 (false, true) => Ok(ModulePathSuccess {
6499 path: secondary_path,
6500 directory_ownership: DirectoryOwnership::Owned {
6505 (false, false) => Err(Error::FileNotFoundForModule {
6506 mod_name: mod_name.clone(),
6507 default_path: default_path_str,
6508 secondary_path: secondary_path_str,
6509 dir_path: dir_path.display().to_string(),
6511 (true, true) => Err(Error::DuplicatePaths {
6512 mod_name: mod_name.clone(),
6513 default_path: default_path_str,
6514 secondary_path: secondary_path_str,
6520 path_exists: default_exists || secondary_exists,
6525 fn submod_path(&mut self,
6527 outer_attrs: &[Attribute],
6529 -> PResult<'a, ModulePathSuccess> {
6530 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6531 return Ok(ModulePathSuccess {
6532 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6533 // All `#[path]` files are treated as though they are a `mod.rs` file.
6534 // This means that `mod foo;` declarations inside `#[path]`-included
6535 // files are siblings,
6537 // Note that this will produce weirdness when a file named `foo.rs` is
6538 // `#[path]` included and contains a `mod foo;` declaration.
6539 // If you encounter this, it's your own darn fault :P
6540 Some(_) => DirectoryOwnership::Owned { relative: None },
6541 _ => DirectoryOwnership::UnownedViaMod(true),
6548 let relative = match self.directory.ownership {
6549 DirectoryOwnership::Owned { relative } => relative,
6550 DirectoryOwnership::UnownedViaBlock |
6551 DirectoryOwnership::UnownedViaMod(_) => None,
6553 let paths = Parser::default_submod_path(
6554 id, relative, &self.directory.path, self.sess.source_map());
6556 match self.directory.ownership {
6557 DirectoryOwnership::Owned { .. } => {
6558 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6560 DirectoryOwnership::UnownedViaBlock => {
6562 "Cannot declare a non-inline module inside a block \
6563 unless it has a path attribute";
6564 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6565 if paths.path_exists {
6566 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6568 err.span_note(id_sp, &msg);
6572 DirectoryOwnership::UnownedViaMod(warn) => {
6574 if let Ok(result) = paths.result {
6575 return Ok(ModulePathSuccess { warn: true, ..result });
6578 let mut err = self.diagnostic().struct_span_err(id_sp,
6579 "cannot declare a new module at this location");
6580 if !id_sp.is_dummy() {
6581 let src_path = self.sess.source_map().span_to_filename(id_sp);
6582 if let FileName::Real(src_path) = src_path {
6583 if let Some(stem) = src_path.file_stem() {
6584 let mut dest_path = src_path.clone();
6585 dest_path.set_file_name(stem);
6586 dest_path.push("mod.rs");
6587 err.span_note(id_sp,
6588 &format!("maybe move this module `{}` to its own \
6589 directory via `{}`", src_path.display(),
6590 dest_path.display()));
6594 if paths.path_exists {
6595 err.span_note(id_sp,
6596 &format!("... or maybe `use` the module `{}` instead \
6597 of possibly redeclaring it",
6605 /// Reads a module from a source file.
6609 directory_ownership: DirectoryOwnership,
6612 ) -> PResult<'a, (ast::Mod, Vec<Attribute>)> {
6613 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6614 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6615 let mut err = String::from("circular modules: ");
6616 let len = included_mod_stack.len();
6617 for p in &included_mod_stack[i.. len] {
6618 err.push_str(&p.to_string_lossy());
6619 err.push_str(" -> ");
6621 err.push_str(&path.to_string_lossy());
6622 return Err(self.span_fatal(id_sp, &err[..]));
6624 included_mod_stack.push(path.clone());
6625 drop(included_mod_stack);
6628 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6629 p0.cfg_mods = self.cfg_mods;
6630 let mod_inner_lo = p0.token.span;
6631 let mod_attrs = p0.parse_inner_attributes()?;
6632 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6634 self.sess.included_mod_stack.borrow_mut().pop();
6638 /// Parses a function declaration from a foreign module.
6639 fn parse_item_foreign_fn(
6641 vis: ast::Visibility,
6643 attrs: Vec<Attribute>,
6645 ) -> PResult<'a, ForeignItem> {
6646 self.expect_keyword(kw::Fn)?;
6648 let (ident, mut generics) = self.parse_fn_header()?;
6649 let decl = self.parse_fn_decl(true)?;
6650 generics.where_clause = self.parse_where_clause()?;
6651 let hi = self.token.span;
6652 self.parse_semi_or_incorrect_foreign_fn_body(&ident, extern_sp)?;
6653 Ok(ast::ForeignItem {
6656 node: ForeignItemKind::Fn(decl, generics),
6657 id: ast::DUMMY_NODE_ID,
6663 /// Parses a static item from a foreign module.
6664 /// Assumes that the `static` keyword is already parsed.
6665 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6666 -> PResult<'a, ForeignItem> {
6667 let mutbl = self.parse_mutability();
6668 let ident = self.parse_ident()?;
6669 self.expect(&token::Colon)?;
6670 let ty = self.parse_ty()?;
6671 let hi = self.token.span;
6672 self.expect(&token::Semi)?;
6676 node: ForeignItemKind::Static(ty, mutbl),
6677 id: ast::DUMMY_NODE_ID,
6683 /// Parses a type from a foreign module.
6684 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6685 -> PResult<'a, ForeignItem> {
6686 self.expect_keyword(kw::Type)?;
6688 let ident = self.parse_ident()?;
6689 let hi = self.token.span;
6690 self.expect(&token::Semi)?;
6691 Ok(ast::ForeignItem {
6694 node: ForeignItemKind::Ty,
6695 id: ast::DUMMY_NODE_ID,
6701 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6702 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6703 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6705 let mut ident = if self.token.is_keyword(kw::SelfLower) {
6706 self.parse_path_segment_ident()
6710 let mut idents = vec![];
6711 let mut replacement = vec![];
6712 let mut fixed_crate_name = false;
6713 // Accept `extern crate name-like-this` for better diagnostics
6714 let dash = token::BinOp(token::BinOpToken::Minus);
6715 if self.token == dash { // Do not include `-` as part of the expected tokens list
6716 while self.eat(&dash) {
6717 fixed_crate_name = true;
6718 replacement.push((self.prev_span, "_".to_string()));
6719 idents.push(self.parse_ident()?);
6722 if fixed_crate_name {
6723 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6724 let mut fixed_name = format!("{}", ident.name);
6725 for part in idents {
6726 fixed_name.push_str(&format!("_{}", part.name));
6728 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6730 self.struct_span_err(fixed_name_sp, error_msg)
6731 .span_label(fixed_name_sp, "dash-separated idents are not valid")
6732 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
6738 /// Parses `extern crate` links.
6743 /// extern crate foo;
6744 /// extern crate bar as foo;
6746 fn parse_item_extern_crate(&mut self,
6748 visibility: Visibility,
6749 attrs: Vec<Attribute>)
6750 -> PResult<'a, P<Item>> {
6751 // Accept `extern crate name-like-this` for better diagnostics
6752 let orig_name = self.parse_crate_name_with_dashes()?;
6753 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6754 (rename, Some(orig_name.name))
6758 self.expect(&token::Semi)?;
6760 let span = lo.to(self.prev_span);
6761 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6764 /// Parses `extern` for foreign ABIs modules.
6766 /// `extern` is expected to have been
6767 /// consumed before calling this method.
6771 /// ```ignore (only-for-syntax-highlight)
6775 fn parse_item_foreign_mod(
6778 opt_abi: Option<Abi>,
6779 visibility: Visibility,
6780 mut attrs: Vec<Attribute>,
6782 ) -> PResult<'a, P<Item>> {
6783 self.expect(&token::OpenDelim(token::Brace))?;
6785 let abi = opt_abi.unwrap_or(Abi::C);
6787 attrs.extend(self.parse_inner_attributes()?);
6789 let mut foreign_items = vec![];
6790 while !self.eat(&token::CloseDelim(token::Brace)) {
6791 foreign_items.push(self.parse_foreign_item(extern_sp)?);
6794 let prev_span = self.prev_span;
6795 let m = ast::ForeignMod {
6797 items: foreign_items
6799 let invalid = Ident::invalid();
6800 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6803 /// Parses `type Foo = Bar;` or returns `None`
6804 /// without modifying the parser state.
6805 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6806 // This parses the grammar:
6807 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6808 if self.eat_keyword(kw::Type) {
6809 Some(self.parse_type_alias())
6815 /// Parses a type alias or opaque type.
6816 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6817 let ident = self.parse_ident()?;
6818 let mut tps = self.parse_generics()?;
6819 tps.where_clause = self.parse_where_clause()?;
6820 self.expect(&token::Eq)?;
6821 let alias = if self.check_keyword(kw::Impl) {
6823 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6824 AliasKind::OpaqueTy(bounds)
6826 let ty = self.parse_ty()?;
6829 self.expect(&token::Semi)?;
6830 Ok((ident, alias, tps))
6833 /// Parses the part of an enum declaration following the `{`.
6834 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6835 let mut variants = Vec::new();
6836 while self.token != token::CloseDelim(token::Brace) {
6837 let variant_attrs = self.parse_outer_attributes()?;
6838 let vlo = self.token.span;
6841 let ident = self.parse_ident()?;
6843 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
6844 // Parse a struct variant.
6845 let (fields, recovered) = self.parse_record_struct_body()?;
6846 VariantData::Struct(fields, recovered)
6847 } else if self.check(&token::OpenDelim(token::Paren)) {
6849 self.parse_tuple_struct_body()?,
6853 VariantData::Unit(ast::DUMMY_NODE_ID)
6856 let disr_expr = if self.eat(&token::Eq) {
6858 id: ast::DUMMY_NODE_ID,
6859 value: self.parse_expr()?,
6865 let vr = ast::Variant_ {
6867 id: ast::DUMMY_NODE_ID,
6868 attrs: variant_attrs,
6872 variants.push(respan(vlo.to(self.prev_span), vr));
6874 if !self.eat(&token::Comma) {
6875 if self.token.is_ident() && !self.token.is_reserved_ident() {
6876 let sp = self.sess.source_map().next_point(self.prev_span);
6877 self.struct_span_err(sp, "missing comma")
6878 .span_suggestion_short(
6882 Applicability::MaybeIncorrect,
6890 self.expect(&token::CloseDelim(token::Brace))?;
6892 Ok(ast::EnumDef { variants })
6895 /// Parses an enum declaration.
6896 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6897 let id = self.parse_ident()?;
6898 let mut generics = self.parse_generics()?;
6899 generics.where_clause = self.parse_where_clause()?;
6900 self.expect(&token::OpenDelim(token::Brace))?;
6902 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6903 self.recover_stmt();
6904 self.eat(&token::CloseDelim(token::Brace));
6907 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6910 /// Parses a string as an ABI spec on an extern type or module. Consumes
6911 /// the `extern` keyword, if one is found.
6912 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6913 match self.token.kind {
6914 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
6915 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
6916 let sp = self.token.span;
6917 self.expect_no_suffix(sp, "an ABI spec", suffix);
6919 match abi::lookup(&symbol.as_str()) {
6920 Some(abi) => Ok(Some(abi)),
6922 let prev_span = self.prev_span;
6924 self.sess.span_diagnostic,
6927 "invalid ABI: found `{}`",
6930 .span_label(prev_span, "invalid ABI")
6931 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
6942 fn is_static_global(&mut self) -> bool {
6943 if self.check_keyword(kw::Static) {
6944 // Check if this could be a closure
6945 !self.look_ahead(1, |token| {
6946 if token.is_keyword(kw::Move) {
6950 token::BinOp(token::Or) | token::OrOr => true,
6961 attrs: Vec<Attribute>,
6962 macros_allowed: bool,
6963 attributes_allowed: bool,
6964 ) -> PResult<'a, Option<P<Item>>> {
6965 let mut unclosed_delims = vec![];
6966 let (ret, tokens) = self.collect_tokens(|this| {
6967 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
6968 unclosed_delims.append(&mut this.unclosed_delims);
6971 self.unclosed_delims.append(&mut unclosed_delims);
6973 // Once we've parsed an item and recorded the tokens we got while
6974 // parsing we may want to store `tokens` into the item we're about to
6975 // return. Note, though, that we specifically didn't capture tokens
6976 // related to outer attributes. The `tokens` field here may later be
6977 // used with procedural macros to convert this item back into a token
6978 // stream, but during expansion we may be removing attributes as we go
6981 // If we've got inner attributes then the `tokens` we've got above holds
6982 // these inner attributes. If an inner attribute is expanded we won't
6983 // actually remove it from the token stream, so we'll just keep yielding
6984 // it (bad!). To work around this case for now we just avoid recording
6985 // `tokens` if we detect any inner attributes. This should help keep
6986 // expansion correct, but we should fix this bug one day!
6989 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6990 i.tokens = Some(tokens);
6997 /// Parses one of the items allowed by the flags.
6998 fn parse_item_implementation(
7000 attrs: Vec<Attribute>,
7001 macros_allowed: bool,
7002 attributes_allowed: bool,
7003 ) -> PResult<'a, Option<P<Item>>> {
7004 maybe_whole!(self, NtItem, |item| {
7005 let mut item = item.into_inner();
7006 let mut attrs = attrs;
7007 mem::swap(&mut item.attrs, &mut attrs);
7008 item.attrs.extend(attrs);
7012 let lo = self.token.span;
7014 let visibility = self.parse_visibility(false)?;
7016 if self.eat_keyword(kw::Use) {
7018 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7019 self.expect(&token::Semi)?;
7021 let span = lo.to(self.prev_span);
7023 self.mk_item(span, Ident::invalid(), item_, visibility, attrs);
7024 return Ok(Some(item));
7027 if self.eat_keyword(kw::Extern) {
7028 let extern_sp = self.prev_span;
7029 if self.eat_keyword(kw::Crate) {
7030 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7033 let opt_abi = self.parse_opt_abi()?;
7035 if self.eat_keyword(kw::Fn) {
7036 // EXTERN FUNCTION ITEM
7037 let fn_span = self.prev_span;
7038 let abi = opt_abi.unwrap_or(Abi::C);
7039 let (ident, item_, extra_attrs) =
7040 self.parse_item_fn(Unsafety::Normal,
7041 respan(fn_span, IsAsync::NotAsync),
7042 respan(fn_span, Constness::NotConst),
7044 let prev_span = self.prev_span;
7045 let item = self.mk_item(lo.to(prev_span),
7049 maybe_append(attrs, extra_attrs));
7050 return Ok(Some(item));
7051 } else if self.check(&token::OpenDelim(token::Brace)) {
7053 self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs, extern_sp)?,
7060 if self.is_static_global() {
7063 let m = if self.eat_keyword(kw::Mut) {
7066 Mutability::Immutable
7068 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7069 let prev_span = self.prev_span;
7070 let item = self.mk_item(lo.to(prev_span),
7074 maybe_append(attrs, extra_attrs));
7075 return Ok(Some(item));
7077 if self.eat_keyword(kw::Const) {
7078 let const_span = self.prev_span;
7079 if self.check_keyword(kw::Fn)
7080 || (self.check_keyword(kw::Unsafe)
7081 && self.is_keyword_ahead(1, &[kw::Fn])) {
7082 // CONST FUNCTION ITEM
7083 let unsafety = self.parse_unsafety();
7085 let (ident, item_, extra_attrs) =
7086 self.parse_item_fn(unsafety,
7087 respan(const_span, IsAsync::NotAsync),
7088 respan(const_span, Constness::Const),
7090 let prev_span = self.prev_span;
7091 let item = self.mk_item(lo.to(prev_span),
7095 maybe_append(attrs, extra_attrs));
7096 return Ok(Some(item));
7100 if self.eat_keyword(kw::Mut) {
7101 let prev_span = self.prev_span;
7102 self.struct_span_err(prev_span, "const globals cannot be mutable")
7103 .span_label(prev_span, "cannot be mutable")
7106 "you might want to declare a static instead",
7107 "static".to_owned(),
7108 Applicability::MaybeIncorrect,
7112 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7113 let prev_span = self.prev_span;
7114 let item = self.mk_item(lo.to(prev_span),
7118 maybe_append(attrs, extra_attrs));
7119 return Ok(Some(item));
7122 // Parse `async unsafe? fn`.
7123 if self.check_keyword(kw::Async) {
7124 let async_span = self.token.span;
7125 if self.is_keyword_ahead(1, &[kw::Fn])
7126 || self.is_keyword_ahead(2, &[kw::Fn])
7128 // ASYNC FUNCTION ITEM
7129 self.bump(); // `async`
7130 let unsafety = self.parse_unsafety(); // `unsafe`?
7131 self.expect_keyword(kw::Fn)?; // `fn`
7132 let fn_span = self.prev_span;
7133 let (ident, item_, extra_attrs) =
7134 self.parse_item_fn(unsafety,
7135 respan(async_span, IsAsync::Async {
7136 closure_id: ast::DUMMY_NODE_ID,
7137 return_impl_trait_id: ast::DUMMY_NODE_ID,
7139 respan(fn_span, Constness::NotConst),
7141 let prev_span = self.prev_span;
7142 let item = self.mk_item(lo.to(prev_span),
7146 maybe_append(attrs, extra_attrs));
7147 self.ban_async_in_2015(async_span);
7148 return Ok(Some(item));
7151 if self.check_keyword(kw::Unsafe) &&
7152 self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
7154 // UNSAFE TRAIT ITEM
7155 self.bump(); // `unsafe`
7156 let is_auto = if self.eat_keyword(kw::Trait) {
7159 self.expect_keyword(kw::Auto)?;
7160 self.expect_keyword(kw::Trait)?;
7163 let (ident, item_, extra_attrs) =
7164 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7165 let prev_span = self.prev_span;
7166 let item = self.mk_item(lo.to(prev_span),
7170 maybe_append(attrs, extra_attrs));
7171 return Ok(Some(item));
7173 if self.check_keyword(kw::Impl) ||
7174 self.check_keyword(kw::Unsafe) &&
7175 self.is_keyword_ahead(1, &[kw::Impl]) ||
7176 self.check_keyword(kw::Default) &&
7177 self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) {
7179 let defaultness = self.parse_defaultness();
7180 let unsafety = self.parse_unsafety();
7181 self.expect_keyword(kw::Impl)?;
7182 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7183 let span = lo.to(self.prev_span);
7184 return Ok(Some(self.mk_item(span, ident, item, visibility,
7185 maybe_append(attrs, extra_attrs))));
7187 if self.check_keyword(kw::Fn) {
7190 let fn_span = self.prev_span;
7191 let (ident, item_, extra_attrs) =
7192 self.parse_item_fn(Unsafety::Normal,
7193 respan(fn_span, IsAsync::NotAsync),
7194 respan(fn_span, Constness::NotConst),
7196 let prev_span = self.prev_span;
7197 let item = self.mk_item(lo.to(prev_span),
7201 maybe_append(attrs, extra_attrs));
7202 return Ok(Some(item));
7204 if self.check_keyword(kw::Unsafe)
7205 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7206 // UNSAFE FUNCTION ITEM
7207 self.bump(); // `unsafe`
7208 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7209 self.check(&token::OpenDelim(token::Brace));
7210 let abi = if self.eat_keyword(kw::Extern) {
7211 self.parse_opt_abi()?.unwrap_or(Abi::C)
7215 self.expect_keyword(kw::Fn)?;
7216 let fn_span = self.prev_span;
7217 let (ident, item_, extra_attrs) =
7218 self.parse_item_fn(Unsafety::Unsafe,
7219 respan(fn_span, IsAsync::NotAsync),
7220 respan(fn_span, Constness::NotConst),
7222 let prev_span = self.prev_span;
7223 let item = self.mk_item(lo.to(prev_span),
7227 maybe_append(attrs, extra_attrs));
7228 return Ok(Some(item));
7230 if self.eat_keyword(kw::Mod) {
7232 let (ident, item_, extra_attrs) =
7233 self.parse_item_mod(&attrs[..])?;
7234 let prev_span = self.prev_span;
7235 let item = self.mk_item(lo.to(prev_span),
7239 maybe_append(attrs, extra_attrs));
7240 return Ok(Some(item));
7242 if let Some(type_) = self.eat_type() {
7243 let (ident, alias, generics) = type_?;
7245 let item_ = match alias {
7246 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7247 AliasKind::OpaqueTy(bounds) => ItemKind::OpaqueTy(bounds, generics),
7249 let prev_span = self.prev_span;
7250 let item = self.mk_item(lo.to(prev_span),
7255 return Ok(Some(item));
7257 if self.eat_keyword(kw::Enum) {
7259 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7260 let prev_span = self.prev_span;
7261 let item = self.mk_item(lo.to(prev_span),
7265 maybe_append(attrs, extra_attrs));
7266 return Ok(Some(item));
7268 if self.check_keyword(kw::Trait)
7269 || (self.check_keyword(kw::Auto)
7270 && self.is_keyword_ahead(1, &[kw::Trait]))
7272 let is_auto = if self.eat_keyword(kw::Trait) {
7275 self.expect_keyword(kw::Auto)?;
7276 self.expect_keyword(kw::Trait)?;
7280 let (ident, item_, extra_attrs) =
7281 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7282 let prev_span = self.prev_span;
7283 let item = self.mk_item(lo.to(prev_span),
7287 maybe_append(attrs, extra_attrs));
7288 return Ok(Some(item));
7290 if self.eat_keyword(kw::Struct) {
7292 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7293 let prev_span = self.prev_span;
7294 let item = self.mk_item(lo.to(prev_span),
7298 maybe_append(attrs, extra_attrs));
7299 return Ok(Some(item));
7301 if self.is_union_item() {
7304 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7305 let prev_span = self.prev_span;
7306 let item = self.mk_item(lo.to(prev_span),
7310 maybe_append(attrs, extra_attrs));
7311 return Ok(Some(item));
7313 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7314 return Ok(Some(macro_def));
7317 // Verify whether we have encountered a struct or method definition where the user forgot to
7318 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7319 if visibility.node.is_pub() &&
7320 self.check_ident() &&
7321 self.look_ahead(1, |t| *t != token::Not)
7323 // Space between `pub` keyword and the identifier
7326 // ^^^ `sp` points here
7327 let sp = self.prev_span.between(self.token.span);
7328 let full_sp = self.prev_span.to(self.token.span);
7329 let ident_sp = self.token.span;
7330 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7331 // possible public struct definition where `struct` was forgotten
7332 let ident = self.parse_ident().unwrap();
7333 let msg = format!("add `struct` here to parse `{}` as a public struct",
7335 let mut err = self.diagnostic()
7336 .struct_span_err(sp, "missing `struct` for struct definition");
7337 err.span_suggestion_short(
7338 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7341 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7342 let ident = self.parse_ident().unwrap();
7344 let kw_name = if let Ok(Some(_)) = self.parse_self_arg_with_attrs()
7345 .map_err(|mut e| e.cancel())
7351 self.consume_block(token::Paren);
7352 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7353 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7355 ("fn", kw_name, false)
7356 } else if self.check(&token::OpenDelim(token::Brace)) {
7358 ("fn", kw_name, false)
7359 } else if self.check(&token::Colon) {
7363 ("fn` or `struct", "function or struct", true)
7366 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7367 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7369 self.consume_block(token::Brace);
7370 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7374 err.span_suggestion_short(
7375 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7378 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
7379 err.span_suggestion(
7381 "if you meant to call a macro, try",
7382 format!("{}!", snippet),
7383 // this is the `ambiguous` conditional branch
7384 Applicability::MaybeIncorrect
7387 err.help("if you meant to call a macro, remove the `pub` \
7388 and add a trailing `!` after the identifier");
7392 } else if self.look_ahead(1, |t| *t == token::Lt) {
7393 let ident = self.parse_ident().unwrap();
7394 self.eat_to_tokens(&[&token::Gt]);
7396 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7397 if let Ok(Some(_)) = self.parse_self_arg_with_attrs()
7398 .map_err(|mut e| e.cancel())
7400 ("fn", "method", false)
7402 ("fn", "function", false)
7404 } else if self.check(&token::OpenDelim(token::Brace)) {
7405 ("struct", "struct", false)
7407 ("fn` or `struct", "function or struct", true)
7409 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7410 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7412 err.span_suggestion_short(
7414 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7415 format!(" {} ", kw),
7416 Applicability::MachineApplicable,
7422 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7425 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
7426 fn ban_async_in_2015(&self, async_span: Span) {
7427 if async_span.rust_2015() {
7429 .struct_span_err_with_code(
7431 "`async fn` is not permitted in the 2015 edition",
7432 DiagnosticId::Error("E0670".into())
7438 /// Parses a foreign item.
7439 crate fn parse_foreign_item(&mut self, extern_sp: Span) -> PResult<'a, ForeignItem> {
7440 maybe_whole!(self, NtForeignItem, |ni| ni);
7442 let attrs = self.parse_outer_attributes()?;
7443 let lo = self.token.span;
7444 let visibility = self.parse_visibility(false)?;
7446 // FOREIGN STATIC ITEM
7447 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7448 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
7449 if self.token.is_keyword(kw::Const) {
7451 .struct_span_err(self.token.span, "extern items cannot be `const`")
7454 "try using a static value",
7455 "static".to_owned(),
7456 Applicability::MachineApplicable
7459 self.bump(); // `static` or `const`
7460 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7462 // FOREIGN FUNCTION ITEM
7463 if self.check_keyword(kw::Fn) {
7464 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?);
7466 // FOREIGN TYPE ITEM
7467 if self.check_keyword(kw::Type) {
7468 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7471 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7475 ident: Ident::invalid(),
7476 span: lo.to(self.prev_span),
7477 id: ast::DUMMY_NODE_ID,
7480 node: ForeignItemKind::Macro(mac),
7485 if !attrs.is_empty() {
7486 self.expected_item_err(&attrs)?;
7494 /// This is the fall-through for parsing items.
7495 fn parse_macro_use_or_failure(
7497 attrs: Vec<Attribute> ,
7498 macros_allowed: bool,
7499 attributes_allowed: bool,
7501 visibility: Visibility
7502 ) -> PResult<'a, Option<P<Item>>> {
7503 if macros_allowed && self.token.is_path_start() &&
7504 !(self.is_async_fn() && self.token.span.rust_2015()) {
7505 // MACRO INVOCATION ITEM
7507 let prev_span = self.prev_span;
7508 self.complain_if_pub_macro(&visibility.node, prev_span);
7510 let mac_lo = self.token.span;
7513 let path = self.parse_path(PathStyle::Mod)?;
7514 self.expect(&token::Not)?;
7515 let (delim, tts) = self.expect_delimited_token_tree()?;
7516 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
7517 self.report_invalid_macro_expansion_item();
7520 let hi = self.prev_span;
7521 let mac = respan(mac_lo.to(hi), Mac_ { path, tts, delim });
7523 self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs);
7524 return Ok(Some(item));
7527 // FAILURE TO PARSE ITEM
7528 match visibility.node {
7529 VisibilityKind::Inherited => {}
7531 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7535 if !attributes_allowed && !attrs.is_empty() {
7536 self.expected_item_err(&attrs)?;
7541 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
7542 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7543 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7545 if self.token.is_path_start() &&
7546 !(self.is_async_fn() && self.token.span.rust_2015()) {
7547 let prev_span = self.prev_span;
7548 let lo = self.token.span;
7549 let path = self.parse_path(PathStyle::Mod)?;
7551 if path.segments.len() == 1 {
7552 if !self.eat(&token::Not) {
7553 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7556 self.expect(&token::Not)?;
7559 if let Some(vis) = vis {
7560 self.complain_if_pub_macro(&vis.node, prev_span);
7565 // eat a matched-delimiter token tree:
7566 let (delim, tts) = self.expect_delimited_token_tree()?;
7567 if delim != MacDelimiter::Brace {
7568 self.expect(&token::Semi)?;
7571 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path, tts, delim })))
7577 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7578 where F: FnOnce(&mut Self) -> PResult<'a, R>
7580 // Record all tokens we parse when parsing this item.
7581 let mut tokens = Vec::new();
7582 let prev_collecting = match self.token_cursor.frame.last_token {
7583 LastToken::Collecting(ref mut list) => {
7584 Some(mem::take(list))
7586 LastToken::Was(ref mut last) => {
7587 tokens.extend(last.take());
7591 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7592 let prev = self.token_cursor.stack.len();
7594 let last_token = if self.token_cursor.stack.len() == prev {
7595 &mut self.token_cursor.frame.last_token
7596 } else if self.token_cursor.stack.get(prev).is_none() {
7597 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
7598 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
7600 return Ok((ret?, TokenStream::new(vec![])));
7602 &mut self.token_cursor.stack[prev].last_token
7605 // Pull out the tokens that we've collected from the call to `f` above.
7606 let mut collected_tokens = match *last_token {
7607 LastToken::Collecting(ref mut v) => mem::take(v),
7608 LastToken::Was(ref was) => {
7609 let msg = format!("our vector went away? - found Was({:?})", was);
7610 debug!("collect_tokens: {}", msg);
7611 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
7612 // This can happen due to a bad interaction of two unrelated recovery mechanisms
7613 // with mismatched delimiters *and* recovery lookahead on the likely typo
7614 // `pub ident(` (#62895, different but similar to the case above).
7615 return Ok((ret?, TokenStream::new(vec![])));
7619 // If we're not at EOF our current token wasn't actually consumed by
7620 // `f`, but it'll still be in our list that we pulled out. In that case
7622 let extra_token = if self.token != token::Eof {
7623 collected_tokens.pop()
7628 // If we were previously collecting tokens, then this was a recursive
7629 // call. In that case we need to record all the tokens we collected in
7630 // our parent list as well. To do that we push a clone of our stream
7631 // onto the previous list.
7632 match prev_collecting {
7634 list.extend(collected_tokens.iter().cloned());
7635 list.extend(extra_token);
7636 *last_token = LastToken::Collecting(list);
7639 *last_token = LastToken::Was(extra_token);
7643 Ok((ret?, TokenStream::new(collected_tokens)))
7646 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7647 let attrs = self.parse_outer_attributes()?;
7648 self.parse_item_(attrs, true, false)
7652 fn is_import_coupler(&mut self) -> bool {
7653 self.check(&token::ModSep) &&
7654 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7655 *t == token::BinOp(token::Star))
7658 /// Parses a `UseTree`.
7661 /// USE_TREE = [`::`] `*` |
7662 /// [`::`] `{` USE_TREE_LIST `}` |
7664 /// PATH `::` `{` USE_TREE_LIST `}` |
7665 /// PATH [`as` IDENT]
7667 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7668 let lo = self.token.span;
7670 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7671 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7672 self.check(&token::BinOp(token::Star)) ||
7673 self.is_import_coupler() {
7674 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7675 let mod_sep_ctxt = self.token.span.ctxt();
7676 if self.eat(&token::ModSep) {
7677 prefix.segments.push(
7678 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7682 if self.eat(&token::BinOp(token::Star)) {
7685 UseTreeKind::Nested(self.parse_use_tree_list()?)
7688 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7689 prefix = self.parse_path(PathStyle::Mod)?;
7691 if self.eat(&token::ModSep) {
7692 if self.eat(&token::BinOp(token::Star)) {
7695 UseTreeKind::Nested(self.parse_use_tree_list()?)
7698 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7702 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7705 /// Parses a `UseTreeKind::Nested(list)`.
7708 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7710 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7711 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, ast::DUMMY_NODE_ID)))
7715 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7716 if self.eat_keyword(kw::As) {
7717 self.parse_ident_or_underscore().map(Some)
7723 /// Parses a source module as a crate. This is the main entry point for the parser.
7724 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7725 let lo = self.token.span;
7726 let krate = Ok(ast::Crate {
7727 attrs: self.parse_inner_attributes()?,
7728 module: self.parse_mod_items(&token::Eof, lo)?,
7729 span: lo.to(self.token.span),
7734 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7735 let ret = match self.token.kind {
7736 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
7737 (symbol, ast::StrStyle::Cooked, suffix),
7738 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
7739 (symbol, ast::StrStyle::Raw(n), suffix),
7746 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7747 match self.parse_optional_str() {
7748 Some((s, style, suf)) => {
7749 let sp = self.prev_span;
7750 self.expect_no_suffix(sp, "a string literal", suf);
7754 let msg = "expected string literal";
7755 let mut err = self.fatal(msg);
7756 err.span_label(self.token.span, msg);
7762 fn report_invalid_macro_expansion_item(&self) {
7763 self.struct_span_err(
7765 "macros that expand to items must be delimited with braces or followed by a semicolon",
7766 ).multipart_suggestion(
7767 "change the delimiters to curly braces",
7769 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
7770 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
7772 Applicability::MaybeIncorrect,
7774 self.sess.source_map.next_point(self.prev_span),
7777 Applicability::MaybeIncorrect,
7782 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
7783 for unmatched in unclosed_delims.iter() {
7784 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
7785 "incorrect close delimiter: `{}`",
7786 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
7788 err.span_label(unmatched.found_span, "incorrect close delimiter");
7789 if let Some(sp) = unmatched.candidate_span {
7790 err.span_label(sp, "close delimiter possibly meant for this");
7792 if let Some(sp) = unmatched.unclosed_span {
7793 err.span_label(sp, "un-closed delimiter");
7797 unclosed_delims.clear();