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 existential 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 Existential(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()
152 /// As maybe_whole_expr, but for things other than expressions
153 macro_rules! maybe_whole {
154 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
155 if let token::Interpolated(nt) = &$p.token.kind {
156 if let token::$constructor(x) = &**nt {
165 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
166 macro_rules! maybe_recover_from_interpolated_ty_qpath {
167 ($self: expr, $allow_qpath_recovery: expr) => {
168 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
169 if let token::Interpolated(nt) = &$self.token.kind {
170 if let token::NtTy(ty) = &**nt {
173 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
180 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
181 if let Some(ref mut rhs) = rhs {
187 #[derive(Debug, Clone, Copy, PartialEq)]
199 // NOTE: `Ident`s are handled by `common.rs`.
202 pub struct Parser<'a> {
203 pub sess: &'a ParseSess,
204 /// The current normalized token.
205 /// "Normalized" means that some interpolated tokens
206 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
207 /// with non-interpolated identifier and lifetime tokens they refer to.
208 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
210 /// Span of the current non-normalized token.
211 meta_var_span: Option<Span>,
212 /// Span of the previous non-normalized token.
214 /// Kind of the previous normalized token (in simplified form).
215 prev_token_kind: PrevTokenKind,
216 restrictions: Restrictions,
217 /// Used to determine the path to externally loaded source files.
218 crate directory: Directory<'a>,
219 /// `true` to parse sub-modules in other files.
220 pub recurse_into_file_modules: bool,
221 /// Name of the root module this parser originated from. If `None`, then the
222 /// name is not known. This does not change while the parser is descending
223 /// into modules, and sub-parsers have new values for this name.
224 pub root_module_name: Option<String>,
225 crate expected_tokens: Vec<TokenType>,
226 crate token_cursor: TokenCursor,
227 desugar_doc_comments: bool,
228 /// `true` we should configure out of line modules as we parse.
230 /// This field is used to keep track of how many left angle brackets we have seen. This is
231 /// required in order to detect extra leading left angle brackets (`<` characters) and error
234 /// See the comments in the `parse_path_segment` function for more details.
235 crate unmatched_angle_bracket_count: u32,
236 crate max_angle_bracket_count: u32,
237 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
238 /// it gets removed from here. Every entry left at the end gets emitted as an independent
240 crate unclosed_delims: Vec<UnmatchedBrace>,
241 crate last_unexpected_token_span: Option<Span>,
242 crate last_type_ascription: Option<(Span, bool /* likely path typo */)>,
243 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
244 crate subparser_name: Option<&'static str>,
247 impl<'a> Drop for Parser<'a> {
249 let diag = self.diagnostic();
250 emit_unclosed_delims(&mut self.unclosed_delims, diag);
255 crate struct TokenCursor {
256 crate frame: TokenCursorFrame,
257 crate stack: Vec<TokenCursorFrame>,
261 crate struct TokenCursorFrame {
262 crate delim: token::DelimToken,
263 crate span: DelimSpan,
264 crate open_delim: bool,
265 crate tree_cursor: tokenstream::Cursor,
266 crate close_delim: bool,
267 crate last_token: LastToken,
270 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
271 /// by the parser, and then that's transitively used to record the tokens that
272 /// each parse AST item is created with.
274 /// Right now this has two states, either collecting tokens or not collecting
275 /// tokens. If we're collecting tokens we just save everything off into a local
276 /// `Vec`. This should eventually though likely save tokens from the original
277 /// token stream and just use slicing of token streams to avoid creation of a
278 /// whole new vector.
280 /// The second state is where we're passively not recording tokens, but the last
281 /// token is still tracked for when we want to start recording tokens. This
282 /// "last token" means that when we start recording tokens we'll want to ensure
283 /// that this, the first token, is included in the output.
285 /// You can find some more example usage of this in the `collect_tokens` method
288 crate enum LastToken {
289 Collecting(Vec<TreeAndJoint>),
290 Was(Option<TreeAndJoint>),
293 impl TokenCursorFrame {
294 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
298 open_delim: delim == token::NoDelim,
299 tree_cursor: tts.clone().into_trees(),
300 close_delim: delim == token::NoDelim,
301 last_token: LastToken::Was(None),
307 fn next(&mut self) -> Token {
309 let tree = if !self.frame.open_delim {
310 self.frame.open_delim = true;
311 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
312 } else if let Some(tree) = self.frame.tree_cursor.next() {
314 } else if !self.frame.close_delim {
315 self.frame.close_delim = true;
316 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
317 } else if let Some(frame) = self.stack.pop() {
321 return Token::new(token::Eof, DUMMY_SP);
324 match self.frame.last_token {
325 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
326 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
330 TokenTree::Token(token) => return token,
331 TokenTree::Delimited(sp, delim, tts) => {
332 let frame = TokenCursorFrame::new(sp, delim, &tts);
333 self.stack.push(mem::replace(&mut self.frame, frame));
339 fn next_desugared(&mut self) -> Token {
340 let (name, sp) = match self.next() {
341 Token { kind: token::DocComment(name), span } => (name, span),
345 let stripped = strip_doc_comment_decoration(&name.as_str());
347 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
348 // required to wrap the text.
349 let mut num_of_hashes = 0;
351 for ch in stripped.chars() {
354 '#' if count > 0 => count + 1,
357 num_of_hashes = cmp::max(num_of_hashes, count);
360 let delim_span = DelimSpan::from_single(sp);
361 let body = TokenTree::Delimited(
365 TokenTree::token(token::Ident(sym::doc, false), sp),
366 TokenTree::token(token::Eq, sp),
367 TokenTree::token(TokenKind::lit(
368 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
371 .iter().cloned().collect::<TokenStream>().into(),
374 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
377 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
378 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
379 .iter().cloned().collect::<TokenStream>().into()
381 [TokenTree::token(token::Pound, sp), body]
382 .iter().cloned().collect::<TokenStream>().into()
390 #[derive(Clone, PartialEq)]
391 crate enum TokenType {
403 crate fn to_string(&self) -> String {
405 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
406 TokenType::Keyword(kw) => format!("`{}`", kw),
407 TokenType::Operator => "an operator".to_string(),
408 TokenType::Lifetime => "lifetime".to_string(),
409 TokenType::Ident => "identifier".to_string(),
410 TokenType::Path => "path".to_string(),
411 TokenType::Type => "type".to_string(),
412 TokenType::Const => "const".to_string(),
417 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
418 /// `IDENT<<u8 as Trait>::AssocTy>`.
420 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
421 /// that `IDENT` is not the ident of a fn trait.
422 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
423 t == &token::ModSep || t == &token::Lt ||
424 t == &token::BinOp(token::Shl)
427 /// Information about the path to a module.
428 pub struct ModulePath {
431 pub result: Result<ModulePathSuccess, Error>,
434 pub struct ModulePathSuccess {
436 pub directory_ownership: DirectoryOwnership,
443 AttributesParsed(ThinVec<Attribute>),
444 AlreadyParsed(P<Expr>),
447 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
448 fn from(o: Option<ThinVec<Attribute>>) -> Self {
449 if let Some(attrs) = o {
450 LhsExpr::AttributesParsed(attrs)
452 LhsExpr::NotYetParsed
457 impl From<P<Expr>> for LhsExpr {
458 fn from(expr: P<Expr>) -> Self {
459 LhsExpr::AlreadyParsed(expr)
463 #[derive(Copy, Clone, Debug)]
464 crate enum TokenExpectType {
469 impl<'a> Parser<'a> {
473 directory: Option<Directory<'a>>,
474 recurse_into_file_modules: bool,
475 desugar_doc_comments: bool,
476 subparser_name: Option<&'static str>,
478 let mut parser = Parser {
480 token: Token::dummy(),
483 prev_token_kind: PrevTokenKind::Other,
484 restrictions: Restrictions::empty(),
485 recurse_into_file_modules,
486 directory: Directory {
487 path: Cow::from(PathBuf::new()),
488 ownership: DirectoryOwnership::Owned { relative: None }
490 root_module_name: None,
491 expected_tokens: Vec::new(),
492 token_cursor: TokenCursor {
493 frame: TokenCursorFrame::new(
500 desugar_doc_comments,
502 unmatched_angle_bracket_count: 0,
503 max_angle_bracket_count: 0,
504 unclosed_delims: Vec::new(),
505 last_unexpected_token_span: None,
506 last_type_ascription: None,
510 parser.token = parser.next_tok();
512 if let Some(directory) = directory {
513 parser.directory = directory;
514 } else if !parser.token.span.is_dummy() {
515 if let FileName::Real(mut path) =
516 sess.source_map().span_to_unmapped_path(parser.token.span) {
518 parser.directory.path = Cow::from(path);
522 parser.process_potential_macro_variable();
526 fn next_tok(&mut self) -> Token {
527 let mut next = if self.desugar_doc_comments {
528 self.token_cursor.next_desugared()
530 self.token_cursor.next()
532 if next.span.is_dummy() {
533 // Tweak the location for better diagnostics, but keep syntactic context intact.
534 next.span = self.prev_span.with_ctxt(next.span.ctxt());
539 /// Converts the current token to a string using `self`'s reader.
540 pub fn this_token_to_string(&self) -> String {
541 pprust::token_to_string(&self.token)
544 crate fn token_descr(&self) -> Option<&'static str> {
545 Some(match &self.token.kind {
546 _ if self.token.is_special_ident() => "reserved identifier",
547 _ if self.token.is_used_keyword() => "keyword",
548 _ if self.token.is_unused_keyword() => "reserved keyword",
549 token::DocComment(..) => "doc comment",
554 crate fn this_token_descr(&self) -> String {
555 if let Some(prefix) = self.token_descr() {
556 format!("{} `{}`", prefix, self.this_token_to_string())
558 format!("`{}`", self.this_token_to_string())
562 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
563 match self.expect_one_of(&[], &[]) {
565 Ok(_) => unreachable!(),
569 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
570 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
571 if self.expected_tokens.is_empty() {
572 if self.token == *t {
576 self.unexpected_try_recover(t)
579 self.expect_one_of(slice::from_ref(t), &[])
583 /// Expect next token to be edible or inedible token. If edible,
584 /// then consume it; if inedible, then return without consuming
585 /// anything. Signal a fatal error if next token is unexpected.
586 pub fn expect_one_of(
588 edible: &[TokenKind],
589 inedible: &[TokenKind],
590 ) -> PResult<'a, bool /* recovered */> {
591 if edible.contains(&self.token.kind) {
594 } else if inedible.contains(&self.token.kind) {
595 // leave it in the input
597 } else if self.last_unexpected_token_span == Some(self.token.span) {
600 self.expected_one_of_not_found(edible, inedible)
604 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
605 fn interpolated_or_expr_span(
607 expr: PResult<'a, P<Expr>>,
608 ) -> PResult<'a, (Span, P<Expr>)> {
610 if self.prev_token_kind == PrevTokenKind::Interpolated {
618 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
619 self.parse_ident_common(true)
622 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
623 match self.token.kind {
624 token::Ident(name, _) => {
625 if self.token.is_reserved_ident() {
626 let mut err = self.expected_ident_found();
633 let span = self.token.span;
635 Ok(Ident::new(name, span))
638 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
639 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
641 self.expected_ident_found()
647 /// Checks if the next token is `tok`, and returns `true` if so.
649 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
651 crate fn check(&mut self, tok: &TokenKind) -> bool {
652 let is_present = self.token == *tok;
653 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
657 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
658 pub fn eat(&mut self, tok: &TokenKind) -> bool {
659 let is_present = self.check(tok);
660 if is_present { self.bump() }
664 fn check_keyword(&mut self, kw: Symbol) -> bool {
665 self.expected_tokens.push(TokenType::Keyword(kw));
666 self.token.is_keyword(kw)
669 /// If the next token is the given keyword, eats it and returns
670 /// `true`. Otherwise, returns `false`.
671 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
672 if self.check_keyword(kw) {
680 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
681 if self.token.is_keyword(kw) {
689 /// If the given word is not a keyword, signals an error.
690 /// If the next token is not the given word, signals an error.
691 /// Otherwise, eats it.
692 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
693 if !self.eat_keyword(kw) {
700 crate fn check_ident(&mut self) -> bool {
701 if self.token.is_ident() {
704 self.expected_tokens.push(TokenType::Ident);
709 fn check_path(&mut self) -> bool {
710 if self.token.is_path_start() {
713 self.expected_tokens.push(TokenType::Path);
718 fn check_type(&mut self) -> bool {
719 if self.token.can_begin_type() {
722 self.expected_tokens.push(TokenType::Type);
727 fn check_const_arg(&mut self) -> bool {
728 if self.token.can_begin_const_arg() {
731 self.expected_tokens.push(TokenType::Const);
736 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
737 /// and continues. If a `+` is not seen, returns `false`.
739 /// This is used when token-splitting `+=` into `+`.
740 /// See issue #47856 for an example of when this may occur.
741 fn eat_plus(&mut self) -> bool {
742 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
743 match self.token.kind {
744 token::BinOp(token::Plus) => {
748 token::BinOpEq(token::Plus) => {
749 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
750 self.bump_with(token::Eq, span);
758 /// Checks to see if the next token is either `+` or `+=`.
759 /// Otherwise returns `false`.
760 fn check_plus(&mut self) -> bool {
761 if self.token.is_like_plus() {
765 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
770 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
771 /// `&` and continues. If an `&` is not seen, signals an error.
772 fn expect_and(&mut self) -> PResult<'a, ()> {
773 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
774 match self.token.kind {
775 token::BinOp(token::And) => {
780 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
781 Ok(self.bump_with(token::BinOp(token::And), span))
783 _ => self.unexpected()
787 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
788 /// `|` and continues. If an `|` is not seen, signals an error.
789 fn expect_or(&mut self) -> PResult<'a, ()> {
790 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
791 match self.token.kind {
792 token::BinOp(token::Or) => {
797 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
798 Ok(self.bump_with(token::BinOp(token::Or), span))
800 _ => self.unexpected()
804 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
805 literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
808 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
809 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
810 /// and continue. If a `<` is not seen, returns false.
812 /// This is meant to be used when parsing generics on a path to get the
814 fn eat_lt(&mut self) -> bool {
815 self.expected_tokens.push(TokenType::Token(token::Lt));
816 let ate = match self.token.kind {
821 token::BinOp(token::Shl) => {
822 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
823 self.bump_with(token::Lt, span);
827 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
828 self.bump_with(token::BinOp(token::Minus), span);
835 // See doc comment for `unmatched_angle_bracket_count`.
836 self.unmatched_angle_bracket_count += 1;
837 self.max_angle_bracket_count += 1;
838 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
844 fn expect_lt(&mut self) -> PResult<'a, ()> {
852 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
853 /// with a single `>` and continues. If a `>` is not seen, signals an error.
854 fn expect_gt(&mut self) -> PResult<'a, ()> {
855 self.expected_tokens.push(TokenType::Token(token::Gt));
856 let ate = match self.token.kind {
861 token::BinOp(token::Shr) => {
862 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
863 Some(self.bump_with(token::Gt, span))
865 token::BinOpEq(token::Shr) => {
866 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
867 Some(self.bump_with(token::Ge, span))
870 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
871 Some(self.bump_with(token::Eq, span))
878 // See doc comment for `unmatched_angle_bracket_count`.
879 if self.unmatched_angle_bracket_count > 0 {
880 self.unmatched_angle_bracket_count -= 1;
881 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
886 None => self.unexpected(),
890 /// Parses a sequence, including the closing delimiter. The function
891 /// `f` must consume tokens until reaching the next separator or
893 pub fn parse_seq_to_end<T>(
897 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
898 ) -> PResult<'a, Vec<T>> {
899 let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
906 /// Parses a sequence, not including the closing delimiter. The function
907 /// `f` must consume tokens until reaching the next separator or
909 pub fn parse_seq_to_before_end<T>(
913 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
914 ) -> PResult<'a, (Vec<T>, bool, bool)> {
915 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
918 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
919 kets.iter().any(|k| {
921 TokenExpectType::Expect => self.check(k),
922 TokenExpectType::NoExpect => self.token == **k,
927 crate fn parse_seq_to_before_tokens<T>(
931 expect: TokenExpectType,
932 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
933 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
934 let mut first = true;
935 let mut recovered = false;
936 let mut trailing = false;
938 while !self.expect_any_with_type(kets, expect) {
939 if let token::CloseDelim(..) | token::Eof = self.token.kind {
942 if let Some(ref t) = sep.sep {
946 match self.expect(t) {
953 // Attempt to keep parsing if it was a similar separator
954 if let Some(ref tokens) = t.similar_tokens() {
955 if tokens.contains(&self.token.kind) {
960 // Attempt to keep parsing if it was an omitted separator
975 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
984 Ok((v, trailing, recovered))
987 /// Parses a sequence, including the closing delimiter. The function
988 /// `f` must consume tokens until reaching the next separator or
990 fn parse_unspanned_seq<T>(
995 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
996 ) -> PResult<'a, (Vec<T>, bool)> {
998 let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1002 Ok((result, trailing))
1005 fn parse_delim_comma_seq<T>(
1008 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1009 ) -> PResult<'a, (Vec<T>, bool)> {
1010 self.parse_unspanned_seq(
1011 &token::OpenDelim(delim),
1012 &token::CloseDelim(delim),
1013 SeqSep::trailing_allowed(token::Comma),
1018 fn parse_paren_comma_seq<T>(
1020 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1021 ) -> PResult<'a, (Vec<T>, bool)> {
1022 self.parse_delim_comma_seq(token::Paren, f)
1025 /// Advance the parser by one token
1026 pub fn bump(&mut self) {
1027 if self.prev_token_kind == PrevTokenKind::Eof {
1028 // Bumping after EOF is a bad sign, usually an infinite loop.
1029 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1032 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
1034 // Record last token kind for possible error recovery.
1035 self.prev_token_kind = match self.token.kind {
1036 token::DocComment(..) => PrevTokenKind::DocComment,
1037 token::Comma => PrevTokenKind::Comma,
1038 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1039 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1040 token::Interpolated(..) => PrevTokenKind::Interpolated,
1041 token::Eof => PrevTokenKind::Eof,
1042 token::Ident(..) => PrevTokenKind::Ident,
1043 _ => PrevTokenKind::Other,
1046 self.token = self.next_tok();
1047 self.expected_tokens.clear();
1048 // check after each token
1049 self.process_potential_macro_variable();
1052 /// Advance the parser using provided token as a next one. Use this when
1053 /// consuming a part of a token. For example a single `<` from `<<`.
1054 fn bump_with(&mut self, next: TokenKind, span: Span) {
1055 self.prev_span = self.token.span.with_hi(span.lo());
1056 // It would be incorrect to record the kind of the current token, but
1057 // fortunately for tokens currently using `bump_with`, the
1058 // prev_token_kind will be of no use anyway.
1059 self.prev_token_kind = PrevTokenKind::Other;
1060 self.token = Token::new(next, span);
1061 self.expected_tokens.clear();
1064 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1065 F: FnOnce(&Token) -> R,
1068 return f(&self.token);
1071 let frame = &self.token_cursor.frame;
1072 f(&match frame.tree_cursor.look_ahead(dist - 1) {
1073 Some(tree) => match tree {
1074 TokenTree::Token(token) => token,
1075 TokenTree::Delimited(dspan, delim, _) =>
1076 Token::new(token::OpenDelim(delim), dspan.open),
1078 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
1082 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1083 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1084 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1087 /// Is the current token one of the keywords that signals a bare function type?
1088 fn token_is_bare_fn_keyword(&mut self) -> bool {
1089 self.check_keyword(kw::Fn) ||
1090 self.check_keyword(kw::Unsafe) ||
1091 self.check_keyword(kw::Extern)
1094 /// Parses a `TyKind::BareFn` type.
1095 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1098 [unsafe] [extern "ABI"] fn (S) -> T
1108 let unsafety = self.parse_unsafety();
1109 let abi = if self.eat_keyword(kw::Extern) {
1110 self.parse_opt_abi()?.unwrap_or(Abi::C)
1115 self.expect_keyword(kw::Fn)?;
1116 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1117 let ret_ty = self.parse_ret_ty(false)?;
1118 let decl = P(FnDecl {
1123 Ok(TyKind::BareFn(P(BareFnTy {
1131 /// Parses asyncness: `async` or nothing.
1132 fn parse_asyncness(&mut self) -> IsAsync {
1133 if self.eat_keyword(kw::Async) {
1135 closure_id: ast::DUMMY_NODE_ID,
1136 return_impl_trait_id: ast::DUMMY_NODE_ID,
1143 /// Parses unsafety: `unsafe` or nothing.
1144 fn parse_unsafety(&mut self) -> Unsafety {
1145 if self.eat_keyword(kw::Unsafe) {
1152 /// Parses the items in a trait declaration.
1153 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1154 maybe_whole!(self, NtTraitItem, |x| x);
1155 let attrs = self.parse_outer_attributes()?;
1156 let mut unclosed_delims = vec![];
1157 let (mut item, tokens) = self.collect_tokens(|this| {
1158 let item = this.parse_trait_item_(at_end, attrs);
1159 unclosed_delims.append(&mut this.unclosed_delims);
1162 self.unclosed_delims.append(&mut unclosed_delims);
1163 // See `parse_item` for why this clause is here.
1164 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1165 item.tokens = Some(tokens);
1170 fn parse_trait_item_(&mut self,
1172 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1173 let lo = self.token.span;
1175 let (name, node, generics) = if self.eat_keyword(kw::Type) {
1176 self.parse_trait_item_assoc_ty()?
1177 } else if self.is_const_item() {
1178 self.expect_keyword(kw::Const)?;
1179 let ident = self.parse_ident()?;
1180 self.expect(&token::Colon)?;
1181 let ty = self.parse_ty()?;
1182 let default = if self.eat(&token::Eq) {
1183 let expr = self.parse_expr()?;
1184 self.expect(&token::Semi)?;
1187 self.expect(&token::Semi)?;
1190 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1191 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1192 // trait item macro.
1193 (Ident::invalid(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1195 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1197 let ident = self.parse_ident()?;
1198 let mut generics = self.parse_generics()?;
1200 let decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1201 // This is somewhat dubious; We don't want to allow
1202 // argument names to be left off if there is a
1205 // We don't allow argument names to be left off in edition 2018.
1206 let is_name_required = p.token.span.rust_2018();
1207 p.parse_arg_general(true, false, |_| is_name_required)
1209 generics.where_clause = self.parse_where_clause()?;
1211 let sig = ast::MethodSig {
1221 let body = match self.token.kind {
1225 debug!("parse_trait_methods(): parsing required method");
1228 token::OpenDelim(token::Brace) => {
1229 debug!("parse_trait_methods(): parsing provided method");
1231 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1232 attrs.extend(inner_attrs.iter().cloned());
1235 token::Interpolated(ref nt) => {
1237 token::NtBlock(..) => {
1239 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1240 attrs.extend(inner_attrs.iter().cloned());
1244 return self.expected_semi_or_open_brace();
1249 return self.expected_semi_or_open_brace();
1252 (ident, ast::TraitItemKind::Method(sig, body), generics)
1256 id: ast::DUMMY_NODE_ID,
1261 span: lo.to(self.prev_span),
1266 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1267 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1268 if self.eat(&token::RArrow) {
1269 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1271 Ok(FunctionRetTy::Default(self.token.span.shrink_to_lo()))
1276 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1277 self.parse_ty_common(true, true, false)
1280 /// Parses a type in restricted contexts where `+` is not permitted.
1282 /// Example 1: `&'a TYPE`
1283 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1284 /// Example 2: `value1 as TYPE + value2`
1285 /// `+` is prohibited to avoid interactions with expression grammar.
1286 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1287 self.parse_ty_common(false, true, false)
1290 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1291 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1292 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1293 maybe_whole!(self, NtTy, |x| x);
1295 let lo = self.token.span;
1296 let mut impl_dyn_multi = false;
1297 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1298 // `(TYPE)` is a parenthesized type.
1299 // `(TYPE,)` is a tuple with a single field of type TYPE.
1300 let mut ts = vec![];
1301 let mut last_comma = false;
1302 while self.token != token::CloseDelim(token::Paren) {
1303 ts.push(self.parse_ty()?);
1304 if self.eat(&token::Comma) {
1311 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1312 self.expect(&token::CloseDelim(token::Paren))?;
1314 if ts.len() == 1 && !last_comma {
1315 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1316 let maybe_bounds = allow_plus && self.token.is_like_plus();
1318 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1319 TyKind::Path(None, ref path) if maybe_bounds => {
1320 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1322 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1323 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1324 let path = match bounds[0] {
1325 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1326 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1328 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1331 _ => TyKind::Paren(P(ty))
1336 } else if self.eat(&token::Not) {
1339 } else if self.eat(&token::BinOp(token::Star)) {
1341 TyKind::Ptr(self.parse_ptr()?)
1342 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1344 let t = self.parse_ty()?;
1345 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1346 let t = match self.maybe_parse_fixed_length_of_vec()? {
1347 None => TyKind::Slice(t),
1348 Some(length) => TyKind::Array(t, AnonConst {
1349 id: ast::DUMMY_NODE_ID,
1353 self.expect(&token::CloseDelim(token::Bracket))?;
1355 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1358 self.parse_borrowed_pointee()?
1359 } else if self.eat_keyword_noexpect(kw::Typeof) {
1361 // In order to not be ambiguous, the type must be surrounded by parens.
1362 self.expect(&token::OpenDelim(token::Paren))?;
1364 id: ast::DUMMY_NODE_ID,
1365 value: self.parse_expr()?,
1367 self.expect(&token::CloseDelim(token::Paren))?;
1369 } else if self.eat_keyword(kw::Underscore) {
1370 // A type to be inferred `_`
1372 } else if self.token_is_bare_fn_keyword() {
1373 // Function pointer type
1374 self.parse_ty_bare_fn(Vec::new())?
1375 } else if self.check_keyword(kw::For) {
1376 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1377 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1378 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1379 let lo = self.token.span;
1380 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1381 if self.token_is_bare_fn_keyword() {
1382 self.parse_ty_bare_fn(lifetime_defs)?
1384 let path = self.parse_path(PathStyle::Type)?;
1385 let parse_plus = allow_plus && self.check_plus();
1386 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1388 } else if self.eat_keyword(kw::Impl) {
1389 // Always parse bounds greedily for better error recovery.
1390 let bounds = self.parse_generic_bounds(None)?;
1391 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1392 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1393 } else if self.check_keyword(kw::Dyn) &&
1394 (self.token.span.rust_2018() ||
1395 self.look_ahead(1, |t| t.can_begin_bound() &&
1396 !can_continue_type_after_non_fn_ident(t))) {
1397 self.bump(); // `dyn`
1398 // Always parse bounds greedily for better error recovery.
1399 let bounds = self.parse_generic_bounds(None)?;
1400 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1401 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1402 } else if self.check(&token::Question) ||
1403 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1404 // Bound list (trait object type)
1405 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1406 TraitObjectSyntax::None)
1407 } else if self.eat_lt() {
1409 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1410 TyKind::Path(Some(qself), path)
1411 } else if self.token.is_path_start() {
1413 let path = self.parse_path(PathStyle::Type)?;
1414 if self.eat(&token::Not) {
1415 // Macro invocation in type position
1416 let (delim, tts) = self.expect_delimited_token_tree()?;
1417 let node = Mac_ { path, tts, delim };
1418 TyKind::Mac(respan(lo.to(self.prev_span), node))
1420 // Just a type path or bound list (trait object type) starting with a trait.
1422 // `Trait1 + Trait2 + 'a`
1423 if allow_plus && self.check_plus() {
1424 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1426 TyKind::Path(None, path)
1429 } else if self.check(&token::DotDotDot) {
1430 if allow_c_variadic {
1431 self.eat(&token::DotDotDot);
1434 return Err(self.fatal(
1435 "only foreign functions are allowed to be C-variadic"
1439 let msg = format!("expected type, found {}", self.this_token_descr());
1440 let mut err = self.fatal(&msg);
1441 err.span_label(self.token.span, "expected type");
1442 self.maybe_annotate_with_ascription(&mut err, true);
1446 let span = lo.to(self.prev_span);
1447 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1449 // Try to recover from use of `+` with incorrect priority.
1450 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1451 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1452 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1455 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1456 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1457 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1458 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1460 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1461 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1463 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1466 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1467 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1468 let mutbl = self.parse_mutability();
1469 let ty = self.parse_ty_no_plus()?;
1470 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }));
1473 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1474 let mutbl = if self.eat_keyword(kw::Mut) {
1476 } else if self.eat_keyword(kw::Const) {
1477 Mutability::Immutable
1479 let span = self.prev_span;
1480 let msg = "expected mut or const in raw pointer type";
1481 self.struct_span_err(span, msg)
1482 .span_label(span, msg)
1483 .help("use `*mut T` or `*const T` as appropriate")
1485 Mutability::Immutable
1487 let t = self.parse_ty_no_plus()?;
1488 Ok(MutTy { ty: t, mutbl })
1491 fn is_named_argument(&self) -> bool {
1492 let offset = match self.token.kind {
1493 token::Interpolated(ref nt) => match **nt {
1494 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1497 token::BinOp(token::And) | token::AndAnd => 1,
1498 _ if self.token.is_keyword(kw::Mut) => 1,
1502 self.look_ahead(offset, |t| t.is_ident()) &&
1503 self.look_ahead(offset + 1, |t| t == &token::Colon)
1506 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1508 /// This version of parse arg doesn't necessarily require identifier names.
1509 fn parse_arg_general<F>(
1511 is_trait_item: bool,
1512 allow_c_variadic: bool,
1513 is_name_required: F,
1514 ) -> PResult<'a, Arg>
1516 F: Fn(&token::Token) -> bool
1518 let lo = self.token.span;
1519 let attrs = self.parse_arg_attributes()?;
1520 if let Some(mut arg) = self.parse_self_arg()? {
1521 arg.attrs = attrs.into();
1522 return self.recover_bad_self_arg(arg, is_trait_item);
1525 let is_name_required = is_name_required(&self.token);
1526 let (pat, ty) = if is_name_required || self.is_named_argument() {
1527 debug!("parse_arg_general parse_pat (is_name_required:{})", is_name_required);
1529 let pat = self.parse_pat(Some("argument name"))?;
1530 if let Err(mut err) = self.expect(&token::Colon) {
1531 if let Some(ident) = self.argument_without_type(
1538 return Ok(dummy_arg(ident));
1544 self.eat_incorrect_doc_comment_for_arg_type();
1545 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1547 debug!("parse_arg_general ident_to_pat");
1548 let parser_snapshot_before_ty = self.clone();
1549 self.eat_incorrect_doc_comment_for_arg_type();
1550 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1551 if ty.is_ok() && self.token != token::Comma &&
1552 self.token != token::CloseDelim(token::Paren) {
1553 // This wasn't actually a type, but a pattern looking like a type,
1554 // so we are going to rollback and re-parse for recovery.
1555 ty = self.unexpected();
1559 let ident = Ident::new(kw::Invalid, self.prev_span);
1561 id: ast::DUMMY_NODE_ID,
1562 node: PatKind::Ident(
1563 BindingMode::ByValue(Mutability::Immutable), ident, None),
1569 // If this is a C-variadic argument and we hit an error, return the
1571 if self.token == token::DotDotDot {
1574 // Recover from attempting to parse the argument as a type without pattern.
1576 mem::replace(self, parser_snapshot_before_ty);
1577 self.recover_arg_parse()?
1582 let span = lo.to(self.token.span);
1584 Ok(Arg { attrs: attrs.into(), id: ast::DUMMY_NODE_ID, pat, span, ty })
1587 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
1588 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1589 let lo = self.token.span;
1590 let attrs = self.parse_arg_attributes()?;
1591 let pat = self.parse_pat(Some("argument name"))?;
1592 let t = if self.eat(&token::Colon) {
1596 id: ast::DUMMY_NODE_ID,
1597 node: TyKind::Infer,
1598 span: self.prev_span,
1601 let span = lo.to(self.token.span);
1603 attrs: attrs.into(),
1607 id: ast::DUMMY_NODE_ID
1611 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1612 if self.eat(&token::Semi) {
1613 Ok(Some(self.parse_expr()?))
1619 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1620 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1621 maybe_whole_expr!(self);
1623 let minus_lo = self.token.span;
1624 let minus_present = self.eat(&token::BinOp(token::Minus));
1625 let lo = self.token.span;
1626 let literal = self.parse_lit()?;
1627 let hi = self.prev_span;
1628 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1631 let minus_hi = self.prev_span;
1632 let unary = self.mk_unary(UnOp::Neg, expr);
1633 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1639 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1640 match self.token.kind {
1641 token::Ident(name, _) if name.is_path_segment_keyword() => {
1642 let span = self.token.span;
1644 Ok(Ident::new(name, span))
1646 _ => self.parse_ident(),
1650 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
1651 match self.token.kind {
1652 token::Ident(name, false) if name == kw::Underscore => {
1653 let span = self.token.span;
1655 Ok(Ident::new(name, span))
1657 _ => self.parse_ident(),
1661 /// Parses a qualified path.
1662 /// Assumes that the leading `<` has been parsed already.
1664 /// `qualified_path = <type [as trait_ref]>::path`
1669 /// `<T as U>::F::a<S>` (without disambiguator)
1670 /// `<T as U>::F::a::<S>` (with disambiguator)
1671 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1672 let lo = self.prev_span;
1673 let ty = self.parse_ty()?;
1675 // `path` will contain the prefix of the path up to the `>`,
1676 // if any (e.g., `U` in the `<T as U>::*` examples
1677 // above). `path_span` has the span of that path, or an empty
1678 // span in the case of something like `<T>::Bar`.
1679 let (mut path, path_span);
1680 if self.eat_keyword(kw::As) {
1681 let path_lo = self.token.span;
1682 path = self.parse_path(PathStyle::Type)?;
1683 path_span = path_lo.to(self.prev_span);
1685 path_span = self.token.span.to(self.token.span);
1686 path = ast::Path { segments: Vec::new(), span: path_span };
1689 // See doc comment for `unmatched_angle_bracket_count`.
1690 self.expect(&token::Gt)?;
1691 if self.unmatched_angle_bracket_count > 0 {
1692 self.unmatched_angle_bracket_count -= 1;
1693 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1696 self.expect(&token::ModSep)?;
1698 let qself = QSelf { ty, path_span, position: path.segments.len() };
1699 self.parse_path_segments(&mut path.segments, style)?;
1701 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1704 /// Parses simple paths.
1706 /// `path = [::] segment+`
1707 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1710 /// `a::b::C<D>` (without disambiguator)
1711 /// `a::b::C::<D>` (with disambiguator)
1712 /// `Fn(Args)` (without disambiguator)
1713 /// `Fn::(Args)` (with disambiguator)
1714 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1715 maybe_whole!(self, NtPath, |path| {
1716 if style == PathStyle::Mod &&
1717 path.segments.iter().any(|segment| segment.args.is_some()) {
1718 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1723 let lo = self.meta_var_span.unwrap_or(self.token.span);
1724 let mut segments = Vec::new();
1725 let mod_sep_ctxt = self.token.span.ctxt();
1726 if self.eat(&token::ModSep) {
1727 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
1729 self.parse_path_segments(&mut segments, style)?;
1731 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1734 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
1735 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
1737 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1738 let meta_ident = match self.token.kind {
1739 token::Interpolated(ref nt) => match **nt {
1740 token::NtMeta(ref meta) => match meta.node {
1741 ast::MetaItemKind::Word => Some(meta.path.clone()),
1748 if let Some(path) = meta_ident {
1752 self.parse_path(style)
1755 crate fn parse_path_segments(&mut self,
1756 segments: &mut Vec<PathSegment>,
1758 -> PResult<'a, ()> {
1760 let segment = self.parse_path_segment(style)?;
1761 if style == PathStyle::Expr {
1762 // In order to check for trailing angle brackets, we must have finished
1763 // recursing (`parse_path_segment` can indirectly call this function),
1764 // that is, the next token must be the highlighted part of the below example:
1766 // `Foo::<Bar as Baz<T>>::Qux`
1769 // As opposed to the below highlight (if we had only finished the first
1772 // `Foo::<Bar as Baz<T>>::Qux`
1775 // `PathStyle::Expr` is only provided at the root invocation and never in
1776 // `parse_path_segment` to recurse and therefore can be checked to maintain
1778 self.check_trailing_angle_brackets(&segment, token::ModSep);
1780 segments.push(segment);
1782 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1788 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
1789 let ident = self.parse_path_segment_ident()?;
1791 let is_args_start = |token: &Token| match token.kind {
1792 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
1793 | token::LArrow => true,
1796 let check_args_start = |this: &mut Self| {
1797 this.expected_tokens.extend_from_slice(
1798 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1800 is_args_start(&this.token)
1803 Ok(if style == PathStyle::Type && check_args_start(self) ||
1804 style != PathStyle::Mod && self.check(&token::ModSep)
1805 && self.look_ahead(1, |t| is_args_start(t)) {
1806 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
1807 // it isn't, then we reset the unmatched angle bracket count as we're about to start
1808 // parsing a new path.
1809 if style == PathStyle::Expr {
1810 self.unmatched_angle_bracket_count = 0;
1811 self.max_angle_bracket_count = 0;
1814 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1815 self.eat(&token::ModSep);
1816 let lo = self.token.span;
1817 let args = if self.eat_lt() {
1819 let (args, constraints) =
1820 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
1822 let span = lo.to(self.prev_span);
1823 AngleBracketedArgs { args, constraints, span }.into()
1826 let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?;
1827 let span = lo.to(self.prev_span);
1828 let output = if self.eat(&token::RArrow) {
1829 Some(self.parse_ty_common(false, false, false)?)
1833 ParenthesizedArgs { inputs, output, span }.into()
1836 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
1838 // Generic arguments are not found.
1839 PathSegment::from_ident(ident)
1843 crate fn check_lifetime(&mut self) -> bool {
1844 self.expected_tokens.push(TokenType::Lifetime);
1845 self.token.is_lifetime()
1848 /// Parses a single lifetime `'a` or panics.
1849 crate fn expect_lifetime(&mut self) -> Lifetime {
1850 if let Some(ident) = self.token.lifetime() {
1851 let span = self.token.span;
1853 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
1855 self.span_bug(self.token.span, "not a lifetime")
1859 fn eat_label(&mut self) -> Option<Label> {
1860 if let Some(ident) = self.token.lifetime() {
1861 let span = self.token.span;
1863 Some(Label { ident: Ident::new(ident.name, span) })
1869 /// Parses mutability (`mut` or nothing).
1870 fn parse_mutability(&mut self) -> Mutability {
1871 if self.eat_keyword(kw::Mut) {
1874 Mutability::Immutable
1878 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1879 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1881 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1883 Ok(Ident::new(symbol, self.prev_span))
1885 self.parse_ident_common(false)
1889 /// Parse ident (COLON expr)?
1890 fn parse_field(&mut self) -> PResult<'a, Field> {
1891 let attrs = self.parse_outer_attributes()?;
1892 let lo = self.token.span;
1894 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1895 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1896 t == &token::Colon || t == &token::Eq
1898 let fieldname = self.parse_field_name()?;
1900 // Check for an equals token. This means the source incorrectly attempts to
1901 // initialize a field with an eq rather than a colon.
1902 if self.token == token::Eq {
1904 .struct_span_err(self.token.span, "expected `:`, found `=`")
1906 fieldname.span.shrink_to_hi().to(self.token.span),
1907 "replace equals symbol with a colon",
1909 Applicability::MachineApplicable,
1914 (fieldname, self.parse_expr()?, false)
1916 let fieldname = self.parse_ident_common(false)?;
1918 // Mimic `x: x` for the `x` field shorthand.
1919 let path = ast::Path::from_ident(fieldname);
1920 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1921 (fieldname, expr, true)
1925 span: lo.to(expr.span),
1928 attrs: attrs.into(),
1932 crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1933 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
1936 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1937 ExprKind::Unary(unop, expr)
1940 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1941 ExprKind::Binary(binop, lhs, rhs)
1944 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1945 ExprKind::Call(f, args)
1948 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1949 ExprKind::Index(expr, idx)
1953 start: Option<P<Expr>>,
1954 end: Option<P<Expr>>,
1955 limits: RangeLimits)
1956 -> PResult<'a, ast::ExprKind> {
1957 if end.is_none() && limits == RangeLimits::Closed {
1958 Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
1960 Ok(ExprKind::Range(start, end, limits))
1964 fn mk_assign_op(&self, binop: ast::BinOp,
1965 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1966 ExprKind::AssignOp(binop, lhs, rhs)
1969 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
1970 let delim = match self.token.kind {
1971 token::OpenDelim(delim) => delim,
1973 let msg = "expected open delimiter";
1974 let mut err = self.fatal(msg);
1975 err.span_label(self.token.span, msg);
1979 let tts = match self.parse_token_tree() {
1980 TokenTree::Delimited(_, _, tts) => tts,
1981 _ => unreachable!(),
1983 let delim = match delim {
1984 token::Paren => MacDelimiter::Parenthesis,
1985 token::Bracket => MacDelimiter::Bracket,
1986 token::Brace => MacDelimiter::Brace,
1987 token::NoDelim => self.bug("unexpected no delimiter"),
1989 Ok((delim, tts.into()))
1992 /// At the bottom (top?) of the precedence hierarchy,
1993 /// Parses things like parenthesized exprs, macros, `return`, etc.
1995 /// N.B., this does not parse outer attributes, and is private because it only works
1996 /// correctly if called from `parse_dot_or_call_expr()`.
1997 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1998 maybe_recover_from_interpolated_ty_qpath!(self, true);
1999 maybe_whole_expr!(self);
2001 // Outer attributes are already parsed and will be
2002 // added to the return value after the fact.
2004 // Therefore, prevent sub-parser from parsing
2005 // attributes by giving them a empty "already parsed" list.
2006 let mut attrs = ThinVec::new();
2008 let lo = self.token.span;
2009 let mut hi = self.token.span;
2013 macro_rules! parse_lit {
2015 match self.parse_lit() {
2017 hi = self.prev_span;
2018 ex = ExprKind::Lit(literal);
2021 self.cancel(&mut err);
2022 return Err(self.expected_expression_found());
2028 // Note: when adding new syntax here, don't forget to adjust TokenKind::can_begin_expr().
2029 match self.token.kind {
2030 // This match arm is a special-case of the `_` match arm below and
2031 // could be removed without changing functionality, but it's faster
2032 // to have it here, especially for programs with large constants.
2033 token::Literal(_) => {
2036 token::OpenDelim(token::Paren) => {
2039 attrs.extend(self.parse_inner_attributes()?);
2041 // (e) is parenthesized e
2042 // (e,) is a tuple with only one field, e
2043 let mut es = vec![];
2044 let mut trailing_comma = false;
2045 let mut recovered = false;
2046 while self.token != token::CloseDelim(token::Paren) {
2047 es.push(match self.parse_expr() {
2050 // recover from parse error in tuple list
2051 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2054 recovered = self.expect_one_of(
2056 &[token::Comma, token::CloseDelim(token::Paren)],
2058 if self.eat(&token::Comma) {
2059 trailing_comma = true;
2061 trailing_comma = false;
2069 hi = self.prev_span;
2070 ex = if es.len() == 1 && !trailing_comma {
2071 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2076 token::OpenDelim(token::Brace) => {
2077 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2079 token::BinOp(token::Or) | token::OrOr => {
2080 return self.parse_lambda_expr(attrs);
2082 token::OpenDelim(token::Bracket) => {
2085 attrs.extend(self.parse_inner_attributes()?);
2087 if self.eat(&token::CloseDelim(token::Bracket)) {
2089 ex = ExprKind::Array(Vec::new());
2092 let first_expr = self.parse_expr()?;
2093 if self.eat(&token::Semi) {
2094 // Repeating array syntax: [ 0; 512 ]
2095 let count = AnonConst {
2096 id: ast::DUMMY_NODE_ID,
2097 value: self.parse_expr()?,
2099 self.expect(&token::CloseDelim(token::Bracket))?;
2100 ex = ExprKind::Repeat(first_expr, count);
2101 } else if self.eat(&token::Comma) {
2102 // Vector with two or more elements.
2103 let remaining_exprs = self.parse_seq_to_end(
2104 &token::CloseDelim(token::Bracket),
2105 SeqSep::trailing_allowed(token::Comma),
2106 |p| Ok(p.parse_expr()?)
2108 let mut exprs = vec![first_expr];
2109 exprs.extend(remaining_exprs);
2110 ex = ExprKind::Array(exprs);
2112 // Vector with one element.
2113 self.expect(&token::CloseDelim(token::Bracket))?;
2114 ex = ExprKind::Array(vec![first_expr]);
2117 hi = self.prev_span;
2121 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2123 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2125 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
2126 return self.parse_lambda_expr(attrs);
2128 if self.eat_keyword(kw::If) {
2129 return self.parse_if_expr(attrs);
2131 if self.eat_keyword(kw::For) {
2132 let lo = self.prev_span;
2133 return self.parse_for_expr(None, lo, attrs);
2135 if self.eat_keyword(kw::While) {
2136 let lo = self.prev_span;
2137 return self.parse_while_expr(None, lo, attrs);
2139 if let Some(label) = self.eat_label() {
2140 let lo = label.ident.span;
2141 self.expect(&token::Colon)?;
2142 if self.eat_keyword(kw::While) {
2143 return self.parse_while_expr(Some(label), lo, attrs)
2145 if self.eat_keyword(kw::For) {
2146 return self.parse_for_expr(Some(label), lo, attrs)
2148 if self.eat_keyword(kw::Loop) {
2149 return self.parse_loop_expr(Some(label), lo, attrs)
2151 if self.token == token::OpenDelim(token::Brace) {
2152 return self.parse_block_expr(Some(label),
2154 BlockCheckMode::Default,
2157 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2158 let mut err = self.fatal(msg);
2159 err.span_label(self.token.span, msg);
2162 if self.eat_keyword(kw::Loop) {
2163 let lo = self.prev_span;
2164 return self.parse_loop_expr(None, lo, attrs);
2166 if self.eat_keyword(kw::Continue) {
2167 let label = self.eat_label();
2168 let ex = ExprKind::Continue(label);
2169 let hi = self.prev_span;
2170 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2172 if self.eat_keyword(kw::Match) {
2173 let match_sp = self.prev_span;
2174 return self.parse_match_expr(attrs).map_err(|mut err| {
2175 err.span_label(match_sp, "while parsing this match expression");
2179 if self.eat_keyword(kw::Unsafe) {
2180 return self.parse_block_expr(
2183 BlockCheckMode::Unsafe(ast::UserProvided),
2186 if self.is_do_catch_block() {
2187 let mut db = self.fatal("found removed `do catch` syntax");
2188 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2191 if self.is_try_block() {
2192 let lo = self.token.span;
2193 assert!(self.eat_keyword(kw::Try));
2194 return self.parse_try_block(lo, attrs);
2197 // Span::rust_2018() is somewhat expensive; don't get it repeatedly.
2198 let is_span_rust_2018 = self.token.span.rust_2018();
2199 if is_span_rust_2018 && self.check_keyword(kw::Async) {
2200 return if self.is_async_block() { // check for `async {` and `async move {`
2201 self.parse_async_block(attrs)
2203 self.parse_lambda_expr(attrs)
2206 if self.eat_keyword(kw::Return) {
2207 if self.token.can_begin_expr() {
2208 let e = self.parse_expr()?;
2210 ex = ExprKind::Ret(Some(e));
2212 ex = ExprKind::Ret(None);
2214 } else if self.eat_keyword(kw::Break) {
2215 let label = self.eat_label();
2216 let e = if self.token.can_begin_expr()
2217 && !(self.token == token::OpenDelim(token::Brace)
2218 && self.restrictions.contains(
2219 Restrictions::NO_STRUCT_LITERAL)) {
2220 Some(self.parse_expr()?)
2224 ex = ExprKind::Break(label, e);
2225 hi = self.prev_span;
2226 } else if self.eat_keyword(kw::Yield) {
2227 if self.token.can_begin_expr() {
2228 let e = self.parse_expr()?;
2230 ex = ExprKind::Yield(Some(e));
2232 ex = ExprKind::Yield(None);
2234 } else if self.eat_keyword(kw::Let) {
2235 return self.parse_let_expr(attrs);
2236 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
2237 let (await_hi, e_kind) = self.parse_await_macro_or_alt(lo, self.prev_span)?;
2240 } else if self.token.is_path_start() {
2241 let path = self.parse_path(PathStyle::Expr)?;
2243 // `!`, as an operator, is prefix, so we know this isn't that
2244 if self.eat(&token::Not) {
2245 // MACRO INVOCATION expression
2246 let (delim, tts) = self.expect_delimited_token_tree()?;
2247 hi = self.prev_span;
2248 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2249 } else if self.check(&token::OpenDelim(token::Brace)) {
2250 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2254 ex = ExprKind::Path(None, path);
2258 ex = ExprKind::Path(None, path);
2261 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2262 // Don't complain about bare semicolons after unclosed braces
2263 // recovery in order to keep the error count down. Fixing the
2264 // delimiters will possibly also fix the bare semicolon found in
2265 // expression context. For example, silence the following error:
2267 // error: expected expression, found `;`
2271 // | ^ expected expression
2274 return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()));
2281 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2282 self.maybe_recover_from_bad_qpath(expr, true)
2285 /// Parse `await!(<expr>)` calls, or alternatively recover from incorrect but reasonable
2286 /// alternative syntaxes `await <expr>`, `await? <expr>`, `await(<expr>)` and
2287 /// `await { <expr> }`.
2288 fn parse_await_macro_or_alt(
2292 ) -> PResult<'a, (Span, ExprKind)> {
2293 if self.token == token::Not {
2294 // Handle correct `await!(<expr>)`.
2295 // FIXME: make this an error when `await!` is no longer supported
2296 // https://github.com/rust-lang/rust/issues/60610
2297 self.expect(&token::Not)?;
2298 self.expect(&token::OpenDelim(token::Paren))?;
2299 let expr = self.parse_expr().map_err(|mut err| {
2300 err.span_label(await_sp, "while parsing this await macro call");
2303 self.expect(&token::CloseDelim(token::Paren))?;
2304 Ok((self.prev_span, ExprKind::Await(ast::AwaitOrigin::MacroLike, expr)))
2305 } else { // Handle `await <expr>`.
2306 self.parse_incorrect_await_syntax(lo, await_sp)
2310 fn maybe_parse_struct_expr(
2314 attrs: &ThinVec<Attribute>,
2315 ) -> Option<PResult<'a, P<Expr>>> {
2316 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2317 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2318 // `{ ident, ` cannot start a block
2319 self.look_ahead(2, |t| t == &token::Comma) ||
2320 self.look_ahead(2, |t| t == &token::Colon) && (
2321 // `{ ident: token, ` cannot start a block
2322 self.look_ahead(4, |t| t == &token::Comma) ||
2323 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2324 self.look_ahead(3, |t| !t.can_begin_type())
2328 if struct_allowed || certainly_not_a_block() {
2329 // This is a struct literal, but we don't can't accept them here
2330 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2331 if let (Ok(expr), false) = (&expr, struct_allowed) {
2332 self.struct_span_err(
2334 "struct literals are not allowed here",
2336 .multipart_suggestion(
2337 "surround the struct literal with parentheses",
2339 (lo.shrink_to_lo(), "(".to_string()),
2340 (expr.span.shrink_to_hi(), ")".to_string()),
2342 Applicability::MachineApplicable,
2351 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2352 -> PResult<'a, P<Expr>> {
2353 let struct_sp = lo.to(self.prev_span);
2355 let mut fields = Vec::new();
2356 let mut base = None;
2358 attrs.extend(self.parse_inner_attributes()?);
2360 while self.token != token::CloseDelim(token::Brace) {
2361 if self.eat(&token::DotDot) {
2362 let exp_span = self.prev_span;
2363 match self.parse_expr() {
2369 self.recover_stmt();
2372 if self.token == token::Comma {
2373 self.struct_span_err(
2374 exp_span.to(self.prev_span),
2375 "cannot use a comma after the base struct",
2377 .span_suggestion_short(
2379 "remove this comma",
2381 Applicability::MachineApplicable
2383 .note("the base struct must always be the last field")
2385 self.recover_stmt();
2390 let mut recovery_field = None;
2391 if let token::Ident(name, _) = self.token.kind {
2392 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2393 // Use in case of error after field-looking code: `S { foo: () with a }`
2394 recovery_field = Some(ast::Field {
2395 ident: Ident::new(name, self.token.span),
2396 span: self.token.span,
2397 expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
2398 is_shorthand: false,
2399 attrs: ThinVec::new(),
2403 let mut parsed_field = None;
2404 match self.parse_field() {
2405 Ok(f) => parsed_field = Some(f),
2407 e.span_label(struct_sp, "while parsing this struct");
2410 // If the next token is a comma, then try to parse
2411 // what comes next as additional fields, rather than
2412 // bailing out until next `}`.
2413 if self.token != token::Comma {
2414 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2415 if self.token != token::Comma {
2422 match self.expect_one_of(&[token::Comma],
2423 &[token::CloseDelim(token::Brace)]) {
2424 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2425 // only include the field if there's no parse error for the field name
2429 if let Some(f) = recovery_field {
2432 e.span_label(struct_sp, "while parsing this struct");
2434 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2435 self.eat(&token::Comma);
2440 let span = lo.to(self.token.span);
2441 self.expect(&token::CloseDelim(token::Brace))?;
2442 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2445 fn parse_or_use_outer_attributes(&mut self,
2446 already_parsed_attrs: Option<ThinVec<Attribute>>)
2447 -> PResult<'a, ThinVec<Attribute>> {
2448 if let Some(attrs) = already_parsed_attrs {
2451 self.parse_outer_attributes().map(|a| a.into())
2455 /// Parses a block or unsafe block.
2456 crate fn parse_block_expr(
2458 opt_label: Option<Label>,
2460 blk_mode: BlockCheckMode,
2461 outer_attrs: ThinVec<Attribute>,
2462 ) -> PResult<'a, P<Expr>> {
2463 self.expect(&token::OpenDelim(token::Brace))?;
2465 let mut attrs = outer_attrs;
2466 attrs.extend(self.parse_inner_attributes()?);
2468 let blk = self.parse_block_tail(lo, blk_mode)?;
2469 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2472 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2473 fn parse_dot_or_call_expr(&mut self,
2474 already_parsed_attrs: Option<ThinVec<Attribute>>)
2475 -> PResult<'a, P<Expr>> {
2476 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2478 let b = self.parse_bottom_expr();
2479 let (span, b) = self.interpolated_or_expr_span(b)?;
2480 self.parse_dot_or_call_expr_with(b, span, attrs)
2483 fn parse_dot_or_call_expr_with(&mut self,
2486 mut attrs: ThinVec<Attribute>)
2487 -> PResult<'a, P<Expr>> {
2488 // Stitch the list of outer attributes onto the return value.
2489 // A little bit ugly, but the best way given the current code
2491 self.parse_dot_or_call_expr_with_(e0, lo)
2493 expr.map(|mut expr| {
2494 attrs.extend::<Vec<_>>(expr.attrs.into());
2497 ExprKind::If(..) if !expr.attrs.is_empty() => {
2498 // Just point to the first attribute in there...
2499 let span = expr.attrs[0].span;
2502 "attributes are not yet allowed on `if` \
2512 // Assuming we have just parsed `.`, continue parsing into an expression.
2513 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2514 if self.token.span.rust_2018() && self.eat_keyword(kw::Await) {
2515 let span = lo.to(self.prev_span);
2516 let await_expr = self.mk_expr(
2518 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
2521 self.recover_from_await_method_call();
2522 return Ok(await_expr);
2524 let segment = self.parse_path_segment(PathStyle::Expr)?;
2525 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2527 Ok(match self.token.kind {
2528 token::OpenDelim(token::Paren) => {
2529 // Method call `expr.f()`
2530 let mut args = self.parse_paren_expr_seq()?;
2531 args.insert(0, self_arg);
2533 let span = lo.to(self.prev_span);
2534 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2537 // Field access `expr.f`
2538 if let Some(args) = segment.args {
2539 self.span_err(args.span(),
2540 "field expressions may not have generic arguments");
2543 let span = lo.to(self.prev_span);
2544 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2549 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2554 while self.eat(&token::Question) {
2555 let hi = self.prev_span;
2556 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2560 if self.eat(&token::Dot) {
2561 match self.token.kind {
2562 token::Ident(..) => {
2563 e = self.parse_dot_suffix(e, lo)?;
2565 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
2566 let span = self.token.span;
2568 let field = ExprKind::Field(e, Ident::new(symbol, span));
2569 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2571 self.expect_no_suffix(span, "a tuple index", suffix);
2573 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
2575 let fstr = symbol.as_str();
2576 let msg = format!("unexpected token: `{}`", symbol);
2577 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
2578 err.span_label(self.prev_span, "unexpected token");
2579 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2580 let float = match fstr.parse::<f64>().ok() {
2584 let sugg = pprust::to_string(|s| {
2588 s.print_usize(float.trunc() as usize);
2591 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2593 err.span_suggestion(
2594 lo.to(self.prev_span),
2595 "try parenthesizing the first index",
2597 Applicability::MachineApplicable
2604 // FIXME Could factor this out into non_fatal_unexpected or something.
2605 let actual = self.this_token_to_string();
2606 self.span_err(self.token.span, &format!("unexpected token: `{}`", actual));
2611 if self.expr_is_complete(&e) { break; }
2612 match self.token.kind {
2614 token::OpenDelim(token::Paren) => {
2615 let seq = self.parse_paren_expr_seq().map(|es| {
2616 let nd = self.mk_call(e, es);
2617 let hi = self.prev_span;
2618 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2620 e = self.recover_seq_parse_error(token::Paren, lo, seq);
2624 // Could be either an index expression or a slicing expression.
2625 token::OpenDelim(token::Bracket) => {
2627 let ix = self.parse_expr()?;
2628 hi = self.token.span;
2629 self.expect(&token::CloseDelim(token::Bracket))?;
2630 let index = self.mk_index(e, ix);
2631 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2639 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
2640 self.parse_paren_comma_seq(|p| p.parse_expr()).map(|(r, _)| r)
2643 crate fn process_potential_macro_variable(&mut self) {
2644 self.token = match self.token.kind {
2645 token::Dollar if self.token.span.ctxt() != SyntaxContext::empty() &&
2646 self.look_ahead(1, |t| t.is_ident()) => {
2648 let name = match self.token.kind {
2649 token::Ident(name, _) => name,
2652 let span = self.prev_span.to(self.token.span);
2654 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
2655 .span_label(span, "unknown macro variable")
2660 token::Interpolated(ref nt) => {
2661 self.meta_var_span = Some(self.token.span);
2662 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2663 // and lifetime tokens, so the former are never encountered during normal parsing.
2665 token::NtIdent(ident, is_raw) =>
2666 Token::new(token::Ident(ident.name, is_raw), ident.span),
2667 token::NtLifetime(ident) =>
2668 Token::new(token::Lifetime(ident.name), ident.span),
2676 /// Parses a single token tree from the input.
2677 crate fn parse_token_tree(&mut self) -> TokenTree {
2678 match self.token.kind {
2679 token::OpenDelim(..) => {
2680 let frame = mem::replace(&mut self.token_cursor.frame,
2681 self.token_cursor.stack.pop().unwrap());
2682 self.token.span = frame.span.entire();
2684 TokenTree::Delimited(
2687 frame.tree_cursor.stream.into(),
2690 token::CloseDelim(_) | token::Eof => unreachable!(),
2692 let token = self.token.take();
2694 TokenTree::Token(token)
2699 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
2700 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2701 let mut tts = Vec::new();
2702 while self.token != token::Eof {
2703 tts.push(self.parse_token_tree());
2708 pub fn parse_tokens(&mut self) -> TokenStream {
2709 let mut result = Vec::new();
2711 match self.token.kind {
2712 token::Eof | token::CloseDelim(..) => break,
2713 _ => result.push(self.parse_token_tree().into()),
2716 TokenStream::new(result)
2719 /// Parse a prefix-unary-operator expr
2720 fn parse_prefix_expr(&mut self,
2721 already_parsed_attrs: Option<ThinVec<Attribute>>)
2722 -> PResult<'a, P<Expr>> {
2723 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2724 let lo = self.token.span;
2725 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
2726 let (hi, ex) = match self.token.kind {
2729 let e = self.parse_prefix_expr(None);
2730 let (span, e) = self.interpolated_or_expr_span(e)?;
2731 (lo.to(span), self.mk_unary(UnOp::Not, e))
2733 // Suggest `!` for bitwise negation when encountering a `~`
2736 let e = self.parse_prefix_expr(None);
2737 let (span, e) = self.interpolated_or_expr_span(e)?;
2738 let span_of_tilde = lo;
2739 self.struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator")
2740 .span_suggestion_short(
2742 "use `!` to perform bitwise negation",
2744 Applicability::MachineApplicable
2747 (lo.to(span), self.mk_unary(UnOp::Not, e))
2749 token::BinOp(token::Minus) => {
2751 let e = self.parse_prefix_expr(None);
2752 let (span, e) = self.interpolated_or_expr_span(e)?;
2753 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2755 token::BinOp(token::Star) => {
2757 let e = self.parse_prefix_expr(None);
2758 let (span, e) = self.interpolated_or_expr_span(e)?;
2759 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2761 token::BinOp(token::And) | token::AndAnd => {
2763 let m = self.parse_mutability();
2764 let e = self.parse_prefix_expr(None);
2765 let (span, e) = self.interpolated_or_expr_span(e)?;
2766 (lo.to(span), ExprKind::AddrOf(m, e))
2768 token::Ident(..) if self.token.is_keyword(kw::Box) => {
2770 let e = self.parse_prefix_expr(None);
2771 let (span, e) = self.interpolated_or_expr_span(e)?;
2772 (lo.to(span), ExprKind::Box(e))
2774 token::Ident(..) if self.token.is_ident_named(sym::not) => {
2775 // `not` is just an ordinary identifier in Rust-the-language,
2776 // but as `rustc`-the-compiler, we can issue clever diagnostics
2777 // for confused users who really want to say `!`
2778 let token_cannot_continue_expr = |t: &Token| match t.kind {
2779 // These tokens can start an expression after `!`, but
2780 // can't continue an expression after an ident
2781 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
2782 token::Literal(..) | token::Pound => true,
2783 token::Interpolated(ref nt) => match **nt {
2784 token::NtIdent(..) | token::NtExpr(..) |
2785 token::NtBlock(..) | token::NtPath(..) => true,
2790 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2791 if cannot_continue_expr {
2793 // Emit the error ...
2794 self.struct_span_err(
2796 &format!("unexpected {} after identifier",self.this_token_descr())
2798 .span_suggestion_short(
2799 // Span the `not` plus trailing whitespace to avoid
2800 // trailing whitespace after the `!` in our suggestion
2801 self.sess.source_map()
2802 .span_until_non_whitespace(lo.to(self.token.span)),
2803 "use `!` to perform logical negation",
2805 Applicability::MachineApplicable
2808 // —and recover! (just as if we were in the block
2809 // for the `token::Not` arm)
2810 let e = self.parse_prefix_expr(None);
2811 let (span, e) = self.interpolated_or_expr_span(e)?;
2812 (lo.to(span), self.mk_unary(UnOp::Not, e))
2814 return self.parse_dot_or_call_expr(Some(attrs));
2817 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2819 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2822 /// Parses an associative expression.
2824 /// This parses an expression accounting for associativity and precedence of the operators in
2827 fn parse_assoc_expr(&mut self,
2828 already_parsed_attrs: Option<ThinVec<Attribute>>)
2829 -> PResult<'a, P<Expr>> {
2830 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2833 /// Parses an associative expression with operators of at least `min_prec` precedence.
2834 fn parse_assoc_expr_with(
2838 ) -> PResult<'a, P<Expr>> {
2839 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2842 let attrs = match lhs {
2843 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2846 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
2847 return self.parse_prefix_range_expr(attrs);
2849 self.parse_prefix_expr(attrs)?
2852 let last_type_ascription_set = self.last_type_ascription.is_some();
2854 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
2856 self.last_type_ascription = None;
2857 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2860 (false, _) => {} // continue parsing the expression
2861 // An exhaustive check is done in the following block, but these are checked first
2862 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
2863 // want to keep their span info to improve diagnostics in these cases in a later stage.
2864 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
2865 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
2866 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
2867 (true, Some(AssocOp::Add)) // `{ 42 } + 42
2868 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
2869 // `if x { a } else { b } && if y { c } else { d }`
2870 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
2871 self.last_type_ascription = None;
2872 // These cases are ambiguous and can't be identified in the parser alone
2873 let sp = self.sess.source_map().start_point(self.token.span);
2874 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
2877 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
2878 self.last_type_ascription = None;
2881 (true, Some(_)) => {
2882 // We've found an expression that would be parsed as a statement, but the next
2883 // token implies this should be parsed as an expression.
2884 // For example: `if let Some(x) = x { x } else { 0 } / 2`
2885 let mut err = self.struct_span_err(self.token.span, &format!(
2886 "expected expression, found `{}`",
2887 pprust::token_to_string(&self.token),
2889 err.span_label(self.token.span, "expected expression");
2890 self.sess.expr_parentheses_needed(
2893 Some(pprust::expr_to_string(&lhs),
2898 self.expected_tokens.push(TokenType::Operator);
2899 while let Some(op) = AssocOp::from_token(&self.token) {
2901 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2902 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2903 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2904 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2905 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2906 (PrevTokenKind::Interpolated, _) => self.prev_span,
2907 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2908 if path.segments.len() == 1 => self.prev_span,
2912 let cur_op_span = self.token.span;
2913 let restrictions = if op.is_assign_like() {
2914 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2918 let prec = op.precedence();
2919 if prec < min_prec {
2922 // Check for deprecated `...` syntax
2923 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2924 self.err_dotdotdot_syntax(self.token.span);
2928 if op.is_comparison() {
2929 self.check_no_chained_comparison(&lhs, &op);
2932 if op == AssocOp::As {
2933 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2935 } else if op == AssocOp::Colon {
2936 let maybe_path = self.could_ascription_be_path(&lhs.node);
2937 self.last_type_ascription = Some((self.prev_span, maybe_path));
2939 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
2941 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2942 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2943 // generalise it to the Fixity::None code.
2945 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2946 // two variants are handled with `parse_prefix_range_expr` call above.
2947 let rhs = if self.is_at_start_of_range_notation_rhs() {
2948 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
2952 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2957 let limits = if op == AssocOp::DotDot {
2958 RangeLimits::HalfOpen
2963 let r = self.mk_range(Some(lhs), rhs, limits)?;
2964 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2968 let fixity = op.fixity();
2969 let prec_adjustment = match fixity {
2972 // We currently have no non-associative operators that are not handled above by
2973 // the special cases. The code is here only for future convenience.
2976 let rhs = self.with_res(
2977 restrictions - Restrictions::STMT_EXPR,
2978 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
2981 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
2982 // including the attributes.
2986 .filter(|a| a.style == AttrStyle::Outer)
2988 .map_or(lhs_span, |a| a.span);
2989 let span = lhs_span.to(rhs.span);
2991 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2992 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2993 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2994 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2995 AssocOp::Greater | AssocOp::GreaterEqual => {
2996 let ast_op = op.to_ast_binop().unwrap();
2997 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
2998 self.mk_expr(span, binary, ThinVec::new())
3000 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3001 AssocOp::AssignOp(k) => {
3003 token::Plus => BinOpKind::Add,
3004 token::Minus => BinOpKind::Sub,
3005 token::Star => BinOpKind::Mul,
3006 token::Slash => BinOpKind::Div,
3007 token::Percent => BinOpKind::Rem,
3008 token::Caret => BinOpKind::BitXor,
3009 token::And => BinOpKind::BitAnd,
3010 token::Or => BinOpKind::BitOr,
3011 token::Shl => BinOpKind::Shl,
3012 token::Shr => BinOpKind::Shr,
3014 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3015 self.mk_expr(span, aopexpr, ThinVec::new())
3017 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3018 self.bug("AssocOp should have been handled by special case")
3022 if let Fixity::None = fixity { break }
3024 if last_type_ascription_set {
3025 self.last_type_ascription = None;
3030 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3031 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3032 -> PResult<'a, P<Expr>> {
3033 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3034 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3037 // Save the state of the parser before parsing type normally, in case there is a
3038 // LessThan comparison after this cast.
3039 let parser_snapshot_before_type = self.clone();
3040 match self.parse_ty_no_plus() {
3042 Ok(mk_expr(self, rhs))
3044 Err(mut type_err) => {
3045 // Rewind to before attempting to parse the type with generics, to recover
3046 // from situations like `x as usize < y` in which we first tried to parse
3047 // `usize < y` as a type with generic arguments.
3048 let parser_snapshot_after_type = self.clone();
3049 mem::replace(self, parser_snapshot_before_type);
3051 match self.parse_path(PathStyle::Expr) {
3053 let (op_noun, op_verb) = match self.token.kind {
3054 token::Lt => ("comparison", "comparing"),
3055 token::BinOp(token::Shl) => ("shift", "shifting"),
3057 // We can end up here even without `<` being the next token, for
3058 // example because `parse_ty_no_plus` returns `Err` on keywords,
3059 // but `parse_path` returns `Ok` on them due to error recovery.
3060 // Return original error and parser state.
3061 mem::replace(self, parser_snapshot_after_type);
3062 return Err(type_err);
3066 // Successfully parsed the type path leaving a `<` yet to parse.
3069 // Report non-fatal diagnostics, keep `x as usize` as an expression
3070 // in AST and continue parsing.
3071 let msg = format!("`<` is interpreted as a start of generic \
3072 arguments for `{}`, not a {}", path, op_noun);
3073 let span_after_type = parser_snapshot_after_type.token.span;
3074 let expr = mk_expr(self, P(Ty {
3076 node: TyKind::Path(None, path),
3077 id: ast::DUMMY_NODE_ID
3080 let expr_str = self.span_to_snippet(expr.span)
3081 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3083 self.struct_span_err(self.token.span, &msg)
3085 self.look_ahead(1, |t| t.span).to(span_after_type),
3086 "interpreted as generic arguments"
3088 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
3091 &format!("try {} the cast value", op_verb),
3092 format!("({})", expr_str),
3093 Applicability::MachineApplicable
3099 Err(mut path_err) => {
3100 // Couldn't parse as a path, return original error and parser state.
3102 mem::replace(self, parser_snapshot_after_type);
3110 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3111 fn parse_prefix_range_expr(&mut self,
3112 already_parsed_attrs: Option<ThinVec<Attribute>>)
3113 -> PResult<'a, P<Expr>> {
3114 // Check for deprecated `...` syntax
3115 if self.token == token::DotDotDot {
3116 self.err_dotdotdot_syntax(self.token.span);
3119 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
3120 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3122 let tok = self.token.clone();
3123 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3124 let lo = self.token.span;
3125 let mut hi = self.token.span;
3127 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3128 // RHS must be parsed with more associativity than the dots.
3129 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3130 Some(self.parse_assoc_expr_with(next_prec,
3131 LhsExpr::NotYetParsed)
3139 let limits = if tok == token::DotDot {
3140 RangeLimits::HalfOpen
3145 let r = self.mk_range(None, opt_end, limits)?;
3146 Ok(self.mk_expr(lo.to(hi), r, attrs))
3149 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3150 if self.token.can_begin_expr() {
3151 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3152 if self.token == token::OpenDelim(token::Brace) {
3153 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3161 /// Parses an `if` expression (`if` token already eaten).
3162 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3163 let lo = self.prev_span;
3164 let cond = self.parse_cond_expr()?;
3166 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3167 // verify that the last statement is either an implicit return (no `;`) or an explicit
3168 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3169 // the dead code lint.
3170 if self.eat_keyword(kw::Else) || !cond.returns() {
3171 let sp = self.sess.source_map().next_point(lo);
3172 let mut err = self.diagnostic()
3173 .struct_span_err(sp, "missing condition for `if` statemement");
3174 err.span_label(sp, "expected if condition here");
3177 let not_block = self.token != token::OpenDelim(token::Brace);
3178 let thn = self.parse_block().map_err(|mut err| {
3180 err.span_label(lo, "this `if` statement has a condition, but no block");
3184 let mut els: Option<P<Expr>> = None;
3185 let mut hi = thn.span;
3186 if self.eat_keyword(kw::Else) {
3187 let elexpr = self.parse_else_expr()?;
3191 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3194 /// Parse the condition of a `if`- or `while`-expression
3195 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
3196 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3198 if let ExprKind::Let(..) = cond.node {
3199 // Remove the last feature gating of a `let` expression since it's stable.
3200 let last = self.sess.let_chains_spans.borrow_mut().pop();
3201 debug_assert_eq!(cond.span, last.unwrap());
3207 /// Parses a `let $pats = $expr` pseudo-expression.
3208 /// The `let` token has already been eaten.
3209 fn parse_let_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3210 let lo = self.prev_span;
3211 let pats = self.parse_pats()?;
3212 self.expect(&token::Eq)?;
3213 let expr = self.with_res(
3214 Restrictions::NO_STRUCT_LITERAL,
3215 |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
3217 let span = lo.to(expr.span);
3218 self.sess.let_chains_spans.borrow_mut().push(span);
3219 Ok(self.mk_expr(span, ExprKind::Let(pats, expr), attrs))
3222 /// Parses `move |args| expr`.
3223 fn parse_lambda_expr(&mut self,
3224 attrs: ThinVec<Attribute>)
3225 -> PResult<'a, P<Expr>>
3227 let lo = self.token.span;
3229 let movability = if self.eat_keyword(kw::Static) {
3235 let asyncness = if self.token.span.rust_2018() {
3236 self.parse_asyncness()
3240 if asyncness.is_async() {
3241 // Feature gate `async ||` closures.
3242 self.sess.async_closure_spans.borrow_mut().push(self.prev_span);
3245 let capture_clause = self.parse_capture_clause();
3246 let decl = self.parse_fn_block_decl()?;
3247 let decl_hi = self.prev_span;
3248 let body = match decl.output {
3249 FunctionRetTy::Default(_) => {
3250 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3251 self.parse_expr_res(restrictions, None)?
3254 // If an explicit return type is given, require a
3255 // block to appear (RFC 968).
3256 let body_lo = self.token.span;
3257 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3263 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3267 /// `else` token already eaten
3268 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3269 if self.eat_keyword(kw::If) {
3270 return self.parse_if_expr(ThinVec::new());
3272 let blk = self.parse_block()?;
3273 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3277 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3280 opt_label: Option<Label>,
3282 mut attrs: ThinVec<Attribute>
3283 ) -> PResult<'a, P<Expr>> {
3284 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3286 // Record whether we are about to parse `for (`.
3287 // This is used below for recovery in case of `for ( $stuff ) $block`
3288 // in which case we will suggest `for $stuff $block`.
3289 let begin_paren = match self.token.kind {
3290 token::OpenDelim(token::Paren) => Some(self.token.span),
3294 let pat = self.parse_top_level_pat()?;
3295 if !self.eat_keyword(kw::In) {
3296 let in_span = self.prev_span.between(self.token.span);
3297 self.struct_span_err(in_span, "missing `in` in `for` loop")
3298 .span_suggestion_short(
3300 "try adding `in` here", " in ".into(),
3301 // has been misleading, at least in the past (closed Issue #48492)
3302 Applicability::MaybeIncorrect
3306 let in_span = self.prev_span;
3307 self.check_for_for_in_in_typo(in_span);
3308 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3310 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
3312 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3313 attrs.extend(iattrs);
3315 let hi = self.prev_span;
3316 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3319 /// Parses a `while` or `while let` expression (`while` token already eaten).
3320 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3322 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3323 let cond = self.parse_cond_expr()?;
3324 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3325 attrs.extend(iattrs);
3326 let span = span_lo.to(body.span);
3327 Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs))
3330 /// Parse `loop {...}`, `loop` token already eaten.
3331 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3333 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3334 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3335 attrs.extend(iattrs);
3336 let span = span_lo.to(body.span);
3337 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3340 /// Parse an optional `move` prefix to a closure lke construct.
3341 fn parse_capture_clause(&mut self) -> CaptureBy {
3342 if self.eat_keyword(kw::Move) {
3349 /// Parses an `async move? {...}` expression.
3350 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3351 let span_lo = self.token.span;
3352 self.expect_keyword(kw::Async)?;
3353 let capture_clause = self.parse_capture_clause();
3354 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3355 attrs.extend(iattrs);
3357 span_lo.to(body.span),
3358 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3361 /// Parses a `try {...}` expression (`try` token already eaten).
3362 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3363 -> PResult<'a, P<Expr>>
3365 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3366 attrs.extend(iattrs);
3367 if self.eat_keyword(kw::Catch) {
3368 let mut error = self.struct_span_err(self.prev_span,
3369 "keyword `catch` cannot follow a `try` block");
3370 error.help("try using `match` on the result of the `try` block instead");
3374 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3378 // `match` token already eaten
3379 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3380 let match_span = self.prev_span;
3381 let lo = self.prev_span;
3382 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3384 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3385 if self.token == token::Semi {
3386 e.span_suggestion_short(
3388 "try removing this `match`",
3390 Applicability::MaybeIncorrect // speculative
3395 attrs.extend(self.parse_inner_attributes()?);
3397 let mut arms: Vec<Arm> = Vec::new();
3398 while self.token != token::CloseDelim(token::Brace) {
3399 match self.parse_arm() {
3400 Ok(arm) => arms.push(arm),
3402 // Recover by skipping to the end of the block.
3404 self.recover_stmt();
3405 let span = lo.to(self.token.span);
3406 if self.token == token::CloseDelim(token::Brace) {
3409 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3413 let hi = self.token.span;
3415 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3418 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3419 let attrs = self.parse_outer_attributes()?;
3420 let lo = self.token.span;
3421 let pats = self.parse_pats()?;
3422 let guard = if self.eat_keyword(kw::If) {
3423 Some(self.parse_expr()?)
3427 let arrow_span = self.token.span;
3428 self.expect(&token::FatArrow)?;
3429 let arm_start_span = self.token.span;
3431 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3432 .map_err(|mut err| {
3433 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3437 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3438 && self.token != token::CloseDelim(token::Brace);
3440 let hi = self.token.span;
3443 let cm = self.sess.source_map();
3444 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3445 .map_err(|mut err| {
3446 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3447 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3448 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3449 && expr_lines.lines.len() == 2
3450 && self.token == token::FatArrow => {
3451 // We check whether there's any trailing code in the parse span,
3452 // if there isn't, we very likely have the following:
3455 // | -- - missing comma
3459 // | - ^^ self.token.span
3461 // | parsed until here as `"y" & X`
3462 err.span_suggestion_short(
3463 cm.next_point(arm_start_span),
3464 "missing a comma here to end this `match` arm",
3466 Applicability::MachineApplicable
3470 err.span_label(arrow_span,
3471 "while parsing the `match` arm starting here");
3477 self.eat(&token::Comma);
3489 /// Parses an expression.
3491 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3492 self.parse_expr_res(Restrictions::empty(), None)
3495 /// Evaluates the closure with restrictions in place.
3497 /// Afters the closure is evaluated, restrictions are reset.
3498 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3499 where F: FnOnce(&mut Self) -> T
3501 let old = self.restrictions;
3502 self.restrictions = r;
3504 self.restrictions = old;
3509 /// Parses an expression, subject to the given restrictions.
3511 fn parse_expr_res(&mut self, r: Restrictions,
3512 already_parsed_attrs: Option<ThinVec<Attribute>>)
3513 -> PResult<'a, P<Expr>> {
3514 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3517 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
3518 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3519 if self.eat(&token::Eq) {
3520 Ok(Some(self.parse_expr()?))
3522 Ok(Some(self.parse_expr()?))
3528 /// Parses patterns, separated by '|' s.
3529 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3530 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
3531 self.eat(&token::BinOp(token::Or));
3533 let mut pats = Vec::new();
3535 pats.push(self.parse_top_level_pat()?);
3537 if self.token == token::OrOr {
3538 self.struct_span_err(self.token.span, "unexpected token `||` after pattern")
3541 "use a single `|` to specify multiple patterns",
3543 Applicability::MachineApplicable
3547 } else if self.eat(&token::BinOp(token::Or)) {
3548 // This is a No-op. Continue the loop to parse the next
3559 attrs: Vec<Attribute>
3560 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3561 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3563 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3564 // Parsing a pattern of the form "fieldname: pat"
3565 let fieldname = self.parse_field_name()?;
3567 let pat = self.parse_pat(None)?;
3569 (pat, fieldname, false)
3571 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3572 let is_box = self.eat_keyword(kw::Box);
3573 let boxed_span = self.token.span;
3574 let is_ref = self.eat_keyword(kw::Ref);
3575 let is_mut = self.eat_keyword(kw::Mut);
3576 let fieldname = self.parse_ident()?;
3577 hi = self.prev_span;
3579 let bind_type = match (is_ref, is_mut) {
3580 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3581 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3582 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3583 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3585 let fieldpat = P(Pat {
3586 id: ast::DUMMY_NODE_ID,
3587 node: PatKind::Ident(bind_type, fieldname, None),
3588 span: boxed_span.to(hi),
3591 let subpat = if is_box {
3593 id: ast::DUMMY_NODE_ID,
3594 node: PatKind::Box(fieldpat),
3600 (subpat, fieldname, true)
3603 Ok(source_map::Spanned {
3605 node: ast::FieldPat {
3609 attrs: attrs.into(),
3614 /// Parses the fields of a struct-like pattern.
3615 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3616 let mut fields = Vec::new();
3617 let mut etc = false;
3618 let mut ate_comma = true;
3619 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3620 let mut etc_span = None;
3622 while self.token != token::CloseDelim(token::Brace) {
3623 let attrs = self.parse_outer_attributes()?;
3624 let lo = self.token.span;
3626 // check that a comma comes after every field
3628 let err = self.struct_span_err(self.prev_span, "expected `,`");
3629 if let Some(mut delayed) = delayed_err {
3636 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3638 let mut etc_sp = self.token.span;
3640 if self.token == token::DotDotDot { // Issue #46718
3641 // Accept `...` as if it were `..` to avoid further errors
3642 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
3645 "to omit remaining fields, use one fewer `.`",
3647 Applicability::MachineApplicable
3651 self.bump(); // `..` || `...`
3653 if self.token == token::CloseDelim(token::Brace) {
3654 etc_span = Some(etc_sp);
3657 let token_str = self.this_token_descr();
3658 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3660 err.span_label(self.token.span, "expected `}`");
3661 let mut comma_sp = None;
3662 if self.token == token::Comma { // Issue #49257
3663 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
3664 etc_sp = etc_sp.to(nw_span);
3665 err.span_label(etc_sp,
3666 "`..` must be at the end and cannot have a trailing comma");
3667 comma_sp = Some(self.token.span);
3672 etc_span = Some(etc_sp.until(self.token.span));
3673 if self.token == token::CloseDelim(token::Brace) {
3674 // If the struct looks otherwise well formed, recover and continue.
3675 if let Some(sp) = comma_sp {
3676 err.span_suggestion_short(
3678 "remove this comma",
3680 Applicability::MachineApplicable,
3685 } else if self.token.is_ident() && ate_comma {
3686 // Accept fields coming after `..,`.
3687 // This way we avoid "pattern missing fields" errors afterwards.
3688 // We delay this error until the end in order to have a span for a
3690 if let Some(mut delayed_err) = delayed_err {
3694 delayed_err = Some(err);
3697 if let Some(mut err) = delayed_err {
3704 fields.push(match self.parse_pat_field(lo, attrs) {
3707 if let Some(mut delayed_err) = delayed_err {
3713 ate_comma = self.eat(&token::Comma);
3716 if let Some(mut err) = delayed_err {
3717 if let Some(etc_span) = etc_span {
3718 err.multipart_suggestion(
3719 "move the `..` to the end of the field list",
3721 (etc_span, String::new()),
3722 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3724 Applicability::MachineApplicable,
3729 return Ok((fields, etc));
3732 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3733 if self.token.is_path_start() {
3734 let lo = self.token.span;
3735 let (qself, path) = if self.eat_lt() {
3736 // Parse a qualified path
3737 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3740 // Parse an unqualified path
3741 (None, self.parse_path(PathStyle::Expr)?)
3743 let hi = self.prev_span;
3744 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3746 self.parse_literal_maybe_minus()
3750 /// Is the current token suitable as the start of a range patterns end?
3751 fn is_pat_range_end_start(&self) -> bool {
3752 self.token.is_path_start() // e.g. `MY_CONST`;
3753 || self.token == token::Dot // e.g. `.5` for recovery;
3754 || self.token.can_begin_literal_or_bool() // e.g. `42`.
3757 // Helper function to decide whether to parse as ident binding
3758 // or to try to do something more complex like range patterns.
3759 fn parse_as_ident(&mut self) -> bool {
3760 self.look_ahead(1, |t| match t.kind {
3761 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3762 token::DotDotDot | token::DotDotEq | token::DotDot |
3763 token::ModSep | token::Not => false,
3768 /// Parse and throw away a parentesized comma separated
3769 /// sequence of patterns until `)` is reached.
3770 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
3771 while !self.check(&token::CloseDelim(token::Paren)) {
3772 self.parse_pat(None)?;
3773 if !self.eat(&token::Comma) {
3780 /// A wrapper around `parse_pat` with some special error handling for the
3781 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3782 /// to subpatterns within such).
3783 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3784 let pat = self.parse_pat(None)?;
3785 if self.token == token::Comma {
3786 // An unexpected comma after a top-level pattern is a clue that the
3787 // user (perhaps more accustomed to some other language) forgot the
3788 // parentheses in what should have been a tuple pattern; return a
3789 // suggestion-enhanced error here rather than choking on the comma
3791 let comma_span = self.token.span;
3793 if let Err(mut err) = self.skip_pat_list() {
3794 // We didn't expect this to work anyway; we just wanted
3795 // to advance to the end of the comma-sequence so we know
3796 // the span to suggest parenthesizing
3799 let seq_span = pat.span.to(self.prev_span);
3800 let mut err = self.struct_span_err(comma_span,
3801 "unexpected `,` in pattern");
3802 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
3803 err.span_suggestion(
3805 "try adding parentheses to match on a tuple..",
3806 format!("({})", seq_snippet),
3807 Applicability::MachineApplicable
3810 "..or a vertical bar to match on multiple alternatives",
3811 format!("{}", seq_snippet.replace(",", " |")),
3812 Applicability::MachineApplicable
3820 /// Parses a pattern.
3821 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
3822 self.parse_pat_with_range_pat(true, expected)
3825 /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
3826 fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
3827 let lo = self.prev_span;
3828 let end = self.parse_pat_range_end()?;
3829 let range_span = lo.to(end.span);
3830 let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
3833 .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
3836 "try using the minimum value for the type",
3837 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
3838 Applicability::HasPlaceholders,
3842 Ok(PatKind::Range(begin, end, respan(lo, re)))
3845 /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern or recover
3846 /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
3847 fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
3848 if self.is_pat_range_end_start() {
3849 // Parsing e.g. `X..=Y`.
3850 self.parse_pat_range_end()
3852 // Parsing e.g. `X..`.
3853 let range_span = begin.span.to(self.prev_span);
3858 &format!("`X{}` range patterns are not supported", form),
3862 "try using the maximum value for the type",
3863 format!("{}{}MAX", pprust::expr_to_string(&begin), form),
3864 Applicability::HasPlaceholders,
3868 Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
3872 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
3874 fn parse_pat_with_range_pat(
3876 allow_range_pat: bool,
3877 expected: Option<&'static str>,
3878 ) -> PResult<'a, P<Pat>> {
3879 maybe_recover_from_interpolated_ty_qpath!(self, true);
3880 maybe_whole!(self, NtPat, |x| x);
3882 let lo = self.token.span;
3884 match self.token.kind {
3885 token::BinOp(token::And) | token::AndAnd => {
3886 // Parse &pat / &mut pat
3888 let mutbl = self.parse_mutability();
3889 if let token::Lifetime(name) = self.token.kind {
3890 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
3891 err.span_label(self.token.span, "unexpected lifetime");
3894 let subpat = self.parse_pat_with_range_pat(false, expected)?;
3895 pat = PatKind::Ref(subpat, mutbl);
3897 token::OpenDelim(token::Paren) => {
3898 // Parse a tuple or parenthesis pattern.
3899 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| p.parse_pat(None))?;
3901 // Here, `(pat,)` is a tuple pattern.
3902 // For backward compatibility, `(..)` is a tuple pattern as well.
3903 pat = if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
3904 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3906 PatKind::Tuple(fields)
3909 token::OpenDelim(token::Bracket) => {
3910 // Parse `[pat, pat,...]` as a slice pattern.
3911 let (slice, _) = self.parse_delim_comma_seq(token::Bracket, |p| p.parse_pat(None))?;
3912 pat = PatKind::Slice(slice);
3916 pat = if self.is_pat_range_end_start() {
3917 // Parse `..42` for recovery.
3918 self.parse_pat_range_to(RangeEnd::Excluded, "..")?
3920 // A rest pattern `..`.
3924 token::DotDotEq => {
3925 // Parse `..=42` for recovery.
3927 pat = self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?;
3929 token::DotDotDot => {
3930 // Parse `...42` for recovery.
3932 pat = self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?;
3934 // At this point, token != &, &&, (, [
3935 _ => if self.eat_keyword(kw::Underscore) {
3937 pat = PatKind::Wild;
3938 } else if self.eat_keyword(kw::Mut) {
3939 // Parse mut ident @ pat / mut ref ident @ pat
3940 let mutref_span = self.prev_span.to(self.token.span);
3941 let binding_mode = if self.eat_keyword(kw::Ref) {
3943 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3946 "try switching the order",
3948 Applicability::MachineApplicable
3950 BindingMode::ByRef(Mutability::Mutable)
3952 BindingMode::ByValue(Mutability::Mutable)
3954 pat = self.parse_pat_ident(binding_mode)?;
3955 } else if self.eat_keyword(kw::Ref) {
3956 // Parse ref ident @ pat / ref mut ident @ pat
3957 let mutbl = self.parse_mutability();
3958 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3959 } else if self.eat_keyword(kw::Box) {
3961 let subpat = self.parse_pat_with_range_pat(false, None)?;
3962 pat = PatKind::Box(subpat);
3963 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3964 self.parse_as_ident() {
3965 // Parse ident @ pat
3966 // This can give false positives and parse nullary enums,
3967 // they are dealt with later in resolve
3968 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3969 pat = self.parse_pat_ident(binding_mode)?;
3970 } else if self.token.is_path_start() {
3971 // Parse pattern starting with a path
3972 let (qself, path) = if self.eat_lt() {
3973 // Parse a qualified path
3974 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3977 // Parse an unqualified path
3978 (None, self.parse_path(PathStyle::Expr)?)
3980 match self.token.kind {
3981 token::Not if qself.is_none() => {
3982 // Parse macro invocation
3984 let (delim, tts) = self.expect_delimited_token_tree()?;
3985 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
3986 pat = PatKind::Mac(mac);
3988 token::DotDotDot | token::DotDotEq | token::DotDot => {
3989 let (end_kind, form) = match self.token.kind {
3990 token::DotDot => (RangeEnd::Excluded, ".."),
3991 token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
3992 token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
3993 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3996 let op_span = self.token.span;
3998 let span = lo.to(self.prev_span);
3999 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4001 let end = self.parse_pat_range_end_opt(&begin, form)?;
4002 pat = PatKind::Range(begin, end, respan(op_span, end_kind));
4004 token::OpenDelim(token::Brace) => {
4005 if qself.is_some() {
4006 let msg = "unexpected `{` after qualified path";
4007 let mut err = self.fatal(msg);
4008 err.span_label(self.token.span, msg);
4011 // Parse struct pattern
4013 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4015 self.recover_stmt();
4019 pat = PatKind::Struct(path, fields, etc);
4021 token::OpenDelim(token::Paren) => {
4022 if qself.is_some() {
4023 let msg = "unexpected `(` after qualified path";
4024 let mut err = self.fatal(msg);
4025 err.span_label(self.token.span, msg);
4028 // Parse tuple struct or enum pattern
4029 let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat(None))?;
4030 pat = PatKind::TupleStruct(path, fields)
4032 _ => pat = PatKind::Path(qself, path),
4035 // Try to parse everything else as literal with optional minus
4036 match self.parse_literal_maybe_minus() {
4038 let op_span = self.token.span;
4039 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4040 self.check(&token::DotDotDot) {
4041 let (end_kind, form) = if self.eat(&token::DotDotDot) {
4042 (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
4043 } else if self.eat(&token::DotDotEq) {
4044 (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
4045 } else if self.eat(&token::DotDot) {
4046 (RangeEnd::Excluded, "..")
4048 panic!("impossible case: we already matched \
4049 on a range-operator token")
4051 let end = self.parse_pat_range_end_opt(&begin, form)?;
4052 pat = PatKind::Range(begin, end, respan(op_span, end_kind))
4054 pat = PatKind::Lit(begin);
4058 self.cancel(&mut err);
4059 let expected = expected.unwrap_or("pattern");
4061 "expected {}, found {}",
4063 self.this_token_descr(),
4065 let mut err = self.fatal(&msg);
4066 err.span_label(self.token.span, format!("expected {}", expected));
4067 let sp = self.sess.source_map().start_point(self.token.span);
4068 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4069 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4077 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4078 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4080 if !allow_range_pat {
4083 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4085 PatKind::Range(..) => {
4086 let mut err = self.struct_span_err(
4088 "the range pattern here has ambiguous interpretation",
4090 err.span_suggestion(
4092 "add parentheses to clarify the precedence",
4093 format!("({})", pprust::pat_to_string(&pat)),
4094 // "ambiguous interpretation" implies that we have to be guessing
4095 Applicability::MaybeIncorrect
4106 /// Parses `ident` or `ident @ pat`.
4107 /// used by the copy foo and ref foo patterns to give a good
4108 /// error message when parsing mistakes like `ref foo(a, b)`.
4109 fn parse_pat_ident(&mut self,
4110 binding_mode: ast::BindingMode)
4111 -> PResult<'a, PatKind> {
4112 let ident = self.parse_ident()?;
4113 let sub = if self.eat(&token::At) {
4114 Some(self.parse_pat(Some("binding pattern"))?)
4119 // just to be friendly, if they write something like
4121 // we end up here with ( as the current token. This shortly
4122 // leads to a parse error. Note that if there is no explicit
4123 // binding mode then we do not end up here, because the lookahead
4124 // will direct us over to parse_enum_variant()
4125 if self.token == token::OpenDelim(token::Paren) {
4126 return Err(self.span_fatal(
4128 "expected identifier, found enum pattern"))
4131 Ok(PatKind::Ident(binding_mode, ident, sub))
4134 /// Parses a local variable declaration.
4135 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4136 let lo = self.prev_span;
4137 let pat = self.parse_top_level_pat()?;
4139 let (err, ty) = if self.eat(&token::Colon) {
4140 // Save the state of the parser before parsing type normally, in case there is a `:`
4141 // instead of an `=` typo.
4142 let parser_snapshot_before_type = self.clone();
4143 let colon_sp = self.prev_span;
4144 match self.parse_ty() {
4145 Ok(ty) => (None, Some(ty)),
4147 // Rewind to before attempting to parse the type and continue parsing
4148 let parser_snapshot_after_type = self.clone();
4149 mem::replace(self, parser_snapshot_before_type);
4151 let snippet = self.span_to_snippet(pat.span).unwrap();
4152 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4153 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4159 let init = match (self.parse_initializer(err.is_some()), err) {
4160 (Ok(init), None) => { // init parsed, ty parsed
4163 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4164 // Could parse the type as if it were the initializer, it is likely there was a
4165 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4166 err.span_suggestion_short(
4168 "use `=` if you meant to assign",
4170 Applicability::MachineApplicable
4173 // As this was parsed successfully, continue as if the code has been fixed for the
4174 // rest of the file. It will still fail due to the emitted error, but we avoid
4178 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4180 // Couldn't parse the type nor the initializer, only raise the type error and
4181 // return to the parser state before parsing the type as the initializer.
4182 // let x: <parse_error>;
4183 mem::replace(self, snapshot);
4186 (Err(err), None) => { // init error, ty parsed
4187 // Couldn't parse the initializer and we're not attempting to recover a failed
4188 // parse of the type, return the error.
4192 let hi = if self.token == token::Semi {
4201 id: ast::DUMMY_NODE_ID,
4207 /// Parses a structure field.
4208 fn parse_name_and_ty(&mut self,
4211 attrs: Vec<Attribute>)
4212 -> PResult<'a, StructField> {
4213 let name = self.parse_ident()?;
4214 self.expect(&token::Colon)?;
4215 let ty = self.parse_ty()?;
4217 span: lo.to(self.prev_span),
4220 id: ast::DUMMY_NODE_ID,
4226 /// Emits an expected-item-after-attributes error.
4227 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4228 let message = match attrs.last() {
4229 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4230 _ => "expected item after attributes",
4233 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4234 if attrs.last().unwrap().is_sugared_doc {
4235 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4240 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4241 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4242 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4243 Ok(self.parse_stmt_(true))
4246 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4247 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4249 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4254 fn is_async_block(&self) -> bool {
4255 self.token.is_keyword(kw::Async) &&
4258 self.is_keyword_ahead(1, &[kw::Move]) &&
4259 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4261 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4266 fn is_async_fn(&self) -> bool {
4267 self.token.is_keyword(kw::Async) &&
4268 self.is_keyword_ahead(1, &[kw::Fn])
4271 fn is_do_catch_block(&self) -> bool {
4272 self.token.is_keyword(kw::Do) &&
4273 self.is_keyword_ahead(1, &[kw::Catch]) &&
4274 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4275 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4278 fn is_try_block(&self) -> bool {
4279 self.token.is_keyword(kw::Try) &&
4280 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4281 self.token.span.rust_2018() &&
4282 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4283 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4286 fn is_union_item(&self) -> bool {
4287 self.token.is_keyword(kw::Union) &&
4288 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4291 fn is_crate_vis(&self) -> bool {
4292 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4295 fn is_existential_type_decl(&self) -> bool {
4296 self.token.is_keyword(kw::Existential) &&
4297 self.is_keyword_ahead(1, &[kw::Type])
4300 fn is_auto_trait_item(&self) -> bool {
4302 (self.token.is_keyword(kw::Auto) &&
4303 self.is_keyword_ahead(1, &[kw::Trait]))
4304 || // unsafe auto trait
4305 (self.token.is_keyword(kw::Unsafe) &&
4306 self.is_keyword_ahead(1, &[kw::Auto]) &&
4307 self.is_keyword_ahead(2, &[kw::Trait]))
4310 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4311 -> PResult<'a, Option<P<Item>>> {
4312 let token_lo = self.token.span;
4313 let (ident, def) = if self.eat_keyword(kw::Macro) {
4314 let ident = self.parse_ident()?;
4315 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4316 match self.parse_token_tree() {
4317 TokenTree::Delimited(_, _, tts) => tts,
4318 _ => unreachable!(),
4320 } else if self.check(&token::OpenDelim(token::Paren)) {
4321 let args = self.parse_token_tree();
4322 let body = if self.check(&token::OpenDelim(token::Brace)) {
4323 self.parse_token_tree()
4328 TokenStream::new(vec![
4330 TokenTree::token(token::FatArrow, token_lo.to(self.prev_span)).into(),
4338 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4339 } else if self.check_keyword(sym::macro_rules) &&
4340 self.look_ahead(1, |t| *t == token::Not) &&
4341 self.look_ahead(2, |t| t.is_ident()) {
4342 let prev_span = self.prev_span;
4343 self.complain_if_pub_macro(&vis.node, prev_span);
4347 let ident = self.parse_ident()?;
4348 let (delim, tokens) = self.expect_delimited_token_tree()?;
4349 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
4350 self.report_invalid_macro_expansion_item();
4353 (ident, ast::MacroDef { tokens, legacy: true })
4358 let span = lo.to(self.prev_span);
4359 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4362 fn parse_stmt_without_recovery(
4364 macro_legacy_warnings: bool,
4365 ) -> PResult<'a, Option<Stmt>> {
4366 maybe_whole!(self, NtStmt, |x| Some(x));
4368 let attrs = self.parse_outer_attributes()?;
4369 let lo = self.token.span;
4371 Ok(Some(if self.eat_keyword(kw::Let) {
4373 id: ast::DUMMY_NODE_ID,
4374 node: StmtKind::Local(self.parse_local(attrs.into())?),
4375 span: lo.to(self.prev_span),
4377 } else if let Some(macro_def) = self.eat_macro_def(
4379 &source_map::respan(lo, VisibilityKind::Inherited),
4383 id: ast::DUMMY_NODE_ID,
4384 node: StmtKind::Item(macro_def),
4385 span: lo.to(self.prev_span),
4387 // Starts like a simple path, being careful to avoid contextual keywords
4388 // such as a union items, item with `crate` visibility or auto trait items.
4389 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4390 // like a path (1 token), but it fact not a path.
4391 // `union::b::c` - path, `union U { ... }` - not a path.
4392 // `crate::b::c` - path, `crate struct S;` - not a path.
4393 } else if self.token.is_path_start() &&
4394 !self.token.is_qpath_start() &&
4395 !self.is_union_item() &&
4396 !self.is_crate_vis() &&
4397 !self.is_existential_type_decl() &&
4398 !self.is_auto_trait_item() &&
4399 !self.is_async_fn() {
4400 let path = self.parse_path(PathStyle::Expr)?;
4402 if !self.eat(&token::Not) {
4403 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4404 self.parse_struct_expr(lo, path, ThinVec::new())?
4406 let hi = self.prev_span;
4407 self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new())
4410 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4411 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4412 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4415 return Ok(Some(Stmt {
4416 id: ast::DUMMY_NODE_ID,
4417 node: StmtKind::Expr(expr),
4418 span: lo.to(self.prev_span),
4422 let (delim, tts) = self.expect_delimited_token_tree()?;
4423 let hi = self.prev_span;
4425 let style = if delim == MacDelimiter::Brace {
4426 MacStmtStyle::Braces
4428 MacStmtStyle::NoBraces
4431 let mac = respan(lo.to(hi), Mac_ { path, tts, delim });
4432 let node = if delim == MacDelimiter::Brace ||
4433 self.token == token::Semi || self.token == token::Eof {
4434 StmtKind::Mac(P((mac, style, attrs.into())))
4436 // We used to incorrectly stop parsing macro-expanded statements here.
4437 // If the next token will be an error anyway but could have parsed with the
4438 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4439 else if macro_legacy_warnings &&
4440 self.token.can_begin_expr() &&
4441 match self.token.kind {
4442 // These can continue an expression, so we can't stop parsing and warn.
4443 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4444 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4445 token::BinOp(token::And) | token::BinOp(token::Or) |
4446 token::AndAnd | token::OrOr |
4447 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4450 self.warn_missing_semicolon();
4451 StmtKind::Mac(P((mac, style, attrs.into())))
4453 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
4454 let e = self.maybe_recover_from_bad_qpath(e, true)?;
4455 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4456 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4460 id: ast::DUMMY_NODE_ID,
4465 // FIXME: Bad copy of attrs
4466 let old_directory_ownership =
4467 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4468 let item = self.parse_item_(attrs.clone(), false, true)?;
4469 self.directory.ownership = old_directory_ownership;
4473 id: ast::DUMMY_NODE_ID,
4474 span: lo.to(i.span),
4475 node: StmtKind::Item(i),
4478 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4479 if !attrs.is_empty() {
4480 if s.prev_token_kind == PrevTokenKind::DocComment {
4481 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4482 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4484 s.token.span, "expected statement after outer attribute"
4490 // Do not attempt to parse an expression if we're done here.
4491 if self.token == token::Semi {
4492 unused_attrs(&attrs, self);
4497 if self.token == token::CloseDelim(token::Brace) {
4498 unused_attrs(&attrs, self);
4502 // Remainder are line-expr stmts.
4503 let e = self.parse_expr_res(
4504 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4506 id: ast::DUMMY_NODE_ID,
4507 span: lo.to(e.span),
4508 node: StmtKind::Expr(e),
4515 /// Checks if this expression is a successfully parsed statement.
4516 fn expr_is_complete(&self, e: &Expr) -> bool {
4517 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4518 !classify::expr_requires_semi_to_be_stmt(e)
4521 /// Parses a block. No inner attributes are allowed.
4522 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4523 maybe_whole!(self, NtBlock, |x| x);
4525 let lo = self.token.span;
4527 if !self.eat(&token::OpenDelim(token::Brace)) {
4528 let sp = self.token.span;
4529 let tok = self.this_token_descr();
4530 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4531 let do_not_suggest_help =
4532 self.token.is_keyword(kw::In) || self.token == token::Colon;
4534 if self.token.is_ident_named(sym::and) {
4535 e.span_suggestion_short(
4537 "use `&&` instead of `and` for the boolean operator",
4539 Applicability::MaybeIncorrect,
4542 if self.token.is_ident_named(sym::or) {
4543 e.span_suggestion_short(
4545 "use `||` instead of `or` for the boolean operator",
4547 Applicability::MaybeIncorrect,
4551 // Check to see if the user has written something like
4556 // Which is valid in other languages, but not Rust.
4557 match self.parse_stmt_without_recovery(false) {
4559 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4560 || do_not_suggest_help {
4561 // if the next token is an open brace (e.g., `if a b {`), the place-
4562 // inside-a-block suggestion would be more likely wrong than right
4563 e.span_label(sp, "expected `{`");
4566 let mut stmt_span = stmt.span;
4567 // expand the span to include the semicolon, if it exists
4568 if self.eat(&token::Semi) {
4569 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4571 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
4574 "try placing this code inside a block",
4575 format!("{{ {} }}", snippet),
4576 // speculative, has been misleading in the past (#46836)
4577 Applicability::MaybeIncorrect,
4582 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4583 self.cancel(&mut e);
4587 e.span_label(sp, "expected `{`");
4591 self.parse_block_tail(lo, BlockCheckMode::Default)
4594 /// Parses a block. Inner attributes are allowed.
4595 crate fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4596 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4598 let lo = self.token.span;
4599 self.expect(&token::OpenDelim(token::Brace))?;
4600 Ok((self.parse_inner_attributes()?,
4601 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4604 /// Parses the rest of a block expression or function body.
4605 /// Precondition: already parsed the '{'.
4606 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4607 let mut stmts = vec![];
4608 while !self.eat(&token::CloseDelim(token::Brace)) {
4609 if self.token == token::Eof {
4612 let stmt = match self.parse_full_stmt(false) {
4615 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4617 id: ast::DUMMY_NODE_ID,
4618 node: StmtKind::Expr(DummyResult::raw_expr(self.token.span, true)),
4619 span: self.token.span,
4624 if let Some(stmt) = stmt {
4627 // Found only `;` or `}`.
4633 id: ast::DUMMY_NODE_ID,
4635 span: lo.to(self.prev_span),
4639 /// Parses a statement, including the trailing semicolon.
4640 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4641 // skip looking for a trailing semicolon when we have an interpolated statement
4642 maybe_whole!(self, NtStmt, |x| Some(x));
4644 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4646 None => return Ok(None),
4650 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4651 // expression without semicolon
4652 if classify::expr_requires_semi_to_be_stmt(expr) {
4653 // Just check for errors and recover; do not eat semicolon yet.
4655 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4658 self.recover_stmt();
4659 // Don't complain about type errors in body tail after parse error (#57383).
4660 let sp = expr.span.to(self.prev_span);
4661 stmt.node = StmtKind::Expr(DummyResult::raw_expr(sp, true));
4665 StmtKind::Local(..) => {
4666 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4667 if macro_legacy_warnings && self.token != token::Semi {
4668 self.warn_missing_semicolon();
4670 self.expect_one_of(&[], &[token::Semi])?;
4676 if self.eat(&token::Semi) {
4677 stmt = stmt.add_trailing_semicolon();
4679 stmt.span = stmt.span.to(self.prev_span);
4683 fn warn_missing_semicolon(&self) {
4684 self.diagnostic().struct_span_warn(self.token.span, {
4685 &format!("expected `;`, found {}", self.this_token_descr())
4687 "This was erroneously allowed and will become a hard error in a future release"
4691 fn err_dotdotdot_syntax(&self, span: Span) {
4692 self.diagnostic().struct_span_err(span, {
4693 "unexpected token: `...`"
4695 span, "use `..` for an exclusive range", "..".to_owned(),
4696 Applicability::MaybeIncorrect
4698 span, "or `..=` for an inclusive range", "..=".to_owned(),
4699 Applicability::MaybeIncorrect
4703 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
4706 /// BOUND = TY_BOUND | LT_BOUND
4707 /// LT_BOUND = LIFETIME (e.g., `'a`)
4708 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4709 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
4711 fn parse_generic_bounds_common(&mut self,
4713 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4714 let mut bounds = Vec::new();
4715 let mut negative_bounds = Vec::new();
4716 let mut last_plus_span = None;
4717 let mut was_negative = false;
4719 // This needs to be synchronized with `TokenKind::can_begin_bound`.
4720 let is_bound_start = self.check_path() || self.check_lifetime() ||
4721 self.check(&token::Not) || // used for error reporting only
4722 self.check(&token::Question) ||
4723 self.check_keyword(kw::For) ||
4724 self.check(&token::OpenDelim(token::Paren));
4726 let lo = self.token.span;
4727 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4728 let inner_lo = self.token.span;
4729 let is_negative = self.eat(&token::Not);
4730 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4731 if self.token.is_lifetime() {
4732 if let Some(question_span) = question {
4733 self.span_err(question_span,
4734 "`?` may only modify trait bounds, not lifetime bounds");
4736 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4738 let inner_span = inner_lo.to(self.prev_span);
4739 self.expect(&token::CloseDelim(token::Paren))?;
4740 let mut err = self.struct_span_err(
4741 lo.to(self.prev_span),
4742 "parenthesized lifetime bounds are not supported"
4744 if let Ok(snippet) = self.span_to_snippet(inner_span) {
4745 err.span_suggestion_short(
4746 lo.to(self.prev_span),
4747 "remove the parentheses",
4749 Applicability::MachineApplicable
4755 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4756 let path = self.parse_path(PathStyle::Type)?;
4758 self.expect(&token::CloseDelim(token::Paren))?;
4760 let poly_span = lo.to(self.prev_span);
4762 was_negative = true;
4763 if let Some(sp) = last_plus_span.or(colon_span) {
4764 negative_bounds.push(sp.to(poly_span));
4767 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
4768 let modifier = if question.is_some() {
4769 TraitBoundModifier::Maybe
4771 TraitBoundModifier::None
4773 bounds.push(GenericBound::Trait(poly_trait, modifier));
4780 if !allow_plus || !self.eat_plus() {
4783 last_plus_span = Some(self.prev_span);
4787 if !negative_bounds.is_empty() || was_negative {
4788 let plural = negative_bounds.len() > 1;
4789 let last_span = negative_bounds.last().map(|sp| *sp);
4790 let mut err = self.struct_span_err(
4792 "negative trait bounds are not supported",
4794 if let Some(sp) = last_span {
4795 err.span_label(sp, "negative trait bounds are not supported");
4797 if let Some(bound_list) = colon_span {
4798 let bound_list = bound_list.to(self.prev_span);
4799 let mut new_bound_list = String::new();
4800 if !bounds.is_empty() {
4801 let mut snippets = bounds.iter().map(|bound| bound.span())
4802 .map(|span| self.span_to_snippet(span));
4803 while let Some(Ok(snippet)) = snippets.next() {
4804 new_bound_list.push_str(" + ");
4805 new_bound_list.push_str(&snippet);
4807 new_bound_list = new_bound_list.replacen(" +", ":", 1);
4809 err.span_suggestion_hidden(
4811 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
4813 Applicability::MachineApplicable,
4822 crate fn parse_generic_bounds(&mut self,
4823 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4824 self.parse_generic_bounds_common(true, colon_span)
4827 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4830 /// BOUND = LT_BOUND (e.g., `'a`)
4832 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4833 let mut lifetimes = Vec::new();
4834 while self.check_lifetime() {
4835 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4837 if !self.eat_plus() {
4844 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
4845 fn parse_ty_param(&mut self,
4846 preceding_attrs: Vec<Attribute>)
4847 -> PResult<'a, GenericParam> {
4848 let ident = self.parse_ident()?;
4850 // Parse optional colon and param bounds.
4851 let bounds = if self.eat(&token::Colon) {
4852 self.parse_generic_bounds(Some(self.prev_span))?
4857 let default = if self.eat(&token::Eq) {
4858 Some(self.parse_ty()?)
4865 id: ast::DUMMY_NODE_ID,
4866 attrs: preceding_attrs.into(),
4868 kind: GenericParamKind::Type {
4874 /// Parses the following grammar:
4876 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4877 fn parse_trait_item_assoc_ty(&mut self)
4878 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4879 let ident = self.parse_ident()?;
4880 let mut generics = self.parse_generics()?;
4882 // Parse optional colon and param bounds.
4883 let bounds = if self.eat(&token::Colon) {
4884 self.parse_generic_bounds(None)?
4888 generics.where_clause = self.parse_where_clause()?;
4890 let default = if self.eat(&token::Eq) {
4891 Some(self.parse_ty()?)
4895 self.expect(&token::Semi)?;
4897 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4900 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
4901 self.expect_keyword(kw::Const)?;
4902 let ident = self.parse_ident()?;
4903 self.expect(&token::Colon)?;
4904 let ty = self.parse_ty()?;
4908 id: ast::DUMMY_NODE_ID,
4909 attrs: preceding_attrs.into(),
4911 kind: GenericParamKind::Const {
4917 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
4918 /// a trailing comma and erroneous trailing attributes.
4919 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4920 let mut params = Vec::new();
4922 let attrs = self.parse_outer_attributes()?;
4923 if self.check_lifetime() {
4924 let lifetime = self.expect_lifetime();
4925 // Parse lifetime parameter.
4926 let bounds = if self.eat(&token::Colon) {
4927 self.parse_lt_param_bounds()
4931 params.push(ast::GenericParam {
4932 ident: lifetime.ident,
4934 attrs: attrs.into(),
4936 kind: ast::GenericParamKind::Lifetime,
4938 } else if self.check_keyword(kw::Const) {
4939 // Parse const parameter.
4940 params.push(self.parse_const_param(attrs)?);
4941 } else if self.check_ident() {
4942 // Parse type parameter.
4943 params.push(self.parse_ty_param(attrs)?);
4945 // Check for trailing attributes and stop parsing.
4946 if !attrs.is_empty() {
4947 if !params.is_empty() {
4948 self.struct_span_err(
4950 &format!("trailing attribute after generic parameter"),
4952 .span_label(attrs[0].span, "attributes must go before parameters")
4955 self.struct_span_err(
4957 &format!("attribute without generic parameters"),
4961 "attributes are only permitted when preceding parameters",
4969 if !self.eat(&token::Comma) {
4976 /// Parses a set of optional generic type parameter declarations. Where
4977 /// clauses are not parsed here, and must be added later via
4978 /// `parse_where_clause()`.
4980 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4981 /// | ( < lifetimes , typaramseq ( , )? > )
4982 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4983 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4984 let span_lo = self.token.span;
4985 let (params, span) = if self.eat_lt() {
4986 let params = self.parse_generic_params()?;
4988 (params, span_lo.to(self.prev_span))
4990 (vec![], self.prev_span.between(self.token.span))
4994 where_clause: WhereClause {
4995 predicates: Vec::new(),
5002 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5003 /// For the purposes of understanding the parsing logic of generic arguments, this function
5004 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5005 /// had the correct amount of leading angle brackets.
5007 /// ```ignore (diagnostics)
5008 /// bar::<<<<T as Foo>::Output>();
5009 /// ^^ help: remove extra angle brackets
5011 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5015 ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5016 // We need to detect whether there are extra leading left angle brackets and produce an
5017 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5018 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5019 // then there won't be matching `>` tokens to find.
5021 // To explain how this detection works, consider the following example:
5023 // ```ignore (diagnostics)
5024 // bar::<<<<T as Foo>::Output>();
5025 // ^^ help: remove extra angle brackets
5028 // Parsing of the left angle brackets starts in this function. We start by parsing the
5029 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5032 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5033 // *Unmatched count:* 1
5034 // *`parse_path_segment` calls deep:* 0
5036 // This has the effect of recursing as this function is called if a `<` character
5037 // is found within the expected generic arguments:
5039 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5040 // *Unmatched count:* 2
5041 // *`parse_path_segment` calls deep:* 1
5043 // Eventually we will have recursed until having consumed all of the `<` tokens and
5044 // this will be reflected in the count:
5046 // *Upcoming tokens:* `T as Foo>::Output>;`
5047 // *Unmatched count:* 4
5048 // `parse_path_segment` calls deep:* 3
5050 // The parser will continue until reaching the first `>` - this will decrement the
5051 // unmatched angle bracket count and return to the parent invocation of this function
5052 // having succeeded in parsing:
5054 // *Upcoming tokens:* `::Output>;`
5055 // *Unmatched count:* 3
5056 // *`parse_path_segment` calls deep:* 2
5058 // This will continue until the next `>` character which will also return successfully
5059 // to the parent invocation of this function and decrement the count:
5061 // *Upcoming tokens:* `;`
5062 // *Unmatched count:* 2
5063 // *`parse_path_segment` calls deep:* 1
5065 // At this point, this function will expect to find another matching `>` character but
5066 // won't be able to and will return an error. This will continue all the way up the
5067 // call stack until the first invocation:
5069 // *Upcoming tokens:* `;`
5070 // *Unmatched count:* 2
5071 // *`parse_path_segment` calls deep:* 0
5073 // In doing this, we have managed to work out how many unmatched leading left angle
5074 // brackets there are, but we cannot recover as the unmatched angle brackets have
5075 // already been consumed. To remedy this, we keep a snapshot of the parser state
5076 // before we do the above. We can then inspect whether we ended up with a parsing error
5077 // and unmatched left angle brackets and if so, restore the parser state before we
5078 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5079 // recover by attempting to parse again.
5081 // In practice, the recursion of this function is indirect and there will be other
5082 // locations that consume some `<` characters - as long as we update the count when
5083 // this happens, it isn't an issue.
5085 let is_first_invocation = style == PathStyle::Expr;
5086 // Take a snapshot before attempting to parse - we can restore this later.
5087 let snapshot = if is_first_invocation {
5093 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5094 match self.parse_generic_args() {
5095 Ok(value) => Ok(value),
5096 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5097 // Cancel error from being unable to find `>`. We know the error
5098 // must have been this due to a non-zero unmatched angle bracket
5102 // Swap `self` with our backup of the parser state before attempting to parse
5103 // generic arguments.
5104 let snapshot = mem::replace(self, snapshot.unwrap());
5107 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5108 snapshot.count={:?}",
5109 snapshot.unmatched_angle_bracket_count,
5112 // Eat the unmatched angle brackets.
5113 for _ in 0..snapshot.unmatched_angle_bracket_count {
5117 // Make a span over ${unmatched angle bracket count} characters.
5118 let span = lo.with_hi(
5119 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5121 let plural = snapshot.unmatched_angle_bracket_count > 1;
5126 "unmatched angle bracket{}",
5127 if plural { "s" } else { "" }
5133 "remove extra angle bracket{}",
5134 if plural { "s" } else { "" }
5137 Applicability::MachineApplicable,
5141 // Try again without unmatched angle bracket characters.
5142 self.parse_generic_args()
5148 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5149 /// possibly including trailing comma.
5150 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5151 let mut args = Vec::new();
5152 let mut constraints = Vec::new();
5153 let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new();
5154 let mut assoc_ty_constraints: Vec<Span> = Vec::new();
5156 let args_lo = self.token.span;
5159 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5160 // Parse lifetime argument.
5161 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5162 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5163 } else if self.check_ident() && self.look_ahead(1,
5164 |t| t == &token::Eq || t == &token::Colon) {
5165 // Parse associated type constraint.
5166 let lo = self.token.span;
5167 let ident = self.parse_ident()?;
5168 let kind = if self.eat(&token::Eq) {
5169 AssocTyConstraintKind::Equality {
5170 ty: self.parse_ty()?,
5172 } else if self.eat(&token::Colon) {
5173 AssocTyConstraintKind::Bound {
5174 bounds: self.parse_generic_bounds(Some(self.prev_span))?,
5179 let span = lo.to(self.prev_span);
5180 constraints.push(AssocTyConstraint {
5181 id: ast::DUMMY_NODE_ID,
5186 assoc_ty_constraints.push(span);
5187 } else if self.check_const_arg() {
5188 // Parse const argument.
5189 let expr = if let token::OpenDelim(token::Brace) = self.token.kind {
5190 self.parse_block_expr(
5191 None, self.token.span, BlockCheckMode::Default, ThinVec::new()
5193 } else if self.token.is_ident() {
5194 // FIXME(const_generics): to distinguish between idents for types and consts,
5195 // we should introduce a GenericArg::Ident in the AST and distinguish when
5196 // lowering to the HIR. For now, idents for const args are not permitted.
5197 if self.token.is_keyword(kw::True) || self.token.is_keyword(kw::False) {
5198 self.parse_literal_maybe_minus()?
5201 self.fatal("identifiers may currently not be used for const generics")
5205 self.parse_literal_maybe_minus()?
5207 let value = AnonConst {
5208 id: ast::DUMMY_NODE_ID,
5211 args.push(GenericArg::Const(value));
5212 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5213 } else if self.check_type() {
5214 // Parse type argument.
5215 args.push(GenericArg::Type(self.parse_ty()?));
5216 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5221 if !self.eat(&token::Comma) {
5226 // FIXME: we would like to report this in ast_validation instead, but we currently do not
5227 // preserve ordering of generic parameters with respect to associated type binding, so we
5228 // lose that information after parsing.
5229 if misplaced_assoc_ty_constraints.len() > 0 {
5230 let mut err = self.struct_span_err(
5231 args_lo.to(self.prev_span),
5232 "associated type bindings must be declared after generic parameters",
5234 for span in misplaced_assoc_ty_constraints {
5237 "this associated type binding should be moved after the generic parameters",
5243 Ok((args, constraints))
5246 /// Parses an optional where-clause and places it in `generics`.
5248 /// ```ignore (only-for-syntax-highlight)
5249 /// where T : Trait<U, V> + 'b, 'a : 'b
5251 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5252 let mut where_clause = WhereClause {
5253 predicates: Vec::new(),
5254 span: self.prev_span.to(self.prev_span),
5257 if !self.eat_keyword(kw::Where) {
5258 return Ok(where_clause);
5260 let lo = self.prev_span;
5262 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5263 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5264 // change we parse those generics now, but report an error.
5265 if self.choose_generics_over_qpath() {
5266 let generics = self.parse_generics()?;
5267 self.struct_span_err(
5269 "generic parameters on `where` clauses are reserved for future use",
5271 .span_label(generics.span, "currently unsupported")
5276 let lo = self.token.span;
5277 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5278 let lifetime = self.expect_lifetime();
5279 // Bounds starting with a colon are mandatory, but possibly empty.
5280 self.expect(&token::Colon)?;
5281 let bounds = self.parse_lt_param_bounds();
5282 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5283 ast::WhereRegionPredicate {
5284 span: lo.to(self.prev_span),
5289 } else if self.check_type() {
5290 // Parse optional `for<'a, 'b>`.
5291 // This `for` is parsed greedily and applies to the whole predicate,
5292 // the bounded type can have its own `for` applying only to it.
5294 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
5295 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
5296 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
5297 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5299 // Parse type with mandatory colon and (possibly empty) bounds,
5300 // or with mandatory equality sign and the second type.
5301 let ty = self.parse_ty()?;
5302 if self.eat(&token::Colon) {
5303 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
5304 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5305 ast::WhereBoundPredicate {
5306 span: lo.to(self.prev_span),
5307 bound_generic_params: lifetime_defs,
5312 // FIXME: Decide what should be used here, `=` or `==`.
5313 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5314 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5315 let rhs_ty = self.parse_ty()?;
5316 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5317 ast::WhereEqPredicate {
5318 span: lo.to(self.prev_span),
5321 id: ast::DUMMY_NODE_ID,
5325 return self.unexpected();
5331 if !self.eat(&token::Comma) {
5336 where_clause.span = lo.to(self.prev_span);
5340 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
5341 -> PResult<'a, (Vec<Arg> , bool)> {
5342 let sp = self.token.span;
5343 let mut c_variadic = false;
5344 let (args, _): (Vec<Option<Arg>>, _) = self.parse_paren_comma_seq(|p| {
5345 let do_not_enforce_named_arguments_for_c_variadic =
5346 |token: &token::Token| -> bool {
5347 if token == &token::DotDotDot {
5353 match p.parse_arg_general(
5356 do_not_enforce_named_arguments_for_c_variadic
5359 if let TyKind::CVarArgs = arg.ty.node {
5361 if p.token != token::CloseDelim(token::Paren) {
5362 let span = p.token.span;
5364 "`...` must be the last argument of a C-variadic function");
5375 let lo = p.prev_span;
5376 // Skip every token until next possible arg or end.
5377 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5378 // Create a placeholder argument for proper arg count (issue #34264).
5379 let span = lo.to(p.prev_span);
5380 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
5385 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5387 if c_variadic && args.is_empty() {
5389 "C-variadic function must be declared with at least one named argument");
5392 Ok((args, c_variadic))
5395 /// Parses the argument list and result type of a function declaration.
5396 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
5397 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
5398 let ret_ty = self.parse_ret_ty(true)?;
5407 /// Returns the parsed optional self argument and whether a self shortcut was used.
5409 /// See `parse_self_arg_with_attrs` to collect attributes.
5410 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5411 let expect_ident = |this: &mut Self| match this.token.kind {
5412 // Preserve hygienic context.
5413 token::Ident(name, _) =>
5414 { let span = this.token.span; this.bump(); Ident::new(name, span) }
5417 let isolated_self = |this: &mut Self, n| {
5418 this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
5419 this.look_ahead(n + 1, |t| t != &token::ModSep)
5422 // Parse optional `self` parameter of a method.
5423 // Only a limited set of initial token sequences is considered `self` parameters; anything
5424 // else is parsed as a normal function parameter list, so some lookahead is required.
5425 let eself_lo = self.token.span;
5426 let (eself, eself_ident, eself_hi) = match self.token.kind {
5427 token::BinOp(token::And) => {
5433 (if isolated_self(self, 1) {
5435 SelfKind::Region(None, Mutability::Immutable)
5436 } else if self.is_keyword_ahead(1, &[kw::Mut]) &&
5437 isolated_self(self, 2) {
5440 SelfKind::Region(None, Mutability::Mutable)
5441 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5442 isolated_self(self, 2) {
5444 let lt = self.expect_lifetime();
5445 SelfKind::Region(Some(lt), Mutability::Immutable)
5446 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5447 self.is_keyword_ahead(2, &[kw::Mut]) &&
5448 isolated_self(self, 3) {
5450 let lt = self.expect_lifetime();
5452 SelfKind::Region(Some(lt), Mutability::Mutable)
5455 }, expect_ident(self), self.prev_span)
5457 token::BinOp(token::Star) => {
5462 // Emit special error for `self` cases.
5463 let msg = "cannot pass `self` by raw pointer";
5464 (if isolated_self(self, 1) {
5466 self.struct_span_err(self.token.span, msg)
5467 .span_label(self.token.span, msg)
5469 SelfKind::Value(Mutability::Immutable)
5470 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5471 isolated_self(self, 2) {
5474 self.struct_span_err(self.token.span, msg)
5475 .span_label(self.token.span, msg)
5477 SelfKind::Value(Mutability::Immutable)
5480 }, expect_ident(self), self.prev_span)
5482 token::Ident(..) => {
5483 if isolated_self(self, 0) {
5486 let eself_ident = expect_ident(self);
5487 let eself_hi = self.prev_span;
5488 (if self.eat(&token::Colon) {
5489 let ty = self.parse_ty()?;
5490 SelfKind::Explicit(ty, Mutability::Immutable)
5492 SelfKind::Value(Mutability::Immutable)
5493 }, eself_ident, eself_hi)
5494 } else if self.token.is_keyword(kw::Mut) &&
5495 isolated_self(self, 1) {
5499 let eself_ident = expect_ident(self);
5500 let eself_hi = self.prev_span;
5501 (if self.eat(&token::Colon) {
5502 let ty = self.parse_ty()?;
5503 SelfKind::Explicit(ty, Mutability::Mutable)
5505 SelfKind::Value(Mutability::Mutable)
5506 }, eself_ident, eself_hi)
5511 _ => return Ok(None),
5514 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5515 Ok(Some(Arg::from_self(ThinVec::default(), eself, eself_ident)))
5518 /// Returns the parsed optional self argument with attributes and whether a self
5519 /// shortcut was used.
5520 fn parse_self_arg_with_attrs(&mut self) -> PResult<'a, Option<Arg>> {
5521 let attrs = self.parse_arg_attributes()?;
5522 let arg_opt = self.parse_self_arg()?;
5523 Ok(arg_opt.map(|mut arg| {
5524 arg.attrs = attrs.into();
5529 /// Parses the parameter list and result type of a function that may have a `self` parameter.
5530 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5531 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5533 self.expect(&token::OpenDelim(token::Paren))?;
5535 // Parse optional self argument.
5536 let self_arg = self.parse_self_arg_with_attrs()?;
5538 // Parse the rest of the function parameter list.
5539 let sep = SeqSep::trailing_allowed(token::Comma);
5540 let (mut fn_inputs, recovered) = if let Some(self_arg) = self_arg {
5541 if self.check(&token::CloseDelim(token::Paren)) {
5542 (vec![self_arg], false)
5543 } else if self.eat(&token::Comma) {
5544 let mut fn_inputs = vec![self_arg];
5545 let (mut input, _, recovered) = self.parse_seq_to_before_end(
5546 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
5547 fn_inputs.append(&mut input);
5548 (fn_inputs, recovered)
5550 match self.expect_one_of(&[], &[]) {
5551 Err(err) => return Err(err),
5552 Ok(recovered) => (vec![self_arg], recovered),
5556 let (input, _, recovered) =
5557 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
5562 // Parse closing paren and return type.
5563 self.expect(&token::CloseDelim(token::Paren))?;
5565 // Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
5566 self.deduplicate_recovered_arg_names(&mut fn_inputs);
5570 output: self.parse_ret_ty(true)?,
5575 /// Parses the `|arg, arg|` header of a closure.
5576 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5577 let inputs_captures = {
5578 if self.eat(&token::OrOr) {
5581 self.expect(&token::BinOp(token::Or))?;
5582 let args = self.parse_seq_to_before_tokens(
5583 &[&token::BinOp(token::Or), &token::OrOr],
5584 SeqSep::trailing_allowed(token::Comma),
5585 TokenExpectType::NoExpect,
5586 |p| p.parse_fn_block_arg()
5592 let output = self.parse_ret_ty(true)?;
5595 inputs: inputs_captures,
5601 /// Parses the name and optional generic types of a function header.
5602 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5603 let id = self.parse_ident()?;
5604 let generics = self.parse_generics()?;
5608 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5609 attrs: Vec<Attribute>) -> P<Item> {
5613 id: ast::DUMMY_NODE_ID,
5621 /// Parses an item-position function declaration.
5622 fn parse_item_fn(&mut self,
5624 asyncness: Spanned<IsAsync>,
5625 constness: Spanned<Constness>,
5627 -> PResult<'a, ItemInfo> {
5628 let (ident, mut generics) = self.parse_fn_header()?;
5629 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
5630 let decl = self.parse_fn_decl(allow_c_variadic)?;
5631 generics.where_clause = self.parse_where_clause()?;
5632 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5633 let header = FnHeader { unsafety, asyncness, constness, abi };
5634 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5637 /// Returns `true` if we are looking at `const ID`
5638 /// (returns `false` for things like `const fn`, etc.).
5639 fn is_const_item(&self) -> bool {
5640 self.token.is_keyword(kw::Const) &&
5641 !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
5644 /// Parses all the "front matter" for a `fn` declaration, up to
5645 /// and including the `fn` keyword:
5649 /// - `const unsafe fn`
5652 fn parse_fn_front_matter(&mut self)
5660 let is_const_fn = self.eat_keyword(kw::Const);
5661 let const_span = self.prev_span;
5662 let asyncness = self.parse_asyncness();
5663 if let IsAsync::Async { .. } = asyncness {
5664 self.ban_async_in_2015(self.prev_span);
5666 let asyncness = respan(self.prev_span, asyncness);
5667 let unsafety = self.parse_unsafety();
5668 let (constness, unsafety, abi) = if is_const_fn {
5669 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5671 let abi = if self.eat_keyword(kw::Extern) {
5672 self.parse_opt_abi()?.unwrap_or(Abi::C)
5676 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5678 if !self.eat_keyword(kw::Fn) {
5679 // It is possible for `expect_one_of` to recover given the contents of
5680 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
5681 // account for this.
5682 if !self.expect_one_of(&[], &[])? { unreachable!() }
5684 Ok((constness, unsafety, asyncness, abi))
5687 /// Parses an impl item.
5688 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5689 maybe_whole!(self, NtImplItem, |x| x);
5690 let attrs = self.parse_outer_attributes()?;
5691 let mut unclosed_delims = vec![];
5692 let (mut item, tokens) = self.collect_tokens(|this| {
5693 let item = this.parse_impl_item_(at_end, attrs);
5694 unclosed_delims.append(&mut this.unclosed_delims);
5697 self.unclosed_delims.append(&mut unclosed_delims);
5699 // See `parse_item` for why this clause is here.
5700 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5701 item.tokens = Some(tokens);
5706 fn parse_impl_item_(&mut self,
5708 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5709 let lo = self.token.span;
5710 let vis = self.parse_visibility(false)?;
5711 let defaultness = self.parse_defaultness();
5712 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5713 let (name, alias, generics) = type_?;
5714 let kind = match alias {
5715 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5716 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5718 (name, kind, generics)
5719 } else if self.is_const_item() {
5720 // This parses the grammar:
5721 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5722 self.expect_keyword(kw::Const)?;
5723 let name = self.parse_ident()?;
5724 self.expect(&token::Colon)?;
5725 let typ = self.parse_ty()?;
5726 self.expect(&token::Eq)?;
5727 let expr = self.parse_expr()?;
5728 self.expect(&token::Semi)?;
5729 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5731 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5732 attrs.extend(inner_attrs);
5733 (name, node, generics)
5737 id: ast::DUMMY_NODE_ID,
5738 span: lo.to(self.prev_span),
5749 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
5751 VisibilityKind::Inherited => {}
5753 let mut err = if self.token.is_keyword(sym::macro_rules) {
5754 let mut err = self.diagnostic()
5755 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5756 err.span_suggestion(
5758 "try exporting the macro",
5759 "#[macro_export]".to_owned(),
5760 Applicability::MaybeIncorrect // speculative
5764 let mut err = self.diagnostic()
5765 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5766 err.help("try adjusting the macro to put `pub` inside the invocation");
5774 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
5775 -> DiagnosticBuilder<'a>
5777 let expected_kinds = if item_type == "extern" {
5778 "missing `fn`, `type`, or `static`"
5780 "missing `fn`, `type`, or `const`"
5783 // Given this code `path(`, it seems like this is not
5784 // setting the visibility of a macro invocation, but rather
5785 // a mistyped method declaration.
5786 // Create a diagnostic pointing out that `fn` is missing.
5788 // x | pub path(&self) {
5789 // | ^ missing `fn`, `type`, or `const`
5791 // ^^ `sp` below will point to this
5792 let sp = prev_span.between(self.prev_span);
5793 let mut err = self.diagnostic().struct_span_err(
5795 &format!("{} for {}-item declaration",
5796 expected_kinds, item_type));
5797 err.span_label(sp, expected_kinds);
5801 /// Parse a method or a macro invocation in a trait impl.
5802 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5803 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5804 ast::ImplItemKind)> {
5805 // code copied from parse_macro_use_or_failure... abstraction!
5806 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5808 Ok((Ident::invalid(), vec![], ast::Generics::default(),
5809 ast::ImplItemKind::Macro(mac)))
5811 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5812 let ident = self.parse_ident()?;
5813 let mut generics = self.parse_generics()?;
5814 let decl = self.parse_fn_decl_with_self(|p| {
5815 p.parse_arg_general(true, false, |_| true)
5817 generics.where_clause = self.parse_where_clause()?;
5819 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5820 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5821 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5822 ast::MethodSig { header, decl },
5828 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
5829 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5830 let ident = self.parse_ident()?;
5831 let mut tps = self.parse_generics()?;
5833 // Parse optional colon and supertrait bounds.
5834 let bounds = if self.eat(&token::Colon) {
5835 self.parse_generic_bounds(Some(self.prev_span))?
5840 if self.eat(&token::Eq) {
5841 // it's a trait alias
5842 let bounds = self.parse_generic_bounds(None)?;
5843 tps.where_clause = self.parse_where_clause()?;
5844 self.expect(&token::Semi)?;
5845 if is_auto == IsAuto::Yes {
5846 let msg = "trait aliases cannot be `auto`";
5847 self.struct_span_err(self.prev_span, msg)
5848 .span_label(self.prev_span, msg)
5851 if unsafety != Unsafety::Normal {
5852 let msg = "trait aliases cannot be `unsafe`";
5853 self.struct_span_err(self.prev_span, msg)
5854 .span_label(self.prev_span, msg)
5857 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5859 // it's a normal trait
5860 tps.where_clause = self.parse_where_clause()?;
5861 self.expect(&token::OpenDelim(token::Brace))?;
5862 let mut trait_items = vec![];
5863 while !self.eat(&token::CloseDelim(token::Brace)) {
5864 if let token::DocComment(_) = self.token.kind {
5865 if self.look_ahead(1,
5866 |tok| tok == &token::CloseDelim(token::Brace)) {
5867 self.diagnostic().struct_span_err_with_code(
5869 "found a documentation comment that doesn't document anything",
5870 DiagnosticId::Error("E0584".into()),
5873 "doc comments must come before what they document, maybe a \
5874 comment was intended with `//`?",
5881 let mut at_end = false;
5882 match self.parse_trait_item(&mut at_end) {
5883 Ok(item) => trait_items.push(item),
5887 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5892 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5896 fn choose_generics_over_qpath(&self) -> bool {
5897 // There's an ambiguity between generic parameters and qualified paths in impls.
5898 // If we see `<` it may start both, so we have to inspect some following tokens.
5899 // The following combinations can only start generics,
5900 // but not qualified paths (with one exception):
5901 // `<` `>` - empty generic parameters
5902 // `<` `#` - generic parameters with attributes
5903 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5904 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5905 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5906 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5907 // `<` const - generic const parameter
5908 // The only truly ambiguous case is
5909 // `<` IDENT `>` `::` IDENT ...
5910 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5911 // because this is what almost always expected in practice, qualified paths in impls
5912 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5913 self.token == token::Lt &&
5914 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5915 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5916 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5917 t == &token::Colon || t == &token::Eq) ||
5918 self.is_keyword_ahead(1, &[kw::Const]))
5921 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5922 self.expect(&token::OpenDelim(token::Brace))?;
5923 let attrs = self.parse_inner_attributes()?;
5925 let mut impl_items = Vec::new();
5926 while !self.eat(&token::CloseDelim(token::Brace)) {
5927 let mut at_end = false;
5928 match self.parse_impl_item(&mut at_end) {
5929 Ok(impl_item) => impl_items.push(impl_item),
5933 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5938 Ok((impl_items, attrs))
5941 /// Parses an implementation item, `impl` keyword is already parsed.
5943 /// impl<'a, T> TYPE { /* impl items */ }
5944 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5945 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5947 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5948 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5949 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5950 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5951 -> PResult<'a, ItemInfo> {
5952 // First, parse generic parameters if necessary.
5953 let mut generics = if self.choose_generics_over_qpath() {
5954 self.parse_generics()?
5956 ast::Generics::default()
5959 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5960 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5962 ast::ImplPolarity::Negative
5964 ast::ImplPolarity::Positive
5967 // Parse both types and traits as a type, then reinterpret if necessary.
5968 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
5969 let ty_first = if self.token.is_keyword(kw::For) &&
5970 self.look_ahead(1, |t| t != &token::Lt) {
5971 let span = self.prev_span.between(self.token.span);
5972 self.struct_span_err(span, "missing trait in a trait impl").emit();
5973 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
5978 // If `for` is missing we try to recover.
5979 let has_for = self.eat_keyword(kw::For);
5980 let missing_for_span = self.prev_span.between(self.token.span);
5982 let ty_second = if self.token == token::DotDot {
5983 // We need to report this error after `cfg` expansion for compatibility reasons
5984 self.bump(); // `..`, do not add it to expected tokens
5985 Some(DummyResult::raw_ty(self.prev_span, true))
5986 } else if has_for || self.token.can_begin_type() {
5987 Some(self.parse_ty()?)
5992 generics.where_clause = self.parse_where_clause()?;
5994 let (impl_items, attrs) = self.parse_impl_body()?;
5996 let item_kind = match ty_second {
5997 Some(ty_second) => {
5998 // impl Trait for Type
6000 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6001 .span_suggestion_short(
6004 " for ".to_string(),
6005 Applicability::MachineApplicable,
6009 let ty_first = ty_first.into_inner();
6010 let path = match ty_first.node {
6011 // This notably includes paths passed through `ty` macro fragments (#46438).
6012 TyKind::Path(None, path) => path,
6014 self.span_err(ty_first.span, "expected a trait, found type");
6015 err_path(ty_first.span)
6018 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6020 ItemKind::Impl(unsafety, polarity, defaultness,
6021 generics, Some(trait_ref), ty_second, impl_items)
6025 ItemKind::Impl(unsafety, polarity, defaultness,
6026 generics, None, ty_first, impl_items)
6030 Ok((Ident::invalid(), item_kind, Some(attrs)))
6033 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6034 if self.eat_keyword(kw::For) {
6036 let params = self.parse_generic_params()?;
6038 // We rely on AST validation to rule out invalid cases: There must not be type
6039 // parameters, and the lifetime parameters must not have bounds.
6046 /// Parses `struct Foo { ... }`.
6047 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6048 let class_name = self.parse_ident()?;
6050 let mut generics = self.parse_generics()?;
6052 // There is a special case worth noting here, as reported in issue #17904.
6053 // If we are parsing a tuple struct it is the case that the where clause
6054 // should follow the field list. Like so:
6056 // struct Foo<T>(T) where T: Copy;
6058 // If we are parsing a normal record-style struct it is the case
6059 // that the where clause comes before the body, and after the generics.
6060 // So if we look ahead and see a brace or a where-clause we begin
6061 // parsing a record style struct.
6063 // Otherwise if we look ahead and see a paren we parse a tuple-style
6066 let vdata = if self.token.is_keyword(kw::Where) {
6067 generics.where_clause = self.parse_where_clause()?;
6068 if self.eat(&token::Semi) {
6069 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6070 VariantData::Unit(ast::DUMMY_NODE_ID)
6072 // If we see: `struct Foo<T> where T: Copy { ... }`
6073 let (fields, recovered) = self.parse_record_struct_body()?;
6074 VariantData::Struct(fields, recovered)
6076 // No `where` so: `struct Foo<T>;`
6077 } else if self.eat(&token::Semi) {
6078 VariantData::Unit(ast::DUMMY_NODE_ID)
6079 // Record-style struct definition
6080 } else if self.token == token::OpenDelim(token::Brace) {
6081 let (fields, recovered) = self.parse_record_struct_body()?;
6082 VariantData::Struct(fields, recovered)
6083 // Tuple-style struct definition with optional where-clause.
6084 } else if self.token == token::OpenDelim(token::Paren) {
6085 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6086 generics.where_clause = self.parse_where_clause()?;
6087 self.expect(&token::Semi)?;
6090 let token_str = self.this_token_descr();
6091 let mut err = self.fatal(&format!(
6092 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6095 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
6099 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6102 /// Parses `union Foo { ... }`.
6103 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6104 let class_name = self.parse_ident()?;
6106 let mut generics = self.parse_generics()?;
6108 let vdata = if self.token.is_keyword(kw::Where) {
6109 generics.where_clause = self.parse_where_clause()?;
6110 let (fields, recovered) = self.parse_record_struct_body()?;
6111 VariantData::Struct(fields, recovered)
6112 } else if self.token == token::OpenDelim(token::Brace) {
6113 let (fields, recovered) = self.parse_record_struct_body()?;
6114 VariantData::Struct(fields, recovered)
6116 let token_str = self.this_token_descr();
6117 let mut err = self.fatal(&format!(
6118 "expected `where` or `{{` after union name, found {}", token_str));
6119 err.span_label(self.token.span, "expected `where` or `{` after union name");
6123 Ok((class_name, ItemKind::Union(vdata, generics), None))
6126 fn parse_record_struct_body(
6128 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6129 let mut fields = Vec::new();
6130 let mut recovered = false;
6131 if self.eat(&token::OpenDelim(token::Brace)) {
6132 while self.token != token::CloseDelim(token::Brace) {
6133 let field = self.parse_struct_decl_field().map_err(|e| {
6134 self.recover_stmt();
6139 Ok(field) => fields.push(field),
6145 self.eat(&token::CloseDelim(token::Brace));
6147 let token_str = self.this_token_descr();
6148 let mut err = self.fatal(&format!(
6149 "expected `where`, or `{{` after struct name, found {}", token_str));
6150 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
6154 Ok((fields, recovered))
6157 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6158 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6159 // Unit like structs are handled in parse_item_struct function
6160 self.parse_paren_comma_seq(|p| {
6161 let attrs = p.parse_outer_attributes()?;
6162 let lo = p.token.span;
6163 let vis = p.parse_visibility(true)?;
6164 let ty = p.parse_ty()?;
6166 span: lo.to(ty.span),
6169 id: ast::DUMMY_NODE_ID,
6176 /// Parses a structure field declaration.
6177 fn parse_single_struct_field(&mut self,
6180 attrs: Vec<Attribute> )
6181 -> PResult<'a, StructField> {
6182 let mut seen_comma: bool = false;
6183 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6184 if self.token == token::Comma {
6187 match self.token.kind {
6191 token::CloseDelim(token::Brace) => {}
6192 token::DocComment(_) => {
6193 let previous_span = self.prev_span;
6194 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
6195 self.bump(); // consume the doc comment
6196 let comma_after_doc_seen = self.eat(&token::Comma);
6197 // `seen_comma` is always false, because we are inside doc block
6198 // condition is here to make code more readable
6199 if seen_comma == false && comma_after_doc_seen == true {
6202 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6205 if seen_comma == false {
6206 let sp = self.sess.source_map().next_point(previous_span);
6207 err.span_suggestion(
6209 "missing comma here",
6211 Applicability::MachineApplicable
6218 let sp = self.sess.source_map().next_point(self.prev_span);
6219 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6220 self.this_token_descr()));
6221 if self.token.is_ident() {
6222 // This is likely another field; emit the diagnostic and keep going
6223 err.span_suggestion(
6225 "try adding a comma",
6227 Applicability::MachineApplicable,
6238 /// Parses an element of a struct declaration.
6239 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6240 let attrs = self.parse_outer_attributes()?;
6241 let lo = self.token.span;
6242 let vis = self.parse_visibility(false)?;
6243 self.parse_single_struct_field(lo, vis, attrs)
6246 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6247 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6248 /// If the following element can't be a tuple (i.e., it's a function definition), then
6249 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6250 /// so emit a proper diagnostic.
6251 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6252 maybe_whole!(self, NtVis, |x| x);
6254 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
6255 if self.is_crate_vis() {
6256 self.bump(); // `crate`
6257 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6260 if !self.eat_keyword(kw::Pub) {
6261 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6262 // keyword to grab a span from for inherited visibility; an empty span at the
6263 // beginning of the current token would seem to be the "Schelling span".
6264 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
6266 let lo = self.prev_span;
6268 if self.check(&token::OpenDelim(token::Paren)) {
6269 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6270 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6271 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6272 // by the following tokens.
6273 if self.is_keyword_ahead(1, &[kw::Crate]) &&
6274 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
6278 self.bump(); // `crate`
6279 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6281 lo.to(self.prev_span),
6282 VisibilityKind::Crate(CrateSugar::PubCrate),
6285 } else if self.is_keyword_ahead(1, &[kw::In]) {
6288 self.bump(); // `in`
6289 let path = self.parse_path(PathStyle::Mod)?; // `path`
6290 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6291 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6293 id: ast::DUMMY_NODE_ID,
6296 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6297 self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
6299 // `pub(self)` or `pub(super)`
6301 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6302 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6303 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6305 id: ast::DUMMY_NODE_ID,
6308 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6309 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6311 let msg = "incorrect visibility restriction";
6312 let suggestion = r##"some possible visibility restrictions are:
6313 `pub(crate)`: visible only on the current crate
6314 `pub(super)`: visible only in the current module's parent
6315 `pub(in path::to::module)`: visible only on the specified path"##;
6316 let path = self.parse_path(PathStyle::Mod)?;
6318 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6319 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6320 struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg)
6325 format!("in {}", path),
6326 Applicability::MachineApplicable,
6328 .emit(); // emit diagnostic, but continue with public visibility
6332 Ok(respan(lo, VisibilityKind::Public))
6335 /// Parses defaultness (i.e., `default` or nothing).
6336 fn parse_defaultness(&mut self) -> Defaultness {
6337 // `pub` is included for better error messages
6338 if self.check_keyword(kw::Default) &&
6339 self.is_keyword_ahead(1, &[
6349 self.bump(); // `default`
6350 Defaultness::Default
6356 /// Given a termination token, parses all of the items in a module.
6357 fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
6358 let mut items = vec![];
6359 while let Some(item) = self.parse_item()? {
6361 self.maybe_consume_incorrect_semicolon(&items);
6364 if !self.eat(term) {
6365 let token_str = self.this_token_descr();
6366 if !self.maybe_consume_incorrect_semicolon(&items) {
6367 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6368 err.span_label(self.token.span, "expected item");
6373 let hi = if self.token.span.is_dummy() {
6380 inner: inner_lo.to(hi),
6386 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6387 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6388 self.expect(&token::Colon)?;
6389 let ty = self.parse_ty()?;
6390 self.expect(&token::Eq)?;
6391 let e = self.parse_expr()?;
6392 self.expect(&token::Semi)?;
6393 let item = match m {
6394 Some(m) => ItemKind::Static(ty, m, e),
6395 None => ItemKind::Const(ty, e),
6397 Ok((id, item, None))
6400 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6401 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6402 let (in_cfg, outer_attrs) = {
6403 let mut strip_unconfigured = crate::config::StripUnconfigured {
6405 features: None, // don't perform gated feature checking
6407 let mut outer_attrs = outer_attrs.to_owned();
6408 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
6409 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6412 let id_span = self.token.span;
6413 let id = self.parse_ident()?;
6414 if self.eat(&token::Semi) {
6415 if in_cfg && self.recurse_into_file_modules {
6416 // This mod is in an external file. Let's go get it!
6417 let ModulePathSuccess { path, directory_ownership, warn } =
6418 self.submod_path(id, &outer_attrs, id_span)?;
6419 let (module, mut attrs) =
6420 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6421 // Record that we fetched the mod from an external file
6423 let attr = Attribute {
6424 id: attr::mk_attr_id(),
6425 style: ast::AttrStyle::Outer,
6426 path: ast::Path::from_ident(
6427 Ident::with_empty_ctxt(sym::warn_directory_ownership)),
6428 tokens: TokenStream::empty(),
6429 is_sugared_doc: false,
6432 attr::mark_known(&attr);
6435 Ok((id, ItemKind::Mod(module), Some(attrs)))
6437 let placeholder = ast::Mod {
6442 Ok((id, ItemKind::Mod(placeholder), None))
6445 let old_directory = self.directory.clone();
6446 self.push_directory(id, &outer_attrs);
6448 self.expect(&token::OpenDelim(token::Brace))?;
6449 let mod_inner_lo = self.token.span;
6450 let attrs = self.parse_inner_attributes()?;
6451 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6453 self.directory = old_directory;
6454 Ok((id, ItemKind::Mod(module), Some(attrs)))
6458 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6459 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6460 self.directory.path.to_mut().push(&path.as_str());
6461 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6463 // We have to push on the current module name in the case of relative
6464 // paths in order to ensure that any additional module paths from inline
6465 // `mod x { ... }` come after the relative extension.
6467 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6468 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6469 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6470 if let Some(ident) = relative.take() { // remove the relative offset
6471 self.directory.path.to_mut().push(ident.as_str());
6474 self.directory.path.to_mut().push(&id.as_str());
6478 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6479 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6482 // On windows, the base path might have the form
6483 // `\\?\foo\bar` in which case it does not tolerate
6484 // mixed `/` and `\` separators, so canonicalize
6487 let s = s.replace("/", "\\");
6488 Some(dir_path.join(s))
6494 /// Returns a path to a module.
6495 pub fn default_submod_path(
6497 relative: Option<ast::Ident>,
6499 source_map: &SourceMap) -> ModulePath
6501 // If we're in a foo.rs file instead of a mod.rs file,
6502 // we need to look for submodules in
6503 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6504 // `./<id>.rs` and `./<id>/mod.rs`.
6505 let relative_prefix_string;
6506 let relative_prefix = if let Some(ident) = relative {
6507 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6508 &relative_prefix_string
6513 let mod_name = id.to_string();
6514 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6515 let secondary_path_str = format!("{}{}{}mod.rs",
6516 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6517 let default_path = dir_path.join(&default_path_str);
6518 let secondary_path = dir_path.join(&secondary_path_str);
6519 let default_exists = source_map.file_exists(&default_path);
6520 let secondary_exists = source_map.file_exists(&secondary_path);
6522 let result = match (default_exists, secondary_exists) {
6523 (true, false) => Ok(ModulePathSuccess {
6525 directory_ownership: DirectoryOwnership::Owned {
6530 (false, true) => Ok(ModulePathSuccess {
6531 path: secondary_path,
6532 directory_ownership: DirectoryOwnership::Owned {
6537 (false, false) => Err(Error::FileNotFoundForModule {
6538 mod_name: mod_name.clone(),
6539 default_path: default_path_str,
6540 secondary_path: secondary_path_str,
6541 dir_path: dir_path.display().to_string(),
6543 (true, true) => Err(Error::DuplicatePaths {
6544 mod_name: mod_name.clone(),
6545 default_path: default_path_str,
6546 secondary_path: secondary_path_str,
6552 path_exists: default_exists || secondary_exists,
6557 fn submod_path(&mut self,
6559 outer_attrs: &[Attribute],
6561 -> PResult<'a, ModulePathSuccess> {
6562 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6563 return Ok(ModulePathSuccess {
6564 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6565 // All `#[path]` files are treated as though they are a `mod.rs` file.
6566 // This means that `mod foo;` declarations inside `#[path]`-included
6567 // files are siblings,
6569 // Note that this will produce weirdness when a file named `foo.rs` is
6570 // `#[path]` included and contains a `mod foo;` declaration.
6571 // If you encounter this, it's your own darn fault :P
6572 Some(_) => DirectoryOwnership::Owned { relative: None },
6573 _ => DirectoryOwnership::UnownedViaMod(true),
6580 let relative = match self.directory.ownership {
6581 DirectoryOwnership::Owned { relative } => relative,
6582 DirectoryOwnership::UnownedViaBlock |
6583 DirectoryOwnership::UnownedViaMod(_) => None,
6585 let paths = Parser::default_submod_path(
6586 id, relative, &self.directory.path, self.sess.source_map());
6588 match self.directory.ownership {
6589 DirectoryOwnership::Owned { .. } => {
6590 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6592 DirectoryOwnership::UnownedViaBlock => {
6594 "Cannot declare a non-inline module inside a block \
6595 unless it has a path attribute";
6596 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6597 if paths.path_exists {
6598 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6600 err.span_note(id_sp, &msg);
6604 DirectoryOwnership::UnownedViaMod(warn) => {
6606 if let Ok(result) = paths.result {
6607 return Ok(ModulePathSuccess { warn: true, ..result });
6610 let mut err = self.diagnostic().struct_span_err(id_sp,
6611 "cannot declare a new module at this location");
6612 if !id_sp.is_dummy() {
6613 let src_path = self.sess.source_map().span_to_filename(id_sp);
6614 if let FileName::Real(src_path) = src_path {
6615 if let Some(stem) = src_path.file_stem() {
6616 let mut dest_path = src_path.clone();
6617 dest_path.set_file_name(stem);
6618 dest_path.push("mod.rs");
6619 err.span_note(id_sp,
6620 &format!("maybe move this module `{}` to its own \
6621 directory via `{}`", src_path.display(),
6622 dest_path.display()));
6626 if paths.path_exists {
6627 err.span_note(id_sp,
6628 &format!("... or maybe `use` the module `{}` instead \
6629 of possibly redeclaring it",
6637 /// Reads a module from a source file.
6641 directory_ownership: DirectoryOwnership,
6644 ) -> PResult<'a, (ast::Mod, Vec<Attribute>)> {
6645 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6646 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6647 let mut err = String::from("circular modules: ");
6648 let len = included_mod_stack.len();
6649 for p in &included_mod_stack[i.. len] {
6650 err.push_str(&p.to_string_lossy());
6651 err.push_str(" -> ");
6653 err.push_str(&path.to_string_lossy());
6654 return Err(self.span_fatal(id_sp, &err[..]));
6656 included_mod_stack.push(path.clone());
6657 drop(included_mod_stack);
6660 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6661 p0.cfg_mods = self.cfg_mods;
6662 let mod_inner_lo = p0.token.span;
6663 let mod_attrs = p0.parse_inner_attributes()?;
6664 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6666 self.sess.included_mod_stack.borrow_mut().pop();
6670 /// Parses a function declaration from a foreign module.
6671 fn parse_item_foreign_fn(
6673 vis: ast::Visibility,
6675 attrs: Vec<Attribute>,
6677 ) -> PResult<'a, ForeignItem> {
6678 self.expect_keyword(kw::Fn)?;
6680 let (ident, mut generics) = self.parse_fn_header()?;
6681 let decl = self.parse_fn_decl(true)?;
6682 generics.where_clause = self.parse_where_clause()?;
6683 let hi = self.token.span;
6684 self.parse_semi_or_incorrect_foreign_fn_body(&ident, extern_sp)?;
6685 Ok(ast::ForeignItem {
6688 node: ForeignItemKind::Fn(decl, generics),
6689 id: ast::DUMMY_NODE_ID,
6695 /// Parses a static item from a foreign module.
6696 /// Assumes that the `static` keyword is already parsed.
6697 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6698 -> PResult<'a, ForeignItem> {
6699 let mutbl = self.parse_mutability();
6700 let ident = self.parse_ident()?;
6701 self.expect(&token::Colon)?;
6702 let ty = self.parse_ty()?;
6703 let hi = self.token.span;
6704 self.expect(&token::Semi)?;
6708 node: ForeignItemKind::Static(ty, mutbl),
6709 id: ast::DUMMY_NODE_ID,
6715 /// Parses a type from a foreign module.
6716 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6717 -> PResult<'a, ForeignItem> {
6718 self.expect_keyword(kw::Type)?;
6720 let ident = self.parse_ident()?;
6721 let hi = self.token.span;
6722 self.expect(&token::Semi)?;
6723 Ok(ast::ForeignItem {
6726 node: ForeignItemKind::Ty,
6727 id: ast::DUMMY_NODE_ID,
6733 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6734 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6735 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6737 let mut ident = if self.token.is_keyword(kw::SelfLower) {
6738 self.parse_path_segment_ident()
6742 let mut idents = vec![];
6743 let mut replacement = vec![];
6744 let mut fixed_crate_name = false;
6745 // Accept `extern crate name-like-this` for better diagnostics
6746 let dash = token::BinOp(token::BinOpToken::Minus);
6747 if self.token == dash { // Do not include `-` as part of the expected tokens list
6748 while self.eat(&dash) {
6749 fixed_crate_name = true;
6750 replacement.push((self.prev_span, "_".to_string()));
6751 idents.push(self.parse_ident()?);
6754 if fixed_crate_name {
6755 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6756 let mut fixed_name = format!("{}", ident.name);
6757 for part in idents {
6758 fixed_name.push_str(&format!("_{}", part.name));
6760 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6762 self.struct_span_err(fixed_name_sp, error_msg)
6763 .span_label(fixed_name_sp, "dash-separated idents are not valid")
6764 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
6770 /// Parses `extern crate` links.
6775 /// extern crate foo;
6776 /// extern crate bar as foo;
6778 fn parse_item_extern_crate(&mut self,
6780 visibility: Visibility,
6781 attrs: Vec<Attribute>)
6782 -> PResult<'a, P<Item>> {
6783 // Accept `extern crate name-like-this` for better diagnostics
6784 let orig_name = self.parse_crate_name_with_dashes()?;
6785 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6786 (rename, Some(orig_name.name))
6790 self.expect(&token::Semi)?;
6792 let span = lo.to(self.prev_span);
6793 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6796 /// Parses `extern` for foreign ABIs modules.
6798 /// `extern` is expected to have been
6799 /// consumed before calling this method.
6803 /// ```ignore (only-for-syntax-highlight)
6807 fn parse_item_foreign_mod(
6810 opt_abi: Option<Abi>,
6811 visibility: Visibility,
6812 mut attrs: Vec<Attribute>,
6814 ) -> PResult<'a, P<Item>> {
6815 self.expect(&token::OpenDelim(token::Brace))?;
6817 let abi = opt_abi.unwrap_or(Abi::C);
6819 attrs.extend(self.parse_inner_attributes()?);
6821 let mut foreign_items = vec![];
6822 while !self.eat(&token::CloseDelim(token::Brace)) {
6823 foreign_items.push(self.parse_foreign_item(extern_sp)?);
6826 let prev_span = self.prev_span;
6827 let m = ast::ForeignMod {
6829 items: foreign_items
6831 let invalid = Ident::invalid();
6832 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6835 /// Parses `type Foo = Bar;`
6837 /// `existential type Foo: Bar;`
6840 /// without modifying the parser state.
6841 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6842 // This parses the grammar:
6843 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6844 if self.check_keyword(kw::Type) ||
6845 self.check_keyword(kw::Existential) &&
6846 self.is_keyword_ahead(1, &[kw::Type]) {
6847 let existential = self.eat_keyword(kw::Existential);
6848 assert!(self.eat_keyword(kw::Type));
6849 Some(self.parse_existential_or_alias(existential))
6855 /// Parses a type alias or existential type.
6856 fn parse_existential_or_alias(
6859 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6860 let ident = self.parse_ident()?;
6861 let mut tps = self.parse_generics()?;
6862 tps.where_clause = self.parse_where_clause()?;
6863 let alias = if existential {
6864 self.expect(&token::Colon)?;
6865 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6866 AliasKind::Existential(bounds)
6868 self.expect(&token::Eq)?;
6869 let ty = self.parse_ty()?;
6872 self.expect(&token::Semi)?;
6873 Ok((ident, alias, tps))
6876 /// Parses the part of an enum declaration following the `{`.
6877 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6878 let mut variants = Vec::new();
6879 while self.token != token::CloseDelim(token::Brace) {
6880 let variant_attrs = self.parse_outer_attributes()?;
6881 let vlo = self.token.span;
6884 let ident = self.parse_ident()?;
6886 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
6887 // Parse a struct variant.
6888 let (fields, recovered) = self.parse_record_struct_body()?;
6889 VariantData::Struct(fields, recovered)
6890 } else if self.check(&token::OpenDelim(token::Paren)) {
6892 self.parse_tuple_struct_body()?,
6896 VariantData::Unit(ast::DUMMY_NODE_ID)
6899 let disr_expr = if self.eat(&token::Eq) {
6901 id: ast::DUMMY_NODE_ID,
6902 value: self.parse_expr()?,
6908 let vr = ast::Variant_ {
6910 id: ast::DUMMY_NODE_ID,
6911 attrs: variant_attrs,
6915 variants.push(respan(vlo.to(self.prev_span), vr));
6917 if !self.eat(&token::Comma) {
6918 if self.token.is_ident() && !self.token.is_reserved_ident() {
6919 let sp = self.sess.source_map().next_point(self.prev_span);
6920 self.struct_span_err(sp, "missing comma")
6921 .span_suggestion_short(
6925 Applicability::MaybeIncorrect,
6933 self.expect(&token::CloseDelim(token::Brace))?;
6935 Ok(ast::EnumDef { variants })
6938 /// Parses an enum declaration.
6939 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6940 let id = self.parse_ident()?;
6941 let mut generics = self.parse_generics()?;
6942 generics.where_clause = self.parse_where_clause()?;
6943 self.expect(&token::OpenDelim(token::Brace))?;
6945 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6946 self.recover_stmt();
6947 self.eat(&token::CloseDelim(token::Brace));
6950 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6953 /// Parses a string as an ABI spec on an extern type or module. Consumes
6954 /// the `extern` keyword, if one is found.
6955 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6956 match self.token.kind {
6957 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
6958 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
6959 let sp = self.token.span;
6960 self.expect_no_suffix(sp, "an ABI spec", suffix);
6962 match abi::lookup(&symbol.as_str()) {
6963 Some(abi) => Ok(Some(abi)),
6965 let prev_span = self.prev_span;
6967 self.sess.span_diagnostic,
6970 "invalid ABI: found `{}`",
6973 .span_label(prev_span, "invalid ABI")
6974 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
6985 fn is_static_global(&mut self) -> bool {
6986 if self.check_keyword(kw::Static) {
6987 // Check if this could be a closure
6988 !self.look_ahead(1, |token| {
6989 if token.is_keyword(kw::Move) {
6993 token::BinOp(token::Or) | token::OrOr => true,
7004 attrs: Vec<Attribute>,
7005 macros_allowed: bool,
7006 attributes_allowed: bool,
7007 ) -> PResult<'a, Option<P<Item>>> {
7008 let mut unclosed_delims = vec![];
7009 let (ret, tokens) = self.collect_tokens(|this| {
7010 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7011 unclosed_delims.append(&mut this.unclosed_delims);
7014 self.unclosed_delims.append(&mut unclosed_delims);
7016 // Once we've parsed an item and recorded the tokens we got while
7017 // parsing we may want to store `tokens` into the item we're about to
7018 // return. Note, though, that we specifically didn't capture tokens
7019 // related to outer attributes. The `tokens` field here may later be
7020 // used with procedural macros to convert this item back into a token
7021 // stream, but during expansion we may be removing attributes as we go
7024 // If we've got inner attributes then the `tokens` we've got above holds
7025 // these inner attributes. If an inner attribute is expanded we won't
7026 // actually remove it from the token stream, so we'll just keep yielding
7027 // it (bad!). To work around this case for now we just avoid recording
7028 // `tokens` if we detect any inner attributes. This should help keep
7029 // expansion correct, but we should fix this bug one day!
7032 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7033 i.tokens = Some(tokens);
7040 /// Parses one of the items allowed by the flags.
7041 fn parse_item_implementation(
7043 attrs: Vec<Attribute>,
7044 macros_allowed: bool,
7045 attributes_allowed: bool,
7046 ) -> PResult<'a, Option<P<Item>>> {
7047 maybe_whole!(self, NtItem, |item| {
7048 let mut item = item.into_inner();
7049 let mut attrs = attrs;
7050 mem::swap(&mut item.attrs, &mut attrs);
7051 item.attrs.extend(attrs);
7055 let lo = self.token.span;
7057 let visibility = self.parse_visibility(false)?;
7059 if self.eat_keyword(kw::Use) {
7061 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7062 self.expect(&token::Semi)?;
7064 let span = lo.to(self.prev_span);
7066 self.mk_item(span, Ident::invalid(), item_, visibility, attrs);
7067 return Ok(Some(item));
7070 if self.eat_keyword(kw::Extern) {
7071 let extern_sp = self.prev_span;
7072 if self.eat_keyword(kw::Crate) {
7073 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7076 let opt_abi = self.parse_opt_abi()?;
7078 if self.eat_keyword(kw::Fn) {
7079 // EXTERN FUNCTION ITEM
7080 let fn_span = self.prev_span;
7081 let abi = opt_abi.unwrap_or(Abi::C);
7082 let (ident, item_, extra_attrs) =
7083 self.parse_item_fn(Unsafety::Normal,
7084 respan(fn_span, IsAsync::NotAsync),
7085 respan(fn_span, Constness::NotConst),
7087 let prev_span = self.prev_span;
7088 let item = self.mk_item(lo.to(prev_span),
7092 maybe_append(attrs, extra_attrs));
7093 return Ok(Some(item));
7094 } else if self.check(&token::OpenDelim(token::Brace)) {
7096 self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs, extern_sp)?,
7103 if self.is_static_global() {
7106 let m = if self.eat_keyword(kw::Mut) {
7109 Mutability::Immutable
7111 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7112 let prev_span = self.prev_span;
7113 let item = self.mk_item(lo.to(prev_span),
7117 maybe_append(attrs, extra_attrs));
7118 return Ok(Some(item));
7120 if self.eat_keyword(kw::Const) {
7121 let const_span = self.prev_span;
7122 if self.check_keyword(kw::Fn)
7123 || (self.check_keyword(kw::Unsafe)
7124 && self.is_keyword_ahead(1, &[kw::Fn])) {
7125 // CONST FUNCTION ITEM
7126 let unsafety = self.parse_unsafety();
7128 let (ident, item_, extra_attrs) =
7129 self.parse_item_fn(unsafety,
7130 respan(const_span, IsAsync::NotAsync),
7131 respan(const_span, Constness::Const),
7133 let prev_span = self.prev_span;
7134 let item = self.mk_item(lo.to(prev_span),
7138 maybe_append(attrs, extra_attrs));
7139 return Ok(Some(item));
7143 if self.eat_keyword(kw::Mut) {
7144 let prev_span = self.prev_span;
7145 self.struct_span_err(prev_span, "const globals cannot be mutable")
7146 .span_label(prev_span, "cannot be mutable")
7149 "you might want to declare a static instead",
7150 "static".to_owned(),
7151 Applicability::MaybeIncorrect,
7155 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7156 let prev_span = self.prev_span;
7157 let item = self.mk_item(lo.to(prev_span),
7161 maybe_append(attrs, extra_attrs));
7162 return Ok(Some(item));
7165 // Parse `async unsafe? fn`.
7166 if self.check_keyword(kw::Async) {
7167 let async_span = self.token.span;
7168 if self.is_keyword_ahead(1, &[kw::Fn])
7169 || self.is_keyword_ahead(2, &[kw::Fn])
7171 // ASYNC FUNCTION ITEM
7172 self.bump(); // `async`
7173 let unsafety = self.parse_unsafety(); // `unsafe`?
7174 self.expect_keyword(kw::Fn)?; // `fn`
7175 let fn_span = self.prev_span;
7176 let (ident, item_, extra_attrs) =
7177 self.parse_item_fn(unsafety,
7178 respan(async_span, IsAsync::Async {
7179 closure_id: ast::DUMMY_NODE_ID,
7180 return_impl_trait_id: ast::DUMMY_NODE_ID,
7182 respan(fn_span, Constness::NotConst),
7184 let prev_span = self.prev_span;
7185 let item = self.mk_item(lo.to(prev_span),
7189 maybe_append(attrs, extra_attrs));
7190 self.ban_async_in_2015(async_span);
7191 return Ok(Some(item));
7194 if self.check_keyword(kw::Unsafe) &&
7195 self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
7197 // UNSAFE TRAIT ITEM
7198 self.bump(); // `unsafe`
7199 let is_auto = if self.eat_keyword(kw::Trait) {
7202 self.expect_keyword(kw::Auto)?;
7203 self.expect_keyword(kw::Trait)?;
7206 let (ident, item_, extra_attrs) =
7207 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7208 let prev_span = self.prev_span;
7209 let item = self.mk_item(lo.to(prev_span),
7213 maybe_append(attrs, extra_attrs));
7214 return Ok(Some(item));
7216 if self.check_keyword(kw::Impl) ||
7217 self.check_keyword(kw::Unsafe) &&
7218 self.is_keyword_ahead(1, &[kw::Impl]) ||
7219 self.check_keyword(kw::Default) &&
7220 self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) {
7222 let defaultness = self.parse_defaultness();
7223 let unsafety = self.parse_unsafety();
7224 self.expect_keyword(kw::Impl)?;
7225 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7226 let span = lo.to(self.prev_span);
7227 return Ok(Some(self.mk_item(span, ident, item, visibility,
7228 maybe_append(attrs, extra_attrs))));
7230 if self.check_keyword(kw::Fn) {
7233 let fn_span = self.prev_span;
7234 let (ident, item_, extra_attrs) =
7235 self.parse_item_fn(Unsafety::Normal,
7236 respan(fn_span, IsAsync::NotAsync),
7237 respan(fn_span, Constness::NotConst),
7239 let prev_span = self.prev_span;
7240 let item = self.mk_item(lo.to(prev_span),
7244 maybe_append(attrs, extra_attrs));
7245 return Ok(Some(item));
7247 if self.check_keyword(kw::Unsafe)
7248 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7249 // UNSAFE FUNCTION ITEM
7250 self.bump(); // `unsafe`
7251 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7252 self.check(&token::OpenDelim(token::Brace));
7253 let abi = if self.eat_keyword(kw::Extern) {
7254 self.parse_opt_abi()?.unwrap_or(Abi::C)
7258 self.expect_keyword(kw::Fn)?;
7259 let fn_span = self.prev_span;
7260 let (ident, item_, extra_attrs) =
7261 self.parse_item_fn(Unsafety::Unsafe,
7262 respan(fn_span, IsAsync::NotAsync),
7263 respan(fn_span, Constness::NotConst),
7265 let prev_span = self.prev_span;
7266 let item = self.mk_item(lo.to(prev_span),
7270 maybe_append(attrs, extra_attrs));
7271 return Ok(Some(item));
7273 if self.eat_keyword(kw::Mod) {
7275 let (ident, item_, extra_attrs) =
7276 self.parse_item_mod(&attrs[..])?;
7277 let prev_span = self.prev_span;
7278 let item = self.mk_item(lo.to(prev_span),
7282 maybe_append(attrs, extra_attrs));
7283 return Ok(Some(item));
7285 if let Some(type_) = self.eat_type() {
7286 let (ident, alias, generics) = type_?;
7288 let item_ = match alias {
7289 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7290 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7292 let prev_span = self.prev_span;
7293 let item = self.mk_item(lo.to(prev_span),
7298 return Ok(Some(item));
7300 if self.eat_keyword(kw::Enum) {
7302 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7303 let prev_span = self.prev_span;
7304 let item = self.mk_item(lo.to(prev_span),
7308 maybe_append(attrs, extra_attrs));
7309 return Ok(Some(item));
7311 if self.check_keyword(kw::Trait)
7312 || (self.check_keyword(kw::Auto)
7313 && self.is_keyword_ahead(1, &[kw::Trait]))
7315 let is_auto = if self.eat_keyword(kw::Trait) {
7318 self.expect_keyword(kw::Auto)?;
7319 self.expect_keyword(kw::Trait)?;
7323 let (ident, item_, extra_attrs) =
7324 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7325 let prev_span = self.prev_span;
7326 let item = self.mk_item(lo.to(prev_span),
7330 maybe_append(attrs, extra_attrs));
7331 return Ok(Some(item));
7333 if self.eat_keyword(kw::Struct) {
7335 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7336 let prev_span = self.prev_span;
7337 let item = self.mk_item(lo.to(prev_span),
7341 maybe_append(attrs, extra_attrs));
7342 return Ok(Some(item));
7344 if self.is_union_item() {
7347 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7348 let prev_span = self.prev_span;
7349 let item = self.mk_item(lo.to(prev_span),
7353 maybe_append(attrs, extra_attrs));
7354 return Ok(Some(item));
7356 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7357 return Ok(Some(macro_def));
7360 // Verify whether we have encountered a struct or method definition where the user forgot to
7361 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7362 if visibility.node.is_pub() &&
7363 self.check_ident() &&
7364 self.look_ahead(1, |t| *t != token::Not)
7366 // Space between `pub` keyword and the identifier
7369 // ^^^ `sp` points here
7370 let sp = self.prev_span.between(self.token.span);
7371 let full_sp = self.prev_span.to(self.token.span);
7372 let ident_sp = self.token.span;
7373 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7374 // possible public struct definition where `struct` was forgotten
7375 let ident = self.parse_ident().unwrap();
7376 let msg = format!("add `struct` here to parse `{}` as a public struct",
7378 let mut err = self.diagnostic()
7379 .struct_span_err(sp, "missing `struct` for struct definition");
7380 err.span_suggestion_short(
7381 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7384 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7385 let ident = self.parse_ident().unwrap();
7387 let kw_name = if let Ok(Some(_)) = self.parse_self_arg_with_attrs()
7388 .map_err(|mut e| e.cancel())
7394 self.consume_block(token::Paren);
7395 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7396 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7398 ("fn", kw_name, false)
7399 } else if self.check(&token::OpenDelim(token::Brace)) {
7401 ("fn", kw_name, false)
7402 } else if self.check(&token::Colon) {
7406 ("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 self.consume_block(token::Brace);
7413 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7417 err.span_suggestion_short(
7418 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7421 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
7422 err.span_suggestion(
7424 "if you meant to call a macro, try",
7425 format!("{}!", snippet),
7426 // this is the `ambiguous` conditional branch
7427 Applicability::MaybeIncorrect
7430 err.help("if you meant to call a macro, remove the `pub` \
7431 and add a trailing `!` after the identifier");
7435 } else if self.look_ahead(1, |t| *t == token::Lt) {
7436 let ident = self.parse_ident().unwrap();
7437 self.eat_to_tokens(&[&token::Gt]);
7439 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7440 if let Ok(Some(_)) = self.parse_self_arg_with_attrs()
7441 .map_err(|mut e| e.cancel())
7443 ("fn", "method", false)
7445 ("fn", "function", false)
7447 } else if self.check(&token::OpenDelim(token::Brace)) {
7448 ("struct", "struct", false)
7450 ("fn` or `struct", "function or struct", true)
7452 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7453 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7455 err.span_suggestion_short(
7457 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7458 format!(" {} ", kw),
7459 Applicability::MachineApplicable,
7465 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7468 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
7469 fn ban_async_in_2015(&self, async_span: Span) {
7470 if async_span.rust_2015() {
7472 .struct_span_err_with_code(
7474 "`async fn` is not permitted in the 2015 edition",
7475 DiagnosticId::Error("E0670".into())
7481 /// Parses a foreign item.
7482 crate fn parse_foreign_item(&mut self, extern_sp: Span) -> PResult<'a, ForeignItem> {
7483 maybe_whole!(self, NtForeignItem, |ni| ni);
7485 let attrs = self.parse_outer_attributes()?;
7486 let lo = self.token.span;
7487 let visibility = self.parse_visibility(false)?;
7489 // FOREIGN STATIC ITEM
7490 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7491 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
7492 if self.token.is_keyword(kw::Const) {
7494 .struct_span_err(self.token.span, "extern items cannot be `const`")
7497 "try using a static value",
7498 "static".to_owned(),
7499 Applicability::MachineApplicable
7502 self.bump(); // `static` or `const`
7503 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7505 // FOREIGN FUNCTION ITEM
7506 if self.check_keyword(kw::Fn) {
7507 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?);
7509 // FOREIGN TYPE ITEM
7510 if self.check_keyword(kw::Type) {
7511 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7514 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7518 ident: Ident::invalid(),
7519 span: lo.to(self.prev_span),
7520 id: ast::DUMMY_NODE_ID,
7523 node: ForeignItemKind::Macro(mac),
7528 if !attrs.is_empty() {
7529 self.expected_item_err(&attrs)?;
7537 /// This is the fall-through for parsing items.
7538 fn parse_macro_use_or_failure(
7540 attrs: Vec<Attribute> ,
7541 macros_allowed: bool,
7542 attributes_allowed: bool,
7544 visibility: Visibility
7545 ) -> PResult<'a, Option<P<Item>>> {
7546 if macros_allowed && self.token.is_path_start() &&
7547 !(self.is_async_fn() && self.token.span.rust_2015()) {
7548 // MACRO INVOCATION ITEM
7550 let prev_span = self.prev_span;
7551 self.complain_if_pub_macro(&visibility.node, prev_span);
7553 let mac_lo = self.token.span;
7556 let path = self.parse_path(PathStyle::Mod)?;
7557 self.expect(&token::Not)?;
7558 let (delim, tts) = self.expect_delimited_token_tree()?;
7559 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
7560 self.report_invalid_macro_expansion_item();
7563 let hi = self.prev_span;
7564 let mac = respan(mac_lo.to(hi), Mac_ { path, tts, delim });
7566 self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs);
7567 return Ok(Some(item));
7570 // FAILURE TO PARSE ITEM
7571 match visibility.node {
7572 VisibilityKind::Inherited => {}
7574 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7578 if !attributes_allowed && !attrs.is_empty() {
7579 self.expected_item_err(&attrs)?;
7584 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
7585 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7586 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7588 if self.token.is_path_start() &&
7589 !(self.is_async_fn() && self.token.span.rust_2015()) {
7590 let prev_span = self.prev_span;
7591 let lo = self.token.span;
7592 let path = self.parse_path(PathStyle::Mod)?;
7594 if path.segments.len() == 1 {
7595 if !self.eat(&token::Not) {
7596 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7599 self.expect(&token::Not)?;
7602 if let Some(vis) = vis {
7603 self.complain_if_pub_macro(&vis.node, prev_span);
7608 // eat a matched-delimiter token tree:
7609 let (delim, tts) = self.expect_delimited_token_tree()?;
7610 if delim != MacDelimiter::Brace {
7611 self.expect(&token::Semi)?;
7614 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path, tts, delim })))
7620 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7621 where F: FnOnce(&mut Self) -> PResult<'a, R>
7623 // Record all tokens we parse when parsing this item.
7624 let mut tokens = Vec::new();
7625 let prev_collecting = match self.token_cursor.frame.last_token {
7626 LastToken::Collecting(ref mut list) => {
7627 Some(mem::take(list))
7629 LastToken::Was(ref mut last) => {
7630 tokens.extend(last.take());
7634 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7635 let prev = self.token_cursor.stack.len();
7637 let last_token = if self.token_cursor.stack.len() == prev {
7638 &mut self.token_cursor.frame.last_token
7639 } else if self.token_cursor.stack.get(prev).is_none() {
7640 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
7641 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
7643 return Ok((ret?, TokenStream::new(vec![])));
7645 &mut self.token_cursor.stack[prev].last_token
7648 // Pull out the tokens that we've collected from the call to `f` above.
7649 let mut collected_tokens = match *last_token {
7650 LastToken::Collecting(ref mut v) => mem::take(v),
7651 LastToken::Was(ref was) => {
7652 let msg = format!("our vector went away? - found Was({:?})", was);
7653 debug!("collect_tokens: {}", msg);
7654 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
7655 // This can happen due to a bad interaction of two unrelated recovery mechanisms
7656 // with mismatched delimiters *and* recovery lookahead on the likely typo
7657 // `pub ident(` (#62895, different but similar to the case above).
7658 return Ok((ret?, TokenStream::new(vec![])));
7662 // If we're not at EOF our current token wasn't actually consumed by
7663 // `f`, but it'll still be in our list that we pulled out. In that case
7665 let extra_token = if self.token != token::Eof {
7666 collected_tokens.pop()
7671 // If we were previously collecting tokens, then this was a recursive
7672 // call. In that case we need to record all the tokens we collected in
7673 // our parent list as well. To do that we push a clone of our stream
7674 // onto the previous list.
7675 match prev_collecting {
7677 list.extend(collected_tokens.iter().cloned());
7678 list.extend(extra_token);
7679 *last_token = LastToken::Collecting(list);
7682 *last_token = LastToken::Was(extra_token);
7686 Ok((ret?, TokenStream::new(collected_tokens)))
7689 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7690 let attrs = self.parse_outer_attributes()?;
7691 self.parse_item_(attrs, true, false)
7695 fn is_import_coupler(&mut self) -> bool {
7696 self.check(&token::ModSep) &&
7697 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7698 *t == token::BinOp(token::Star))
7701 /// Parses a `UseTree`.
7704 /// USE_TREE = [`::`] `*` |
7705 /// [`::`] `{` USE_TREE_LIST `}` |
7707 /// PATH `::` `{` USE_TREE_LIST `}` |
7708 /// PATH [`as` IDENT]
7710 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7711 let lo = self.token.span;
7713 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7714 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7715 self.check(&token::BinOp(token::Star)) ||
7716 self.is_import_coupler() {
7717 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7718 let mod_sep_ctxt = self.token.span.ctxt();
7719 if self.eat(&token::ModSep) {
7720 prefix.segments.push(
7721 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7725 if self.eat(&token::BinOp(token::Star)) {
7728 UseTreeKind::Nested(self.parse_use_tree_list()?)
7731 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7732 prefix = self.parse_path(PathStyle::Mod)?;
7734 if self.eat(&token::ModSep) {
7735 if self.eat(&token::BinOp(token::Star)) {
7738 UseTreeKind::Nested(self.parse_use_tree_list()?)
7741 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7745 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7748 /// Parses a `UseTreeKind::Nested(list)`.
7751 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7753 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7754 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, ast::DUMMY_NODE_ID)))
7758 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7759 if self.eat_keyword(kw::As) {
7760 self.parse_ident_or_underscore().map(Some)
7766 /// Parses a source module as a crate. This is the main entry point for the parser.
7767 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7768 let lo = self.token.span;
7769 let krate = Ok(ast::Crate {
7770 attrs: self.parse_inner_attributes()?,
7771 module: self.parse_mod_items(&token::Eof, lo)?,
7772 span: lo.to(self.token.span),
7777 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7778 let ret = match self.token.kind {
7779 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
7780 (symbol, ast::StrStyle::Cooked, suffix),
7781 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
7782 (symbol, ast::StrStyle::Raw(n), suffix),
7789 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7790 match self.parse_optional_str() {
7791 Some((s, style, suf)) => {
7792 let sp = self.prev_span;
7793 self.expect_no_suffix(sp, "a string literal", suf);
7797 let msg = "expected string literal";
7798 let mut err = self.fatal(msg);
7799 err.span_label(self.token.span, msg);
7805 fn report_invalid_macro_expansion_item(&self) {
7806 self.struct_span_err(
7808 "macros that expand to items must be delimited with braces or followed by a semicolon",
7809 ).multipart_suggestion(
7810 "change the delimiters to curly braces",
7812 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
7813 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
7815 Applicability::MaybeIncorrect,
7817 self.sess.source_map.next_point(self.prev_span),
7820 Applicability::MaybeIncorrect,
7825 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
7826 for unmatched in unclosed_delims.iter() {
7827 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
7828 "incorrect close delimiter: `{}`",
7829 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
7831 err.span_label(unmatched.found_span, "incorrect close delimiter");
7832 if let Some(sp) = unmatched.candidate_span {
7833 err.span_label(sp, "close delimiter possibly meant for this");
7835 if let Some(sp) = unmatched.unclosed_span {
7836 err.span_label(sp, "un-closed delimiter");
7840 unclosed_delims.clear();