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, Guard, 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::source_map::{self, SourceMap, Spanned, respan};
38 use crate::parse::{SeqSep, classify, literal, token};
39 use crate::parse::lexer::UnmatchedBrace;
40 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
41 use crate::parse::token::{Token, DelimToken};
42 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
43 use crate::util::parser::{AssocOp, Fixity};
44 use crate::print::pprust;
46 use crate::parse::PResult;
48 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
49 use crate::symbol::{kw, sym, Symbol};
50 use crate::parse::diagnostics::{Error, dummy_arg};
52 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
53 use rustc_target::spec::abi::{self, Abi};
54 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($p.span, ExprKind::Path(None, path), ThinVec::new()));
137 token::NtBlock(block) => {
138 let block = block.clone();
140 return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
148 /// As maybe_whole_expr, but for things other than expressions
149 macro_rules! maybe_whole {
150 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
151 if let token::Interpolated(nt) = &$p.token.kind {
152 if let token::$constructor(x) = &**nt {
161 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
162 macro_rules! maybe_recover_from_interpolated_ty_qpath {
163 ($self: expr, $allow_qpath_recovery: expr) => {
164 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
165 if let token::Interpolated(nt) = &$self.token.kind {
166 if let token::NtTy(ty) = &**nt {
169 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
176 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
177 if let Some(ref mut rhs) = rhs {
183 #[derive(Debug, Clone, Copy, PartialEq)]
195 // NOTE: `Ident`s are handled by `common.rs`.
198 pub struct Parser<'a> {
199 pub sess: &'a ParseSess,
200 /// The current token.
202 /// The span of the previous token.
203 meta_var_span: Option<Span>,
204 /// The span of the previous token.
206 /// The previous token kind.
207 prev_token_kind: PrevTokenKind,
208 restrictions: Restrictions,
209 /// Used to determine the path to externally loaded source files.
210 crate directory: Directory<'a>,
211 /// `true` to parse sub-modules in other files.
212 pub recurse_into_file_modules: bool,
213 /// Name of the root module this parser originated from. If `None`, then the
214 /// name is not known. This does not change while the parser is descending
215 /// into modules, and sub-parsers have new values for this name.
216 pub root_module_name: Option<String>,
217 crate expected_tokens: Vec<TokenType>,
218 crate token_cursor: TokenCursor,
219 desugar_doc_comments: bool,
220 /// `true` we should configure out of line modules as we parse.
222 /// This field is used to keep track of how many left angle brackets we have seen. This is
223 /// required in order to detect extra leading left angle brackets (`<` characters) and error
226 /// See the comments in the `parse_path_segment` function for more details.
227 crate unmatched_angle_bracket_count: u32,
228 crate max_angle_bracket_count: u32,
229 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
230 /// it gets removed from here. Every entry left at the end gets emitted as an independent
232 crate unclosed_delims: Vec<UnmatchedBrace>,
233 crate last_unexpected_token_span: Option<Span>,
234 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
235 crate subparser_name: Option<&'static str>,
238 impl<'a> Drop for Parser<'a> {
240 let diag = self.diagnostic();
241 emit_unclosed_delims(&mut self.unclosed_delims, diag);
245 // FIXME: Parser uses `self.span` all the time.
246 // Remove this impl if you think that using `self.token.span` instead is acceptable.
247 impl Deref for Parser<'_> {
249 fn deref(&self) -> &Self::Target {
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(sp: 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 { kind: token::Eof, span: 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 (sp, name) = match self.next() {
341 Token { span, kind: token::DocComment(name) } => (span, name),
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(sp, token::Ident(ast::Ident::with_empty_ctxt(sym::doc), false)),
366 TokenTree::token(sp, token::Eq),
367 TokenTree::token(sp, 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(sp, token::Pound), TokenTree::token(sp, token::Not), body]
379 .iter().cloned().collect::<TokenStream>().into()
381 [TokenTree::token(sp, token::Pound), body]
382 .iter().cloned().collect::<TokenStream>().into()
390 #[derive(Clone, PartialEq)]
391 crate enum TokenType {
392 Token(token::TokenKind),
403 crate fn to_string(&self) -> String {
405 TokenType::Token(ref t) => format!("`{}`", pprust::token_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::TokenKind) -> 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 { kind: token::Whitespace, span: DUMMY_SP },
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,
509 parser.token = parser.next_tok();
511 if let Some(directory) = directory {
512 parser.directory = directory;
513 } else if !parser.span.is_dummy() {
514 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
516 parser.directory.path = Cow::from(path);
520 parser.process_potential_macro_variable();
524 fn next_tok(&mut self) -> Token {
525 let mut next = if self.desugar_doc_comments {
526 self.token_cursor.next_desugared()
528 self.token_cursor.next()
530 if next.span.is_dummy() {
531 // Tweak the location for better diagnostics, but keep syntactic context intact.
532 next.span = self.prev_span.with_ctxt(next.span.ctxt());
537 /// Converts the current token to a string using `self`'s reader.
538 pub fn this_token_to_string(&self) -> String {
539 pprust::token_to_string(&self.token)
542 crate fn token_descr(&self) -> Option<&'static str> {
543 Some(match &self.token.kind {
544 t if t.is_special_ident() => "reserved identifier",
545 t if t.is_used_keyword() => "keyword",
546 t if t.is_unused_keyword() => "reserved keyword",
547 token::DocComment(..) => "doc comment",
552 crate fn this_token_descr(&self) -> String {
553 if let Some(prefix) = self.token_descr() {
554 format!("{} `{}`", prefix, self.this_token_to_string())
556 format!("`{}`", self.this_token_to_string())
560 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
561 match self.expect_one_of(&[], &[]) {
563 Ok(_) => unreachable!(),
567 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
568 pub fn expect(&mut self, t: &token::TokenKind) -> PResult<'a, bool /* recovered */> {
569 if self.expected_tokens.is_empty() {
570 if self.token == *t {
574 self.unexpected_try_recover(t)
577 self.expect_one_of(slice::from_ref(t), &[])
581 /// Expect next token to be edible or inedible token. If edible,
582 /// then consume it; if inedible, then return without consuming
583 /// anything. Signal a fatal error if next token is unexpected.
584 pub fn expect_one_of(
586 edible: &[token::TokenKind],
587 inedible: &[token::TokenKind],
588 ) -> PResult<'a, bool /* recovered */> {
589 if edible.contains(&self.token) {
592 } else if inedible.contains(&self.token) {
593 // leave it in the input
595 } else if self.last_unexpected_token_span == Some(self.span) {
598 self.expected_one_of_not_found(edible, inedible)
602 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
603 fn interpolated_or_expr_span(
605 expr: PResult<'a, P<Expr>>,
606 ) -> PResult<'a, (Span, P<Expr>)> {
608 if self.prev_token_kind == PrevTokenKind::Interpolated {
616 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
617 self.parse_ident_common(true)
620 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
621 match self.token.kind {
622 token::Ident(ident, _) => {
623 if self.token.is_reserved_ident() {
624 let mut err = self.expected_ident_found();
631 let span = self.span;
633 Ok(Ident::new(ident.name, span))
636 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
637 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
639 self.expected_ident_found()
645 /// Checks if the next token is `tok`, and returns `true` if so.
647 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
649 crate fn check(&mut self, tok: &token::TokenKind) -> bool {
650 let is_present = self.token == *tok;
651 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
655 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
656 pub fn eat(&mut self, tok: &token::TokenKind) -> bool {
657 let is_present = self.check(tok);
658 if is_present { self.bump() }
662 fn check_keyword(&mut self, kw: Symbol) -> bool {
663 self.expected_tokens.push(TokenType::Keyword(kw));
664 self.token.is_keyword(kw)
667 /// If the next token is the given keyword, eats it and returns
668 /// `true`. Otherwise, returns `false`.
669 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
670 if self.check_keyword(kw) {
678 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
679 if self.token.is_keyword(kw) {
687 /// If the given word is not a keyword, signals an error.
688 /// If the next token is not the given word, signals an error.
689 /// Otherwise, eats it.
690 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
691 if !self.eat_keyword(kw) {
698 crate fn check_ident(&mut self) -> bool {
699 if self.token.is_ident() {
702 self.expected_tokens.push(TokenType::Ident);
707 fn check_path(&mut self) -> bool {
708 if self.token.is_path_start() {
711 self.expected_tokens.push(TokenType::Path);
716 fn check_type(&mut self) -> bool {
717 if self.token.can_begin_type() {
720 self.expected_tokens.push(TokenType::Type);
725 fn check_const_arg(&mut self) -> bool {
726 if self.token.can_begin_const_arg() {
729 self.expected_tokens.push(TokenType::Const);
734 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
735 /// and continues. If a `+` is not seen, returns `false`.
737 /// This is used when token-splitting `+=` into `+`.
738 /// See issue #47856 for an example of when this may occur.
739 fn eat_plus(&mut self) -> bool {
740 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
741 match self.token.kind {
742 token::BinOp(token::Plus) => {
746 token::BinOpEq(token::Plus) => {
747 let span = self.span.with_lo(self.span.lo() + BytePos(1));
748 self.bump_with(token::Eq, span);
756 /// Checks to see if the next token is either `+` or `+=`.
757 /// Otherwise returns `false`.
758 fn check_plus(&mut self) -> bool {
759 if self.token.is_like_plus() {
763 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
768 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
769 /// `&` and continues. If an `&` is not seen, signals an error.
770 fn expect_and(&mut self) -> PResult<'a, ()> {
771 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
772 match self.token.kind {
773 token::BinOp(token::And) => {
778 let span = self.span.with_lo(self.span.lo() + BytePos(1));
779 Ok(self.bump_with(token::BinOp(token::And), span))
781 _ => self.unexpected()
785 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
786 /// `|` and continues. If an `|` is not seen, signals an error.
787 fn expect_or(&mut self) -> PResult<'a, ()> {
788 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
789 match self.token.kind {
790 token::BinOp(token::Or) => {
795 let span = self.span.with_lo(self.span.lo() + BytePos(1));
796 Ok(self.bump_with(token::BinOp(token::Or), span))
798 _ => self.unexpected()
802 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
803 literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
806 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
807 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
808 /// and continue. If a `<` is not seen, returns false.
810 /// This is meant to be used when parsing generics on a path to get the
812 fn eat_lt(&mut self) -> bool {
813 self.expected_tokens.push(TokenType::Token(token::Lt));
814 let ate = match self.token.kind {
819 token::BinOp(token::Shl) => {
820 let span = self.span.with_lo(self.span.lo() + BytePos(1));
821 self.bump_with(token::Lt, span);
825 let span = self.span.with_lo(self.span.lo() + BytePos(1));
826 self.bump_with(token::BinOp(token::Minus), span);
833 // See doc comment for `unmatched_angle_bracket_count`.
834 self.unmatched_angle_bracket_count += 1;
835 self.max_angle_bracket_count += 1;
836 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
842 fn expect_lt(&mut self) -> PResult<'a, ()> {
850 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
851 /// with a single `>` and continues. If a `>` is not seen, signals an error.
852 fn expect_gt(&mut self) -> PResult<'a, ()> {
853 self.expected_tokens.push(TokenType::Token(token::Gt));
854 let ate = match self.token.kind {
859 token::BinOp(token::Shr) => {
860 let span = self.span.with_lo(self.span.lo() + BytePos(1));
861 Some(self.bump_with(token::Gt, span))
863 token::BinOpEq(token::Shr) => {
864 let span = self.span.with_lo(self.span.lo() + BytePos(1));
865 Some(self.bump_with(token::Ge, span))
868 let span = self.span.with_lo(self.span.lo() + BytePos(1));
869 Some(self.bump_with(token::Eq, span))
876 // See doc comment for `unmatched_angle_bracket_count`.
877 if self.unmatched_angle_bracket_count > 0 {
878 self.unmatched_angle_bracket_count -= 1;
879 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
884 None => self.unexpected(),
888 /// Parses a sequence, including the closing delimiter. The function
889 /// `f` must consume tokens until reaching the next separator or
891 pub fn parse_seq_to_end<T, F>(&mut self,
892 ket: &token::TokenKind,
895 -> PResult<'a, Vec<T>> where
896 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
898 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
905 /// Parses a sequence, not including the closing delimiter. The function
906 /// `f` must consume tokens until reaching the next separator or
908 pub fn parse_seq_to_before_end<T, F>(
910 ket: &token::TokenKind,
913 ) -> PResult<'a, (Vec<T>, bool)>
914 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
916 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
919 crate fn parse_seq_to_before_tokens<T, F>(
921 kets: &[&token::TokenKind],
923 expect: TokenExpectType,
925 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
926 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
928 let mut first = true;
929 let mut recovered = false;
931 while !kets.iter().any(|k| {
933 TokenExpectType::Expect => self.check(k),
934 TokenExpectType::NoExpect => self.token == **k,
937 match self.token.kind {
938 token::CloseDelim(..) | token::Eof => break,
941 if let Some(ref t) = sep.sep {
945 match self.expect(t) {
952 // Attempt to keep parsing if it was a similar separator
953 if let Some(ref tokens) = t.similar_tokens() {
954 if tokens.contains(&self.token) {
959 // Attempt to keep parsing if it was an omitted separator
974 if sep.trailing_sep_allowed && kets.iter().any(|k| {
976 TokenExpectType::Expect => self.check(k),
977 TokenExpectType::NoExpect => self.token == **k,
990 /// Parses a sequence, including the closing delimiter. The function
991 /// `f` must consume tokens until reaching the next separator or
993 fn parse_unspanned_seq<T, F>(
995 bra: &token::TokenKind,
996 ket: &token::TokenKind,
999 ) -> PResult<'a, Vec<T>> where
1000 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1003 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1010 /// Advance the parser by one token
1011 pub fn bump(&mut self) {
1012 if self.prev_token_kind == PrevTokenKind::Eof {
1013 // Bumping after EOF is a bad sign, usually an infinite loop.
1014 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1017 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1019 // Record last token kind for possible error recovery.
1020 self.prev_token_kind = match self.token.kind {
1021 token::DocComment(..) => PrevTokenKind::DocComment,
1022 token::Comma => PrevTokenKind::Comma,
1023 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1024 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1025 token::Interpolated(..) => PrevTokenKind::Interpolated,
1026 token::Eof => PrevTokenKind::Eof,
1027 token::Ident(..) => PrevTokenKind::Ident,
1028 _ => PrevTokenKind::Other,
1031 self.token = self.next_tok();
1032 self.expected_tokens.clear();
1033 // check after each token
1034 self.process_potential_macro_variable();
1037 /// Advance the parser using provided token as a next one. Use this when
1038 /// consuming a part of a token. For example a single `<` from `<<`.
1039 fn bump_with(&mut self, next: token::TokenKind, span: Span) {
1040 self.prev_span = self.span.with_hi(span.lo());
1041 // It would be incorrect to record the kind of the current token, but
1042 // fortunately for tokens currently using `bump_with`, the
1043 // prev_token_kind will be of no use anyway.
1044 self.prev_token_kind = PrevTokenKind::Other;
1045 self.token = Token { kind: next, span };
1046 self.expected_tokens.clear();
1049 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1050 F: FnOnce(&token::Token) -> R,
1053 // FIXME: Avoid cloning here.
1054 return f(&self.token);
1057 let frame = &self.token_cursor.frame;
1058 f(&match frame.tree_cursor.look_ahead(dist - 1) {
1059 Some(tree) => match tree {
1060 TokenTree::Token(token) => token,
1061 TokenTree::Delimited(dspan, delim, _) => Token { kind: token::OpenDelim(delim), span: dspan.open },
1063 None => Token { kind: token::CloseDelim(frame.delim), span: frame.span.close }
1067 crate fn look_ahead_span(&self, dist: usize) -> Span {
1072 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1073 Some(TokenTree::Token(token)) => token.span,
1074 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1075 None => self.look_ahead_span(dist - 1),
1079 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1080 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1081 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1084 /// Is the current token one of the keywords that signals a bare function type?
1085 fn token_is_bare_fn_keyword(&mut self) -> bool {
1086 self.check_keyword(kw::Fn) ||
1087 self.check_keyword(kw::Unsafe) ||
1088 self.check_keyword(kw::Extern)
1091 /// Parses a `TyKind::BareFn` type.
1092 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1095 [unsafe] [extern "ABI"] fn (S) -> T
1105 let unsafety = self.parse_unsafety();
1106 let abi = if self.eat_keyword(kw::Extern) {
1107 self.parse_opt_abi()?.unwrap_or(Abi::C)
1112 self.expect_keyword(kw::Fn)?;
1113 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1114 let ret_ty = self.parse_ret_ty(false)?;
1115 let decl = P(FnDecl {
1120 Ok(TyKind::BareFn(P(BareFnTy {
1128 /// Parses asyncness: `async` or nothing.
1129 fn parse_asyncness(&mut self) -> IsAsync {
1130 if self.eat_keyword(kw::Async) {
1132 closure_id: ast::DUMMY_NODE_ID,
1133 return_impl_trait_id: ast::DUMMY_NODE_ID,
1140 /// Parses unsafety: `unsafe` or nothing.
1141 fn parse_unsafety(&mut self) -> Unsafety {
1142 if self.eat_keyword(kw::Unsafe) {
1149 /// Parses the items in a trait declaration.
1150 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1151 maybe_whole!(self, NtTraitItem, |x| x);
1152 let attrs = self.parse_outer_attributes()?;
1153 let mut unclosed_delims = vec![];
1154 let (mut item, tokens) = self.collect_tokens(|this| {
1155 let item = this.parse_trait_item_(at_end, attrs);
1156 unclosed_delims.append(&mut this.unclosed_delims);
1159 self.unclosed_delims.append(&mut unclosed_delims);
1160 // See `parse_item` for why this clause is here.
1161 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1162 item.tokens = Some(tokens);
1167 fn parse_trait_item_(&mut self,
1169 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1172 let (name, node, generics) = if self.eat_keyword(kw::Type) {
1173 self.parse_trait_item_assoc_ty()?
1174 } else if self.is_const_item() {
1175 self.expect_keyword(kw::Const)?;
1176 let ident = self.parse_ident()?;
1177 self.expect(&token::Colon)?;
1178 let ty = self.parse_ty()?;
1179 let default = if self.eat(&token::Eq) {
1180 let expr = self.parse_expr()?;
1181 self.expect(&token::Semi)?;
1184 self.expect(&token::Semi)?;
1187 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1188 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1189 // trait item macro.
1190 (Ident::invalid(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1192 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1194 let ident = self.parse_ident()?;
1195 let mut generics = self.parse_generics()?;
1197 let decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1198 // This is somewhat dubious; We don't want to allow
1199 // argument names to be left off if there is a
1202 // We don't allow argument names to be left off in edition 2018.
1203 p.parse_arg_general(p.span.rust_2018(), true, false)
1205 generics.where_clause = self.parse_where_clause()?;
1207 let sig = ast::MethodSig {
1217 let body = match self.token.kind {
1221 debug!("parse_trait_methods(): parsing required method");
1224 token::OpenDelim(token::Brace) => {
1225 debug!("parse_trait_methods(): parsing provided method");
1227 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1228 attrs.extend(inner_attrs.iter().cloned());
1231 token::Interpolated(ref nt) => {
1233 token::NtBlock(..) => {
1235 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1236 attrs.extend(inner_attrs.iter().cloned());
1240 return self.expected_semi_or_open_brace();
1245 return self.expected_semi_or_open_brace();
1248 (ident, ast::TraitItemKind::Method(sig, body), generics)
1252 id: ast::DUMMY_NODE_ID,
1257 span: lo.to(self.prev_span),
1262 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1263 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1264 if self.eat(&token::RArrow) {
1265 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1267 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1272 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1273 self.parse_ty_common(true, true, false)
1276 /// Parses a type in restricted contexts where `+` is not permitted.
1278 /// Example 1: `&'a TYPE`
1279 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1280 /// Example 2: `value1 as TYPE + value2`
1281 /// `+` is prohibited to avoid interactions with expression grammar.
1282 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1283 self.parse_ty_common(false, true, false)
1286 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1287 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1288 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1289 maybe_whole!(self, NtTy, |x| x);
1292 let mut impl_dyn_multi = false;
1293 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1294 // `(TYPE)` is a parenthesized type.
1295 // `(TYPE,)` is a tuple with a single field of type TYPE.
1296 let mut ts = vec![];
1297 let mut last_comma = false;
1298 while self.token != token::CloseDelim(token::Paren) {
1299 ts.push(self.parse_ty()?);
1300 if self.eat(&token::Comma) {
1307 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1308 self.expect(&token::CloseDelim(token::Paren))?;
1310 if ts.len() == 1 && !last_comma {
1311 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1312 let maybe_bounds = allow_plus && self.token.is_like_plus();
1314 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1315 TyKind::Path(None, ref path) if maybe_bounds => {
1316 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1318 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1319 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1320 let path = match bounds[0] {
1321 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1322 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1324 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1327 _ => TyKind::Paren(P(ty))
1332 } else if self.eat(&token::Not) {
1335 } else if self.eat(&token::BinOp(token::Star)) {
1337 TyKind::Ptr(self.parse_ptr()?)
1338 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1340 let t = self.parse_ty()?;
1341 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1342 let t = match self.maybe_parse_fixed_length_of_vec()? {
1343 None => TyKind::Slice(t),
1344 Some(length) => TyKind::Array(t, AnonConst {
1345 id: ast::DUMMY_NODE_ID,
1349 self.expect(&token::CloseDelim(token::Bracket))?;
1351 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1354 self.parse_borrowed_pointee()?
1355 } else if self.eat_keyword_noexpect(kw::Typeof) {
1357 // In order to not be ambiguous, the type must be surrounded by parens.
1358 self.expect(&token::OpenDelim(token::Paren))?;
1360 id: ast::DUMMY_NODE_ID,
1361 value: self.parse_expr()?,
1363 self.expect(&token::CloseDelim(token::Paren))?;
1365 } else if self.eat_keyword(kw::Underscore) {
1366 // A type to be inferred `_`
1368 } else if self.token_is_bare_fn_keyword() {
1369 // Function pointer type
1370 self.parse_ty_bare_fn(Vec::new())?
1371 } else if self.check_keyword(kw::For) {
1372 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1373 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1374 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1376 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1377 if self.token_is_bare_fn_keyword() {
1378 self.parse_ty_bare_fn(lifetime_defs)?
1380 let path = self.parse_path(PathStyle::Type)?;
1381 let parse_plus = allow_plus && self.check_plus();
1382 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1384 } else if self.eat_keyword(kw::Impl) {
1385 // Always parse bounds greedily for better error recovery.
1386 let bounds = self.parse_generic_bounds(None)?;
1387 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1388 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1389 } else if self.check_keyword(kw::Dyn) &&
1390 (self.span.rust_2018() ||
1391 self.look_ahead(1, |t| t.can_begin_bound() &&
1392 !can_continue_type_after_non_fn_ident(t))) {
1393 self.bump(); // `dyn`
1394 // Always parse bounds greedily for better error recovery.
1395 let bounds = self.parse_generic_bounds(None)?;
1396 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1397 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1398 } else if self.check(&token::Question) ||
1399 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1400 // Bound list (trait object type)
1401 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1402 TraitObjectSyntax::None)
1403 } else if self.eat_lt() {
1405 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1406 TyKind::Path(Some(qself), path)
1407 } else if self.token.is_path_start() {
1409 let path = self.parse_path(PathStyle::Type)?;
1410 if self.eat(&token::Not) {
1411 // Macro invocation in type position
1412 let (delim, tts) = self.expect_delimited_token_tree()?;
1413 let node = Mac_ { path, tts, delim };
1414 TyKind::Mac(respan(lo.to(self.prev_span), node))
1416 // Just a type path or bound list (trait object type) starting with a trait.
1418 // `Trait1 + Trait2 + 'a`
1419 if allow_plus && self.check_plus() {
1420 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1422 TyKind::Path(None, path)
1425 } else if self.check(&token::DotDotDot) {
1426 if allow_c_variadic {
1427 self.eat(&token::DotDotDot);
1430 return Err(self.fatal(
1431 "only foreign functions are allowed to be C-variadic"
1435 let msg = format!("expected type, found {}", self.this_token_descr());
1436 return Err(self.fatal(&msg));
1439 let span = lo.to(self.prev_span);
1440 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1442 // Try to recover from use of `+` with incorrect priority.
1443 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1444 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1445 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1448 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1449 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1450 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1451 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1453 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1454 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1456 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1459 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1460 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1461 let mutbl = self.parse_mutability();
1462 let ty = self.parse_ty_no_plus()?;
1463 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1466 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1467 let mutbl = if self.eat_keyword(kw::Mut) {
1469 } else if self.eat_keyword(kw::Const) {
1470 Mutability::Immutable
1472 let span = self.prev_span;
1473 let msg = "expected mut or const in raw pointer type";
1474 self.struct_span_err(span, msg)
1475 .span_label(span, msg)
1476 .help("use `*mut T` or `*const T` as appropriate")
1478 Mutability::Immutable
1480 let t = self.parse_ty_no_plus()?;
1481 Ok(MutTy { ty: t, mutbl: mutbl })
1484 fn is_named_argument(&self) -> bool {
1485 let offset = match self.token.kind {
1486 token::Interpolated(ref nt) => match **nt {
1487 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1490 token::BinOp(token::And) | token::AndAnd => 1,
1491 _ if self.token.is_keyword(kw::Mut) => 1,
1495 self.look_ahead(offset, |t| t.is_ident()) &&
1496 self.look_ahead(offset + 1, |t| t == &token::Colon)
1499 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1501 /// This version of parse arg doesn't necessarily require identifier names.
1502 fn parse_arg_general(
1505 is_trait_item: bool,
1506 allow_c_variadic: bool,
1507 ) -> PResult<'a, Arg> {
1508 if let Ok(Some(arg)) = self.parse_self_arg() {
1509 return self.recover_bad_self_arg(arg, is_trait_item);
1512 let (pat, ty) = if require_name || self.is_named_argument() {
1513 debug!("parse_arg_general parse_pat (require_name:{})", require_name);
1514 self.eat_incorrect_doc_comment("method arguments");
1515 let pat = self.parse_pat(Some("argument name"))?;
1517 if let Err(mut err) = self.expect(&token::Colon) {
1518 if let Some(ident) = self.argument_without_type(
1525 return Ok(dummy_arg(ident));
1531 self.eat_incorrect_doc_comment("a method argument's type");
1532 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1534 debug!("parse_arg_general ident_to_pat");
1535 let parser_snapshot_before_ty = self.clone();
1536 self.eat_incorrect_doc_comment("a method argument's type");
1537 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1538 if ty.is_ok() && self.token != token::Comma &&
1539 self.token != token::CloseDelim(token::Paren) {
1540 // This wasn't actually a type, but a pattern looking like a type,
1541 // so we are going to rollback and re-parse for recovery.
1542 ty = self.unexpected();
1546 let ident = Ident::new(kw::Invalid, self.prev_span);
1548 id: ast::DUMMY_NODE_ID,
1549 node: PatKind::Ident(
1550 BindingMode::ByValue(Mutability::Immutable), ident, None),
1556 // If this is a C-variadic argument and we hit an error, return the
1558 if self.token == token::DotDotDot {
1561 // Recover from attempting to parse the argument as a type without pattern.
1563 mem::replace(self, parser_snapshot_before_ty);
1564 self.recover_arg_parse()?
1569 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1572 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
1573 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1574 let pat = self.parse_pat(Some("argument name"))?;
1575 let t = if self.eat(&token::Colon) {
1579 id: ast::DUMMY_NODE_ID,
1580 node: TyKind::Infer,
1581 span: self.prev_span,
1587 id: ast::DUMMY_NODE_ID
1591 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1592 if self.eat(&token::Semi) {
1593 Ok(Some(self.parse_expr()?))
1599 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1600 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1601 maybe_whole_expr!(self);
1603 let minus_lo = self.span;
1604 let minus_present = self.eat(&token::BinOp(token::Minus));
1606 let literal = self.parse_lit()?;
1607 let hi = self.prev_span;
1608 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1611 let minus_hi = self.prev_span;
1612 let unary = self.mk_unary(UnOp::Neg, expr);
1613 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1619 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1620 match self.token.kind {
1621 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1622 let span = self.span;
1624 Ok(Ident::new(ident.name, span))
1626 _ => self.parse_ident(),
1630 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
1631 match self.token.kind {
1632 token::Ident(ident, false) if ident.name == kw::Underscore => {
1633 let span = self.span;
1635 Ok(Ident::new(ident.name, span))
1637 _ => self.parse_ident(),
1641 /// Parses a qualified path.
1642 /// Assumes that the leading `<` has been parsed already.
1644 /// `qualified_path = <type [as trait_ref]>::path`
1649 /// `<T as U>::F::a<S>` (without disambiguator)
1650 /// `<T as U>::F::a::<S>` (with disambiguator)
1651 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1652 let lo = self.prev_span;
1653 let ty = self.parse_ty()?;
1655 // `path` will contain the prefix of the path up to the `>`,
1656 // if any (e.g., `U` in the `<T as U>::*` examples
1657 // above). `path_span` has the span of that path, or an empty
1658 // span in the case of something like `<T>::Bar`.
1659 let (mut path, path_span);
1660 if self.eat_keyword(kw::As) {
1661 let path_lo = self.span;
1662 path = self.parse_path(PathStyle::Type)?;
1663 path_span = path_lo.to(self.prev_span);
1665 path_span = self.span.to(self.span);
1666 path = ast::Path { segments: Vec::new(), span: path_span };
1669 // See doc comment for `unmatched_angle_bracket_count`.
1670 self.expect(&token::Gt)?;
1671 if self.unmatched_angle_bracket_count > 0 {
1672 self.unmatched_angle_bracket_count -= 1;
1673 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1676 self.expect(&token::ModSep)?;
1678 let qself = QSelf { ty, path_span, position: path.segments.len() };
1679 self.parse_path_segments(&mut path.segments, style)?;
1681 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1684 /// Parses simple paths.
1686 /// `path = [::] segment+`
1687 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1690 /// `a::b::C<D>` (without disambiguator)
1691 /// `a::b::C::<D>` (with disambiguator)
1692 /// `Fn(Args)` (without disambiguator)
1693 /// `Fn::(Args)` (with disambiguator)
1694 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1695 maybe_whole!(self, NtPath, |path| {
1696 if style == PathStyle::Mod &&
1697 path.segments.iter().any(|segment| segment.args.is_some()) {
1698 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1703 let lo = self.meta_var_span.unwrap_or(self.span);
1704 let mut segments = Vec::new();
1705 let mod_sep_ctxt = self.span.ctxt();
1706 if self.eat(&token::ModSep) {
1707 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
1709 self.parse_path_segments(&mut segments, style)?;
1711 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1714 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
1715 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
1717 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1718 let meta_ident = match self.token.kind {
1719 token::Interpolated(ref nt) => match **nt {
1720 token::NtMeta(ref meta) => match meta.node {
1721 ast::MetaItemKind::Word => Some(meta.path.clone()),
1728 if let Some(path) = meta_ident {
1732 self.parse_path(style)
1735 crate fn parse_path_segments(&mut self,
1736 segments: &mut Vec<PathSegment>,
1738 -> PResult<'a, ()> {
1740 let segment = self.parse_path_segment(style)?;
1741 if style == PathStyle::Expr {
1742 // In order to check for trailing angle brackets, we must have finished
1743 // recursing (`parse_path_segment` can indirectly call this function),
1744 // that is, the next token must be the highlighted part of the below example:
1746 // `Foo::<Bar as Baz<T>>::Qux`
1749 // As opposed to the below highlight (if we had only finished the first
1752 // `Foo::<Bar as Baz<T>>::Qux`
1755 // `PathStyle::Expr` is only provided at the root invocation and never in
1756 // `parse_path_segment` to recurse and therefore can be checked to maintain
1758 self.check_trailing_angle_brackets(&segment, token::ModSep);
1760 segments.push(segment);
1762 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1768 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
1769 let ident = self.parse_path_segment_ident()?;
1771 let is_args_start = |token: &token::TokenKind| match *token {
1772 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
1773 | token::LArrow => true,
1776 let check_args_start = |this: &mut Self| {
1777 this.expected_tokens.extend_from_slice(
1778 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1780 is_args_start(&this.token)
1783 Ok(if style == PathStyle::Type && check_args_start(self) ||
1784 style != PathStyle::Mod && self.check(&token::ModSep)
1785 && self.look_ahead(1, |t| is_args_start(t)) {
1786 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
1787 // it isn't, then we reset the unmatched angle bracket count as we're about to start
1788 // parsing a new path.
1789 if style == PathStyle::Expr {
1790 self.unmatched_angle_bracket_count = 0;
1791 self.max_angle_bracket_count = 0;
1794 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1795 self.eat(&token::ModSep);
1797 let args = if self.eat_lt() {
1799 let (args, constraints) =
1800 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
1802 let span = lo.to(self.prev_span);
1803 AngleBracketedArgs { args, constraints, span }.into()
1807 let (inputs, recovered) = self.parse_seq_to_before_tokens(
1808 &[&token::CloseDelim(token::Paren)],
1809 SeqSep::trailing_allowed(token::Comma),
1810 TokenExpectType::Expect,
1815 let span = lo.to(self.prev_span);
1816 let output = if self.eat(&token::RArrow) {
1817 Some(self.parse_ty_common(false, false, false)?)
1821 ParenthesizedArgs { inputs, output, span }.into()
1824 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
1826 // Generic arguments are not found.
1827 PathSegment::from_ident(ident)
1831 crate fn check_lifetime(&mut self) -> bool {
1832 self.expected_tokens.push(TokenType::Lifetime);
1833 self.token.is_lifetime()
1836 /// Parses a single lifetime `'a` or panics.
1837 crate fn expect_lifetime(&mut self) -> Lifetime {
1838 if let Some(ident) = self.token.lifetime() {
1839 let span = self.span;
1841 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
1843 self.span_bug(self.span, "not a lifetime")
1847 fn eat_label(&mut self) -> Option<Label> {
1848 if let Some(ident) = self.token.lifetime() {
1849 let span = self.span;
1851 Some(Label { ident: Ident::new(ident.name, span) })
1857 /// Parses mutability (`mut` or nothing).
1858 fn parse_mutability(&mut self) -> Mutability {
1859 if self.eat_keyword(kw::Mut) {
1862 Mutability::Immutable
1866 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1867 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind {
1868 self.expect_no_suffix(self.span, "a tuple index", suffix);
1870 Ok(Ident::new(symbol, self.prev_span))
1872 self.parse_ident_common(false)
1876 /// Parse ident (COLON expr)?
1877 fn parse_field(&mut self) -> PResult<'a, Field> {
1878 let attrs = self.parse_outer_attributes()?;
1881 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1882 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1883 t == &token::Colon || t == &token::Eq
1885 let fieldname = self.parse_field_name()?;
1887 // Check for an equals token. This means the source incorrectly attempts to
1888 // initialize a field with an eq rather than a colon.
1889 if self.token == token::Eq {
1891 .struct_span_err(self.span, "expected `:`, found `=`")
1893 fieldname.span.shrink_to_hi().to(self.span),
1894 "replace equals symbol with a colon",
1896 Applicability::MachineApplicable,
1901 (fieldname, self.parse_expr()?, false)
1903 let fieldname = self.parse_ident_common(false)?;
1905 // Mimic `x: x` for the `x` field shorthand.
1906 let path = ast::Path::from_ident(fieldname);
1907 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1908 (fieldname, expr, true)
1912 span: lo.to(expr.span),
1915 attrs: attrs.into(),
1919 crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1920 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
1923 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1924 ExprKind::Unary(unop, expr)
1927 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1928 ExprKind::Binary(binop, lhs, rhs)
1931 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1932 ExprKind::Call(f, args)
1935 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1936 ExprKind::Index(expr, idx)
1940 start: Option<P<Expr>>,
1941 end: Option<P<Expr>>,
1942 limits: RangeLimits)
1943 -> PResult<'a, ast::ExprKind> {
1944 if end.is_none() && limits == RangeLimits::Closed {
1945 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
1947 Ok(ExprKind::Range(start, end, limits))
1951 fn mk_assign_op(&self, binop: ast::BinOp,
1952 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1953 ExprKind::AssignOp(binop, lhs, rhs)
1956 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
1957 let delim = match self.token.kind {
1958 token::OpenDelim(delim) => delim,
1960 let msg = "expected open delimiter";
1961 let mut err = self.fatal(msg);
1962 err.span_label(self.span, msg);
1966 let tts = match self.parse_token_tree() {
1967 TokenTree::Delimited(_, _, tts) => tts,
1968 _ => unreachable!(),
1970 let delim = match delim {
1971 token::Paren => MacDelimiter::Parenthesis,
1972 token::Bracket => MacDelimiter::Bracket,
1973 token::Brace => MacDelimiter::Brace,
1974 token::NoDelim => self.bug("unexpected no delimiter"),
1976 Ok((delim, tts.into()))
1979 /// At the bottom (top?) of the precedence hierarchy,
1980 /// Parses things like parenthesized exprs, macros, `return`, etc.
1982 /// N.B., this does not parse outer attributes, and is private because it only works
1983 /// correctly if called from `parse_dot_or_call_expr()`.
1984 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1985 maybe_recover_from_interpolated_ty_qpath!(self, true);
1986 maybe_whole_expr!(self);
1988 // Outer attributes are already parsed and will be
1989 // added to the return value after the fact.
1991 // Therefore, prevent sub-parser from parsing
1992 // attributes by giving them a empty "already parsed" list.
1993 let mut attrs = ThinVec::new();
1996 let mut hi = self.span;
2000 // Note: when adding new syntax here, don't forget to adjust TokenKind::can_begin_expr().
2001 match self.token.kind {
2002 token::OpenDelim(token::Paren) => {
2005 attrs.extend(self.parse_inner_attributes()?);
2007 // (e) is parenthesized e
2008 // (e,) is a tuple with only one field, e
2009 let mut es = vec![];
2010 let mut trailing_comma = false;
2011 let mut recovered = false;
2012 while self.token != token::CloseDelim(token::Paren) {
2013 es.push(match self.parse_expr() {
2016 // recover from parse error in tuple list
2017 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2020 recovered = self.expect_one_of(
2022 &[token::Comma, token::CloseDelim(token::Paren)],
2024 if self.eat(&token::Comma) {
2025 trailing_comma = true;
2027 trailing_comma = false;
2035 hi = self.prev_span;
2036 ex = if es.len() == 1 && !trailing_comma {
2037 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2042 token::OpenDelim(token::Brace) => {
2043 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2045 token::BinOp(token::Or) | token::OrOr => {
2046 return self.parse_lambda_expr(attrs);
2048 token::OpenDelim(token::Bracket) => {
2051 attrs.extend(self.parse_inner_attributes()?);
2053 if self.eat(&token::CloseDelim(token::Bracket)) {
2055 ex = ExprKind::Array(Vec::new());
2058 let first_expr = self.parse_expr()?;
2059 if self.eat(&token::Semi) {
2060 // Repeating array syntax: [ 0; 512 ]
2061 let count = AnonConst {
2062 id: ast::DUMMY_NODE_ID,
2063 value: self.parse_expr()?,
2065 self.expect(&token::CloseDelim(token::Bracket))?;
2066 ex = ExprKind::Repeat(first_expr, count);
2067 } else if self.eat(&token::Comma) {
2068 // Vector with two or more elements.
2069 let remaining_exprs = self.parse_seq_to_end(
2070 &token::CloseDelim(token::Bracket),
2071 SeqSep::trailing_allowed(token::Comma),
2072 |p| Ok(p.parse_expr()?)
2074 let mut exprs = vec![first_expr];
2075 exprs.extend(remaining_exprs);
2076 ex = ExprKind::Array(exprs);
2078 // Vector with one element.
2079 self.expect(&token::CloseDelim(token::Bracket))?;
2080 ex = ExprKind::Array(vec![first_expr]);
2083 hi = self.prev_span;
2087 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2089 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2091 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
2092 return self.parse_lambda_expr(attrs);
2094 if self.eat_keyword(kw::If) {
2095 return self.parse_if_expr(attrs);
2097 if self.eat_keyword(kw::For) {
2098 let lo = self.prev_span;
2099 return self.parse_for_expr(None, lo, attrs);
2101 if self.eat_keyword(kw::While) {
2102 let lo = self.prev_span;
2103 return self.parse_while_expr(None, lo, attrs);
2105 if let Some(label) = self.eat_label() {
2106 let lo = label.ident.span;
2107 self.expect(&token::Colon)?;
2108 if self.eat_keyword(kw::While) {
2109 return self.parse_while_expr(Some(label), lo, attrs)
2111 if self.eat_keyword(kw::For) {
2112 return self.parse_for_expr(Some(label), lo, attrs)
2114 if self.eat_keyword(kw::Loop) {
2115 return self.parse_loop_expr(Some(label), lo, attrs)
2117 if self.token == token::OpenDelim(token::Brace) {
2118 return self.parse_block_expr(Some(label),
2120 BlockCheckMode::Default,
2123 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2124 let mut err = self.fatal(msg);
2125 err.span_label(self.span, msg);
2128 if self.eat_keyword(kw::Loop) {
2129 let lo = self.prev_span;
2130 return self.parse_loop_expr(None, lo, attrs);
2132 if self.eat_keyword(kw::Continue) {
2133 let label = self.eat_label();
2134 let ex = ExprKind::Continue(label);
2135 let hi = self.prev_span;
2136 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2138 if self.eat_keyword(kw::Match) {
2139 let match_sp = self.prev_span;
2140 return self.parse_match_expr(attrs).map_err(|mut err| {
2141 err.span_label(match_sp, "while parsing this match expression");
2145 if self.eat_keyword(kw::Unsafe) {
2146 return self.parse_block_expr(
2149 BlockCheckMode::Unsafe(ast::UserProvided),
2152 if self.is_do_catch_block() {
2153 let mut db = self.fatal("found removed `do catch` syntax");
2154 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2157 if self.is_try_block() {
2159 assert!(self.eat_keyword(kw::Try));
2160 return self.parse_try_block(lo, attrs);
2163 // Span::rust_2018() is somewhat expensive; don't get it repeatedly.
2164 let is_span_rust_2018 = self.span.rust_2018();
2165 if is_span_rust_2018 && self.check_keyword(kw::Async) {
2166 return if self.is_async_block() { // check for `async {` and `async move {`
2167 self.parse_async_block(attrs)
2169 self.parse_lambda_expr(attrs)
2172 if self.eat_keyword(kw::Return) {
2173 if self.token.can_begin_expr() {
2174 let e = self.parse_expr()?;
2176 ex = ExprKind::Ret(Some(e));
2178 ex = ExprKind::Ret(None);
2180 } else if self.eat_keyword(kw::Break) {
2181 let label = self.eat_label();
2182 let e = if self.token.can_begin_expr()
2183 && !(self.token == token::OpenDelim(token::Brace)
2184 && self.restrictions.contains(
2185 Restrictions::NO_STRUCT_LITERAL)) {
2186 Some(self.parse_expr()?)
2190 ex = ExprKind::Break(label, e);
2191 hi = self.prev_span;
2192 } else if self.eat_keyword(kw::Yield) {
2193 if self.token.can_begin_expr() {
2194 let e = self.parse_expr()?;
2196 ex = ExprKind::Yield(Some(e));
2198 ex = ExprKind::Yield(None);
2200 } else if self.token.is_keyword(kw::Let) {
2201 // Catch this syntax error here, instead of in `parse_ident`, so
2202 // that we can explicitly mention that let is not to be used as an expression
2203 let mut db = self.fatal("expected expression, found statement (`let`)");
2204 db.span_label(self.span, "expected expression");
2205 db.note("variable declaration using `let` is a statement");
2207 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
2208 let (await_hi, e_kind) = self.parse_await_macro_or_alt(lo, self.prev_span)?;
2211 } else if self.token.is_path_start() {
2212 let path = self.parse_path(PathStyle::Expr)?;
2214 // `!`, as an operator, is prefix, so we know this isn't that
2215 if self.eat(&token::Not) {
2216 // MACRO INVOCATION expression
2217 let (delim, tts) = self.expect_delimited_token_tree()?;
2218 hi = self.prev_span;
2219 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2220 } else if self.check(&token::OpenDelim(token::Brace)) {
2221 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2225 ex = ExprKind::Path(None, path);
2229 ex = ExprKind::Path(None, path);
2232 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2233 // Don't complain about bare semicolons after unclosed braces
2234 // recovery in order to keep the error count down. Fixing the
2235 // delimiters will possibly also fix the bare semicolon found in
2236 // expression context. For example, silence the following error:
2238 // error: expected expression, found `;`
2242 // | ^ expected expression
2245 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2247 match self.parse_literal_maybe_minus() {
2250 ex = expr.node.clone();
2253 self.cancel(&mut err);
2254 return Err(self.expected_expression_found());
2261 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2262 self.maybe_recover_from_bad_qpath(expr, true)
2265 /// Parse `await!(<expr>)` calls, or alternatively recover from incorrect but reasonable
2266 /// alternative syntaxes `await <expr>`, `await? <expr>`, `await(<expr>)` and
2267 /// `await { <expr> }`.
2268 fn parse_await_macro_or_alt(
2272 ) -> PResult<'a, (Span, ExprKind)> {
2273 if self.token == token::Not {
2274 // Handle correct `await!(<expr>)`.
2275 // FIXME: make this an error when `await!` is no longer supported
2276 // https://github.com/rust-lang/rust/issues/60610
2277 self.expect(&token::Not)?;
2278 self.expect(&token::OpenDelim(token::Paren))?;
2279 let expr = self.parse_expr().map_err(|mut err| {
2280 err.span_label(await_sp, "while parsing this await macro call");
2283 self.expect(&token::CloseDelim(token::Paren))?;
2284 Ok((self.prev_span, ExprKind::Await(ast::AwaitOrigin::MacroLike, expr)))
2285 } else { // Handle `await <expr>`.
2286 self.parse_incorrect_await_syntax(lo, await_sp)
2290 fn maybe_parse_struct_expr(
2294 attrs: &ThinVec<Attribute>,
2295 ) -> Option<PResult<'a, P<Expr>>> {
2296 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2297 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2298 // `{ ident, ` cannot start a block
2299 self.look_ahead(2, |t| t == &token::Comma) ||
2300 self.look_ahead(2, |t| t == &token::Colon) && (
2301 // `{ ident: token, ` cannot start a block
2302 self.look_ahead(4, |t| t == &token::Comma) ||
2303 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2304 self.look_ahead(3, |t| !t.can_begin_type())
2308 if struct_allowed || certainly_not_a_block() {
2309 // This is a struct literal, but we don't can't accept them here
2310 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2311 if let (Ok(expr), false) = (&expr, struct_allowed) {
2312 let mut err = self.diagnostic().struct_span_err(
2314 "struct literals are not allowed here",
2316 err.multipart_suggestion(
2317 "surround the struct literal with parentheses",
2319 (lo.shrink_to_lo(), "(".to_string()),
2320 (expr.span.shrink_to_hi(), ")".to_string()),
2322 Applicability::MachineApplicable,
2331 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2332 -> PResult<'a, P<Expr>> {
2333 let struct_sp = lo.to(self.prev_span);
2335 let mut fields = Vec::new();
2336 let mut base = None;
2338 attrs.extend(self.parse_inner_attributes()?);
2340 while self.token != token::CloseDelim(token::Brace) {
2341 if self.eat(&token::DotDot) {
2342 let exp_span = self.prev_span;
2343 match self.parse_expr() {
2349 self.recover_stmt();
2352 if self.token == token::Comma {
2353 let mut err = self.sess.span_diagnostic.mut_span_err(
2354 exp_span.to(self.prev_span),
2355 "cannot use a comma after the base struct",
2357 err.span_suggestion_short(
2359 "remove this comma",
2361 Applicability::MachineApplicable
2363 err.note("the base struct must always be the last field");
2365 self.recover_stmt();
2370 let mut recovery_field = None;
2371 if let token::Ident(ident, _) = self.token.kind {
2372 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2373 // Use in case of error after field-looking code: `S { foo: () with a }`
2374 let mut ident = ident.clone();
2375 ident.span = self.span;
2376 recovery_field = Some(ast::Field {
2379 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2380 is_shorthand: false,
2381 attrs: ThinVec::new(),
2385 let mut parsed_field = None;
2386 match self.parse_field() {
2387 Ok(f) => parsed_field = Some(f),
2389 e.span_label(struct_sp, "while parsing this struct");
2392 // If the next token is a comma, then try to parse
2393 // what comes next as additional fields, rather than
2394 // bailing out until next `}`.
2395 if self.token != token::Comma {
2396 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2397 if self.token != token::Comma {
2404 match self.expect_one_of(&[token::Comma],
2405 &[token::CloseDelim(token::Brace)]) {
2406 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2407 // only include the field if there's no parse error for the field name
2411 if let Some(f) = recovery_field {
2414 e.span_label(struct_sp, "while parsing this struct");
2416 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2417 self.eat(&token::Comma);
2422 let span = lo.to(self.span);
2423 self.expect(&token::CloseDelim(token::Brace))?;
2424 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2427 fn parse_or_use_outer_attributes(&mut self,
2428 already_parsed_attrs: Option<ThinVec<Attribute>>)
2429 -> PResult<'a, ThinVec<Attribute>> {
2430 if let Some(attrs) = already_parsed_attrs {
2433 self.parse_outer_attributes().map(|a| a.into())
2437 /// Parses a block or unsafe block.
2438 crate fn parse_block_expr(
2440 opt_label: Option<Label>,
2442 blk_mode: BlockCheckMode,
2443 outer_attrs: ThinVec<Attribute>,
2444 ) -> PResult<'a, P<Expr>> {
2445 self.expect(&token::OpenDelim(token::Brace))?;
2447 let mut attrs = outer_attrs;
2448 attrs.extend(self.parse_inner_attributes()?);
2450 let blk = self.parse_block_tail(lo, blk_mode)?;
2451 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2454 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2455 fn parse_dot_or_call_expr(&mut self,
2456 already_parsed_attrs: Option<ThinVec<Attribute>>)
2457 -> PResult<'a, P<Expr>> {
2458 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2460 let b = self.parse_bottom_expr();
2461 let (span, b) = self.interpolated_or_expr_span(b)?;
2462 self.parse_dot_or_call_expr_with(b, span, attrs)
2465 fn parse_dot_or_call_expr_with(&mut self,
2468 mut attrs: ThinVec<Attribute>)
2469 -> PResult<'a, P<Expr>> {
2470 // Stitch the list of outer attributes onto the return value.
2471 // A little bit ugly, but the best way given the current code
2473 self.parse_dot_or_call_expr_with_(e0, lo)
2475 expr.map(|mut expr| {
2476 attrs.extend::<Vec<_>>(expr.attrs.into());
2479 ExprKind::If(..) | ExprKind::IfLet(..) => {
2480 if !expr.attrs.is_empty() {
2481 // Just point to the first attribute in there...
2482 let span = expr.attrs[0].span;
2485 "attributes are not yet allowed on `if` \
2496 // Assuming we have just parsed `.`, continue parsing into an expression.
2497 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2498 if self.span.rust_2018() && self.eat_keyword(kw::Await) {
2499 let span = lo.to(self.prev_span);
2500 let await_expr = self.mk_expr(
2502 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
2505 self.recover_from_await_method_call();
2506 return Ok(await_expr);
2508 let segment = self.parse_path_segment(PathStyle::Expr)?;
2509 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2511 Ok(match self.token.kind {
2512 token::OpenDelim(token::Paren) => {
2513 // Method call `expr.f()`
2514 let mut args = self.parse_unspanned_seq(
2515 &token::OpenDelim(token::Paren),
2516 &token::CloseDelim(token::Paren),
2517 SeqSep::trailing_allowed(token::Comma),
2518 |p| Ok(p.parse_expr()?)
2520 args.insert(0, self_arg);
2522 let span = lo.to(self.prev_span);
2523 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2526 // Field access `expr.f`
2527 if let Some(args) = segment.args {
2528 self.span_err(args.span(),
2529 "field expressions may not have generic arguments");
2532 let span = lo.to(self.prev_span);
2533 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2538 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2543 while self.eat(&token::Question) {
2544 let hi = self.prev_span;
2545 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2549 if self.eat(&token::Dot) {
2550 match self.token.kind {
2551 token::Ident(..) => {
2552 e = self.parse_dot_suffix(e, lo)?;
2554 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
2555 let span = self.span;
2557 let field = ExprKind::Field(e, Ident::new(symbol, span));
2558 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2560 self.expect_no_suffix(span, "a tuple index", suffix);
2562 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
2564 let fstr = symbol.as_str();
2565 let msg = format!("unexpected token: `{}`", symbol);
2566 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
2567 err.span_label(self.prev_span, "unexpected token");
2568 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2569 let float = match fstr.parse::<f64>().ok() {
2573 let sugg = pprust::to_string(|s| {
2574 use crate::print::pprust::PrintState;
2578 s.print_usize(float.trunc() as usize)?;
2581 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2583 err.span_suggestion(
2584 lo.to(self.prev_span),
2585 "try parenthesizing the first index",
2587 Applicability::MachineApplicable
2594 // FIXME Could factor this out into non_fatal_unexpected or something.
2595 let actual = self.this_token_to_string();
2596 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2601 if self.expr_is_complete(&e) { break; }
2602 match self.token.kind {
2604 token::OpenDelim(token::Paren) => {
2605 let seq = self.parse_unspanned_seq(
2606 &token::OpenDelim(token::Paren),
2607 &token::CloseDelim(token::Paren),
2608 SeqSep::trailing_allowed(token::Comma),
2609 |p| Ok(p.parse_expr()?)
2611 let nd = self.mk_call(e, es);
2612 let hi = self.prev_span;
2613 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2615 e = self.recover_seq_parse_error(token::Paren, lo, seq);
2619 // Could be either an index expression or a slicing expression.
2620 token::OpenDelim(token::Bracket) => {
2622 let ix = self.parse_expr()?;
2624 self.expect(&token::CloseDelim(token::Bracket))?;
2625 let index = self.mk_index(e, ix);
2626 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2634 crate fn process_potential_macro_variable(&mut self) {
2635 self.token = match self.token.kind {
2636 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2637 self.look_ahead(1, |t| t.is_ident()) => {
2639 let name = match self.token.kind {
2640 token::Ident(ident, _) => ident,
2643 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2644 err.span_label(self.span, "unknown macro variable");
2649 token::Interpolated(ref nt) => {
2650 self.meta_var_span = Some(self.span);
2651 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2652 // and lifetime tokens, so the former are never encountered during normal parsing.
2654 token::NtIdent(ident, is_raw) => Token { kind: token::Ident(ident, is_raw), span: ident.span },
2655 token::NtLifetime(ident) => Token { kind: token::Lifetime(ident), span: ident.span },
2663 /// Parses a single token tree from the input.
2664 crate fn parse_token_tree(&mut self) -> TokenTree {
2665 match self.token.kind {
2666 token::OpenDelim(..) => {
2667 let frame = mem::replace(&mut self.token_cursor.frame,
2668 self.token_cursor.stack.pop().unwrap());
2669 self.token.span = frame.span.entire();
2671 TokenTree::Delimited(
2674 frame.tree_cursor.stream.into(),
2677 token::CloseDelim(_) | token::Eof => unreachable!(),
2679 let token = mem::replace(&mut self.token, Token { kind: token::Whitespace, span: DUMMY_SP });
2681 TokenTree::Token(token)
2686 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
2687 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2688 let mut tts = Vec::new();
2689 while self.token != token::Eof {
2690 tts.push(self.parse_token_tree());
2695 pub fn parse_tokens(&mut self) -> TokenStream {
2696 let mut result = Vec::new();
2698 match self.token.kind {
2699 token::Eof | token::CloseDelim(..) => break,
2700 _ => result.push(self.parse_token_tree().into()),
2703 TokenStream::new(result)
2706 /// Parse a prefix-unary-operator expr
2707 fn parse_prefix_expr(&mut self,
2708 already_parsed_attrs: Option<ThinVec<Attribute>>)
2709 -> PResult<'a, P<Expr>> {
2710 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2712 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
2713 let (hi, ex) = match self.token.kind {
2716 let e = self.parse_prefix_expr(None);
2717 let (span, e) = self.interpolated_or_expr_span(e)?;
2718 (lo.to(span), self.mk_unary(UnOp::Not, e))
2720 // Suggest `!` for bitwise negation when encountering a `~`
2723 let e = self.parse_prefix_expr(None);
2724 let (span, e) = self.interpolated_or_expr_span(e)?;
2725 let span_of_tilde = lo;
2726 let mut err = self.diagnostic()
2727 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2728 err.span_suggestion_short(
2730 "use `!` to perform bitwise negation",
2732 Applicability::MachineApplicable
2735 (lo.to(span), self.mk_unary(UnOp::Not, e))
2737 token::BinOp(token::Minus) => {
2739 let e = self.parse_prefix_expr(None);
2740 let (span, e) = self.interpolated_or_expr_span(e)?;
2741 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2743 token::BinOp(token::Star) => {
2745 let e = self.parse_prefix_expr(None);
2746 let (span, e) = self.interpolated_or_expr_span(e)?;
2747 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2749 token::BinOp(token::And) | token::AndAnd => {
2751 let m = self.parse_mutability();
2752 let e = self.parse_prefix_expr(None);
2753 let (span, e) = self.interpolated_or_expr_span(e)?;
2754 (lo.to(span), ExprKind::AddrOf(m, e))
2756 token::Ident(..) if self.token.is_keyword(kw::Box) => {
2758 let e = self.parse_prefix_expr(None);
2759 let (span, e) = self.interpolated_or_expr_span(e)?;
2760 (lo.to(span), ExprKind::Box(e))
2762 token::Ident(..) if self.token.is_ident_named(sym::not) => {
2763 // `not` is just an ordinary identifier in Rust-the-language,
2764 // but as `rustc`-the-compiler, we can issue clever diagnostics
2765 // for confused users who really want to say `!`
2766 let token_cannot_continue_expr = |t: &token::Token| match t.kind {
2767 // These tokens can start an expression after `!`, but
2768 // can't continue an expression after an ident
2769 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2770 token::Literal(..) | token::Pound => true,
2771 token::Interpolated(ref nt) => match **nt {
2772 token::NtIdent(..) | token::NtExpr(..) |
2773 token::NtBlock(..) | token::NtPath(..) => true,
2778 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2779 if cannot_continue_expr {
2781 // Emit the error ...
2782 let mut err = self.diagnostic()
2783 .struct_span_err(self.span,
2784 &format!("unexpected {} after identifier",
2785 self.this_token_descr()));
2786 // span the `not` plus trailing whitespace to avoid
2787 // trailing whitespace after the `!` in our suggestion
2788 let to_replace = self.sess.source_map()
2789 .span_until_non_whitespace(lo.to(self.span));
2790 err.span_suggestion_short(
2792 "use `!` to perform logical negation",
2794 Applicability::MachineApplicable
2797 // —and recover! (just as if we were in the block
2798 // for the `token::Not` arm)
2799 let e = self.parse_prefix_expr(None);
2800 let (span, e) = self.interpolated_or_expr_span(e)?;
2801 (lo.to(span), self.mk_unary(UnOp::Not, e))
2803 return self.parse_dot_or_call_expr(Some(attrs));
2806 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2808 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2811 /// Parses an associative expression.
2813 /// This parses an expression accounting for associativity and precedence of the operators in
2816 fn parse_assoc_expr(&mut self,
2817 already_parsed_attrs: Option<ThinVec<Attribute>>)
2818 -> PResult<'a, P<Expr>> {
2819 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2822 /// Parses an associative expression with operators of at least `min_prec` precedence.
2823 fn parse_assoc_expr_with(&mut self,
2826 -> PResult<'a, P<Expr>> {
2827 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2830 let attrs = match lhs {
2831 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2834 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2835 return self.parse_prefix_range_expr(attrs);
2837 self.parse_prefix_expr(attrs)?
2841 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
2843 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2846 (false, _) => {} // continue parsing the expression
2847 // An exhaustive check is done in the following block, but these are checked first
2848 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
2849 // want to keep their span info to improve diagnostics in these cases in a later stage.
2850 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
2851 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
2852 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
2853 (true, Some(AssocOp::Add)) // `{ 42 } + 42
2854 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
2855 // `if x { a } else { b } && if y { c } else { d }`
2856 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
2857 // These cases are ambiguous and can't be identified in the parser alone
2858 let sp = self.sess.source_map().start_point(self.span);
2859 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
2862 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
2865 (true, Some(_)) => {
2866 // We've found an expression that would be parsed as a statement, but the next
2867 // token implies this should be parsed as an expression.
2868 // For example: `if let Some(x) = x { x } else { 0 } / 2`
2869 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
2870 "expected expression, found `{}`",
2871 pprust::token_to_string(&self.token),
2873 err.span_label(self.span, "expected expression");
2874 self.sess.expr_parentheses_needed(
2877 Some(pprust::expr_to_string(&lhs),
2882 self.expected_tokens.push(TokenType::Operator);
2883 while let Some(op) = AssocOp::from_token(&self.token) {
2885 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2886 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2887 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2888 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2889 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2890 (PrevTokenKind::Interpolated, _) => self.prev_span,
2891 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2892 if path.segments.len() == 1 => self.prev_span,
2896 let cur_op_span = self.span;
2897 let restrictions = if op.is_assign_like() {
2898 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2902 let prec = op.precedence();
2903 if prec < min_prec {
2906 // Check for deprecated `...` syntax
2907 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2908 self.err_dotdotdot_syntax(self.span);
2912 if op.is_comparison() {
2913 self.check_no_chained_comparison(&lhs, &op);
2916 if op == AssocOp::As {
2917 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2919 } else if op == AssocOp::Colon {
2920 let maybe_path = self.could_ascription_be_path(&lhs.node);
2921 let next_sp = self.span;
2923 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2926 self.bad_type_ascription(
2937 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2938 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2939 // generalise it to the Fixity::None code.
2941 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2942 // two variants are handled with `parse_prefix_range_expr` call above.
2943 let rhs = if self.is_at_start_of_range_notation_rhs() {
2944 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
2948 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2953 let limits = if op == AssocOp::DotDot {
2954 RangeLimits::HalfOpen
2959 let r = self.mk_range(Some(lhs), rhs, limits)?;
2960 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2964 let fixity = op.fixity();
2965 let prec_adjustment = match fixity {
2968 // We currently have no non-associative operators that are not handled above by
2969 // the special cases. The code is here only for future convenience.
2972 let rhs = self.with_res(
2973 restrictions - Restrictions::STMT_EXPR,
2974 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
2977 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
2978 // including the attributes.
2982 .filter(|a| a.style == AttrStyle::Outer)
2984 .map_or(lhs_span, |a| a.span);
2985 let span = lhs_span.to(rhs.span);
2987 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2988 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2989 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2990 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2991 AssocOp::Greater | AssocOp::GreaterEqual => {
2992 let ast_op = op.to_ast_binop().unwrap();
2993 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
2994 self.mk_expr(span, binary, ThinVec::new())
2996 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2997 AssocOp::AssignOp(k) => {
2999 token::Plus => BinOpKind::Add,
3000 token::Minus => BinOpKind::Sub,
3001 token::Star => BinOpKind::Mul,
3002 token::Slash => BinOpKind::Div,
3003 token::Percent => BinOpKind::Rem,
3004 token::Caret => BinOpKind::BitXor,
3005 token::And => BinOpKind::BitAnd,
3006 token::Or => BinOpKind::BitOr,
3007 token::Shl => BinOpKind::Shl,
3008 token::Shr => BinOpKind::Shr,
3010 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3011 self.mk_expr(span, aopexpr, ThinVec::new())
3013 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3014 self.bug("AssocOp should have been handled by special case")
3018 if let Fixity::None = fixity { break }
3023 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3024 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3025 -> PResult<'a, P<Expr>> {
3026 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3027 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3030 // Save the state of the parser before parsing type normally, in case there is a
3031 // LessThan comparison after this cast.
3032 let parser_snapshot_before_type = self.clone();
3033 match self.parse_ty_no_plus() {
3035 Ok(mk_expr(self, rhs))
3037 Err(mut type_err) => {
3038 // Rewind to before attempting to parse the type with generics, to recover
3039 // from situations like `x as usize < y` in which we first tried to parse
3040 // `usize < y` as a type with generic arguments.
3041 let parser_snapshot_after_type = self.clone();
3042 mem::replace(self, parser_snapshot_before_type);
3044 match self.parse_path(PathStyle::Expr) {
3046 let (op_noun, op_verb) = match self.token.kind {
3047 token::Lt => ("comparison", "comparing"),
3048 token::BinOp(token::Shl) => ("shift", "shifting"),
3050 // We can end up here even without `<` being the next token, for
3051 // example because `parse_ty_no_plus` returns `Err` on keywords,
3052 // but `parse_path` returns `Ok` on them due to error recovery.
3053 // Return original error and parser state.
3054 mem::replace(self, parser_snapshot_after_type);
3055 return Err(type_err);
3059 // Successfully parsed the type path leaving a `<` yet to parse.
3062 // Report non-fatal diagnostics, keep `x as usize` as an expression
3063 // in AST and continue parsing.
3064 let msg = format!("`<` is interpreted as a start of generic \
3065 arguments for `{}`, not a {}", path, op_noun);
3066 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3067 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3068 "interpreted as generic arguments");
3069 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3071 let expr = mk_expr(self, P(Ty {
3073 node: TyKind::Path(None, path),
3074 id: ast::DUMMY_NODE_ID
3077 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3078 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3079 err.span_suggestion(
3081 &format!("try {} the cast value", op_verb),
3082 format!("({})", expr_str),
3083 Applicability::MachineApplicable
3089 Err(mut path_err) => {
3090 // Couldn't parse as a path, return original error and parser state.
3092 mem::replace(self, parser_snapshot_after_type);
3100 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3101 fn parse_prefix_range_expr(&mut self,
3102 already_parsed_attrs: Option<ThinVec<Attribute>>)
3103 -> PResult<'a, P<Expr>> {
3104 // Check for deprecated `...` syntax
3105 if self.token == token::DotDotDot {
3106 self.err_dotdotdot_syntax(self.span);
3109 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3110 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3112 let tok = self.token.clone();
3113 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3115 let mut hi = self.span;
3117 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3118 // RHS must be parsed with more associativity than the dots.
3119 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3120 Some(self.parse_assoc_expr_with(next_prec,
3121 LhsExpr::NotYetParsed)
3129 let limits = if tok == token::DotDot {
3130 RangeLimits::HalfOpen
3135 let r = self.mk_range(None, opt_end, limits)?;
3136 Ok(self.mk_expr(lo.to(hi), r, attrs))
3139 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3140 if self.token.can_begin_expr() {
3141 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3142 if self.token == token::OpenDelim(token::Brace) {
3143 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3151 /// Parses an `if` or `if let` expression (`if` token already eaten).
3152 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3153 if self.check_keyword(kw::Let) {
3154 return self.parse_if_let_expr(attrs);
3156 let lo = self.prev_span;
3157 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3159 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3160 // verify that the last statement is either an implicit return (no `;`) or an explicit
3161 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3162 // the dead code lint.
3163 if self.eat_keyword(kw::Else) || !cond.returns() {
3164 let sp = self.sess.source_map().next_point(lo);
3165 let mut err = self.diagnostic()
3166 .struct_span_err(sp, "missing condition for `if` statemement");
3167 err.span_label(sp, "expected if condition here");
3170 let not_block = self.token != token::OpenDelim(token::Brace);
3171 let thn = self.parse_block().map_err(|mut err| {
3173 err.span_label(lo, "this `if` statement has a condition, but no block");
3177 let mut els: Option<P<Expr>> = None;
3178 let mut hi = thn.span;
3179 if self.eat_keyword(kw::Else) {
3180 let elexpr = self.parse_else_expr()?;
3184 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3187 /// Parses an `if let` expression (`if` token already eaten).
3188 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3189 -> PResult<'a, P<Expr>> {
3190 let lo = self.prev_span;
3191 self.expect_keyword(kw::Let)?;
3192 let pats = self.parse_pats()?;
3193 self.expect(&token::Eq)?;
3194 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3195 let thn = self.parse_block()?;
3196 let (hi, els) = if self.eat_keyword(kw::Else) {
3197 let expr = self.parse_else_expr()?;
3198 (expr.span, Some(expr))
3202 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3205 /// Parses `move |args| expr`.
3206 fn parse_lambda_expr(&mut self,
3207 attrs: ThinVec<Attribute>)
3208 -> PResult<'a, P<Expr>>
3211 let movability = if self.eat_keyword(kw::Static) {
3216 let asyncness = if self.span.rust_2018() {
3217 self.parse_asyncness()
3221 let capture_clause = if self.eat_keyword(kw::Move) {
3226 let decl = self.parse_fn_block_decl()?;
3227 let decl_hi = self.prev_span;
3228 let body = match decl.output {
3229 FunctionRetTy::Default(_) => {
3230 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3231 self.parse_expr_res(restrictions, None)?
3234 // If an explicit return type is given, require a
3235 // block to appear (RFC 968).
3236 let body_lo = self.span;
3237 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3243 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3247 // `else` token already eaten
3248 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3249 if self.eat_keyword(kw::If) {
3250 return self.parse_if_expr(ThinVec::new());
3252 let blk = self.parse_block()?;
3253 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3257 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3258 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3260 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3261 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3263 let pat = self.parse_top_level_pat()?;
3264 if !self.eat_keyword(kw::In) {
3265 let in_span = self.prev_span.between(self.span);
3266 let mut err = self.sess.span_diagnostic
3267 .struct_span_err(in_span, "missing `in` in `for` loop");
3268 err.span_suggestion_short(
3269 in_span, "try adding `in` here", " in ".into(),
3270 // has been misleading, at least in the past (closed Issue #48492)
3271 Applicability::MaybeIncorrect
3275 let in_span = self.prev_span;
3276 self.check_for_for_in_in_typo(in_span);
3277 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3278 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3279 attrs.extend(iattrs);
3281 let hi = self.prev_span;
3282 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3285 /// Parses a `while` or `while let` expression (`while` token already eaten).
3286 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3288 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3289 if self.token.is_keyword(kw::Let) {
3290 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3292 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3293 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3294 attrs.extend(iattrs);
3295 let span = span_lo.to(body.span);
3296 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3299 /// Parses a `while let` expression (`while` token already eaten).
3300 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3302 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3303 self.expect_keyword(kw::Let)?;
3304 let pats = self.parse_pats()?;
3305 self.expect(&token::Eq)?;
3306 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3307 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3308 attrs.extend(iattrs);
3309 let span = span_lo.to(body.span);
3310 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3313 // parse `loop {...}`, `loop` token already eaten
3314 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3316 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3317 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3318 attrs.extend(iattrs);
3319 let span = span_lo.to(body.span);
3320 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3323 /// Parses an `async move {...}` expression.
3324 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3325 -> PResult<'a, P<Expr>>
3327 let span_lo = self.span;
3328 self.expect_keyword(kw::Async)?;
3329 let capture_clause = if self.eat_keyword(kw::Move) {
3334 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3335 attrs.extend(iattrs);
3337 span_lo.to(body.span),
3338 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3341 /// Parses a `try {...}` expression (`try` token already eaten).
3342 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3343 -> PResult<'a, P<Expr>>
3345 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3346 attrs.extend(iattrs);
3347 if self.eat_keyword(kw::Catch) {
3348 let mut error = self.struct_span_err(self.prev_span,
3349 "keyword `catch` cannot follow a `try` block");
3350 error.help("try using `match` on the result of the `try` block instead");
3354 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3358 // `match` token already eaten
3359 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3360 let match_span = self.prev_span;
3361 let lo = self.prev_span;
3362 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3364 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3365 if self.token == token::Semi {
3366 e.span_suggestion_short(
3368 "try removing this `match`",
3370 Applicability::MaybeIncorrect // speculative
3375 attrs.extend(self.parse_inner_attributes()?);
3377 let mut arms: Vec<Arm> = Vec::new();
3378 while self.token != token::CloseDelim(token::Brace) {
3379 match self.parse_arm() {
3380 Ok(arm) => arms.push(arm),
3382 // Recover by skipping to the end of the block.
3384 self.recover_stmt();
3385 let span = lo.to(self.span);
3386 if self.token == token::CloseDelim(token::Brace) {
3389 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3395 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3398 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3399 let attrs = self.parse_outer_attributes()?;
3401 let pats = self.parse_pats()?;
3402 let guard = if self.eat_keyword(kw::If) {
3403 Some(Guard::If(self.parse_expr()?))
3407 let arrow_span = self.span;
3408 self.expect(&token::FatArrow)?;
3409 let arm_start_span = self.span;
3411 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3412 .map_err(|mut err| {
3413 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3417 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3418 && self.token != token::CloseDelim(token::Brace);
3423 let cm = self.sess.source_map();
3424 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3425 .map_err(|mut err| {
3426 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3427 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3428 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3429 && expr_lines.lines.len() == 2
3430 && self.token == token::FatArrow => {
3431 // We check whether there's any trailing code in the parse span,
3432 // if there isn't, we very likely have the following:
3435 // | -- - missing comma
3441 // | parsed until here as `"y" & X`
3442 err.span_suggestion_short(
3443 cm.next_point(arm_start_span),
3444 "missing a comma here to end this `match` arm",
3446 Applicability::MachineApplicable
3450 err.span_label(arrow_span,
3451 "while parsing the `match` arm starting here");
3457 self.eat(&token::Comma);
3469 /// Parses an expression.
3471 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3472 self.parse_expr_res(Restrictions::empty(), None)
3475 /// Evaluates the closure with restrictions in place.
3477 /// Afters the closure is evaluated, restrictions are reset.
3478 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3479 where F: FnOnce(&mut Self) -> T
3481 let old = self.restrictions;
3482 self.restrictions = r;
3484 self.restrictions = old;
3489 /// Parses an expression, subject to the given restrictions.
3491 fn parse_expr_res(&mut self, r: Restrictions,
3492 already_parsed_attrs: Option<ThinVec<Attribute>>)
3493 -> PResult<'a, P<Expr>> {
3494 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3497 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
3498 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3499 if self.eat(&token::Eq) {
3500 Ok(Some(self.parse_expr()?))
3502 Ok(Some(self.parse_expr()?))
3508 /// Parses patterns, separated by '|' s.
3509 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3510 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
3511 self.eat(&token::BinOp(token::Or));
3513 let mut pats = Vec::new();
3515 pats.push(self.parse_top_level_pat()?);
3517 if self.token == token::OrOr {
3518 let mut err = self.struct_span_err(self.span,
3519 "unexpected token `||` after pattern");
3520 err.span_suggestion(
3522 "use a single `|` to specify multiple patterns",
3524 Applicability::MachineApplicable
3528 } else if self.eat(&token::BinOp(token::Or)) {
3529 // This is a No-op. Continue the loop to parse the next
3537 // Parses a parenthesized list of patterns like
3538 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3539 // - a vector of the patterns that were parsed
3540 // - an option indicating the index of the `..` element
3541 // - a boolean indicating whether a trailing comma was present.
3542 // Trailing commas are significant because (p) and (p,) are different patterns.
3543 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3544 self.expect(&token::OpenDelim(token::Paren))?;
3545 let result = match self.parse_pat_list() {
3546 Ok(result) => result,
3547 Err(mut err) => { // recover from parse error in tuple pattern list
3549 self.consume_block(token::Paren);
3550 return Ok((vec![], Some(0), false));
3553 self.expect(&token::CloseDelim(token::Paren))?;
3557 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3558 let mut fields = Vec::new();
3559 let mut ddpos = None;
3560 let mut prev_dd_sp = None;
3561 let mut trailing_comma = false;
3563 if self.eat(&token::DotDot) {
3564 if ddpos.is_none() {
3565 ddpos = Some(fields.len());
3566 prev_dd_sp = Some(self.prev_span);
3568 // Emit a friendly error, ignore `..` and continue parsing
3569 let mut err = self.struct_span_err(
3571 "`..` can only be used once per tuple or tuple struct pattern",
3573 err.span_label(self.prev_span, "can only be used once per pattern");
3574 if let Some(sp) = prev_dd_sp {
3575 err.span_label(sp, "previously present here");
3579 } else if !self.check(&token::CloseDelim(token::Paren)) {
3580 fields.push(self.parse_pat(None)?);
3585 trailing_comma = self.eat(&token::Comma);
3586 if !trailing_comma {
3591 if ddpos == Some(fields.len()) && trailing_comma {
3592 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3593 let msg = "trailing comma is not permitted after `..`";
3594 self.struct_span_err(self.prev_span, msg)
3595 .span_label(self.prev_span, msg)
3599 Ok((fields, ddpos, trailing_comma))
3602 fn parse_pat_vec_elements(
3604 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3605 let mut before = Vec::new();
3606 let mut slice = None;
3607 let mut after = Vec::new();
3608 let mut first = true;
3609 let mut before_slice = true;
3611 while self.token != token::CloseDelim(token::Bracket) {
3615 self.expect(&token::Comma)?;
3617 if self.token == token::CloseDelim(token::Bracket)
3618 && (before_slice || !after.is_empty()) {
3624 if self.eat(&token::DotDot) {
3626 if self.check(&token::Comma) ||
3627 self.check(&token::CloseDelim(token::Bracket)) {
3628 slice = Some(P(Pat {
3629 id: ast::DUMMY_NODE_ID,
3630 node: PatKind::Wild,
3631 span: self.prev_span,
3633 before_slice = false;
3639 let subpat = self.parse_pat(None)?;
3640 if before_slice && self.eat(&token::DotDot) {
3641 slice = Some(subpat);
3642 before_slice = false;
3643 } else if before_slice {
3644 before.push(subpat);
3650 Ok((before, slice, after))
3656 attrs: Vec<Attribute>
3657 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3658 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3660 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3661 // Parsing a pattern of the form "fieldname: pat"
3662 let fieldname = self.parse_field_name()?;
3664 let pat = self.parse_pat(None)?;
3666 (pat, fieldname, false)
3668 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3669 let is_box = self.eat_keyword(kw::Box);
3670 let boxed_span = self.span;
3671 let is_ref = self.eat_keyword(kw::Ref);
3672 let is_mut = self.eat_keyword(kw::Mut);
3673 let fieldname = self.parse_ident()?;
3674 hi = self.prev_span;
3676 let bind_type = match (is_ref, is_mut) {
3677 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3678 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3679 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3680 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3682 let fieldpat = P(Pat {
3683 id: ast::DUMMY_NODE_ID,
3684 node: PatKind::Ident(bind_type, fieldname, None),
3685 span: boxed_span.to(hi),
3688 let subpat = if is_box {
3690 id: ast::DUMMY_NODE_ID,
3691 node: PatKind::Box(fieldpat),
3697 (subpat, fieldname, true)
3700 Ok(source_map::Spanned {
3702 node: ast::FieldPat {
3706 attrs: attrs.into(),
3711 /// Parses the fields of a struct-like pattern.
3712 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3713 let mut fields = Vec::new();
3714 let mut etc = false;
3715 let mut ate_comma = true;
3716 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3717 let mut etc_span = None;
3719 while self.token != token::CloseDelim(token::Brace) {
3720 let attrs = self.parse_outer_attributes()?;
3723 // check that a comma comes after every field
3725 let err = self.struct_span_err(self.prev_span, "expected `,`");
3726 if let Some(mut delayed) = delayed_err {
3733 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3735 let mut etc_sp = self.span;
3737 if self.token == token::DotDotDot { // Issue #46718
3738 // Accept `...` as if it were `..` to avoid further errors
3739 let mut err = self.struct_span_err(self.span,
3740 "expected field pattern, found `...`");
3741 err.span_suggestion(
3743 "to omit remaining fields, use one fewer `.`",
3745 Applicability::MachineApplicable
3749 self.bump(); // `..` || `...`
3751 if self.token == token::CloseDelim(token::Brace) {
3752 etc_span = Some(etc_sp);
3755 let token_str = self.this_token_descr();
3756 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3758 err.span_label(self.span, "expected `}`");
3759 let mut comma_sp = None;
3760 if self.token == token::Comma { // Issue #49257
3761 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3762 err.span_label(etc_sp,
3763 "`..` must be at the end and cannot have a trailing comma");
3764 comma_sp = Some(self.span);
3769 etc_span = Some(etc_sp.until(self.span));
3770 if self.token == token::CloseDelim(token::Brace) {
3771 // If the struct looks otherwise well formed, recover and continue.
3772 if let Some(sp) = comma_sp {
3773 err.span_suggestion_short(
3775 "remove this comma",
3777 Applicability::MachineApplicable,
3782 } else if self.token.is_ident() && ate_comma {
3783 // Accept fields coming after `..,`.
3784 // This way we avoid "pattern missing fields" errors afterwards.
3785 // We delay this error until the end in order to have a span for a
3787 if let Some(mut delayed_err) = delayed_err {
3791 delayed_err = Some(err);
3794 if let Some(mut err) = delayed_err {
3801 fields.push(match self.parse_pat_field(lo, attrs) {
3804 if let Some(mut delayed_err) = delayed_err {
3810 ate_comma = self.eat(&token::Comma);
3813 if let Some(mut err) = delayed_err {
3814 if let Some(etc_span) = etc_span {
3815 err.multipart_suggestion(
3816 "move the `..` to the end of the field list",
3818 (etc_span, String::new()),
3819 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3821 Applicability::MachineApplicable,
3826 return Ok((fields, etc));
3829 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3830 if self.token.is_path_start() {
3832 let (qself, path) = if self.eat_lt() {
3833 // Parse a qualified path
3834 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3837 // Parse an unqualified path
3838 (None, self.parse_path(PathStyle::Expr)?)
3840 let hi = self.prev_span;
3841 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3843 self.parse_literal_maybe_minus()
3847 // helper function to decide whether to parse as ident binding or to try to do
3848 // something more complex like range patterns
3849 fn parse_as_ident(&mut self) -> bool {
3850 self.look_ahead(1, |t| match t.kind {
3851 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3852 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3853 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3854 // range pattern branch
3855 token::DotDot => None,
3857 }).unwrap_or_else(|| self.look_ahead(2, |t| match t.kind {
3858 token::Comma | token::CloseDelim(token::Bracket) => true,
3863 /// A wrapper around `parse_pat` with some special error handling for the
3864 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3865 /// to subpatterns within such).
3866 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3867 let pat = self.parse_pat(None)?;
3868 if self.token == token::Comma {
3869 // An unexpected comma after a top-level pattern is a clue that the
3870 // user (perhaps more accustomed to some other language) forgot the
3871 // parentheses in what should have been a tuple pattern; return a
3872 // suggestion-enhanced error here rather than choking on the comma
3874 let comma_span = self.span;
3876 if let Err(mut err) = self.parse_pat_list() {
3877 // We didn't expect this to work anyway; we just wanted
3878 // to advance to the end of the comma-sequence so we know
3879 // the span to suggest parenthesizing
3882 let seq_span = pat.span.to(self.prev_span);
3883 let mut err = self.struct_span_err(comma_span,
3884 "unexpected `,` in pattern");
3885 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3886 err.span_suggestion(
3888 "try adding parentheses to match on a tuple..",
3889 format!("({})", seq_snippet),
3890 Applicability::MachineApplicable
3893 "..or a vertical bar to match on multiple alternatives",
3894 format!("{}", seq_snippet.replace(",", " |")),
3895 Applicability::MachineApplicable
3903 /// Parses a pattern.
3904 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
3905 self.parse_pat_with_range_pat(true, expected)
3908 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
3910 fn parse_pat_with_range_pat(
3912 allow_range_pat: bool,
3913 expected: Option<&'static str>,
3914 ) -> PResult<'a, P<Pat>> {
3915 maybe_recover_from_interpolated_ty_qpath!(self, true);
3916 maybe_whole!(self, NtPat, |x| x);
3920 match self.token.kind {
3921 token::BinOp(token::And) | token::AndAnd => {
3922 // Parse &pat / &mut pat
3924 let mutbl = self.parse_mutability();
3925 if let token::Lifetime(ident) = self.token.kind {
3926 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3928 err.span_label(self.span, "unexpected lifetime");
3931 let subpat = self.parse_pat_with_range_pat(false, expected)?;
3932 pat = PatKind::Ref(subpat, mutbl);
3934 token::OpenDelim(token::Paren) => {
3935 // Parse (pat,pat,pat,...) as tuple pattern
3936 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3937 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3938 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3940 PatKind::Tuple(fields, ddpos)
3943 token::OpenDelim(token::Bracket) => {
3944 // Parse [pat,pat,...] as slice pattern
3946 let (before, slice, after) = self.parse_pat_vec_elements()?;
3947 self.expect(&token::CloseDelim(token::Bracket))?;
3948 pat = PatKind::Slice(before, slice, after);
3950 // At this point, token != &, &&, (, [
3951 _ => if self.eat_keyword(kw::Underscore) {
3953 pat = PatKind::Wild;
3954 } else if self.eat_keyword(kw::Mut) {
3955 // Parse mut ident @ pat / mut ref ident @ pat
3956 let mutref_span = self.prev_span.to(self.span);
3957 let binding_mode = if self.eat_keyword(kw::Ref) {
3959 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3962 "try switching the order",
3964 Applicability::MachineApplicable
3966 BindingMode::ByRef(Mutability::Mutable)
3968 BindingMode::ByValue(Mutability::Mutable)
3970 pat = self.parse_pat_ident(binding_mode)?;
3971 } else if self.eat_keyword(kw::Ref) {
3972 // Parse ref ident @ pat / ref mut ident @ pat
3973 let mutbl = self.parse_mutability();
3974 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3975 } else if self.eat_keyword(kw::Box) {
3977 let subpat = self.parse_pat_with_range_pat(false, None)?;
3978 pat = PatKind::Box(subpat);
3979 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3980 self.parse_as_ident() {
3981 // Parse ident @ pat
3982 // This can give false positives and parse nullary enums,
3983 // they are dealt with later in resolve
3984 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3985 pat = self.parse_pat_ident(binding_mode)?;
3986 } else if self.token.is_path_start() {
3987 // Parse pattern starting with a path
3988 let (qself, path) = if self.eat_lt() {
3989 // Parse a qualified path
3990 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3993 // Parse an unqualified path
3994 (None, self.parse_path(PathStyle::Expr)?)
3996 match self.token.kind {
3997 token::Not if qself.is_none() => {
3998 // Parse macro invocation
4000 let (delim, tts) = self.expect_delimited_token_tree()?;
4001 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4002 pat = PatKind::Mac(mac);
4004 token::DotDotDot | token::DotDotEq | token::DotDot => {
4005 let end_kind = match self.token.kind {
4006 token::DotDot => RangeEnd::Excluded,
4007 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4008 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4009 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4012 let op_span = self.span;
4014 let span = lo.to(self.prev_span);
4015 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4017 let end = self.parse_pat_range_end()?;
4018 let op = Spanned { span: op_span, node: end_kind };
4019 pat = PatKind::Range(begin, end, op);
4021 token::OpenDelim(token::Brace) => {
4022 if qself.is_some() {
4023 let msg = "unexpected `{` after qualified path";
4024 let mut err = self.fatal(msg);
4025 err.span_label(self.span, msg);
4028 // Parse struct pattern
4030 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4032 self.recover_stmt();
4036 pat = PatKind::Struct(path, fields, etc);
4038 token::OpenDelim(token::Paren) => {
4039 if qself.is_some() {
4040 let msg = "unexpected `(` after qualified path";
4041 let mut err = self.fatal(msg);
4042 err.span_label(self.span, msg);
4045 // Parse tuple struct or enum pattern
4046 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4047 pat = PatKind::TupleStruct(path, fields, ddpos)
4049 _ => pat = PatKind::Path(qself, path),
4052 // Try to parse everything else as literal with optional minus
4053 match self.parse_literal_maybe_minus() {
4055 let op_span = self.span;
4056 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4057 self.check(&token::DotDotDot) {
4058 let end_kind = if self.eat(&token::DotDotDot) {
4059 RangeEnd::Included(RangeSyntax::DotDotDot)
4060 } else if self.eat(&token::DotDotEq) {
4061 RangeEnd::Included(RangeSyntax::DotDotEq)
4062 } else if self.eat(&token::DotDot) {
4065 panic!("impossible case: we already matched \
4066 on a range-operator token")
4068 let end = self.parse_pat_range_end()?;
4069 let op = Spanned { span: op_span, node: end_kind };
4070 pat = PatKind::Range(begin, end, op);
4072 pat = PatKind::Lit(begin);
4076 self.cancel(&mut err);
4077 let expected = expected.unwrap_or("pattern");
4079 "expected {}, found {}",
4081 self.this_token_descr(),
4083 let mut err = self.fatal(&msg);
4084 err.span_label(self.span, format!("expected {}", expected));
4085 let sp = self.sess.source_map().start_point(self.span);
4086 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4087 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4095 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4096 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4098 if !allow_range_pat {
4101 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4103 PatKind::Range(..) => {
4104 let mut err = self.struct_span_err(
4106 "the range pattern here has ambiguous interpretation",
4108 err.span_suggestion(
4110 "add parentheses to clarify the precedence",
4111 format!("({})", pprust::pat_to_string(&pat)),
4112 // "ambiguous interpretation" implies that we have to be guessing
4113 Applicability::MaybeIncorrect
4124 /// Parses `ident` or `ident @ pat`.
4125 /// used by the copy foo and ref foo patterns to give a good
4126 /// error message when parsing mistakes like `ref foo(a, b)`.
4127 fn parse_pat_ident(&mut self,
4128 binding_mode: ast::BindingMode)
4129 -> PResult<'a, PatKind> {
4130 let ident = self.parse_ident()?;
4131 let sub = if self.eat(&token::At) {
4132 Some(self.parse_pat(Some("binding pattern"))?)
4137 // just to be friendly, if they write something like
4139 // we end up here with ( as the current token. This shortly
4140 // leads to a parse error. Note that if there is no explicit
4141 // binding mode then we do not end up here, because the lookahead
4142 // will direct us over to parse_enum_variant()
4143 if self.token == token::OpenDelim(token::Paren) {
4144 return Err(self.span_fatal(
4146 "expected identifier, found enum pattern"))
4149 Ok(PatKind::Ident(binding_mode, ident, sub))
4152 /// Parses a local variable declaration.
4153 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4154 let lo = self.prev_span;
4155 let pat = self.parse_top_level_pat()?;
4157 let (err, ty) = if self.eat(&token::Colon) {
4158 // Save the state of the parser before parsing type normally, in case there is a `:`
4159 // instead of an `=` typo.
4160 let parser_snapshot_before_type = self.clone();
4161 let colon_sp = self.prev_span;
4162 match self.parse_ty() {
4163 Ok(ty) => (None, Some(ty)),
4165 // Rewind to before attempting to parse the type and continue parsing
4166 let parser_snapshot_after_type = self.clone();
4167 mem::replace(self, parser_snapshot_before_type);
4169 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4170 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4171 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4177 let init = match (self.parse_initializer(err.is_some()), err) {
4178 (Ok(init), None) => { // init parsed, ty parsed
4181 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4182 // Could parse the type as if it were the initializer, it is likely there was a
4183 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4184 err.span_suggestion_short(
4186 "use `=` if you meant to assign",
4188 Applicability::MachineApplicable
4191 // As this was parsed successfully, continue as if the code has been fixed for the
4192 // rest of the file. It will still fail due to the emitted error, but we avoid
4196 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4198 // Couldn't parse the type nor the initializer, only raise the type error and
4199 // return to the parser state before parsing the type as the initializer.
4200 // let x: <parse_error>;
4201 mem::replace(self, snapshot);
4204 (Err(err), None) => { // init error, ty parsed
4205 // Couldn't parse the initializer and we're not attempting to recover a failed
4206 // parse of the type, return the error.
4210 let hi = if self.token == token::Semi {
4219 id: ast::DUMMY_NODE_ID,
4225 /// Parses a structure field.
4226 fn parse_name_and_ty(&mut self,
4229 attrs: Vec<Attribute>)
4230 -> PResult<'a, StructField> {
4231 let name = self.parse_ident()?;
4232 self.expect(&token::Colon)?;
4233 let ty = self.parse_ty()?;
4235 span: lo.to(self.prev_span),
4238 id: ast::DUMMY_NODE_ID,
4244 /// Emits an expected-item-after-attributes error.
4245 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4246 let message = match attrs.last() {
4247 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4248 _ => "expected item after attributes",
4251 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4252 if attrs.last().unwrap().is_sugared_doc {
4253 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4258 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4259 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4260 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4261 Ok(self.parse_stmt_(true))
4264 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4265 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4267 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4272 fn is_async_block(&self) -> bool {
4273 self.token.is_keyword(kw::Async) &&
4276 self.is_keyword_ahead(1, &[kw::Move]) &&
4277 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4279 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4284 fn is_async_fn(&self) -> bool {
4285 self.token.is_keyword(kw::Async) &&
4286 self.is_keyword_ahead(1, &[kw::Fn])
4289 fn is_do_catch_block(&self) -> bool {
4290 self.token.is_keyword(kw::Do) &&
4291 self.is_keyword_ahead(1, &[kw::Catch]) &&
4292 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4293 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4296 fn is_try_block(&self) -> bool {
4297 self.token.is_keyword(kw::Try) &&
4298 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4299 self.span.rust_2018() &&
4300 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4301 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4304 fn is_union_item(&self) -> bool {
4305 self.token.is_keyword(kw::Union) &&
4306 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4309 fn is_crate_vis(&self) -> bool {
4310 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4313 fn is_existential_type_decl(&self) -> bool {
4314 self.token.is_keyword(kw::Existential) &&
4315 self.is_keyword_ahead(1, &[kw::Type])
4318 fn is_auto_trait_item(&self) -> bool {
4320 (self.token.is_keyword(kw::Auto) &&
4321 self.is_keyword_ahead(1, &[kw::Trait]))
4322 || // unsafe auto trait
4323 (self.token.is_keyword(kw::Unsafe) &&
4324 self.is_keyword_ahead(1, &[kw::Auto]) &&
4325 self.is_keyword_ahead(2, &[kw::Trait]))
4328 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4329 -> PResult<'a, Option<P<Item>>> {
4330 let token_lo = self.span;
4331 let (ident, def) = match self.token.kind {
4332 token::Ident(ident, false) if ident.name == kw::Macro => {
4334 let ident = self.parse_ident()?;
4335 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4336 match self.parse_token_tree() {
4337 TokenTree::Delimited(_, _, tts) => tts,
4338 _ => unreachable!(),
4340 } else if self.check(&token::OpenDelim(token::Paren)) {
4341 let args = self.parse_token_tree();
4342 let body = if self.check(&token::OpenDelim(token::Brace)) {
4343 self.parse_token_tree()
4348 TokenStream::new(vec![
4350 TokenTree::token(token_lo.to(self.prev_span), token::FatArrow).into(),
4358 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4360 token::Ident(ident, _) if ident.name == sym::macro_rules &&
4361 self.look_ahead(1, |t| *t == token::Not) => {
4362 let prev_span = self.prev_span;
4363 self.complain_if_pub_macro(&vis.node, prev_span);
4367 let ident = self.parse_ident()?;
4368 let (delim, tokens) = self.expect_delimited_token_tree()?;
4369 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
4370 self.report_invalid_macro_expansion_item();
4373 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4375 _ => return Ok(None),
4378 let span = lo.to(self.prev_span);
4379 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4382 fn parse_stmt_without_recovery(&mut self,
4383 macro_legacy_warnings: bool)
4384 -> PResult<'a, Option<Stmt>> {
4385 maybe_whole!(self, NtStmt, |x| Some(x));
4387 let attrs = self.parse_outer_attributes()?;
4390 Ok(Some(if self.eat_keyword(kw::Let) {
4392 id: ast::DUMMY_NODE_ID,
4393 node: StmtKind::Local(self.parse_local(attrs.into())?),
4394 span: lo.to(self.prev_span),
4396 } else if let Some(macro_def) = self.eat_macro_def(
4398 &source_map::respan(lo, VisibilityKind::Inherited),
4402 id: ast::DUMMY_NODE_ID,
4403 node: StmtKind::Item(macro_def),
4404 span: lo.to(self.prev_span),
4406 // Starts like a simple path, being careful to avoid contextual keywords
4407 // such as a union items, item with `crate` visibility or auto trait items.
4408 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4409 // like a path (1 token), but it fact not a path.
4410 // `union::b::c` - path, `union U { ... }` - not a path.
4411 // `crate::b::c` - path, `crate struct S;` - not a path.
4412 } else if self.token.is_path_start() &&
4413 !self.token.is_qpath_start() &&
4414 !self.is_union_item() &&
4415 !self.is_crate_vis() &&
4416 !self.is_existential_type_decl() &&
4417 !self.is_auto_trait_item() &&
4418 !self.is_async_fn() {
4419 let pth = self.parse_path(PathStyle::Expr)?;
4421 if !self.eat(&token::Not) {
4422 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4423 self.parse_struct_expr(lo, pth, ThinVec::new())?
4425 let hi = self.prev_span;
4426 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4429 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4430 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4431 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4434 return Ok(Some(Stmt {
4435 id: ast::DUMMY_NODE_ID,
4436 node: StmtKind::Expr(expr),
4437 span: lo.to(self.prev_span),
4441 // it's a macro invocation
4442 let id = match self.token.kind {
4443 token::OpenDelim(_) => Ident::invalid(), // no special identifier
4444 _ => self.parse_ident()?,
4447 // check that we're pointing at delimiters (need to check
4448 // again after the `if`, because of `parse_ident`
4449 // consuming more tokens).
4450 match self.token.kind {
4451 token::OpenDelim(_) => {}
4453 // we only expect an ident if we didn't parse one
4455 let ident_str = if id.name == kw::Invalid {
4460 let tok_str = self.this_token_descr();
4461 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4464 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4469 let (delim, tts) = self.expect_delimited_token_tree()?;
4470 let hi = self.prev_span;
4472 let style = if delim == MacDelimiter::Brace {
4473 MacStmtStyle::Braces
4475 MacStmtStyle::NoBraces
4478 if id.name == kw::Invalid {
4479 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4480 let node = if delim == MacDelimiter::Brace ||
4481 self.token == token::Semi || self.token == token::Eof {
4482 StmtKind::Mac(P((mac, style, attrs.into())))
4484 // We used to incorrectly stop parsing macro-expanded statements here.
4485 // If the next token will be an error anyway but could have parsed with the
4486 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4487 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token.kind {
4488 // These can continue an expression, so we can't stop parsing and warn.
4489 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4490 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4491 token::BinOp(token::And) | token::BinOp(token::Or) |
4492 token::AndAnd | token::OrOr |
4493 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4496 self.warn_missing_semicolon();
4497 StmtKind::Mac(P((mac, style, attrs.into())))
4499 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
4500 let e = self.maybe_recover_from_bad_qpath(e, true)?;
4501 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4502 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4506 id: ast::DUMMY_NODE_ID,
4511 // if it has a special ident, it's definitely an item
4513 // Require a semicolon or braces.
4514 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
4515 self.report_invalid_macro_expansion_item();
4517 let span = lo.to(hi);
4519 id: ast::DUMMY_NODE_ID,
4521 node: StmtKind::Item({
4523 span, id /*id is good here*/,
4524 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4525 respan(lo, VisibilityKind::Inherited),
4531 // FIXME: Bad copy of attrs
4532 let old_directory_ownership =
4533 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4534 let item = self.parse_item_(attrs.clone(), false, true)?;
4535 self.directory.ownership = old_directory_ownership;
4539 id: ast::DUMMY_NODE_ID,
4540 span: lo.to(i.span),
4541 node: StmtKind::Item(i),
4544 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4545 if !attrs.is_empty() {
4546 if s.prev_token_kind == PrevTokenKind::DocComment {
4547 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4548 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4549 s.span_err(s.span, "expected statement after outer attribute");
4554 // Do not attempt to parse an expression if we're done here.
4555 if self.token == token::Semi {
4556 unused_attrs(&attrs, self);
4561 if self.token == token::CloseDelim(token::Brace) {
4562 unused_attrs(&attrs, self);
4566 // Remainder are line-expr stmts.
4567 let e = self.parse_expr_res(
4568 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4570 id: ast::DUMMY_NODE_ID,
4571 span: lo.to(e.span),
4572 node: StmtKind::Expr(e),
4579 /// Checks if this expression is a successfully parsed statement.
4580 fn expr_is_complete(&self, e: &Expr) -> bool {
4581 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4582 !classify::expr_requires_semi_to_be_stmt(e)
4585 /// Parses a block. No inner attributes are allowed.
4586 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4587 maybe_whole!(self, NtBlock, |x| x);
4591 if !self.eat(&token::OpenDelim(token::Brace)) {
4593 let tok = self.this_token_descr();
4594 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4595 let do_not_suggest_help =
4596 self.token.is_keyword(kw::In) || self.token == token::Colon;
4598 if self.token.is_ident_named(sym::and) {
4599 e.span_suggestion_short(
4601 "use `&&` instead of `and` for the boolean operator",
4603 Applicability::MaybeIncorrect,
4606 if self.token.is_ident_named(sym::or) {
4607 e.span_suggestion_short(
4609 "use `||` instead of `or` for the boolean operator",
4611 Applicability::MaybeIncorrect,
4615 // Check to see if the user has written something like
4620 // Which is valid in other languages, but not Rust.
4621 match self.parse_stmt_without_recovery(false) {
4623 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4624 || do_not_suggest_help {
4625 // if the next token is an open brace (e.g., `if a b {`), the place-
4626 // inside-a-block suggestion would be more likely wrong than right
4627 e.span_label(sp, "expected `{`");
4630 let mut stmt_span = stmt.span;
4631 // expand the span to include the semicolon, if it exists
4632 if self.eat(&token::Semi) {
4633 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4635 let sugg = pprust::to_string(|s| {
4636 use crate::print::pprust::{PrintState, INDENT_UNIT};
4637 s.ibox(INDENT_UNIT)?;
4639 s.print_stmt(&stmt)?;
4640 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4644 "try placing this code inside a block",
4646 // speculative, has been misleading in the past (closed Issue #46836)
4647 Applicability::MaybeIncorrect
4651 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4652 self.cancel(&mut e);
4656 e.span_label(sp, "expected `{`");
4660 self.parse_block_tail(lo, BlockCheckMode::Default)
4663 /// Parses a block. Inner attributes are allowed.
4664 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4665 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4668 self.expect(&token::OpenDelim(token::Brace))?;
4669 Ok((self.parse_inner_attributes()?,
4670 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4673 /// Parses the rest of a block expression or function body.
4674 /// Precondition: already parsed the '{'.
4675 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4676 let mut stmts = vec![];
4677 while !self.eat(&token::CloseDelim(token::Brace)) {
4678 let stmt = match self.parse_full_stmt(false) {
4681 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4683 id: ast::DUMMY_NODE_ID,
4684 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
4690 if let Some(stmt) = stmt {
4692 } else if self.token == token::Eof {
4695 // Found only `;` or `}`.
4701 id: ast::DUMMY_NODE_ID,
4703 span: lo.to(self.prev_span),
4707 /// Parses a statement, including the trailing semicolon.
4708 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4709 // skip looking for a trailing semicolon when we have an interpolated statement
4710 maybe_whole!(self, NtStmt, |x| Some(x));
4712 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4714 None => return Ok(None),
4718 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4719 // expression without semicolon
4720 if classify::expr_requires_semi_to_be_stmt(expr) {
4721 // Just check for errors and recover; do not eat semicolon yet.
4723 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4726 self.recover_stmt();
4730 StmtKind::Local(..) => {
4731 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4732 if macro_legacy_warnings && self.token != token::Semi {
4733 self.warn_missing_semicolon();
4735 self.expect_one_of(&[], &[token::Semi])?;
4741 if self.eat(&token::Semi) {
4742 stmt = stmt.add_trailing_semicolon();
4745 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4749 fn warn_missing_semicolon(&self) {
4750 self.diagnostic().struct_span_warn(self.span, {
4751 &format!("expected `;`, found {}", self.this_token_descr())
4753 "This was erroneously allowed and will become a hard error in a future release"
4757 fn err_dotdotdot_syntax(&self, span: Span) {
4758 self.diagnostic().struct_span_err(span, {
4759 "unexpected token: `...`"
4761 span, "use `..` for an exclusive range", "..".to_owned(),
4762 Applicability::MaybeIncorrect
4764 span, "or `..=` for an inclusive range", "..=".to_owned(),
4765 Applicability::MaybeIncorrect
4769 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
4772 /// BOUND = TY_BOUND | LT_BOUND
4773 /// LT_BOUND = LIFETIME (e.g., `'a`)
4774 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4775 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
4777 fn parse_generic_bounds_common(&mut self,
4779 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4780 let mut bounds = Vec::new();
4781 let mut negative_bounds = Vec::new();
4782 let mut last_plus_span = None;
4783 let mut was_negative = false;
4785 // This needs to be synchronized with `TokenKind::can_begin_bound`.
4786 let is_bound_start = self.check_path() || self.check_lifetime() ||
4787 self.check(&token::Not) || // used for error reporting only
4788 self.check(&token::Question) ||
4789 self.check_keyword(kw::For) ||
4790 self.check(&token::OpenDelim(token::Paren));
4793 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4794 let inner_lo = self.span;
4795 let is_negative = self.eat(&token::Not);
4796 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4797 if self.token.is_lifetime() {
4798 if let Some(question_span) = question {
4799 self.span_err(question_span,
4800 "`?` may only modify trait bounds, not lifetime bounds");
4802 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4804 let inner_span = inner_lo.to(self.prev_span);
4805 self.expect(&token::CloseDelim(token::Paren))?;
4806 let mut err = self.struct_span_err(
4807 lo.to(self.prev_span),
4808 "parenthesized lifetime bounds are not supported"
4810 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
4811 err.span_suggestion_short(
4812 lo.to(self.prev_span),
4813 "remove the parentheses",
4815 Applicability::MachineApplicable
4821 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4822 let path = self.parse_path(PathStyle::Type)?;
4824 self.expect(&token::CloseDelim(token::Paren))?;
4826 let poly_span = lo.to(self.prev_span);
4828 was_negative = true;
4829 if let Some(sp) = last_plus_span.or(colon_span) {
4830 negative_bounds.push(sp.to(poly_span));
4833 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
4834 let modifier = if question.is_some() {
4835 TraitBoundModifier::Maybe
4837 TraitBoundModifier::None
4839 bounds.push(GenericBound::Trait(poly_trait, modifier));
4846 if !allow_plus || !self.eat_plus() {
4849 last_plus_span = Some(self.prev_span);
4853 if !negative_bounds.is_empty() || was_negative {
4854 let plural = negative_bounds.len() > 1;
4855 let last_span = negative_bounds.last().map(|sp| *sp);
4856 let mut err = self.struct_span_err(
4858 "negative trait bounds are not supported",
4860 if let Some(sp) = last_span {
4861 err.span_label(sp, "negative trait bounds are not supported");
4863 if let Some(bound_list) = colon_span {
4864 let bound_list = bound_list.to(self.prev_span);
4865 let mut new_bound_list = String::new();
4866 if !bounds.is_empty() {
4867 let mut snippets = bounds.iter().map(|bound| bound.span())
4868 .map(|span| self.sess.source_map().span_to_snippet(span));
4869 while let Some(Ok(snippet)) = snippets.next() {
4870 new_bound_list.push_str(" + ");
4871 new_bound_list.push_str(&snippet);
4873 new_bound_list = new_bound_list.replacen(" +", ":", 1);
4875 err.span_suggestion_hidden(
4877 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
4879 Applicability::MachineApplicable,
4888 crate fn parse_generic_bounds(&mut self,
4889 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4890 self.parse_generic_bounds_common(true, colon_span)
4893 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4896 /// BOUND = LT_BOUND (e.g., `'a`)
4898 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4899 let mut lifetimes = Vec::new();
4900 while self.check_lifetime() {
4901 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4903 if !self.eat_plus() {
4910 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
4911 fn parse_ty_param(&mut self,
4912 preceding_attrs: Vec<Attribute>)
4913 -> PResult<'a, GenericParam> {
4914 let ident = self.parse_ident()?;
4916 // Parse optional colon and param bounds.
4917 let bounds = if self.eat(&token::Colon) {
4918 self.parse_generic_bounds(Some(self.prev_span))?
4923 let default = if self.eat(&token::Eq) {
4924 Some(self.parse_ty()?)
4931 id: ast::DUMMY_NODE_ID,
4932 attrs: preceding_attrs.into(),
4934 kind: GenericParamKind::Type {
4940 /// Parses the following grammar:
4942 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4943 fn parse_trait_item_assoc_ty(&mut self)
4944 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4945 let ident = self.parse_ident()?;
4946 let mut generics = self.parse_generics()?;
4948 // Parse optional colon and param bounds.
4949 let bounds = if self.eat(&token::Colon) {
4950 self.parse_generic_bounds(None)?
4954 generics.where_clause = self.parse_where_clause()?;
4956 let default = if self.eat(&token::Eq) {
4957 Some(self.parse_ty()?)
4961 self.expect(&token::Semi)?;
4963 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4966 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
4967 self.expect_keyword(kw::Const)?;
4968 let ident = self.parse_ident()?;
4969 self.expect(&token::Colon)?;
4970 let ty = self.parse_ty()?;
4974 id: ast::DUMMY_NODE_ID,
4975 attrs: preceding_attrs.into(),
4977 kind: GenericParamKind::Const {
4983 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
4984 /// a trailing comma and erroneous trailing attributes.
4985 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4986 let mut params = Vec::new();
4988 let attrs = self.parse_outer_attributes()?;
4989 if self.check_lifetime() {
4990 let lifetime = self.expect_lifetime();
4991 // Parse lifetime parameter.
4992 let bounds = if self.eat(&token::Colon) {
4993 self.parse_lt_param_bounds()
4997 params.push(ast::GenericParam {
4998 ident: lifetime.ident,
5000 attrs: attrs.into(),
5002 kind: ast::GenericParamKind::Lifetime,
5004 } else if self.check_keyword(kw::Const) {
5005 // Parse const parameter.
5006 params.push(self.parse_const_param(attrs)?);
5007 } else if self.check_ident() {
5008 // Parse type parameter.
5009 params.push(self.parse_ty_param(attrs)?);
5011 // Check for trailing attributes and stop parsing.
5012 if !attrs.is_empty() {
5013 if !params.is_empty() {
5014 self.struct_span_err(
5016 &format!("trailing attribute after generic parameter"),
5018 .span_label(attrs[0].span, "attributes must go before parameters")
5021 self.struct_span_err(
5023 &format!("attribute without generic parameters"),
5027 "attributes are only permitted when preceding parameters",
5035 if !self.eat(&token::Comma) {
5042 /// Parses a set of optional generic type parameter declarations. Where
5043 /// clauses are not parsed here, and must be added later via
5044 /// `parse_where_clause()`.
5046 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5047 /// | ( < lifetimes , typaramseq ( , )? > )
5048 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5049 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5050 let span_lo = self.span;
5051 let (params, span) = if self.eat_lt() {
5052 let params = self.parse_generic_params()?;
5054 (params, span_lo.to(self.prev_span))
5056 (vec![], self.prev_span.between(self.span))
5060 where_clause: WhereClause {
5061 id: ast::DUMMY_NODE_ID,
5062 predicates: Vec::new(),
5069 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5070 /// For the purposes of understanding the parsing logic of generic arguments, this function
5071 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5072 /// had the correct amount of leading angle brackets.
5074 /// ```ignore (diagnostics)
5075 /// bar::<<<<T as Foo>::Output>();
5076 /// ^^ help: remove extra angle brackets
5078 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5082 ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5083 // We need to detect whether there are extra leading left angle brackets and produce an
5084 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5085 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5086 // then there won't be matching `>` tokens to find.
5088 // To explain how this detection works, consider the following example:
5090 // ```ignore (diagnostics)
5091 // bar::<<<<T as Foo>::Output>();
5092 // ^^ help: remove extra angle brackets
5095 // Parsing of the left angle brackets starts in this function. We start by parsing the
5096 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5099 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5100 // *Unmatched count:* 1
5101 // *`parse_path_segment` calls deep:* 0
5103 // This has the effect of recursing as this function is called if a `<` character
5104 // is found within the expected generic arguments:
5106 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5107 // *Unmatched count:* 2
5108 // *`parse_path_segment` calls deep:* 1
5110 // Eventually we will have recursed until having consumed all of the `<` tokens and
5111 // this will be reflected in the count:
5113 // *Upcoming tokens:* `T as Foo>::Output>;`
5114 // *Unmatched count:* 4
5115 // `parse_path_segment` calls deep:* 3
5117 // The parser will continue until reaching the first `>` - this will decrement the
5118 // unmatched angle bracket count and return to the parent invocation of this function
5119 // having succeeded in parsing:
5121 // *Upcoming tokens:* `::Output>;`
5122 // *Unmatched count:* 3
5123 // *`parse_path_segment` calls deep:* 2
5125 // This will continue until the next `>` character which will also return successfully
5126 // to the parent invocation of this function and decrement the count:
5128 // *Upcoming tokens:* `;`
5129 // *Unmatched count:* 2
5130 // *`parse_path_segment` calls deep:* 1
5132 // At this point, this function will expect to find another matching `>` character but
5133 // won't be able to and will return an error. This will continue all the way up the
5134 // call stack until the first invocation:
5136 // *Upcoming tokens:* `;`
5137 // *Unmatched count:* 2
5138 // *`parse_path_segment` calls deep:* 0
5140 // In doing this, we have managed to work out how many unmatched leading left angle
5141 // brackets there are, but we cannot recover as the unmatched angle brackets have
5142 // already been consumed. To remedy this, we keep a snapshot of the parser state
5143 // before we do the above. We can then inspect whether we ended up with a parsing error
5144 // and unmatched left angle brackets and if so, restore the parser state before we
5145 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5146 // recover by attempting to parse again.
5148 // In practice, the recursion of this function is indirect and there will be other
5149 // locations that consume some `<` characters - as long as we update the count when
5150 // this happens, it isn't an issue.
5152 let is_first_invocation = style == PathStyle::Expr;
5153 // Take a snapshot before attempting to parse - we can restore this later.
5154 let snapshot = if is_first_invocation {
5160 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5161 match self.parse_generic_args() {
5162 Ok(value) => Ok(value),
5163 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5164 // Cancel error from being unable to find `>`. We know the error
5165 // must have been this due to a non-zero unmatched angle bracket
5169 // Swap `self` with our backup of the parser state before attempting to parse
5170 // generic arguments.
5171 let snapshot = mem::replace(self, snapshot.unwrap());
5174 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5175 snapshot.count={:?}",
5176 snapshot.unmatched_angle_bracket_count,
5179 // Eat the unmatched angle brackets.
5180 for _ in 0..snapshot.unmatched_angle_bracket_count {
5184 // Make a span over ${unmatched angle bracket count} characters.
5185 let span = lo.with_hi(
5186 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5188 let plural = snapshot.unmatched_angle_bracket_count > 1;
5193 "unmatched angle bracket{}",
5194 if plural { "s" } else { "" }
5200 "remove extra angle bracket{}",
5201 if plural { "s" } else { "" }
5204 Applicability::MachineApplicable,
5208 // Try again without unmatched angle bracket characters.
5209 self.parse_generic_args()
5215 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5216 /// possibly including trailing comma.
5217 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5218 let mut args = Vec::new();
5219 let mut constraints = Vec::new();
5220 let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new();
5221 let mut assoc_ty_constraints: Vec<Span> = Vec::new();
5223 let args_lo = self.span;
5226 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5227 // Parse lifetime argument.
5228 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5229 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5230 } else if self.check_ident() && self.look_ahead(1,
5231 |t| t == &token::Eq || t == &token::Colon) {
5232 // Parse associated type constraint.
5234 let ident = self.parse_ident()?;
5235 let kind = if self.eat(&token::Eq) {
5236 AssocTyConstraintKind::Equality {
5237 ty: self.parse_ty()?,
5239 } else if self.eat(&token::Colon) {
5240 AssocTyConstraintKind::Bound {
5241 bounds: self.parse_generic_bounds(Some(self.prev_span))?,
5246 let span = lo.to(self.prev_span);
5247 constraints.push(AssocTyConstraint {
5248 id: ast::DUMMY_NODE_ID,
5253 assoc_ty_constraints.push(span);
5254 } else if self.check_const_arg() {
5255 // Parse const argument.
5256 let expr = if let token::OpenDelim(token::Brace) = self.token.kind {
5257 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
5258 } else if self.token.is_ident() {
5259 // FIXME(const_generics): to distinguish between idents for types and consts,
5260 // we should introduce a GenericArg::Ident in the AST and distinguish when
5261 // lowering to the HIR. For now, idents for const args are not permitted.
5262 if self.token.is_keyword(kw::True) || self.token.is_keyword(kw::False) {
5263 self.parse_literal_maybe_minus()?
5266 self.fatal("identifiers may currently not be used for const generics")
5270 self.parse_literal_maybe_minus()?
5272 let value = AnonConst {
5273 id: ast::DUMMY_NODE_ID,
5276 args.push(GenericArg::Const(value));
5277 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5278 } else if self.check_type() {
5279 // Parse type argument.
5280 args.push(GenericArg::Type(self.parse_ty()?));
5281 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5286 if !self.eat(&token::Comma) {
5291 // FIXME: we would like to report this in ast_validation instead, but we currently do not
5292 // preserve ordering of generic parameters with respect to associated type binding, so we
5293 // lose that information after parsing.
5294 if misplaced_assoc_ty_constraints.len() > 0 {
5295 let mut err = self.struct_span_err(
5296 args_lo.to(self.prev_span),
5297 "associated type bindings must be declared after generic parameters",
5299 for span in misplaced_assoc_ty_constraints {
5302 "this associated type binding should be moved after the generic parameters",
5308 Ok((args, constraints))
5311 /// Parses an optional where-clause and places it in `generics`.
5313 /// ```ignore (only-for-syntax-highlight)
5314 /// where T : Trait<U, V> + 'b, 'a : 'b
5316 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5317 let mut where_clause = WhereClause {
5318 id: ast::DUMMY_NODE_ID,
5319 predicates: Vec::new(),
5320 span: self.prev_span.to(self.prev_span),
5323 if !self.eat_keyword(kw::Where) {
5324 return Ok(where_clause);
5326 let lo = self.prev_span;
5328 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5329 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5330 // change we parse those generics now, but report an error.
5331 if self.choose_generics_over_qpath() {
5332 let generics = self.parse_generics()?;
5333 self.struct_span_err(
5335 "generic parameters on `where` clauses are reserved for future use",
5337 .span_label(generics.span, "currently unsupported")
5343 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5344 let lifetime = self.expect_lifetime();
5345 // Bounds starting with a colon are mandatory, but possibly empty.
5346 self.expect(&token::Colon)?;
5347 let bounds = self.parse_lt_param_bounds();
5348 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5349 ast::WhereRegionPredicate {
5350 span: lo.to(self.prev_span),
5355 } else if self.check_type() {
5356 // Parse optional `for<'a, 'b>`.
5357 // This `for` is parsed greedily and applies to the whole predicate,
5358 // the bounded type can have its own `for` applying only to it.
5360 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
5361 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
5362 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
5363 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5365 // Parse type with mandatory colon and (possibly empty) bounds,
5366 // or with mandatory equality sign and the second type.
5367 let ty = self.parse_ty()?;
5368 if self.eat(&token::Colon) {
5369 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
5370 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5371 ast::WhereBoundPredicate {
5372 span: lo.to(self.prev_span),
5373 bound_generic_params: lifetime_defs,
5378 // FIXME: Decide what should be used here, `=` or `==`.
5379 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5380 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5381 let rhs_ty = self.parse_ty()?;
5382 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5383 ast::WhereEqPredicate {
5384 span: lo.to(self.prev_span),
5387 id: ast::DUMMY_NODE_ID,
5391 return self.unexpected();
5397 if !self.eat(&token::Comma) {
5402 where_clause.span = lo.to(self.prev_span);
5406 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
5407 -> PResult<'a, (Vec<Arg> , bool)> {
5408 self.expect(&token::OpenDelim(token::Paren))?;
5411 let mut c_variadic = false;
5412 let (args, recovered): (Vec<Option<Arg>>, bool) =
5413 self.parse_seq_to_before_end(
5414 &token::CloseDelim(token::Paren),
5415 SeqSep::trailing_allowed(token::Comma),
5417 // If the argument is a C-variadic argument we should not
5418 // enforce named arguments.
5419 let enforce_named_args = if p.token == token::DotDotDot {
5424 match p.parse_arg_general(enforce_named_args, false,
5427 if let TyKind::CVarArgs = arg.ty.node {
5429 if p.token != token::CloseDelim(token::Paren) {
5432 "`...` must be the last argument of a C-variadic function");
5443 let lo = p.prev_span;
5444 // Skip every token until next possible arg or end.
5445 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5446 // Create a placeholder argument for proper arg count (issue #34264).
5447 let span = lo.to(p.prev_span);
5448 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
5455 self.eat(&token::CloseDelim(token::Paren));
5458 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5460 if c_variadic && args.is_empty() {
5462 "C-variadic function must be declared with at least one named argument");
5465 Ok((args, c_variadic))
5468 /// Parses the argument list and result type of a function declaration.
5469 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
5471 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
5472 let ret_ty = self.parse_ret_ty(true)?;
5481 /// Returns the parsed optional self argument and whether a self shortcut was used.
5482 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5483 let expect_ident = |this: &mut Self| match this.token.kind {
5484 // Preserve hygienic context.
5485 token::Ident(ident, _) =>
5486 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5489 let isolated_self = |this: &mut Self, n| {
5490 this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
5491 this.look_ahead(n + 1, |t| t != &token::ModSep)
5494 // Parse optional `self` parameter of a method.
5495 // Only a limited set of initial token sequences is considered `self` parameters; anything
5496 // else is parsed as a normal function parameter list, so some lookahead is required.
5497 let eself_lo = self.span;
5498 let (eself, eself_ident, eself_hi) = match self.token.kind {
5499 token::BinOp(token::And) => {
5505 (if isolated_self(self, 1) {
5507 SelfKind::Region(None, Mutability::Immutable)
5508 } else if self.is_keyword_ahead(1, &[kw::Mut]) &&
5509 isolated_self(self, 2) {
5512 SelfKind::Region(None, Mutability::Mutable)
5513 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5514 isolated_self(self, 2) {
5516 let lt = self.expect_lifetime();
5517 SelfKind::Region(Some(lt), Mutability::Immutable)
5518 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5519 self.is_keyword_ahead(2, &[kw::Mut]) &&
5520 isolated_self(self, 3) {
5522 let lt = self.expect_lifetime();
5524 SelfKind::Region(Some(lt), Mutability::Mutable)
5527 }, expect_ident(self), self.prev_span)
5529 token::BinOp(token::Star) => {
5534 // Emit special error for `self` cases.
5535 let msg = "cannot pass `self` by raw pointer";
5536 (if isolated_self(self, 1) {
5538 self.struct_span_err(self.span, msg)
5539 .span_label(self.span, msg)
5541 SelfKind::Value(Mutability::Immutable)
5542 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5543 isolated_self(self, 2) {
5546 self.struct_span_err(self.span, msg)
5547 .span_label(self.span, msg)
5549 SelfKind::Value(Mutability::Immutable)
5552 }, expect_ident(self), self.prev_span)
5554 token::Ident(..) => {
5555 if isolated_self(self, 0) {
5558 let eself_ident = expect_ident(self);
5559 let eself_hi = self.prev_span;
5560 (if self.eat(&token::Colon) {
5561 let ty = self.parse_ty()?;
5562 SelfKind::Explicit(ty, Mutability::Immutable)
5564 SelfKind::Value(Mutability::Immutable)
5565 }, eself_ident, eself_hi)
5566 } else if self.token.is_keyword(kw::Mut) &&
5567 isolated_self(self, 1) {
5571 let eself_ident = expect_ident(self);
5572 let eself_hi = self.prev_span;
5573 (if self.eat(&token::Colon) {
5574 let ty = self.parse_ty()?;
5575 SelfKind::Explicit(ty, Mutability::Mutable)
5577 SelfKind::Value(Mutability::Mutable)
5578 }, eself_ident, eself_hi)
5583 _ => return Ok(None),
5586 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5587 Ok(Some(Arg::from_self(eself, eself_ident)))
5590 /// Parses the parameter list and result type of a function that may have a `self` parameter.
5591 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5592 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5594 self.expect(&token::OpenDelim(token::Paren))?;
5596 // Parse optional self argument.
5597 let self_arg = self.parse_self_arg()?;
5599 // Parse the rest of the function parameter list.
5600 let sep = SeqSep::trailing_allowed(token::Comma);
5601 let (mut fn_inputs, recovered) = if let Some(self_arg) = self_arg {
5602 if self.check(&token::CloseDelim(token::Paren)) {
5603 (vec![self_arg], false)
5604 } else if self.eat(&token::Comma) {
5605 let mut fn_inputs = vec![self_arg];
5606 let (mut input, recovered) = self.parse_seq_to_before_end(
5607 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
5608 fn_inputs.append(&mut input);
5609 (fn_inputs, recovered)
5611 match self.expect_one_of(&[], &[]) {
5612 Err(err) => return Err(err),
5613 Ok(recovered) => (vec![self_arg], recovered),
5617 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5621 // Parse closing paren and return type.
5622 self.expect(&token::CloseDelim(token::Paren))?;
5624 // Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
5625 self.deduplicate_recovered_arg_names(&mut fn_inputs);
5629 output: self.parse_ret_ty(true)?,
5634 /// Parses the `|arg, arg|` header of a closure.
5635 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5636 let inputs_captures = {
5637 if self.eat(&token::OrOr) {
5640 self.expect(&token::BinOp(token::Or))?;
5641 let args = self.parse_seq_to_before_tokens(
5642 &[&token::BinOp(token::Or), &token::OrOr],
5643 SeqSep::trailing_allowed(token::Comma),
5644 TokenExpectType::NoExpect,
5645 |p| p.parse_fn_block_arg()
5651 let output = self.parse_ret_ty(true)?;
5654 inputs: inputs_captures,
5660 /// Parses the name and optional generic types of a function header.
5661 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5662 let id = self.parse_ident()?;
5663 let generics = self.parse_generics()?;
5667 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5668 attrs: Vec<Attribute>) -> P<Item> {
5672 id: ast::DUMMY_NODE_ID,
5680 /// Parses an item-position function declaration.
5681 fn parse_item_fn(&mut self,
5683 asyncness: Spanned<IsAsync>,
5684 constness: Spanned<Constness>,
5686 -> PResult<'a, ItemInfo> {
5687 let (ident, mut generics) = self.parse_fn_header()?;
5688 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
5689 let decl = self.parse_fn_decl(allow_c_variadic)?;
5690 generics.where_clause = self.parse_where_clause()?;
5691 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5692 let header = FnHeader { unsafety, asyncness, constness, abi };
5693 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5696 /// Returns `true` if we are looking at `const ID`
5697 /// (returns `false` for things like `const fn`, etc.).
5698 fn is_const_item(&self) -> bool {
5699 self.token.is_keyword(kw::Const) &&
5700 !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
5703 /// Parses all the "front matter" for a `fn` declaration, up to
5704 /// and including the `fn` keyword:
5708 /// - `const unsafe fn`
5711 fn parse_fn_front_matter(&mut self)
5719 let is_const_fn = self.eat_keyword(kw::Const);
5720 let const_span = self.prev_span;
5721 let unsafety = self.parse_unsafety();
5722 let asyncness = self.parse_asyncness();
5723 let asyncness = respan(self.prev_span, asyncness);
5724 let (constness, unsafety, abi) = if is_const_fn {
5725 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5727 let abi = if self.eat_keyword(kw::Extern) {
5728 self.parse_opt_abi()?.unwrap_or(Abi::C)
5732 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5734 if !self.eat_keyword(kw::Fn) {
5735 // It is possible for `expect_one_of` to recover given the contents of
5736 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
5737 // account for this.
5738 if !self.expect_one_of(&[], &[])? { unreachable!() }
5740 Ok((constness, unsafety, asyncness, abi))
5743 /// Parses an impl item.
5744 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5745 maybe_whole!(self, NtImplItem, |x| x);
5746 let attrs = self.parse_outer_attributes()?;
5747 let mut unclosed_delims = vec![];
5748 let (mut item, tokens) = self.collect_tokens(|this| {
5749 let item = this.parse_impl_item_(at_end, attrs);
5750 unclosed_delims.append(&mut this.unclosed_delims);
5753 self.unclosed_delims.append(&mut unclosed_delims);
5755 // See `parse_item` for why this clause is here.
5756 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5757 item.tokens = Some(tokens);
5762 fn parse_impl_item_(&mut self,
5764 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5766 let vis = self.parse_visibility(false)?;
5767 let defaultness = self.parse_defaultness();
5768 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5769 let (name, alias, generics) = type_?;
5770 let kind = match alias {
5771 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5772 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5774 (name, kind, generics)
5775 } else if self.is_const_item() {
5776 // This parses the grammar:
5777 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5778 self.expect_keyword(kw::Const)?;
5779 let name = self.parse_ident()?;
5780 self.expect(&token::Colon)?;
5781 let typ = self.parse_ty()?;
5782 self.expect(&token::Eq)?;
5783 let expr = self.parse_expr()?;
5784 self.expect(&token::Semi)?;
5785 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5787 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5788 attrs.extend(inner_attrs);
5789 (name, node, generics)
5793 id: ast::DUMMY_NODE_ID,
5794 span: lo.to(self.prev_span),
5805 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
5807 VisibilityKind::Inherited => {}
5809 let is_macro_rules: bool = match self.token.kind {
5810 token::Ident(sid, _) => sid.name == sym::macro_rules,
5813 let mut err = if is_macro_rules {
5814 let mut err = self.diagnostic()
5815 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5816 err.span_suggestion(
5818 "try exporting the macro",
5819 "#[macro_export]".to_owned(),
5820 Applicability::MaybeIncorrect // speculative
5824 let mut err = self.diagnostic()
5825 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5826 err.help("try adjusting the macro to put `pub` inside the invocation");
5834 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
5835 -> DiagnosticBuilder<'a>
5837 let expected_kinds = if item_type == "extern" {
5838 "missing `fn`, `type`, or `static`"
5840 "missing `fn`, `type`, or `const`"
5843 // Given this code `path(`, it seems like this is not
5844 // setting the visibility of a macro invocation, but rather
5845 // a mistyped method declaration.
5846 // Create a diagnostic pointing out that `fn` is missing.
5848 // x | pub path(&self) {
5849 // | ^ missing `fn`, `type`, or `const`
5851 // ^^ `sp` below will point to this
5852 let sp = prev_span.between(self.prev_span);
5853 let mut err = self.diagnostic().struct_span_err(
5855 &format!("{} for {}-item declaration",
5856 expected_kinds, item_type));
5857 err.span_label(sp, expected_kinds);
5861 /// Parse a method or a macro invocation in a trait impl.
5862 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5863 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5864 ast::ImplItemKind)> {
5865 // code copied from parse_macro_use_or_failure... abstraction!
5866 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5868 Ok((Ident::invalid(), vec![], ast::Generics::default(),
5869 ast::ImplItemKind::Macro(mac)))
5871 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5872 let ident = self.parse_ident()?;
5873 let mut generics = self.parse_generics()?;
5874 let decl = self.parse_fn_decl_with_self(|p| {
5875 p.parse_arg_general(true, true, false)
5877 generics.where_clause = self.parse_where_clause()?;
5879 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5880 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5881 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5882 ast::MethodSig { header, decl },
5888 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
5889 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5890 let ident = self.parse_ident()?;
5891 let mut tps = self.parse_generics()?;
5893 // Parse optional colon and supertrait bounds.
5894 let bounds = if self.eat(&token::Colon) {
5895 self.parse_generic_bounds(Some(self.prev_span))?
5900 if self.eat(&token::Eq) {
5901 // it's a trait alias
5902 let bounds = self.parse_generic_bounds(None)?;
5903 tps.where_clause = self.parse_where_clause()?;
5904 self.expect(&token::Semi)?;
5905 if is_auto == IsAuto::Yes {
5906 let msg = "trait aliases cannot be `auto`";
5907 self.struct_span_err(self.prev_span, msg)
5908 .span_label(self.prev_span, msg)
5911 if unsafety != Unsafety::Normal {
5912 let msg = "trait aliases cannot be `unsafe`";
5913 self.struct_span_err(self.prev_span, msg)
5914 .span_label(self.prev_span, msg)
5917 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5919 // it's a normal trait
5920 tps.where_clause = self.parse_where_clause()?;
5921 self.expect(&token::OpenDelim(token::Brace))?;
5922 let mut trait_items = vec![];
5923 while !self.eat(&token::CloseDelim(token::Brace)) {
5924 if let token::DocComment(_) = self.token.kind {
5925 if self.look_ahead(1,
5926 |tok| tok == &token::CloseDelim(token::Brace)) {
5927 let mut err = self.diagnostic().struct_span_err_with_code(
5929 "found a documentation comment that doesn't document anything",
5930 DiagnosticId::Error("E0584".into()),
5932 err.help("doc comments must come before what they document, maybe a \
5933 comment was intended with `//`?",
5940 let mut at_end = false;
5941 match self.parse_trait_item(&mut at_end) {
5942 Ok(item) => trait_items.push(item),
5946 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5951 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5955 fn choose_generics_over_qpath(&self) -> bool {
5956 // There's an ambiguity between generic parameters and qualified paths in impls.
5957 // If we see `<` it may start both, so we have to inspect some following tokens.
5958 // The following combinations can only start generics,
5959 // but not qualified paths (with one exception):
5960 // `<` `>` - empty generic parameters
5961 // `<` `#` - generic parameters with attributes
5962 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5963 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5964 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5965 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5966 // `<` const - generic const parameter
5967 // The only truly ambiguous case is
5968 // `<` IDENT `>` `::` IDENT ...
5969 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5970 // because this is what almost always expected in practice, qualified paths in impls
5971 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5972 self.token == token::Lt &&
5973 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5974 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5975 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5976 t == &token::Colon || t == &token::Eq) ||
5977 self.is_keyword_ahead(1, &[kw::Const]))
5980 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5981 self.expect(&token::OpenDelim(token::Brace))?;
5982 let attrs = self.parse_inner_attributes()?;
5984 let mut impl_items = Vec::new();
5985 while !self.eat(&token::CloseDelim(token::Brace)) {
5986 let mut at_end = false;
5987 match self.parse_impl_item(&mut at_end) {
5988 Ok(impl_item) => impl_items.push(impl_item),
5992 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5997 Ok((impl_items, attrs))
6000 /// Parses an implementation item, `impl` keyword is already parsed.
6002 /// impl<'a, T> TYPE { /* impl items */ }
6003 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6004 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6006 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6007 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6008 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6009 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6010 -> PResult<'a, ItemInfo> {
6011 // First, parse generic parameters if necessary.
6012 let mut generics = if self.choose_generics_over_qpath() {
6013 self.parse_generics()?
6015 ast::Generics::default()
6018 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6019 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6021 ast::ImplPolarity::Negative
6023 ast::ImplPolarity::Positive
6026 // Parse both types and traits as a type, then reinterpret if necessary.
6027 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
6028 let ty_first = if self.token.is_keyword(kw::For) &&
6029 self.look_ahead(1, |t| t != &token::Lt) {
6030 let span = self.prev_span.between(self.span);
6031 self.struct_span_err(span, "missing trait in a trait impl").emit();
6032 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6037 // If `for` is missing we try to recover.
6038 let has_for = self.eat_keyword(kw::For);
6039 let missing_for_span = self.prev_span.between(self.span);
6041 let ty_second = if self.token == token::DotDot {
6042 // We need to report this error after `cfg` expansion for compatibility reasons
6043 self.bump(); // `..`, do not add it to expected tokens
6044 Some(DummyResult::raw_ty(self.prev_span, true))
6045 } else if has_for || self.token.can_begin_type() {
6046 Some(self.parse_ty()?)
6051 generics.where_clause = self.parse_where_clause()?;
6053 let (impl_items, attrs) = self.parse_impl_body()?;
6055 let item_kind = match ty_second {
6056 Some(ty_second) => {
6057 // impl Trait for Type
6059 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6060 .span_suggestion_short(
6063 " for ".to_string(),
6064 Applicability::MachineApplicable,
6068 let ty_first = ty_first.into_inner();
6069 let path = match ty_first.node {
6070 // This notably includes paths passed through `ty` macro fragments (#46438).
6071 TyKind::Path(None, path) => path,
6073 self.span_err(ty_first.span, "expected a trait, found type");
6074 err_path(ty_first.span)
6077 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6079 ItemKind::Impl(unsafety, polarity, defaultness,
6080 generics, Some(trait_ref), ty_second, impl_items)
6084 ItemKind::Impl(unsafety, polarity, defaultness,
6085 generics, None, ty_first, impl_items)
6089 Ok((Ident::invalid(), item_kind, Some(attrs)))
6092 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6093 if self.eat_keyword(kw::For) {
6095 let params = self.parse_generic_params()?;
6097 // We rely on AST validation to rule out invalid cases: There must not be type
6098 // parameters, and the lifetime parameters must not have bounds.
6105 /// Parses `struct Foo { ... }`.
6106 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6107 let class_name = self.parse_ident()?;
6109 let mut generics = self.parse_generics()?;
6111 // There is a special case worth noting here, as reported in issue #17904.
6112 // If we are parsing a tuple struct it is the case that the where clause
6113 // should follow the field list. Like so:
6115 // struct Foo<T>(T) where T: Copy;
6117 // If we are parsing a normal record-style struct it is the case
6118 // that the where clause comes before the body, and after the generics.
6119 // So if we look ahead and see a brace or a where-clause we begin
6120 // parsing a record style struct.
6122 // Otherwise if we look ahead and see a paren we parse a tuple-style
6125 let vdata = if self.token.is_keyword(kw::Where) {
6126 generics.where_clause = self.parse_where_clause()?;
6127 if self.eat(&token::Semi) {
6128 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6129 VariantData::Unit(ast::DUMMY_NODE_ID)
6131 // If we see: `struct Foo<T> where T: Copy { ... }`
6132 let (fields, recovered) = self.parse_record_struct_body()?;
6133 VariantData::Struct(fields, recovered)
6135 // No `where` so: `struct Foo<T>;`
6136 } else if self.eat(&token::Semi) {
6137 VariantData::Unit(ast::DUMMY_NODE_ID)
6138 // Record-style struct definition
6139 } else if self.token == token::OpenDelim(token::Brace) {
6140 let (fields, recovered) = self.parse_record_struct_body()?;
6141 VariantData::Struct(fields, recovered)
6142 // Tuple-style struct definition with optional where-clause.
6143 } else if self.token == token::OpenDelim(token::Paren) {
6144 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6145 generics.where_clause = self.parse_where_clause()?;
6146 self.expect(&token::Semi)?;
6149 let token_str = self.this_token_descr();
6150 let mut err = self.fatal(&format!(
6151 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6154 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6158 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6161 /// Parses `union Foo { ... }`.
6162 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6163 let class_name = self.parse_ident()?;
6165 let mut generics = self.parse_generics()?;
6167 let vdata = if self.token.is_keyword(kw::Where) {
6168 generics.where_clause = self.parse_where_clause()?;
6169 let (fields, recovered) = self.parse_record_struct_body()?;
6170 VariantData::Struct(fields, recovered)
6171 } else if self.token == token::OpenDelim(token::Brace) {
6172 let (fields, recovered) = self.parse_record_struct_body()?;
6173 VariantData::Struct(fields, recovered)
6175 let token_str = self.this_token_descr();
6176 let mut err = self.fatal(&format!(
6177 "expected `where` or `{{` after union name, found {}", token_str));
6178 err.span_label(self.span, "expected `where` or `{` after union name");
6182 Ok((class_name, ItemKind::Union(vdata, generics), None))
6185 fn parse_record_struct_body(
6187 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6188 let mut fields = Vec::new();
6189 let mut recovered = false;
6190 if self.eat(&token::OpenDelim(token::Brace)) {
6191 while self.token != token::CloseDelim(token::Brace) {
6192 let field = self.parse_struct_decl_field().map_err(|e| {
6193 self.recover_stmt();
6198 Ok(field) => fields.push(field),
6204 self.eat(&token::CloseDelim(token::Brace));
6206 let token_str = self.this_token_descr();
6207 let mut err = self.fatal(&format!(
6208 "expected `where`, or `{{` after struct name, found {}", token_str));
6209 err.span_label(self.span, "expected `where`, or `{` after struct name");
6213 Ok((fields, recovered))
6216 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6217 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6218 // Unit like structs are handled in parse_item_struct function
6219 let fields = self.parse_unspanned_seq(
6220 &token::OpenDelim(token::Paren),
6221 &token::CloseDelim(token::Paren),
6222 SeqSep::trailing_allowed(token::Comma),
6224 let attrs = p.parse_outer_attributes()?;
6226 let vis = p.parse_visibility(true)?;
6227 let ty = p.parse_ty()?;
6229 span: lo.to(ty.span),
6232 id: ast::DUMMY_NODE_ID,
6241 /// Parses a structure field declaration.
6242 fn parse_single_struct_field(&mut self,
6245 attrs: Vec<Attribute> )
6246 -> PResult<'a, StructField> {
6247 let mut seen_comma: bool = false;
6248 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6249 if self.token == token::Comma {
6252 match self.token.kind {
6256 token::CloseDelim(token::Brace) => {}
6257 token::DocComment(_) => {
6258 let previous_span = self.prev_span;
6259 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6260 self.bump(); // consume the doc comment
6261 let comma_after_doc_seen = self.eat(&token::Comma);
6262 // `seen_comma` is always false, because we are inside doc block
6263 // condition is here to make code more readable
6264 if seen_comma == false && comma_after_doc_seen == true {
6267 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6270 if seen_comma == false {
6271 let sp = self.sess.source_map().next_point(previous_span);
6272 err.span_suggestion(
6274 "missing comma here",
6276 Applicability::MachineApplicable
6283 let sp = self.sess.source_map().next_point(self.prev_span);
6284 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6285 self.this_token_descr()));
6286 if self.token.is_ident() {
6287 // This is likely another field; emit the diagnostic and keep going
6288 err.span_suggestion(
6290 "try adding a comma",
6292 Applicability::MachineApplicable,
6303 /// Parses an element of a struct declaration.
6304 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6305 let attrs = self.parse_outer_attributes()?;
6307 let vis = self.parse_visibility(false)?;
6308 self.parse_single_struct_field(lo, vis, attrs)
6311 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6312 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6313 /// If the following element can't be a tuple (i.e., it's a function definition), then
6314 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6315 /// so emit a proper diagnostic.
6316 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6317 maybe_whole!(self, NtVis, |x| x);
6319 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
6320 if self.is_crate_vis() {
6321 self.bump(); // `crate`
6322 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6325 if !self.eat_keyword(kw::Pub) {
6326 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6327 // keyword to grab a span from for inherited visibility; an empty span at the
6328 // beginning of the current token would seem to be the "Schelling span".
6329 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6331 let lo = self.prev_span;
6333 if self.check(&token::OpenDelim(token::Paren)) {
6334 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6335 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6336 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6337 // by the following tokens.
6338 if self.is_keyword_ahead(1, &[kw::Crate]) &&
6339 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
6343 self.bump(); // `crate`
6344 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6346 lo.to(self.prev_span),
6347 VisibilityKind::Crate(CrateSugar::PubCrate),
6350 } else if self.is_keyword_ahead(1, &[kw::In]) {
6353 self.bump(); // `in`
6354 let path = self.parse_path(PathStyle::Mod)?; // `path`
6355 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6356 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6358 id: ast::DUMMY_NODE_ID,
6361 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6362 self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
6364 // `pub(self)` or `pub(super)`
6366 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6367 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6368 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6370 id: ast::DUMMY_NODE_ID,
6373 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6374 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6376 let msg = "incorrect visibility restriction";
6377 let suggestion = r##"some possible visibility restrictions are:
6378 `pub(crate)`: visible only on the current crate
6379 `pub(super)`: visible only in the current module's parent
6380 `pub(in path::to::module)`: visible only on the specified path"##;
6381 let path = self.parse_path(PathStyle::Mod)?;
6383 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6384 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6385 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6386 err.help(suggestion);
6387 err.span_suggestion(
6388 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6390 err.emit(); // emit diagnostic, but continue with public visibility
6394 Ok(respan(lo, VisibilityKind::Public))
6397 /// Parses defaultness (i.e., `default` or nothing).
6398 fn parse_defaultness(&mut self) -> Defaultness {
6399 // `pub` is included for better error messages
6400 if self.check_keyword(kw::Default) &&
6401 self.is_keyword_ahead(1, &[
6411 self.bump(); // `default`
6412 Defaultness::Default
6418 /// Given a termination token, parses all of the items in a module.
6419 fn parse_mod_items(&mut self, term: &token::TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
6420 let mut items = vec![];
6421 while let Some(item) = self.parse_item()? {
6423 self.maybe_consume_incorrect_semicolon(&items);
6426 if !self.eat(term) {
6427 let token_str = self.this_token_descr();
6428 if !self.maybe_consume_incorrect_semicolon(&items) {
6429 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6430 err.span_label(self.span, "expected item");
6435 let hi = if self.span.is_dummy() {
6442 inner: inner_lo.to(hi),
6448 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6449 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6450 self.expect(&token::Colon)?;
6451 let ty = self.parse_ty()?;
6452 self.expect(&token::Eq)?;
6453 let e = self.parse_expr()?;
6454 self.expect(&token::Semi)?;
6455 let item = match m {
6456 Some(m) => ItemKind::Static(ty, m, e),
6457 None => ItemKind::Const(ty, e),
6459 Ok((id, item, None))
6462 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6463 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6464 let (in_cfg, outer_attrs) = {
6465 let mut strip_unconfigured = crate::config::StripUnconfigured {
6467 features: None, // don't perform gated feature checking
6469 let mut outer_attrs = outer_attrs.to_owned();
6470 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
6471 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6474 let id_span = self.span;
6475 let id = self.parse_ident()?;
6476 if self.eat(&token::Semi) {
6477 if in_cfg && self.recurse_into_file_modules {
6478 // This mod is in an external file. Let's go get it!
6479 let ModulePathSuccess { path, directory_ownership, warn } =
6480 self.submod_path(id, &outer_attrs, id_span)?;
6481 let (module, mut attrs) =
6482 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6483 // Record that we fetched the mod from an external file
6485 let attr = Attribute {
6486 id: attr::mk_attr_id(),
6487 style: ast::AttrStyle::Outer,
6488 path: ast::Path::from_ident(
6489 Ident::with_empty_ctxt(sym::warn_directory_ownership)),
6490 tokens: TokenStream::empty(),
6491 is_sugared_doc: false,
6494 attr::mark_known(&attr);
6497 Ok((id, ItemKind::Mod(module), Some(attrs)))
6499 let placeholder = ast::Mod {
6504 Ok((id, ItemKind::Mod(placeholder), None))
6507 let old_directory = self.directory.clone();
6508 self.push_directory(id, &outer_attrs);
6510 self.expect(&token::OpenDelim(token::Brace))?;
6511 let mod_inner_lo = self.span;
6512 let attrs = self.parse_inner_attributes()?;
6513 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6515 self.directory = old_directory;
6516 Ok((id, ItemKind::Mod(module), Some(attrs)))
6520 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6521 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6522 self.directory.path.to_mut().push(&path.as_str());
6523 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6525 // We have to push on the current module name in the case of relative
6526 // paths in order to ensure that any additional module paths from inline
6527 // `mod x { ... }` come after the relative extension.
6529 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6530 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6531 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6532 if let Some(ident) = relative.take() { // remove the relative offset
6533 self.directory.path.to_mut().push(ident.as_str());
6536 self.directory.path.to_mut().push(&id.as_str());
6540 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6541 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6544 // On windows, the base path might have the form
6545 // `\\?\foo\bar` in which case it does not tolerate
6546 // mixed `/` and `\` separators, so canonicalize
6549 let s = s.replace("/", "\\");
6550 Some(dir_path.join(s))
6556 /// Returns a path to a module.
6557 pub fn default_submod_path(
6559 relative: Option<ast::Ident>,
6561 source_map: &SourceMap) -> ModulePath
6563 // If we're in a foo.rs file instead of a mod.rs file,
6564 // we need to look for submodules in
6565 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6566 // `./<id>.rs` and `./<id>/mod.rs`.
6567 let relative_prefix_string;
6568 let relative_prefix = if let Some(ident) = relative {
6569 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6570 &relative_prefix_string
6575 let mod_name = id.to_string();
6576 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6577 let secondary_path_str = format!("{}{}{}mod.rs",
6578 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6579 let default_path = dir_path.join(&default_path_str);
6580 let secondary_path = dir_path.join(&secondary_path_str);
6581 let default_exists = source_map.file_exists(&default_path);
6582 let secondary_exists = source_map.file_exists(&secondary_path);
6584 let result = match (default_exists, secondary_exists) {
6585 (true, false) => Ok(ModulePathSuccess {
6587 directory_ownership: DirectoryOwnership::Owned {
6592 (false, true) => Ok(ModulePathSuccess {
6593 path: secondary_path,
6594 directory_ownership: DirectoryOwnership::Owned {
6599 (false, false) => Err(Error::FileNotFoundForModule {
6600 mod_name: mod_name.clone(),
6601 default_path: default_path_str,
6602 secondary_path: secondary_path_str,
6603 dir_path: dir_path.display().to_string(),
6605 (true, true) => Err(Error::DuplicatePaths {
6606 mod_name: mod_name.clone(),
6607 default_path: default_path_str,
6608 secondary_path: secondary_path_str,
6614 path_exists: default_exists || secondary_exists,
6619 fn submod_path(&mut self,
6621 outer_attrs: &[Attribute],
6623 -> PResult<'a, ModulePathSuccess> {
6624 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6625 return Ok(ModulePathSuccess {
6626 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6627 // All `#[path]` files are treated as though they are a `mod.rs` file.
6628 // This means that `mod foo;` declarations inside `#[path]`-included
6629 // files are siblings,
6631 // Note that this will produce weirdness when a file named `foo.rs` is
6632 // `#[path]` included and contains a `mod foo;` declaration.
6633 // If you encounter this, it's your own darn fault :P
6634 Some(_) => DirectoryOwnership::Owned { relative: None },
6635 _ => DirectoryOwnership::UnownedViaMod(true),
6642 let relative = match self.directory.ownership {
6643 DirectoryOwnership::Owned { relative } => relative,
6644 DirectoryOwnership::UnownedViaBlock |
6645 DirectoryOwnership::UnownedViaMod(_) => None,
6647 let paths = Parser::default_submod_path(
6648 id, relative, &self.directory.path, self.sess.source_map());
6650 match self.directory.ownership {
6651 DirectoryOwnership::Owned { .. } => {
6652 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6654 DirectoryOwnership::UnownedViaBlock => {
6656 "Cannot declare a non-inline module inside a block \
6657 unless it has a path attribute";
6658 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6659 if paths.path_exists {
6660 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6662 err.span_note(id_sp, &msg);
6666 DirectoryOwnership::UnownedViaMod(warn) => {
6668 if let Ok(result) = paths.result {
6669 return Ok(ModulePathSuccess { warn: true, ..result });
6672 let mut err = self.diagnostic().struct_span_err(id_sp,
6673 "cannot declare a new module at this location");
6674 if !id_sp.is_dummy() {
6675 let src_path = self.sess.source_map().span_to_filename(id_sp);
6676 if let FileName::Real(src_path) = src_path {
6677 if let Some(stem) = src_path.file_stem() {
6678 let mut dest_path = src_path.clone();
6679 dest_path.set_file_name(stem);
6680 dest_path.push("mod.rs");
6681 err.span_note(id_sp,
6682 &format!("maybe move this module `{}` to its own \
6683 directory via `{}`", src_path.display(),
6684 dest_path.display()));
6688 if paths.path_exists {
6689 err.span_note(id_sp,
6690 &format!("... or maybe `use` the module `{}` instead \
6691 of possibly redeclaring it",
6699 /// Reads a module from a source file.
6700 fn eval_src_mod(&mut self,
6702 directory_ownership: DirectoryOwnership,
6705 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6706 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6707 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6708 let mut err = String::from("circular modules: ");
6709 let len = included_mod_stack.len();
6710 for p in &included_mod_stack[i.. len] {
6711 err.push_str(&p.to_string_lossy());
6712 err.push_str(" -> ");
6714 err.push_str(&path.to_string_lossy());
6715 return Err(self.span_fatal(id_sp, &err[..]));
6717 included_mod_stack.push(path.clone());
6718 drop(included_mod_stack);
6721 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6722 p0.cfg_mods = self.cfg_mods;
6723 let mod_inner_lo = p0.span;
6724 let mod_attrs = p0.parse_inner_attributes()?;
6725 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6727 self.sess.included_mod_stack.borrow_mut().pop();
6731 /// Parses a function declaration from a foreign module.
6732 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6733 -> PResult<'a, ForeignItem> {
6734 self.expect_keyword(kw::Fn)?;
6736 let (ident, mut generics) = self.parse_fn_header()?;
6737 let decl = self.parse_fn_decl(true)?;
6738 generics.where_clause = self.parse_where_clause()?;
6740 self.expect(&token::Semi)?;
6741 Ok(ast::ForeignItem {
6744 node: ForeignItemKind::Fn(decl, generics),
6745 id: ast::DUMMY_NODE_ID,
6751 /// Parses a static item from a foreign module.
6752 /// Assumes that the `static` keyword is already parsed.
6753 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6754 -> PResult<'a, ForeignItem> {
6755 let mutbl = self.parse_mutability();
6756 let ident = self.parse_ident()?;
6757 self.expect(&token::Colon)?;
6758 let ty = self.parse_ty()?;
6760 self.expect(&token::Semi)?;
6764 node: ForeignItemKind::Static(ty, mutbl),
6765 id: ast::DUMMY_NODE_ID,
6771 /// Parses a type from a foreign module.
6772 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6773 -> PResult<'a, ForeignItem> {
6774 self.expect_keyword(kw::Type)?;
6776 let ident = self.parse_ident()?;
6778 self.expect(&token::Semi)?;
6779 Ok(ast::ForeignItem {
6782 node: ForeignItemKind::Ty,
6783 id: ast::DUMMY_NODE_ID,
6789 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6790 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6791 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6793 let mut ident = if self.token.is_keyword(kw::SelfLower) {
6794 self.parse_path_segment_ident()
6798 let mut idents = vec![];
6799 let mut replacement = vec![];
6800 let mut fixed_crate_name = false;
6801 // Accept `extern crate name-like-this` for better diagnostics
6802 let dash = token::BinOp(token::BinOpToken::Minus);
6803 if self.token == dash { // Do not include `-` as part of the expected tokens list
6804 while self.eat(&dash) {
6805 fixed_crate_name = true;
6806 replacement.push((self.prev_span, "_".to_string()));
6807 idents.push(self.parse_ident()?);
6810 if fixed_crate_name {
6811 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6812 let mut fixed_name = format!("{}", ident.name);
6813 for part in idents {
6814 fixed_name.push_str(&format!("_{}", part.name));
6816 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6818 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6819 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6820 err.multipart_suggestion(
6823 Applicability::MachineApplicable,
6830 /// Parses `extern crate` links.
6835 /// extern crate foo;
6836 /// extern crate bar as foo;
6838 fn parse_item_extern_crate(&mut self,
6840 visibility: Visibility,
6841 attrs: Vec<Attribute>)
6842 -> PResult<'a, P<Item>> {
6843 // Accept `extern crate name-like-this` for better diagnostics
6844 let orig_name = self.parse_crate_name_with_dashes()?;
6845 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6846 (rename, Some(orig_name.name))
6850 self.expect(&token::Semi)?;
6852 let span = lo.to(self.prev_span);
6853 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6856 /// Parses `extern` for foreign ABIs modules.
6858 /// `extern` is expected to have been
6859 /// consumed before calling this method.
6863 /// ```ignore (only-for-syntax-highlight)
6867 fn parse_item_foreign_mod(&mut self,
6869 opt_abi: Option<Abi>,
6870 visibility: Visibility,
6871 mut attrs: Vec<Attribute>)
6872 -> PResult<'a, P<Item>> {
6873 self.expect(&token::OpenDelim(token::Brace))?;
6875 let abi = opt_abi.unwrap_or(Abi::C);
6877 attrs.extend(self.parse_inner_attributes()?);
6879 let mut foreign_items = vec![];
6880 while !self.eat(&token::CloseDelim(token::Brace)) {
6881 foreign_items.push(self.parse_foreign_item()?);
6884 let prev_span = self.prev_span;
6885 let m = ast::ForeignMod {
6887 items: foreign_items
6889 let invalid = Ident::invalid();
6890 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6893 /// Parses `type Foo = Bar;`
6895 /// `existential type Foo: Bar;`
6898 /// without modifying the parser state.
6899 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6900 // This parses the grammar:
6901 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6902 if self.check_keyword(kw::Type) ||
6903 self.check_keyword(kw::Existential) &&
6904 self.is_keyword_ahead(1, &[kw::Type]) {
6905 let existential = self.eat_keyword(kw::Existential);
6906 assert!(self.eat_keyword(kw::Type));
6907 Some(self.parse_existential_or_alias(existential))
6913 /// Parses a type alias or existential type.
6914 fn parse_existential_or_alias(
6917 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6918 let ident = self.parse_ident()?;
6919 let mut tps = self.parse_generics()?;
6920 tps.where_clause = self.parse_where_clause()?;
6921 let alias = if existential {
6922 self.expect(&token::Colon)?;
6923 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6924 AliasKind::Existential(bounds)
6926 self.expect(&token::Eq)?;
6927 let ty = self.parse_ty()?;
6930 self.expect(&token::Semi)?;
6931 Ok((ident, alias, tps))
6934 /// Parses the part of an enum declaration following the `{`.
6935 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6936 let mut variants = Vec::new();
6937 let mut any_disr = vec![];
6938 while self.token != token::CloseDelim(token::Brace) {
6939 let variant_attrs = self.parse_outer_attributes()?;
6940 let vlo = self.span;
6943 let mut disr_expr = None;
6945 let ident = self.parse_ident()?;
6946 if self.check(&token::OpenDelim(token::Brace)) {
6947 // Parse a struct variant.
6948 let (fields, recovered) = self.parse_record_struct_body()?;
6949 struct_def = VariantData::Struct(fields, recovered);
6950 } else if self.check(&token::OpenDelim(token::Paren)) {
6951 struct_def = VariantData::Tuple(
6952 self.parse_tuple_struct_body()?,
6955 } else if self.eat(&token::Eq) {
6956 disr_expr = Some(AnonConst {
6957 id: ast::DUMMY_NODE_ID,
6958 value: self.parse_expr()?,
6960 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
6963 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6965 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6968 let vr = ast::Variant_ {
6970 id: ast::DUMMY_NODE_ID,
6971 attrs: variant_attrs,
6975 variants.push(respan(vlo.to(self.prev_span), vr));
6977 if !self.eat(&token::Comma) {
6978 if self.token.is_ident() && !self.token.is_reserved_ident() {
6979 let sp = self.sess.source_map().next_point(self.prev_span);
6980 let mut err = self.struct_span_err(sp, "missing comma");
6981 err.span_suggestion_short(
6985 Applicability::MaybeIncorrect,
6993 self.expect(&token::CloseDelim(token::Brace))?;
6994 self.maybe_report_invalid_custom_discriminants(any_disr, &variants);
6996 Ok(ast::EnumDef { variants })
6999 /// Parses an enum declaration.
7000 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7001 let id = self.parse_ident()?;
7002 let mut generics = self.parse_generics()?;
7003 generics.where_clause = self.parse_where_clause()?;
7004 self.expect(&token::OpenDelim(token::Brace))?;
7006 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7007 self.recover_stmt();
7008 self.eat(&token::CloseDelim(token::Brace));
7011 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7014 /// Parses a string as an ABI spec on an extern type or module. Consumes
7015 /// the `extern` keyword, if one is found.
7016 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7017 match self.token.kind {
7018 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
7019 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
7021 self.expect_no_suffix(sp, "an ABI spec", suffix);
7023 match abi::lookup(&symbol.as_str()) {
7024 Some(abi) => Ok(Some(abi)),
7026 let prev_span = self.prev_span;
7027 let mut err = struct_span_err!(
7028 self.sess.span_diagnostic,
7031 "invalid ABI: found `{}`",
7033 err.span_label(prev_span, "invalid ABI");
7034 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7045 fn is_static_global(&mut self) -> bool {
7046 if self.check_keyword(kw::Static) {
7047 // Check if this could be a closure
7048 !self.look_ahead(1, |token| {
7049 if token.is_keyword(kw::Move) {
7053 token::BinOp(token::Or) | token::OrOr => true,
7064 attrs: Vec<Attribute>,
7065 macros_allowed: bool,
7066 attributes_allowed: bool,
7067 ) -> PResult<'a, Option<P<Item>>> {
7068 let mut unclosed_delims = vec![];
7069 let (ret, tokens) = self.collect_tokens(|this| {
7070 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7071 unclosed_delims.append(&mut this.unclosed_delims);
7074 self.unclosed_delims.append(&mut unclosed_delims);
7076 // Once we've parsed an item and recorded the tokens we got while
7077 // parsing we may want to store `tokens` into the item we're about to
7078 // return. Note, though, that we specifically didn't capture tokens
7079 // related to outer attributes. The `tokens` field here may later be
7080 // used with procedural macros to convert this item back into a token
7081 // stream, but during expansion we may be removing attributes as we go
7084 // If we've got inner attributes then the `tokens` we've got above holds
7085 // these inner attributes. If an inner attribute is expanded we won't
7086 // actually remove it from the token stream, so we'll just keep yielding
7087 // it (bad!). To work around this case for now we just avoid recording
7088 // `tokens` if we detect any inner attributes. This should help keep
7089 // expansion correct, but we should fix this bug one day!
7092 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7093 i.tokens = Some(tokens);
7100 /// Parses one of the items allowed by the flags.
7101 fn parse_item_implementation(
7103 attrs: Vec<Attribute>,
7104 macros_allowed: bool,
7105 attributes_allowed: bool,
7106 ) -> PResult<'a, Option<P<Item>>> {
7107 maybe_whole!(self, NtItem, |item| {
7108 let mut item = item.into_inner();
7109 let mut attrs = attrs;
7110 mem::swap(&mut item.attrs, &mut attrs);
7111 item.attrs.extend(attrs);
7117 let visibility = self.parse_visibility(false)?;
7119 if self.eat_keyword(kw::Use) {
7121 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7122 self.expect(&token::Semi)?;
7124 let span = lo.to(self.prev_span);
7126 self.mk_item(span, Ident::invalid(), item_, visibility, attrs);
7127 return Ok(Some(item));
7130 if self.eat_keyword(kw::Extern) {
7131 if self.eat_keyword(kw::Crate) {
7132 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7135 let opt_abi = self.parse_opt_abi()?;
7137 if self.eat_keyword(kw::Fn) {
7138 // EXTERN FUNCTION ITEM
7139 let fn_span = self.prev_span;
7140 let abi = opt_abi.unwrap_or(Abi::C);
7141 let (ident, item_, extra_attrs) =
7142 self.parse_item_fn(Unsafety::Normal,
7143 respan(fn_span, IsAsync::NotAsync),
7144 respan(fn_span, Constness::NotConst),
7146 let prev_span = self.prev_span;
7147 let item = self.mk_item(lo.to(prev_span),
7151 maybe_append(attrs, extra_attrs));
7152 return Ok(Some(item));
7153 } else if self.check(&token::OpenDelim(token::Brace)) {
7154 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7160 if self.is_static_global() {
7163 let m = if self.eat_keyword(kw::Mut) {
7166 Mutability::Immutable
7168 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7169 let prev_span = self.prev_span;
7170 let item = self.mk_item(lo.to(prev_span),
7174 maybe_append(attrs, extra_attrs));
7175 return Ok(Some(item));
7177 if self.eat_keyword(kw::Const) {
7178 let const_span = self.prev_span;
7179 if self.check_keyword(kw::Fn)
7180 || (self.check_keyword(kw::Unsafe)
7181 && self.is_keyword_ahead(1, &[kw::Fn])) {
7182 // CONST FUNCTION ITEM
7183 let unsafety = self.parse_unsafety();
7185 let (ident, item_, extra_attrs) =
7186 self.parse_item_fn(unsafety,
7187 respan(const_span, IsAsync::NotAsync),
7188 respan(const_span, Constness::Const),
7190 let prev_span = self.prev_span;
7191 let item = self.mk_item(lo.to(prev_span),
7195 maybe_append(attrs, extra_attrs));
7196 return Ok(Some(item));
7200 if self.eat_keyword(kw::Mut) {
7201 let prev_span = self.prev_span;
7202 let mut err = self.diagnostic()
7203 .struct_span_err(prev_span, "const globals cannot be mutable");
7204 err.span_label(prev_span, "cannot be mutable");
7205 err.span_suggestion(
7207 "you might want to declare a static instead",
7208 "static".to_owned(),
7209 Applicability::MaybeIncorrect,
7213 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7214 let prev_span = self.prev_span;
7215 let item = self.mk_item(lo.to(prev_span),
7219 maybe_append(attrs, extra_attrs));
7220 return Ok(Some(item));
7223 // Parse `async unsafe? fn`.
7224 if self.check_keyword(kw::Async) {
7225 let async_span = self.span;
7226 if self.is_keyword_ahead(1, &[kw::Fn])
7227 || self.is_keyword_ahead(2, &[kw::Fn])
7229 // ASYNC FUNCTION ITEM
7230 self.bump(); // `async`
7231 let unsafety = self.parse_unsafety(); // `unsafe`?
7232 self.expect_keyword(kw::Fn)?; // `fn`
7233 let fn_span = self.prev_span;
7234 let (ident, item_, extra_attrs) =
7235 self.parse_item_fn(unsafety,
7236 respan(async_span, IsAsync::Async {
7237 closure_id: ast::DUMMY_NODE_ID,
7238 return_impl_trait_id: ast::DUMMY_NODE_ID,
7240 respan(fn_span, Constness::NotConst),
7242 let prev_span = self.prev_span;
7243 let item = self.mk_item(lo.to(prev_span),
7247 maybe_append(attrs, extra_attrs));
7248 if self.span.rust_2015() {
7249 self.diagnostic().struct_span_err_with_code(
7251 "`async fn` is not permitted in the 2015 edition",
7252 DiagnosticId::Error("E0670".into())
7255 return Ok(Some(item));
7258 if self.check_keyword(kw::Unsafe) &&
7259 self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
7261 // UNSAFE TRAIT ITEM
7262 self.bump(); // `unsafe`
7263 let is_auto = if self.eat_keyword(kw::Trait) {
7266 self.expect_keyword(kw::Auto)?;
7267 self.expect_keyword(kw::Trait)?;
7270 let (ident, item_, extra_attrs) =
7271 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7272 let prev_span = self.prev_span;
7273 let item = self.mk_item(lo.to(prev_span),
7277 maybe_append(attrs, extra_attrs));
7278 return Ok(Some(item));
7280 if self.check_keyword(kw::Impl) ||
7281 self.check_keyword(kw::Unsafe) &&
7282 self.is_keyword_ahead(1, &[kw::Impl]) ||
7283 self.check_keyword(kw::Default) &&
7284 self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) {
7286 let defaultness = self.parse_defaultness();
7287 let unsafety = self.parse_unsafety();
7288 self.expect_keyword(kw::Impl)?;
7289 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7290 let span = lo.to(self.prev_span);
7291 return Ok(Some(self.mk_item(span, ident, item, visibility,
7292 maybe_append(attrs, extra_attrs))));
7294 if self.check_keyword(kw::Fn) {
7297 let fn_span = self.prev_span;
7298 let (ident, item_, extra_attrs) =
7299 self.parse_item_fn(Unsafety::Normal,
7300 respan(fn_span, IsAsync::NotAsync),
7301 respan(fn_span, Constness::NotConst),
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::Unsafe)
7312 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7313 // UNSAFE FUNCTION ITEM
7314 self.bump(); // `unsafe`
7315 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7316 self.check(&token::OpenDelim(token::Brace));
7317 let abi = if self.eat_keyword(kw::Extern) {
7318 self.parse_opt_abi()?.unwrap_or(Abi::C)
7322 self.expect_keyword(kw::Fn)?;
7323 let fn_span = self.prev_span;
7324 let (ident, item_, extra_attrs) =
7325 self.parse_item_fn(Unsafety::Unsafe,
7326 respan(fn_span, IsAsync::NotAsync),
7327 respan(fn_span, Constness::NotConst),
7329 let prev_span = self.prev_span;
7330 let item = self.mk_item(lo.to(prev_span),
7334 maybe_append(attrs, extra_attrs));
7335 return Ok(Some(item));
7337 if self.eat_keyword(kw::Mod) {
7339 let (ident, item_, extra_attrs) =
7340 self.parse_item_mod(&attrs[..])?;
7341 let prev_span = self.prev_span;
7342 let item = self.mk_item(lo.to(prev_span),
7346 maybe_append(attrs, extra_attrs));
7347 return Ok(Some(item));
7349 if let Some(type_) = self.eat_type() {
7350 let (ident, alias, generics) = type_?;
7352 let item_ = match alias {
7353 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7354 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7356 let prev_span = self.prev_span;
7357 let item = self.mk_item(lo.to(prev_span),
7362 return Ok(Some(item));
7364 if self.eat_keyword(kw::Enum) {
7366 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7367 let prev_span = self.prev_span;
7368 let item = self.mk_item(lo.to(prev_span),
7372 maybe_append(attrs, extra_attrs));
7373 return Ok(Some(item));
7375 if self.check_keyword(kw::Trait)
7376 || (self.check_keyword(kw::Auto)
7377 && self.is_keyword_ahead(1, &[kw::Trait]))
7379 let is_auto = if self.eat_keyword(kw::Trait) {
7382 self.expect_keyword(kw::Auto)?;
7383 self.expect_keyword(kw::Trait)?;
7387 let (ident, item_, extra_attrs) =
7388 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7389 let prev_span = self.prev_span;
7390 let item = self.mk_item(lo.to(prev_span),
7394 maybe_append(attrs, extra_attrs));
7395 return Ok(Some(item));
7397 if self.eat_keyword(kw::Struct) {
7399 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7400 let prev_span = self.prev_span;
7401 let item = self.mk_item(lo.to(prev_span),
7405 maybe_append(attrs, extra_attrs));
7406 return Ok(Some(item));
7408 if self.is_union_item() {
7411 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7412 let prev_span = self.prev_span;
7413 let item = self.mk_item(lo.to(prev_span),
7417 maybe_append(attrs, extra_attrs));
7418 return Ok(Some(item));
7420 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7421 return Ok(Some(macro_def));
7424 // Verify whether we have encountered a struct or method definition where the user forgot to
7425 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7426 if visibility.node.is_pub() &&
7427 self.check_ident() &&
7428 self.look_ahead(1, |t| *t != token::Not)
7430 // Space between `pub` keyword and the identifier
7433 // ^^^ `sp` points here
7434 let sp = self.prev_span.between(self.span);
7435 let full_sp = self.prev_span.to(self.span);
7436 let ident_sp = self.span;
7437 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7438 // possible public struct definition where `struct` was forgotten
7439 let ident = self.parse_ident().unwrap();
7440 let msg = format!("add `struct` here to parse `{}` as a public struct",
7442 let mut err = self.diagnostic()
7443 .struct_span_err(sp, "missing `struct` for struct definition");
7444 err.span_suggestion_short(
7445 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7448 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7449 let ident = self.parse_ident().unwrap();
7451 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
7456 self.consume_block(token::Paren);
7457 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7458 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7460 ("fn", kw_name, false)
7461 } else if self.check(&token::OpenDelim(token::Brace)) {
7463 ("fn", kw_name, false)
7464 } else if self.check(&token::Colon) {
7468 ("fn` or `struct", "function or struct", true)
7471 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7472 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7474 self.consume_block(token::Brace);
7475 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7479 err.span_suggestion_short(
7480 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7483 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7484 err.span_suggestion(
7486 "if you meant to call a macro, try",
7487 format!("{}!", snippet),
7488 // this is the `ambiguous` conditional branch
7489 Applicability::MaybeIncorrect
7492 err.help("if you meant to call a macro, remove the `pub` \
7493 and add a trailing `!` after the identifier");
7497 } else if self.look_ahead(1, |t| *t == token::Lt) {
7498 let ident = self.parse_ident().unwrap();
7499 self.eat_to_tokens(&[&token::Gt]);
7501 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7502 if let Ok(Some(_)) = self.parse_self_arg() {
7503 ("fn", "method", false)
7505 ("fn", "function", false)
7507 } else if self.check(&token::OpenDelim(token::Brace)) {
7508 ("struct", "struct", false)
7510 ("fn` or `struct", "function or struct", true)
7512 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7513 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7515 err.span_suggestion_short(
7517 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7518 format!(" {} ", kw),
7519 Applicability::MachineApplicable,
7525 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7528 /// Parses a foreign item.
7529 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7530 maybe_whole!(self, NtForeignItem, |ni| ni);
7532 let attrs = self.parse_outer_attributes()?;
7534 let visibility = self.parse_visibility(false)?;
7536 // FOREIGN STATIC ITEM
7537 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7538 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
7539 if self.token.is_keyword(kw::Const) {
7541 .struct_span_err(self.span, "extern items cannot be `const`")
7544 "try using a static value",
7545 "static".to_owned(),
7546 Applicability::MachineApplicable
7549 self.bump(); // `static` or `const`
7550 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7552 // FOREIGN FUNCTION ITEM
7553 if self.check_keyword(kw::Fn) {
7554 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7556 // FOREIGN TYPE ITEM
7557 if self.check_keyword(kw::Type) {
7558 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7561 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7565 ident: Ident::invalid(),
7566 span: lo.to(self.prev_span),
7567 id: ast::DUMMY_NODE_ID,
7570 node: ForeignItemKind::Macro(mac),
7575 if !attrs.is_empty() {
7576 self.expected_item_err(&attrs)?;
7584 /// This is the fall-through for parsing items.
7585 fn parse_macro_use_or_failure(
7587 attrs: Vec<Attribute> ,
7588 macros_allowed: bool,
7589 attributes_allowed: bool,
7591 visibility: Visibility
7592 ) -> PResult<'a, Option<P<Item>>> {
7593 if macros_allowed && self.token.is_path_start() &&
7594 !(self.is_async_fn() && self.span.rust_2015()) {
7595 // MACRO INVOCATION ITEM
7597 let prev_span = self.prev_span;
7598 self.complain_if_pub_macro(&visibility.node, prev_span);
7600 let mac_lo = self.span;
7603 let pth = self.parse_path(PathStyle::Mod)?;
7604 self.expect(&token::Not)?;
7606 // a 'special' identifier (like what `macro_rules!` uses)
7607 // is optional. We should eventually unify invoc syntax
7609 let id = if self.token.is_ident() {
7612 Ident::invalid() // no special identifier
7614 // eat a matched-delimiter token tree:
7615 let (delim, tts) = self.expect_delimited_token_tree()?;
7616 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
7617 self.report_invalid_macro_expansion_item();
7620 let hi = self.prev_span;
7621 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7622 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7623 return Ok(Some(item));
7626 // FAILURE TO PARSE ITEM
7627 match visibility.node {
7628 VisibilityKind::Inherited => {}
7630 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7634 if !attributes_allowed && !attrs.is_empty() {
7635 self.expected_item_err(&attrs)?;
7640 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
7641 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7642 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7644 if self.token.is_path_start() &&
7645 !(self.is_async_fn() && self.span.rust_2015()) {
7646 let prev_span = self.prev_span;
7648 let pth = self.parse_path(PathStyle::Mod)?;
7650 if pth.segments.len() == 1 {
7651 if !self.eat(&token::Not) {
7652 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7655 self.expect(&token::Not)?;
7658 if let Some(vis) = vis {
7659 self.complain_if_pub_macro(&vis.node, prev_span);
7664 // eat a matched-delimiter token tree:
7665 let (delim, tts) = self.expect_delimited_token_tree()?;
7666 if delim != MacDelimiter::Brace {
7667 self.expect(&token::Semi)?;
7670 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7676 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7677 where F: FnOnce(&mut Self) -> PResult<'a, R>
7679 // Record all tokens we parse when parsing this item.
7680 let mut tokens = Vec::new();
7681 let prev_collecting = match self.token_cursor.frame.last_token {
7682 LastToken::Collecting(ref mut list) => {
7683 Some(mem::replace(list, Vec::new()))
7685 LastToken::Was(ref mut last) => {
7686 tokens.extend(last.take());
7690 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7691 let prev = self.token_cursor.stack.len();
7693 let last_token = if self.token_cursor.stack.len() == prev {
7694 &mut self.token_cursor.frame.last_token
7696 &mut self.token_cursor.stack[prev].last_token
7699 // Pull out the tokens that we've collected from the call to `f` above.
7700 let mut collected_tokens = match *last_token {
7701 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7702 LastToken::Was(_) => panic!("our vector went away?"),
7705 // If we're not at EOF our current token wasn't actually consumed by
7706 // `f`, but it'll still be in our list that we pulled out. In that case
7708 let extra_token = if self.token != token::Eof {
7709 collected_tokens.pop()
7714 // If we were previously collecting tokens, then this was a recursive
7715 // call. In that case we need to record all the tokens we collected in
7716 // our parent list as well. To do that we push a clone of our stream
7717 // onto the previous list.
7718 match prev_collecting {
7720 list.extend(collected_tokens.iter().cloned());
7721 list.extend(extra_token);
7722 *last_token = LastToken::Collecting(list);
7725 *last_token = LastToken::Was(extra_token);
7729 Ok((ret?, TokenStream::new(collected_tokens)))
7732 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7733 let attrs = self.parse_outer_attributes()?;
7734 self.parse_item_(attrs, true, false)
7738 fn is_import_coupler(&mut self) -> bool {
7739 self.check(&token::ModSep) &&
7740 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7741 *t == token::BinOp(token::Star))
7744 /// Parses a `UseTree`.
7747 /// USE_TREE = [`::`] `*` |
7748 /// [`::`] `{` USE_TREE_LIST `}` |
7750 /// PATH `::` `{` USE_TREE_LIST `}` |
7751 /// PATH [`as` IDENT]
7753 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7756 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7757 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7758 self.check(&token::BinOp(token::Star)) ||
7759 self.is_import_coupler() {
7760 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7761 let mod_sep_ctxt = self.span.ctxt();
7762 if self.eat(&token::ModSep) {
7763 prefix.segments.push(
7764 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7768 if self.eat(&token::BinOp(token::Star)) {
7771 UseTreeKind::Nested(self.parse_use_tree_list()?)
7774 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7775 prefix = self.parse_path(PathStyle::Mod)?;
7777 if self.eat(&token::ModSep) {
7778 if self.eat(&token::BinOp(token::Star)) {
7781 UseTreeKind::Nested(self.parse_use_tree_list()?)
7784 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7788 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7791 /// Parses a `UseTreeKind::Nested(list)`.
7794 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7796 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7797 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7798 &token::CloseDelim(token::Brace),
7799 SeqSep::trailing_allowed(token::Comma), |this| {
7800 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7804 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7805 if self.eat_keyword(kw::As) {
7806 self.parse_ident_or_underscore().map(Some)
7812 /// Parses a source module as a crate. This is the main entry point for the parser.
7813 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7815 let krate = Ok(ast::Crate {
7816 attrs: self.parse_inner_attributes()?,
7817 module: self.parse_mod_items(&token::Eof, lo)?,
7818 span: lo.to(self.span),
7823 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7824 let ret = match self.token.kind {
7825 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
7826 (symbol, ast::StrStyle::Cooked, suffix),
7827 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
7828 (symbol, ast::StrStyle::Raw(n), suffix),
7835 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7836 match self.parse_optional_str() {
7837 Some((s, style, suf)) => {
7838 let sp = self.prev_span;
7839 self.expect_no_suffix(sp, "a string literal", suf);
7843 let msg = "expected string literal";
7844 let mut err = self.fatal(msg);
7845 err.span_label(self.span, msg);
7851 fn report_invalid_macro_expansion_item(&self) {
7852 self.struct_span_err(
7854 "macros that expand to items must be delimited with braces or followed by a semicolon",
7855 ).multipart_suggestion(
7856 "change the delimiters to curly braces",
7858 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
7859 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
7861 Applicability::MaybeIncorrect,
7863 self.sess.source_map.next_point(self.prev_span),
7866 Applicability::MaybeIncorrect,
7871 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
7872 for unmatched in unclosed_delims.iter() {
7873 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
7874 "incorrect close delimiter: `{}`",
7875 pprust::token_to_string(&token::CloseDelim(unmatched.found_delim)),
7877 err.span_label(unmatched.found_span, "incorrect close delimiter");
7878 if let Some(sp) = unmatched.candidate_span {
7879 err.span_label(sp, "close delimiter possibly meant for this");
7881 if let Some(sp) = unmatched.unclosed_span {
7882 err.span_label(sp, "un-closed delimiter");
7886 unclosed_delims.clear();