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::ext::hygiene::SyntaxContext;
38 use crate::source_map::{self, SourceMap, Spanned, respan};
39 use crate::parse::{SeqSep, classify, literal, token};
40 use crate::parse::lexer::UnmatchedBrace;
41 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
42 use crate::parse::token::{Token, TokenKind, DelimToken};
43 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
44 use crate::util::parser::{AssocOp, Fixity};
45 use crate::print::pprust;
47 use crate::parse::PResult;
49 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
50 use crate::symbol::{kw, sym, Symbol};
51 use crate::parse::diagnostics::{Error, dummy_arg};
53 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
54 use rustc_target::spec::abi::{self, Abi};
55 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
61 use std::path::{self, Path, PathBuf};
65 /// Whether the type alias or associated type is a concrete type or an existential type
67 /// Just a new name for the same type
69 /// Only trait impls of the type will be usable, not the actual type itself
70 Existential(GenericBounds),
74 struct Restrictions: u8 {
75 const STMT_EXPR = 1 << 0;
76 const NO_STRUCT_LITERAL = 1 << 1;
80 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
82 /// Specifies how to parse a path.
83 #[derive(Copy, Clone, PartialEq)]
85 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
86 /// with something else. For example, in expressions `segment < ....` can be interpreted
87 /// as a comparison and `segment ( ....` can be interpreted as a function call.
88 /// In all such contexts the non-path interpretation is preferred by default for practical
89 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
90 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
92 /// In other contexts, notably in types, no ambiguity exists and paths can be written
93 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
94 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
96 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
97 /// visibilities or attributes.
98 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
99 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
100 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
101 /// tokens when something goes wrong.
105 #[derive(Clone, Copy, PartialEq, Debug)]
106 crate enum SemiColonMode {
112 #[derive(Clone, Copy, PartialEq, Debug)]
113 crate enum BlockMode {
118 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
119 /// dropped into the token stream, which happens while parsing the result of
120 /// macro expansion). Placement of these is not as complex as I feared it would
121 /// be. The important thing is to make sure that lookahead doesn't balk at
122 /// `token::Interpolated` tokens.
123 macro_rules! maybe_whole_expr {
125 if let token::Interpolated(nt) = &$p.token.kind {
127 token::NtExpr(e) | token::NtLiteral(e) => {
132 token::NtPath(path) => {
133 let path = path.clone();
135 return Ok($p.mk_expr(
136 $p.token.span, ExprKind::Path(None, path), ThinVec::new()
139 token::NtBlock(block) => {
140 let block = block.clone();
142 return Ok($p.mk_expr(
143 $p.token.span, ExprKind::Block(block, None), ThinVec::new()
152 /// As maybe_whole_expr, but for things other than expressions
153 macro_rules! maybe_whole {
154 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
155 if let token::Interpolated(nt) = &$p.token.kind {
156 if let token::$constructor(x) = &**nt {
165 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
166 macro_rules! maybe_recover_from_interpolated_ty_qpath {
167 ($self: expr, $allow_qpath_recovery: expr) => {
168 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
169 if let token::Interpolated(nt) = &$self.token.kind {
170 if let token::NtTy(ty) = &**nt {
173 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
180 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
181 if let Some(ref mut rhs) = rhs {
187 #[derive(Debug, Clone, Copy, PartialEq)]
199 // NOTE: `Ident`s are handled by `common.rs`.
202 pub struct Parser<'a> {
203 pub sess: &'a ParseSess,
204 /// The current normalized token.
205 /// "Normalized" means that some interpolated tokens
206 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
207 /// with non-interpolated identifier and lifetime tokens they refer to.
208 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
210 /// Span of the current non-normalized token.
211 meta_var_span: Option<Span>,
212 /// Span of the previous non-normalized token.
214 /// Kind of the previous normalized token (in simplified form).
215 prev_token_kind: PrevTokenKind,
216 restrictions: Restrictions,
217 /// Used to determine the path to externally loaded source files.
218 crate directory: Directory<'a>,
219 /// `true` to parse sub-modules in other files.
220 pub recurse_into_file_modules: bool,
221 /// Name of the root module this parser originated from. If `None`, then the
222 /// name is not known. This does not change while the parser is descending
223 /// into modules, and sub-parsers have new values for this name.
224 pub root_module_name: Option<String>,
225 crate expected_tokens: Vec<TokenType>,
226 crate token_cursor: TokenCursor,
227 desugar_doc_comments: bool,
228 /// `true` we should configure out of line modules as we parse.
230 /// This field is used to keep track of how many left angle brackets we have seen. This is
231 /// required in order to detect extra leading left angle brackets (`<` characters) and error
234 /// See the comments in the `parse_path_segment` function for more details.
235 crate unmatched_angle_bracket_count: u32,
236 crate max_angle_bracket_count: u32,
237 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
238 /// it gets removed from here. Every entry left at the end gets emitted as an independent
240 crate unclosed_delims: Vec<UnmatchedBrace>,
241 crate last_unexpected_token_span: Option<Span>,
242 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
243 crate subparser_name: Option<&'static str>,
246 impl<'a> Drop for Parser<'a> {
248 let diag = self.diagnostic();
249 emit_unclosed_delims(&mut self.unclosed_delims, diag);
254 crate struct TokenCursor {
255 crate frame: TokenCursorFrame,
256 crate stack: Vec<TokenCursorFrame>,
260 crate struct TokenCursorFrame {
261 crate delim: token::DelimToken,
262 crate span: DelimSpan,
263 crate open_delim: bool,
264 crate tree_cursor: tokenstream::Cursor,
265 crate close_delim: bool,
266 crate last_token: LastToken,
269 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
270 /// by the parser, and then that's transitively used to record the tokens that
271 /// each parse AST item is created with.
273 /// Right now this has two states, either collecting tokens or not collecting
274 /// tokens. If we're collecting tokens we just save everything off into a local
275 /// `Vec`. This should eventually though likely save tokens from the original
276 /// token stream and just use slicing of token streams to avoid creation of a
277 /// whole new vector.
279 /// The second state is where we're passively not recording tokens, but the last
280 /// token is still tracked for when we want to start recording tokens. This
281 /// "last token" means that when we start recording tokens we'll want to ensure
282 /// that this, the first token, is included in the output.
284 /// You can find some more example usage of this in the `collect_tokens` method
287 crate enum LastToken {
288 Collecting(Vec<TreeAndJoint>),
289 Was(Option<TreeAndJoint>),
292 impl TokenCursorFrame {
293 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
297 open_delim: delim == token::NoDelim,
298 tree_cursor: tts.clone().into_trees(),
299 close_delim: delim == token::NoDelim,
300 last_token: LastToken::Was(None),
306 fn next(&mut self) -> Token {
308 let tree = if !self.frame.open_delim {
309 self.frame.open_delim = true;
310 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
311 } else if let Some(tree) = self.frame.tree_cursor.next() {
313 } else if !self.frame.close_delim {
314 self.frame.close_delim = true;
315 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
316 } else if let Some(frame) = self.stack.pop() {
320 return Token::new(token::Eof, DUMMY_SP);
323 match self.frame.last_token {
324 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
325 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
329 TokenTree::Token(token) => return token,
330 TokenTree::Delimited(sp, delim, tts) => {
331 let frame = TokenCursorFrame::new(sp, delim, &tts);
332 self.stack.push(mem::replace(&mut self.frame, frame));
338 fn next_desugared(&mut self) -> Token {
339 let (name, sp) = match self.next() {
340 Token { kind: token::DocComment(name), span } => (name, span),
344 let stripped = strip_doc_comment_decoration(&name.as_str());
346 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
347 // required to wrap the text.
348 let mut num_of_hashes = 0;
350 for ch in stripped.chars() {
353 '#' if count > 0 => count + 1,
356 num_of_hashes = cmp::max(num_of_hashes, count);
359 let delim_span = DelimSpan::from_single(sp);
360 let body = TokenTree::Delimited(
364 TokenTree::token(token::Ident(sym::doc, false), sp),
365 TokenTree::token(token::Eq, sp),
366 TokenTree::token(TokenKind::lit(
367 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
370 .iter().cloned().collect::<TokenStream>().into(),
373 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
376 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
377 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
378 .iter().cloned().collect::<TokenStream>().into()
380 [TokenTree::token(token::Pound, sp), body]
381 .iter().cloned().collect::<TokenStream>().into()
389 #[derive(Clone, PartialEq)]
390 crate enum TokenType {
402 crate fn to_string(&self) -> String {
404 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
405 TokenType::Keyword(kw) => format!("`{}`", kw),
406 TokenType::Operator => "an operator".to_string(),
407 TokenType::Lifetime => "lifetime".to_string(),
408 TokenType::Ident => "identifier".to_string(),
409 TokenType::Path => "path".to_string(),
410 TokenType::Type => "type".to_string(),
411 TokenType::Const => "const".to_string(),
416 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
417 /// `IDENT<<u8 as Trait>::AssocTy>`.
419 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
420 /// that `IDENT` is not the ident of a fn trait.
421 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
422 t == &token::ModSep || t == &token::Lt ||
423 t == &token::BinOp(token::Shl)
426 /// Information about the path to a module.
427 pub struct ModulePath {
430 pub result: Result<ModulePathSuccess, Error>,
433 pub struct ModulePathSuccess {
435 pub directory_ownership: DirectoryOwnership,
442 AttributesParsed(ThinVec<Attribute>),
443 AlreadyParsed(P<Expr>),
446 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
447 fn from(o: Option<ThinVec<Attribute>>) -> Self {
448 if let Some(attrs) = o {
449 LhsExpr::AttributesParsed(attrs)
451 LhsExpr::NotYetParsed
456 impl From<P<Expr>> for LhsExpr {
457 fn from(expr: P<Expr>) -> Self {
458 LhsExpr::AlreadyParsed(expr)
462 #[derive(Copy, Clone, Debug)]
463 crate enum TokenExpectType {
468 impl<'a> Parser<'a> {
472 directory: Option<Directory<'a>>,
473 recurse_into_file_modules: bool,
474 desugar_doc_comments: bool,
475 subparser_name: Option<&'static str>,
477 let mut parser = Parser {
479 token: Token::dummy(),
482 prev_token_kind: PrevTokenKind::Other,
483 restrictions: Restrictions::empty(),
484 recurse_into_file_modules,
485 directory: Directory {
486 path: Cow::from(PathBuf::new()),
487 ownership: DirectoryOwnership::Owned { relative: None }
489 root_module_name: None,
490 expected_tokens: Vec::new(),
491 token_cursor: TokenCursor {
492 frame: TokenCursorFrame::new(
499 desugar_doc_comments,
501 unmatched_angle_bracket_count: 0,
502 max_angle_bracket_count: 0,
503 unclosed_delims: Vec::new(),
504 last_unexpected_token_span: None,
508 parser.token = parser.next_tok();
510 if let Some(directory) = directory {
511 parser.directory = directory;
512 } else if !parser.token.span.is_dummy() {
513 if let FileName::Real(mut path) =
514 sess.source_map().span_to_unmapped_path(parser.token.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 _ if self.token.is_special_ident() => "reserved identifier",
545 _ if self.token.is_used_keyword() => "keyword",
546 _ if self.token.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: &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: &[TokenKind],
587 inedible: &[TokenKind],
588 ) -> PResult<'a, bool /* recovered */> {
589 if edible.contains(&self.token.kind) {
592 } else if inedible.contains(&self.token.kind) {
593 // leave it in the input
595 } else if self.last_unexpected_token_span == Some(self.token.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(name, _) => {
623 if self.token.is_reserved_ident() {
624 let mut err = self.expected_ident_found();
631 let span = self.token.span;
633 Ok(Ident::new(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: &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: &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.token.span.with_lo(self.token.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.token.span.with_lo(self.token.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.token.span.with_lo(self.token.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.token.span.with_lo(self.token.span.lo() + BytePos(1));
821 self.bump_with(token::Lt, span);
825 let span = self.token.span.with_lo(self.token.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.token.span.with_lo(self.token.span.lo() + BytePos(1));
861 Some(self.bump_with(token::Gt, span))
863 token::BinOpEq(token::Shr) => {
864 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
865 Some(self.bump_with(token::Ge, span))
868 let span = self.token.span.with_lo(self.token.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,
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>(
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>(
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.kind) {
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>(
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.token.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: TokenKind, span: Span) {
1040 self.prev_span = self.token.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::new(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) -> R,
1053 return f(&self.token);
1056 let frame = &self.token_cursor.frame;
1057 f(&match frame.tree_cursor.look_ahead(dist - 1) {
1058 Some(tree) => match tree {
1059 TokenTree::Token(token) => token,
1060 TokenTree::Delimited(dspan, delim, _) =>
1061 Token::new(token::OpenDelim(delim), dspan.open),
1063 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
1067 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1068 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1069 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1072 /// Is the current token one of the keywords that signals a bare function type?
1073 fn token_is_bare_fn_keyword(&mut self) -> bool {
1074 self.check_keyword(kw::Fn) ||
1075 self.check_keyword(kw::Unsafe) ||
1076 self.check_keyword(kw::Extern)
1079 /// Parses a `TyKind::BareFn` type.
1080 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1083 [unsafe] [extern "ABI"] fn (S) -> T
1093 let unsafety = self.parse_unsafety();
1094 let abi = if self.eat_keyword(kw::Extern) {
1095 self.parse_opt_abi()?.unwrap_or(Abi::C)
1100 self.expect_keyword(kw::Fn)?;
1101 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1102 let ret_ty = self.parse_ret_ty(false)?;
1103 let decl = P(FnDecl {
1108 Ok(TyKind::BareFn(P(BareFnTy {
1116 /// Parses asyncness: `async` or nothing.
1117 fn parse_asyncness(&mut self) -> IsAsync {
1118 if self.eat_keyword(kw::Async) {
1120 closure_id: ast::DUMMY_NODE_ID,
1121 return_impl_trait_id: ast::DUMMY_NODE_ID,
1128 /// Parses unsafety: `unsafe` or nothing.
1129 fn parse_unsafety(&mut self) -> Unsafety {
1130 if self.eat_keyword(kw::Unsafe) {
1137 /// Parses the items in a trait declaration.
1138 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1139 maybe_whole!(self, NtTraitItem, |x| x);
1140 let attrs = self.parse_outer_attributes()?;
1141 let mut unclosed_delims = vec![];
1142 let (mut item, tokens) = self.collect_tokens(|this| {
1143 let item = this.parse_trait_item_(at_end, attrs);
1144 unclosed_delims.append(&mut this.unclosed_delims);
1147 self.unclosed_delims.append(&mut unclosed_delims);
1148 // See `parse_item` for why this clause is here.
1149 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1150 item.tokens = Some(tokens);
1155 fn parse_trait_item_(&mut self,
1157 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1158 let lo = self.token.span;
1160 let (name, node, generics) = if self.eat_keyword(kw::Type) {
1161 self.parse_trait_item_assoc_ty()?
1162 } else if self.is_const_item() {
1163 self.expect_keyword(kw::Const)?;
1164 let ident = self.parse_ident()?;
1165 self.expect(&token::Colon)?;
1166 let ty = self.parse_ty()?;
1167 let default = if self.eat(&token::Eq) {
1168 let expr = self.parse_expr()?;
1169 self.expect(&token::Semi)?;
1172 self.expect(&token::Semi)?;
1175 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1176 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1177 // trait item macro.
1178 (Ident::invalid(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1180 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1182 let ident = self.parse_ident()?;
1183 let mut generics = self.parse_generics()?;
1185 let decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1186 // This is somewhat dubious; We don't want to allow
1187 // argument names to be left off if there is a
1190 // We don't allow argument names to be left off in edition 2018.
1191 let is_name_required = p.token.span.rust_2018();
1192 p.parse_arg_general(true, false, |_| is_name_required)
1194 generics.where_clause = self.parse_where_clause()?;
1196 let sig = ast::MethodSig {
1206 let body = match self.token.kind {
1210 debug!("parse_trait_methods(): parsing required method");
1213 token::OpenDelim(token::Brace) => {
1214 debug!("parse_trait_methods(): parsing provided method");
1216 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1217 attrs.extend(inner_attrs.iter().cloned());
1220 token::Interpolated(ref nt) => {
1222 token::NtBlock(..) => {
1224 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1225 attrs.extend(inner_attrs.iter().cloned());
1229 return self.expected_semi_or_open_brace();
1234 return self.expected_semi_or_open_brace();
1237 (ident, ast::TraitItemKind::Method(sig, body), generics)
1241 id: ast::DUMMY_NODE_ID,
1246 span: lo.to(self.prev_span),
1251 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1252 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1253 if self.eat(&token::RArrow) {
1254 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1256 Ok(FunctionRetTy::Default(self.token.span.shrink_to_lo()))
1261 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1262 self.parse_ty_common(true, true, false)
1265 /// Parses a type in restricted contexts where `+` is not permitted.
1267 /// Example 1: `&'a TYPE`
1268 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1269 /// Example 2: `value1 as TYPE + value2`
1270 /// `+` is prohibited to avoid interactions with expression grammar.
1271 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1272 self.parse_ty_common(false, true, false)
1275 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1276 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1277 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1278 maybe_whole!(self, NtTy, |x| x);
1280 let lo = self.token.span;
1281 let mut impl_dyn_multi = false;
1282 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1283 // `(TYPE)` is a parenthesized type.
1284 // `(TYPE,)` is a tuple with a single field of type TYPE.
1285 let mut ts = vec![];
1286 let mut last_comma = false;
1287 while self.token != token::CloseDelim(token::Paren) {
1288 ts.push(self.parse_ty()?);
1289 if self.eat(&token::Comma) {
1296 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1297 self.expect(&token::CloseDelim(token::Paren))?;
1299 if ts.len() == 1 && !last_comma {
1300 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1301 let maybe_bounds = allow_plus && self.token.is_like_plus();
1303 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1304 TyKind::Path(None, ref path) if maybe_bounds => {
1305 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1307 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1308 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1309 let path = match bounds[0] {
1310 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1311 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1313 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1316 _ => TyKind::Paren(P(ty))
1321 } else if self.eat(&token::Not) {
1324 } else if self.eat(&token::BinOp(token::Star)) {
1326 TyKind::Ptr(self.parse_ptr()?)
1327 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1329 let t = self.parse_ty()?;
1330 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1331 let t = match self.maybe_parse_fixed_length_of_vec()? {
1332 None => TyKind::Slice(t),
1333 Some(length) => TyKind::Array(t, AnonConst {
1334 id: ast::DUMMY_NODE_ID,
1338 self.expect(&token::CloseDelim(token::Bracket))?;
1340 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1343 self.parse_borrowed_pointee()?
1344 } else if self.eat_keyword_noexpect(kw::Typeof) {
1346 // In order to not be ambiguous, the type must be surrounded by parens.
1347 self.expect(&token::OpenDelim(token::Paren))?;
1349 id: ast::DUMMY_NODE_ID,
1350 value: self.parse_expr()?,
1352 self.expect(&token::CloseDelim(token::Paren))?;
1354 } else if self.eat_keyword(kw::Underscore) {
1355 // A type to be inferred `_`
1357 } else if self.token_is_bare_fn_keyword() {
1358 // Function pointer type
1359 self.parse_ty_bare_fn(Vec::new())?
1360 } else if self.check_keyword(kw::For) {
1361 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1362 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1363 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1364 let lo = self.token.span;
1365 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1366 if self.token_is_bare_fn_keyword() {
1367 self.parse_ty_bare_fn(lifetime_defs)?
1369 let path = self.parse_path(PathStyle::Type)?;
1370 let parse_plus = allow_plus && self.check_plus();
1371 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1373 } else if self.eat_keyword(kw::Impl) {
1374 // Always parse bounds greedily for better error recovery.
1375 let bounds = self.parse_generic_bounds(None)?;
1376 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1377 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1378 } else if self.check_keyword(kw::Dyn) &&
1379 (self.token.span.rust_2018() ||
1380 self.look_ahead(1, |t| t.can_begin_bound() &&
1381 !can_continue_type_after_non_fn_ident(t))) {
1382 self.bump(); // `dyn`
1383 // Always parse bounds greedily for better error recovery.
1384 let bounds = self.parse_generic_bounds(None)?;
1385 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1386 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1387 } else if self.check(&token::Question) ||
1388 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1389 // Bound list (trait object type)
1390 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1391 TraitObjectSyntax::None)
1392 } else if self.eat_lt() {
1394 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1395 TyKind::Path(Some(qself), path)
1396 } else if self.token.is_path_start() {
1398 let path = self.parse_path(PathStyle::Type)?;
1399 if self.eat(&token::Not) {
1400 // Macro invocation in type position
1401 let (delim, tts) = self.expect_delimited_token_tree()?;
1402 let node = Mac_ { path, tts, delim };
1403 TyKind::Mac(respan(lo.to(self.prev_span), node))
1405 // Just a type path or bound list (trait object type) starting with a trait.
1407 // `Trait1 + Trait2 + 'a`
1408 if allow_plus && self.check_plus() {
1409 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1411 TyKind::Path(None, path)
1414 } else if self.check(&token::DotDotDot) {
1415 if allow_c_variadic {
1416 self.eat(&token::DotDotDot);
1419 return Err(self.fatal(
1420 "only foreign functions are allowed to be C-variadic"
1424 let msg = format!("expected type, found {}", self.this_token_descr());
1425 return Err(self.fatal(&msg));
1428 let span = lo.to(self.prev_span);
1429 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1431 // Try to recover from use of `+` with incorrect priority.
1432 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1433 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1434 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1437 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1438 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1439 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1440 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1442 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1443 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1445 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1448 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1449 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1450 let mutbl = self.parse_mutability();
1451 let ty = self.parse_ty_no_plus()?;
1452 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1455 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1456 let mutbl = if self.eat_keyword(kw::Mut) {
1458 } else if self.eat_keyword(kw::Const) {
1459 Mutability::Immutable
1461 let span = self.prev_span;
1462 let msg = "expected mut or const in raw pointer type";
1463 self.struct_span_err(span, msg)
1464 .span_label(span, msg)
1465 .help("use `*mut T` or `*const T` as appropriate")
1467 Mutability::Immutable
1469 let t = self.parse_ty_no_plus()?;
1470 Ok(MutTy { ty: t, mutbl: mutbl })
1473 fn is_named_argument(&self) -> bool {
1474 let offset = match self.token.kind {
1475 token::Interpolated(ref nt) => match **nt {
1476 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1479 token::BinOp(token::And) | token::AndAnd => 1,
1480 _ if self.token.is_keyword(kw::Mut) => 1,
1484 self.look_ahead(offset, |t| t.is_ident()) &&
1485 self.look_ahead(offset + 1, |t| t == &token::Colon)
1488 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1490 /// This version of parse arg doesn't necessarily require identifier names.
1491 fn parse_arg_general<F>(
1493 is_trait_item: bool,
1494 allow_c_variadic: bool,
1495 is_name_required: F,
1496 ) -> PResult<'a, Arg>
1498 F: Fn(&token::Token) -> bool
1500 let attrs = self.parse_arg_attributes()?;
1501 if let Ok(Some(mut arg)) = self.parse_self_arg() {
1502 arg.attrs = attrs.into();
1503 return self.recover_bad_self_arg(arg, is_trait_item);
1506 let is_name_required = is_name_required(&self.token);
1507 let (pat, ty) = if is_name_required || self.is_named_argument() {
1508 debug!("parse_arg_general parse_pat (is_name_required:{})", is_name_required);
1510 let pat = self.parse_pat(Some("argument name"))?;
1511 if let Err(mut err) = self.expect(&token::Colon) {
1512 if let Some(ident) = self.argument_without_type(
1519 return Ok(dummy_arg(ident));
1525 self.eat_incorrect_doc_comment_for_arg_type();
1526 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1528 debug!("parse_arg_general ident_to_pat");
1529 let parser_snapshot_before_ty = self.clone();
1530 self.eat_incorrect_doc_comment_for_arg_type();
1531 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1532 if ty.is_ok() && self.token != token::Comma &&
1533 self.token != token::CloseDelim(token::Paren) {
1534 // This wasn't actually a type, but a pattern looking like a type,
1535 // so we are going to rollback and re-parse for recovery.
1536 ty = self.unexpected();
1540 let ident = Ident::new(kw::Invalid, self.prev_span);
1542 id: ast::DUMMY_NODE_ID,
1543 node: PatKind::Ident(
1544 BindingMode::ByValue(Mutability::Immutable), ident, None),
1550 // If this is a C-variadic argument and we hit an error, return the
1552 if self.token == token::DotDotDot {
1555 // Recover from attempting to parse the argument as a type without pattern.
1557 mem::replace(self, parser_snapshot_before_ty);
1558 self.recover_arg_parse()?
1563 Ok(Arg { attrs: attrs.into(), id: ast::DUMMY_NODE_ID, pat, ty })
1566 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
1567 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1568 let attrs = self.parse_arg_attributes()?;
1569 let pat = self.parse_pat(Some("argument name"))?;
1570 let t = if self.eat(&token::Colon) {
1574 id: ast::DUMMY_NODE_ID,
1575 node: TyKind::Infer,
1576 span: self.prev_span,
1580 attrs: attrs.into(),
1583 id: ast::DUMMY_NODE_ID
1587 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1588 if self.eat(&token::Semi) {
1589 Ok(Some(self.parse_expr()?))
1595 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1596 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1597 maybe_whole_expr!(self);
1599 let minus_lo = self.token.span;
1600 let minus_present = self.eat(&token::BinOp(token::Minus));
1601 let lo = self.token.span;
1602 let literal = self.parse_lit()?;
1603 let hi = self.prev_span;
1604 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1607 let minus_hi = self.prev_span;
1608 let unary = self.mk_unary(UnOp::Neg, expr);
1609 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1615 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1616 match self.token.kind {
1617 token::Ident(name, _) if name.is_path_segment_keyword() => {
1618 let span = self.token.span;
1620 Ok(Ident::new(name, span))
1622 _ => self.parse_ident(),
1626 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
1627 match self.token.kind {
1628 token::Ident(name, false) if name == kw::Underscore => {
1629 let span = self.token.span;
1631 Ok(Ident::new(name, span))
1633 _ => self.parse_ident(),
1637 /// Parses a qualified path.
1638 /// Assumes that the leading `<` has been parsed already.
1640 /// `qualified_path = <type [as trait_ref]>::path`
1645 /// `<T as U>::F::a<S>` (without disambiguator)
1646 /// `<T as U>::F::a::<S>` (with disambiguator)
1647 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1648 let lo = self.prev_span;
1649 let ty = self.parse_ty()?;
1651 // `path` will contain the prefix of the path up to the `>`,
1652 // if any (e.g., `U` in the `<T as U>::*` examples
1653 // above). `path_span` has the span of that path, or an empty
1654 // span in the case of something like `<T>::Bar`.
1655 let (mut path, path_span);
1656 if self.eat_keyword(kw::As) {
1657 let path_lo = self.token.span;
1658 path = self.parse_path(PathStyle::Type)?;
1659 path_span = path_lo.to(self.prev_span);
1661 path_span = self.token.span.to(self.token.span);
1662 path = ast::Path { segments: Vec::new(), span: path_span };
1665 // See doc comment for `unmatched_angle_bracket_count`.
1666 self.expect(&token::Gt)?;
1667 if self.unmatched_angle_bracket_count > 0 {
1668 self.unmatched_angle_bracket_count -= 1;
1669 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1672 self.expect(&token::ModSep)?;
1674 let qself = QSelf { ty, path_span, position: path.segments.len() };
1675 self.parse_path_segments(&mut path.segments, style)?;
1677 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1680 /// Parses simple paths.
1682 /// `path = [::] segment+`
1683 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1686 /// `a::b::C<D>` (without disambiguator)
1687 /// `a::b::C::<D>` (with disambiguator)
1688 /// `Fn(Args)` (without disambiguator)
1689 /// `Fn::(Args)` (with disambiguator)
1690 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1691 maybe_whole!(self, NtPath, |path| {
1692 if style == PathStyle::Mod &&
1693 path.segments.iter().any(|segment| segment.args.is_some()) {
1694 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1699 let lo = self.meta_var_span.unwrap_or(self.token.span);
1700 let mut segments = Vec::new();
1701 let mod_sep_ctxt = self.token.span.ctxt();
1702 if self.eat(&token::ModSep) {
1703 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
1705 self.parse_path_segments(&mut segments, style)?;
1707 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1710 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
1711 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
1713 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1714 let meta_ident = match self.token.kind {
1715 token::Interpolated(ref nt) => match **nt {
1716 token::NtMeta(ref meta) => match meta.node {
1717 ast::MetaItemKind::Word => Some(meta.path.clone()),
1724 if let Some(path) = meta_ident {
1728 self.parse_path(style)
1731 crate fn parse_path_segments(&mut self,
1732 segments: &mut Vec<PathSegment>,
1734 -> PResult<'a, ()> {
1736 let segment = self.parse_path_segment(style)?;
1737 if style == PathStyle::Expr {
1738 // In order to check for trailing angle brackets, we must have finished
1739 // recursing (`parse_path_segment` can indirectly call this function),
1740 // that is, the next token must be the highlighted part of the below example:
1742 // `Foo::<Bar as Baz<T>>::Qux`
1745 // As opposed to the below highlight (if we had only finished the first
1748 // `Foo::<Bar as Baz<T>>::Qux`
1751 // `PathStyle::Expr` is only provided at the root invocation and never in
1752 // `parse_path_segment` to recurse and therefore can be checked to maintain
1754 self.check_trailing_angle_brackets(&segment, token::ModSep);
1756 segments.push(segment);
1758 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1764 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
1765 let ident = self.parse_path_segment_ident()?;
1767 let is_args_start = |token: &Token| match token.kind {
1768 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
1769 | token::LArrow => true,
1772 let check_args_start = |this: &mut Self| {
1773 this.expected_tokens.extend_from_slice(
1774 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1776 is_args_start(&this.token)
1779 Ok(if style == PathStyle::Type && check_args_start(self) ||
1780 style != PathStyle::Mod && self.check(&token::ModSep)
1781 && self.look_ahead(1, |t| is_args_start(t)) {
1782 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
1783 // it isn't, then we reset the unmatched angle bracket count as we're about to start
1784 // parsing a new path.
1785 if style == PathStyle::Expr {
1786 self.unmatched_angle_bracket_count = 0;
1787 self.max_angle_bracket_count = 0;
1790 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1791 self.eat(&token::ModSep);
1792 let lo = self.token.span;
1793 let args = if self.eat_lt() {
1795 let (args, constraints) =
1796 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
1798 let span = lo.to(self.prev_span);
1799 AngleBracketedArgs { args, constraints, span }.into()
1803 let (inputs, recovered) = self.parse_seq_to_before_tokens(
1804 &[&token::CloseDelim(token::Paren)],
1805 SeqSep::trailing_allowed(token::Comma),
1806 TokenExpectType::Expect,
1811 let span = lo.to(self.prev_span);
1812 let output = if self.eat(&token::RArrow) {
1813 Some(self.parse_ty_common(false, false, false)?)
1817 ParenthesizedArgs { inputs, output, span }.into()
1820 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
1822 // Generic arguments are not found.
1823 PathSegment::from_ident(ident)
1827 crate fn check_lifetime(&mut self) -> bool {
1828 self.expected_tokens.push(TokenType::Lifetime);
1829 self.token.is_lifetime()
1832 /// Parses a single lifetime `'a` or panics.
1833 crate fn expect_lifetime(&mut self) -> Lifetime {
1834 if let Some(ident) = self.token.lifetime() {
1835 let span = self.token.span;
1837 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
1839 self.span_bug(self.token.span, "not a lifetime")
1843 fn eat_label(&mut self) -> Option<Label> {
1844 if let Some(ident) = self.token.lifetime() {
1845 let span = self.token.span;
1847 Some(Label { ident: Ident::new(ident.name, span) })
1853 /// Parses mutability (`mut` or nothing).
1854 fn parse_mutability(&mut self) -> Mutability {
1855 if self.eat_keyword(kw::Mut) {
1858 Mutability::Immutable
1862 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1863 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1865 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1867 Ok(Ident::new(symbol, self.prev_span))
1869 self.parse_ident_common(false)
1873 /// Parse ident (COLON expr)?
1874 fn parse_field(&mut self) -> PResult<'a, Field> {
1875 let attrs = self.parse_outer_attributes()?;
1876 let lo = self.token.span;
1878 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1879 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1880 t == &token::Colon || t == &token::Eq
1882 let fieldname = self.parse_field_name()?;
1884 // Check for an equals token. This means the source incorrectly attempts to
1885 // initialize a field with an eq rather than a colon.
1886 if self.token == token::Eq {
1888 .struct_span_err(self.token.span, "expected `:`, found `=`")
1890 fieldname.span.shrink_to_hi().to(self.token.span),
1891 "replace equals symbol with a colon",
1893 Applicability::MachineApplicable,
1898 (fieldname, self.parse_expr()?, false)
1900 let fieldname = self.parse_ident_common(false)?;
1902 // Mimic `x: x` for the `x` field shorthand.
1903 let path = ast::Path::from_ident(fieldname);
1904 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1905 (fieldname, expr, true)
1909 span: lo.to(expr.span),
1912 attrs: attrs.into(),
1916 crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1917 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
1920 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1921 ExprKind::Unary(unop, expr)
1924 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1925 ExprKind::Binary(binop, lhs, rhs)
1928 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1929 ExprKind::Call(f, args)
1932 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1933 ExprKind::Index(expr, idx)
1937 start: Option<P<Expr>>,
1938 end: Option<P<Expr>>,
1939 limits: RangeLimits)
1940 -> PResult<'a, ast::ExprKind> {
1941 if end.is_none() && limits == RangeLimits::Closed {
1942 Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
1944 Ok(ExprKind::Range(start, end, limits))
1948 fn mk_assign_op(&self, binop: ast::BinOp,
1949 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1950 ExprKind::AssignOp(binop, lhs, rhs)
1953 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
1954 let delim = match self.token.kind {
1955 token::OpenDelim(delim) => delim,
1957 let msg = "expected open delimiter";
1958 let mut err = self.fatal(msg);
1959 err.span_label(self.token.span, msg);
1963 let tts = match self.parse_token_tree() {
1964 TokenTree::Delimited(_, _, tts) => tts,
1965 _ => unreachable!(),
1967 let delim = match delim {
1968 token::Paren => MacDelimiter::Parenthesis,
1969 token::Bracket => MacDelimiter::Bracket,
1970 token::Brace => MacDelimiter::Brace,
1971 token::NoDelim => self.bug("unexpected no delimiter"),
1973 Ok((delim, tts.into()))
1976 /// At the bottom (top?) of the precedence hierarchy,
1977 /// Parses things like parenthesized exprs, macros, `return`, etc.
1979 /// N.B., this does not parse outer attributes, and is private because it only works
1980 /// correctly if called from `parse_dot_or_call_expr()`.
1981 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1982 maybe_recover_from_interpolated_ty_qpath!(self, true);
1983 maybe_whole_expr!(self);
1985 // Outer attributes are already parsed and will be
1986 // added to the return value after the fact.
1988 // Therefore, prevent sub-parser from parsing
1989 // attributes by giving them a empty "already parsed" list.
1990 let mut attrs = ThinVec::new();
1992 let lo = self.token.span;
1993 let mut hi = self.token.span;
1997 // Note: when adding new syntax here, don't forget to adjust TokenKind::can_begin_expr().
1998 match self.token.kind {
1999 token::OpenDelim(token::Paren) => {
2002 attrs.extend(self.parse_inner_attributes()?);
2004 // (e) is parenthesized e
2005 // (e,) is a tuple with only one field, e
2006 let mut es = vec![];
2007 let mut trailing_comma = false;
2008 let mut recovered = false;
2009 while self.token != token::CloseDelim(token::Paren) {
2010 es.push(match self.parse_expr() {
2013 // recover from parse error in tuple list
2014 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2017 recovered = self.expect_one_of(
2019 &[token::Comma, token::CloseDelim(token::Paren)],
2021 if self.eat(&token::Comma) {
2022 trailing_comma = true;
2024 trailing_comma = false;
2032 hi = self.prev_span;
2033 ex = if es.len() == 1 && !trailing_comma {
2034 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2039 token::OpenDelim(token::Brace) => {
2040 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2042 token::BinOp(token::Or) | token::OrOr => {
2043 return self.parse_lambda_expr(attrs);
2045 token::OpenDelim(token::Bracket) => {
2048 attrs.extend(self.parse_inner_attributes()?);
2050 if self.eat(&token::CloseDelim(token::Bracket)) {
2052 ex = ExprKind::Array(Vec::new());
2055 let first_expr = self.parse_expr()?;
2056 if self.eat(&token::Semi) {
2057 // Repeating array syntax: [ 0; 512 ]
2058 let count = AnonConst {
2059 id: ast::DUMMY_NODE_ID,
2060 value: self.parse_expr()?,
2062 self.expect(&token::CloseDelim(token::Bracket))?;
2063 ex = ExprKind::Repeat(first_expr, count);
2064 } else if self.eat(&token::Comma) {
2065 // Vector with two or more elements.
2066 let remaining_exprs = self.parse_seq_to_end(
2067 &token::CloseDelim(token::Bracket),
2068 SeqSep::trailing_allowed(token::Comma),
2069 |p| Ok(p.parse_expr()?)
2071 let mut exprs = vec![first_expr];
2072 exprs.extend(remaining_exprs);
2073 ex = ExprKind::Array(exprs);
2075 // Vector with one element.
2076 self.expect(&token::CloseDelim(token::Bracket))?;
2077 ex = ExprKind::Array(vec![first_expr]);
2080 hi = self.prev_span;
2084 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2086 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2088 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
2089 return self.parse_lambda_expr(attrs);
2091 if self.eat_keyword(kw::If) {
2092 return self.parse_if_expr(attrs);
2094 if self.eat_keyword(kw::For) {
2095 let lo = self.prev_span;
2096 return self.parse_for_expr(None, lo, attrs);
2098 if self.eat_keyword(kw::While) {
2099 let lo = self.prev_span;
2100 return self.parse_while_expr(None, lo, attrs);
2102 if let Some(label) = self.eat_label() {
2103 let lo = label.ident.span;
2104 self.expect(&token::Colon)?;
2105 if self.eat_keyword(kw::While) {
2106 return self.parse_while_expr(Some(label), lo, attrs)
2108 if self.eat_keyword(kw::For) {
2109 return self.parse_for_expr(Some(label), lo, attrs)
2111 if self.eat_keyword(kw::Loop) {
2112 return self.parse_loop_expr(Some(label), lo, attrs)
2114 if self.token == token::OpenDelim(token::Brace) {
2115 return self.parse_block_expr(Some(label),
2117 BlockCheckMode::Default,
2120 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2121 let mut err = self.fatal(msg);
2122 err.span_label(self.token.span, msg);
2125 if self.eat_keyword(kw::Loop) {
2126 let lo = self.prev_span;
2127 return self.parse_loop_expr(None, lo, attrs);
2129 if self.eat_keyword(kw::Continue) {
2130 let label = self.eat_label();
2131 let ex = ExprKind::Continue(label);
2132 let hi = self.prev_span;
2133 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2135 if self.eat_keyword(kw::Match) {
2136 let match_sp = self.prev_span;
2137 return self.parse_match_expr(attrs).map_err(|mut err| {
2138 err.span_label(match_sp, "while parsing this match expression");
2142 if self.eat_keyword(kw::Unsafe) {
2143 return self.parse_block_expr(
2146 BlockCheckMode::Unsafe(ast::UserProvided),
2149 if self.is_do_catch_block() {
2150 let mut db = self.fatal("found removed `do catch` syntax");
2151 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2154 if self.is_try_block() {
2155 let lo = self.token.span;
2156 assert!(self.eat_keyword(kw::Try));
2157 return self.parse_try_block(lo, attrs);
2160 // Span::rust_2018() is somewhat expensive; don't get it repeatedly.
2161 let is_span_rust_2018 = self.token.span.rust_2018();
2162 if is_span_rust_2018 && self.check_keyword(kw::Async) {
2163 return if self.is_async_block() { // check for `async {` and `async move {`
2164 self.parse_async_block(attrs)
2166 self.parse_lambda_expr(attrs)
2169 if self.eat_keyword(kw::Return) {
2170 if self.token.can_begin_expr() {
2171 let e = self.parse_expr()?;
2173 ex = ExprKind::Ret(Some(e));
2175 ex = ExprKind::Ret(None);
2177 } else if self.eat_keyword(kw::Break) {
2178 let label = self.eat_label();
2179 let e = if self.token.can_begin_expr()
2180 && !(self.token == token::OpenDelim(token::Brace)
2181 && self.restrictions.contains(
2182 Restrictions::NO_STRUCT_LITERAL)) {
2183 Some(self.parse_expr()?)
2187 ex = ExprKind::Break(label, e);
2188 hi = self.prev_span;
2189 } else if self.eat_keyword(kw::Yield) {
2190 if self.token.can_begin_expr() {
2191 let e = self.parse_expr()?;
2193 ex = ExprKind::Yield(Some(e));
2195 ex = ExprKind::Yield(None);
2197 } else if self.token.is_keyword(kw::Let) {
2198 // Catch this syntax error here, instead of in `parse_ident`, so
2199 // that we can explicitly mention that let is not to be used as an expression
2200 let mut db = self.fatal("expected expression, found statement (`let`)");
2201 db.span_label(self.token.span, "expected expression");
2202 db.note("variable declaration using `let` is a statement");
2204 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
2205 let (await_hi, e_kind) = self.parse_await_macro_or_alt(lo, self.prev_span)?;
2208 } else if self.token.is_path_start() {
2209 let path = self.parse_path(PathStyle::Expr)?;
2211 // `!`, as an operator, is prefix, so we know this isn't that
2212 if self.eat(&token::Not) {
2213 // MACRO INVOCATION expression
2214 let (delim, tts) = self.expect_delimited_token_tree()?;
2215 hi = self.prev_span;
2216 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2217 } else if self.check(&token::OpenDelim(token::Brace)) {
2218 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2222 ex = ExprKind::Path(None, path);
2226 ex = ExprKind::Path(None, path);
2229 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2230 // Don't complain about bare semicolons after unclosed braces
2231 // recovery in order to keep the error count down. Fixing the
2232 // delimiters will possibly also fix the bare semicolon found in
2233 // expression context. For example, silence the following error:
2235 // error: expected expression, found `;`
2239 // | ^ expected expression
2242 return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()));
2244 match self.parse_literal_maybe_minus() {
2247 ex = expr.node.clone();
2250 self.cancel(&mut err);
2251 return Err(self.expected_expression_found());
2258 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2259 self.maybe_recover_from_bad_qpath(expr, true)
2262 /// Parse `await!(<expr>)` calls, or alternatively recover from incorrect but reasonable
2263 /// alternative syntaxes `await <expr>`, `await? <expr>`, `await(<expr>)` and
2264 /// `await { <expr> }`.
2265 fn parse_await_macro_or_alt(
2269 ) -> PResult<'a, (Span, ExprKind)> {
2270 if self.token == token::Not {
2271 // Handle correct `await!(<expr>)`.
2272 // FIXME: make this an error when `await!` is no longer supported
2273 // https://github.com/rust-lang/rust/issues/60610
2274 self.expect(&token::Not)?;
2275 self.expect(&token::OpenDelim(token::Paren))?;
2276 let expr = self.parse_expr().map_err(|mut err| {
2277 err.span_label(await_sp, "while parsing this await macro call");
2280 self.expect(&token::CloseDelim(token::Paren))?;
2281 Ok((self.prev_span, ExprKind::Await(ast::AwaitOrigin::MacroLike, expr)))
2282 } else { // Handle `await <expr>`.
2283 self.parse_incorrect_await_syntax(lo, await_sp)
2287 fn maybe_parse_struct_expr(
2291 attrs: &ThinVec<Attribute>,
2292 ) -> Option<PResult<'a, P<Expr>>> {
2293 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2294 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2295 // `{ ident, ` cannot start a block
2296 self.look_ahead(2, |t| t == &token::Comma) ||
2297 self.look_ahead(2, |t| t == &token::Colon) && (
2298 // `{ ident: token, ` cannot start a block
2299 self.look_ahead(4, |t| t == &token::Comma) ||
2300 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2301 self.look_ahead(3, |t| !t.can_begin_type())
2305 if struct_allowed || certainly_not_a_block() {
2306 // This is a struct literal, but we don't can't accept them here
2307 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2308 if let (Ok(expr), false) = (&expr, struct_allowed) {
2309 let mut err = self.diagnostic().struct_span_err(
2311 "struct literals are not allowed here",
2313 err.multipart_suggestion(
2314 "surround the struct literal with parentheses",
2316 (lo.shrink_to_lo(), "(".to_string()),
2317 (expr.span.shrink_to_hi(), ")".to_string()),
2319 Applicability::MachineApplicable,
2328 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2329 -> PResult<'a, P<Expr>> {
2330 let struct_sp = lo.to(self.prev_span);
2332 let mut fields = Vec::new();
2333 let mut base = None;
2335 attrs.extend(self.parse_inner_attributes()?);
2337 while self.token != token::CloseDelim(token::Brace) {
2338 if self.eat(&token::DotDot) {
2339 let exp_span = self.prev_span;
2340 match self.parse_expr() {
2346 self.recover_stmt();
2349 if self.token == token::Comma {
2350 let mut err = self.sess.span_diagnostic.mut_span_err(
2351 exp_span.to(self.prev_span),
2352 "cannot use a comma after the base struct",
2354 err.span_suggestion_short(
2356 "remove this comma",
2358 Applicability::MachineApplicable
2360 err.note("the base struct must always be the last field");
2362 self.recover_stmt();
2367 let mut recovery_field = None;
2368 if let token::Ident(name, _) = self.token.kind {
2369 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2370 // Use in case of error after field-looking code: `S { foo: () with a }`
2371 recovery_field = Some(ast::Field {
2372 ident: Ident::new(name, self.token.span),
2373 span: self.token.span,
2374 expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
2375 is_shorthand: false,
2376 attrs: ThinVec::new(),
2380 let mut parsed_field = None;
2381 match self.parse_field() {
2382 Ok(f) => parsed_field = Some(f),
2384 e.span_label(struct_sp, "while parsing this struct");
2387 // If the next token is a comma, then try to parse
2388 // what comes next as additional fields, rather than
2389 // bailing out until next `}`.
2390 if self.token != token::Comma {
2391 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2392 if self.token != token::Comma {
2399 match self.expect_one_of(&[token::Comma],
2400 &[token::CloseDelim(token::Brace)]) {
2401 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2402 // only include the field if there's no parse error for the field name
2406 if let Some(f) = recovery_field {
2409 e.span_label(struct_sp, "while parsing this struct");
2411 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2412 self.eat(&token::Comma);
2417 let span = lo.to(self.token.span);
2418 self.expect(&token::CloseDelim(token::Brace))?;
2419 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2422 fn parse_or_use_outer_attributes(&mut self,
2423 already_parsed_attrs: Option<ThinVec<Attribute>>)
2424 -> PResult<'a, ThinVec<Attribute>> {
2425 if let Some(attrs) = already_parsed_attrs {
2428 self.parse_outer_attributes().map(|a| a.into())
2432 /// Parses a block or unsafe block.
2433 crate fn parse_block_expr(
2435 opt_label: Option<Label>,
2437 blk_mode: BlockCheckMode,
2438 outer_attrs: ThinVec<Attribute>,
2439 ) -> PResult<'a, P<Expr>> {
2440 self.expect(&token::OpenDelim(token::Brace))?;
2442 let mut attrs = outer_attrs;
2443 attrs.extend(self.parse_inner_attributes()?);
2445 let blk = self.parse_block_tail(lo, blk_mode)?;
2446 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2449 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2450 fn parse_dot_or_call_expr(&mut self,
2451 already_parsed_attrs: Option<ThinVec<Attribute>>)
2452 -> PResult<'a, P<Expr>> {
2453 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2455 let b = self.parse_bottom_expr();
2456 let (span, b) = self.interpolated_or_expr_span(b)?;
2457 self.parse_dot_or_call_expr_with(b, span, attrs)
2460 fn parse_dot_or_call_expr_with(&mut self,
2463 mut attrs: ThinVec<Attribute>)
2464 -> PResult<'a, P<Expr>> {
2465 // Stitch the list of outer attributes onto the return value.
2466 // A little bit ugly, but the best way given the current code
2468 self.parse_dot_or_call_expr_with_(e0, lo)
2470 expr.map(|mut expr| {
2471 attrs.extend::<Vec<_>>(expr.attrs.into());
2474 ExprKind::If(..) | ExprKind::IfLet(..) => {
2475 if !expr.attrs.is_empty() {
2476 // Just point to the first attribute in there...
2477 let span = expr.attrs[0].span;
2480 "attributes are not yet allowed on `if` \
2491 // Assuming we have just parsed `.`, continue parsing into an expression.
2492 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2493 if self.token.span.rust_2018() && self.eat_keyword(kw::Await) {
2494 let span = lo.to(self.prev_span);
2495 let await_expr = self.mk_expr(
2497 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
2500 self.recover_from_await_method_call();
2501 return Ok(await_expr);
2503 let segment = self.parse_path_segment(PathStyle::Expr)?;
2504 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2506 Ok(match self.token.kind {
2507 token::OpenDelim(token::Paren) => {
2508 // Method call `expr.f()`
2509 let mut args = self.parse_unspanned_seq(
2510 &token::OpenDelim(token::Paren),
2511 &token::CloseDelim(token::Paren),
2512 SeqSep::trailing_allowed(token::Comma),
2513 |p| Ok(p.parse_expr()?)
2515 args.insert(0, self_arg);
2517 let span = lo.to(self.prev_span);
2518 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2521 // Field access `expr.f`
2522 if let Some(args) = segment.args {
2523 self.span_err(args.span(),
2524 "field expressions may not have generic arguments");
2527 let span = lo.to(self.prev_span);
2528 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2533 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2538 while self.eat(&token::Question) {
2539 let hi = self.prev_span;
2540 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2544 if self.eat(&token::Dot) {
2545 match self.token.kind {
2546 token::Ident(..) => {
2547 e = self.parse_dot_suffix(e, lo)?;
2549 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
2550 let span = self.token.span;
2552 let field = ExprKind::Field(e, Ident::new(symbol, span));
2553 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2555 self.expect_no_suffix(span, "a tuple index", suffix);
2557 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
2559 let fstr = symbol.as_str();
2560 let msg = format!("unexpected token: `{}`", symbol);
2561 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
2562 err.span_label(self.prev_span, "unexpected token");
2563 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2564 let float = match fstr.parse::<f64>().ok() {
2568 let sugg = pprust::to_string(|s| {
2569 use crate::print::pprust::PrintState;
2573 s.print_usize(float.trunc() as usize)?;
2576 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2578 err.span_suggestion(
2579 lo.to(self.prev_span),
2580 "try parenthesizing the first index",
2582 Applicability::MachineApplicable
2589 // FIXME Could factor this out into non_fatal_unexpected or something.
2590 let actual = self.this_token_to_string();
2591 self.span_err(self.token.span, &format!("unexpected token: `{}`", actual));
2596 if self.expr_is_complete(&e) { break; }
2597 match self.token.kind {
2599 token::OpenDelim(token::Paren) => {
2600 let seq = self.parse_unspanned_seq(
2601 &token::OpenDelim(token::Paren),
2602 &token::CloseDelim(token::Paren),
2603 SeqSep::trailing_allowed(token::Comma),
2604 |p| Ok(p.parse_expr()?)
2606 let nd = self.mk_call(e, es);
2607 let hi = self.prev_span;
2608 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2610 e = self.recover_seq_parse_error(token::Paren, lo, seq);
2614 // Could be either an index expression or a slicing expression.
2615 token::OpenDelim(token::Bracket) => {
2617 let ix = self.parse_expr()?;
2618 hi = self.token.span;
2619 self.expect(&token::CloseDelim(token::Bracket))?;
2620 let index = self.mk_index(e, ix);
2621 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2629 crate fn process_potential_macro_variable(&mut self) {
2630 self.token = match self.token.kind {
2631 token::Dollar if self.token.span.ctxt() != SyntaxContext::empty() &&
2632 self.look_ahead(1, |t| t.is_ident()) => {
2634 let name = match self.token.kind {
2635 token::Ident(name, _) => name,
2638 let span = self.prev_span.to(self.token.span);
2640 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
2641 .span_label(span, "unknown macro variable")
2646 token::Interpolated(ref nt) => {
2647 self.meta_var_span = Some(self.token.span);
2648 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2649 // and lifetime tokens, so the former are never encountered during normal parsing.
2651 token::NtIdent(ident, is_raw) =>
2652 Token::new(token::Ident(ident.name, is_raw), ident.span),
2653 token::NtLifetime(ident) =>
2654 Token::new(token::Lifetime(ident.name), ident.span),
2662 /// Parses a single token tree from the input.
2663 crate fn parse_token_tree(&mut self) -> TokenTree {
2664 match self.token.kind {
2665 token::OpenDelim(..) => {
2666 let frame = mem::replace(&mut self.token_cursor.frame,
2667 self.token_cursor.stack.pop().unwrap());
2668 self.token.span = frame.span.entire();
2670 TokenTree::Delimited(
2673 frame.tree_cursor.stream.into(),
2676 token::CloseDelim(_) | token::Eof => unreachable!(),
2678 let token = self.token.take();
2680 TokenTree::Token(token)
2685 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
2686 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2687 let mut tts = Vec::new();
2688 while self.token != token::Eof {
2689 tts.push(self.parse_token_tree());
2694 pub fn parse_tokens(&mut self) -> TokenStream {
2695 let mut result = Vec::new();
2697 match self.token.kind {
2698 token::Eof | token::CloseDelim(..) => break,
2699 _ => result.push(self.parse_token_tree().into()),
2702 TokenStream::new(result)
2705 /// Parse a prefix-unary-operator expr
2706 fn parse_prefix_expr(&mut self,
2707 already_parsed_attrs: Option<ThinVec<Attribute>>)
2708 -> PResult<'a, P<Expr>> {
2709 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2710 let lo = self.token.span;
2711 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
2712 let (hi, ex) = match self.token.kind {
2715 let e = self.parse_prefix_expr(None);
2716 let (span, e) = self.interpolated_or_expr_span(e)?;
2717 (lo.to(span), self.mk_unary(UnOp::Not, e))
2719 // Suggest `!` for bitwise negation when encountering a `~`
2722 let e = self.parse_prefix_expr(None);
2723 let (span, e) = self.interpolated_or_expr_span(e)?;
2724 let span_of_tilde = lo;
2725 let mut err = self.diagnostic()
2726 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2727 err.span_suggestion_short(
2729 "use `!` to perform bitwise negation",
2731 Applicability::MachineApplicable
2734 (lo.to(span), self.mk_unary(UnOp::Not, e))
2736 token::BinOp(token::Minus) => {
2738 let e = self.parse_prefix_expr(None);
2739 let (span, e) = self.interpolated_or_expr_span(e)?;
2740 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2742 token::BinOp(token::Star) => {
2744 let e = self.parse_prefix_expr(None);
2745 let (span, e) = self.interpolated_or_expr_span(e)?;
2746 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2748 token::BinOp(token::And) | token::AndAnd => {
2750 let m = self.parse_mutability();
2751 let e = self.parse_prefix_expr(None);
2752 let (span, e) = self.interpolated_or_expr_span(e)?;
2753 (lo.to(span), ExprKind::AddrOf(m, e))
2755 token::Ident(..) if self.token.is_keyword(kw::Box) => {
2757 let e = self.parse_prefix_expr(None);
2758 let (span, e) = self.interpolated_or_expr_span(e)?;
2759 (lo.to(span), ExprKind::Box(e))
2761 token::Ident(..) if self.token.is_ident_named(sym::not) => {
2762 // `not` is just an ordinary identifier in Rust-the-language,
2763 // but as `rustc`-the-compiler, we can issue clever diagnostics
2764 // for confused users who really want to say `!`
2765 let token_cannot_continue_expr = |t: &Token| match t.kind {
2766 // These tokens can start an expression after `!`, but
2767 // can't continue an expression after an ident
2768 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
2769 token::Literal(..) | token::Pound => true,
2770 token::Interpolated(ref nt) => match **nt {
2771 token::NtIdent(..) | token::NtExpr(..) |
2772 token::NtBlock(..) | token::NtPath(..) => true,
2777 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2778 if cannot_continue_expr {
2780 // Emit the error ...
2781 let mut err = self.diagnostic()
2782 .struct_span_err(self.token.span,
2783 &format!("unexpected {} after identifier",
2784 self.this_token_descr()));
2785 // span the `not` plus trailing whitespace to avoid
2786 // trailing whitespace after the `!` in our suggestion
2787 let to_replace = self.sess.source_map()
2788 .span_until_non_whitespace(lo.to(self.token.span));
2789 err.span_suggestion_short(
2791 "use `!` to perform logical negation",
2793 Applicability::MachineApplicable
2796 // —and recover! (just as if we were in the block
2797 // for the `token::Not` arm)
2798 let e = self.parse_prefix_expr(None);
2799 let (span, e) = self.interpolated_or_expr_span(e)?;
2800 (lo.to(span), self.mk_unary(UnOp::Not, e))
2802 return self.parse_dot_or_call_expr(Some(attrs));
2805 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2807 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2810 /// Parses an associative expression.
2812 /// This parses an expression accounting for associativity and precedence of the operators in
2815 fn parse_assoc_expr(&mut self,
2816 already_parsed_attrs: Option<ThinVec<Attribute>>)
2817 -> PResult<'a, P<Expr>> {
2818 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2821 /// Parses an associative expression with operators of at least `min_prec` precedence.
2822 fn parse_assoc_expr_with(&mut self,
2825 -> PResult<'a, P<Expr>> {
2826 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2829 let attrs = match lhs {
2830 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2833 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
2834 return self.parse_prefix_range_expr(attrs);
2836 self.parse_prefix_expr(attrs)?
2840 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
2842 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2845 (false, _) => {} // continue parsing the expression
2846 // An exhaustive check is done in the following block, but these are checked first
2847 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
2848 // want to keep their span info to improve diagnostics in these cases in a later stage.
2849 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
2850 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
2851 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
2852 (true, Some(AssocOp::Add)) // `{ 42 } + 42
2853 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
2854 // `if x { a } else { b } && if y { c } else { d }`
2855 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
2856 // These cases are ambiguous and can't be identified in the parser alone
2857 let sp = self.sess.source_map().start_point(self.token.span);
2858 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
2861 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
2864 (true, Some(_)) => {
2865 // We've found an expression that would be parsed as a statement, but the next
2866 // token implies this should be parsed as an expression.
2867 // For example: `if let Some(x) = x { x } else { 0 } / 2`
2868 let mut err = self.sess.span_diagnostic.struct_span_err(self.token.span, &format!(
2869 "expected expression, found `{}`",
2870 pprust::token_to_string(&self.token),
2872 err.span_label(self.token.span, "expected expression");
2873 self.sess.expr_parentheses_needed(
2876 Some(pprust::expr_to_string(&lhs),
2881 self.expected_tokens.push(TokenType::Operator);
2882 while let Some(op) = AssocOp::from_token(&self.token) {
2884 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2885 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2886 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2887 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2888 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2889 (PrevTokenKind::Interpolated, _) => self.prev_span,
2890 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2891 if path.segments.len() == 1 => self.prev_span,
2895 let cur_op_span = self.token.span;
2896 let restrictions = if op.is_assign_like() {
2897 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2901 let prec = op.precedence();
2902 if prec < min_prec {
2905 // Check for deprecated `...` syntax
2906 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2907 self.err_dotdotdot_syntax(self.token.span);
2911 if op.is_comparison() {
2912 self.check_no_chained_comparison(&lhs, &op);
2915 if op == AssocOp::As {
2916 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2918 } else if op == AssocOp::Colon {
2919 let maybe_path = self.could_ascription_be_path(&lhs.node);
2920 let next_sp = self.token.span;
2922 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2925 self.bad_type_ascription(
2936 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2937 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2938 // generalise it to the Fixity::None code.
2940 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2941 // two variants are handled with `parse_prefix_range_expr` call above.
2942 let rhs = if self.is_at_start_of_range_notation_rhs() {
2943 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
2947 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2952 let limits = if op == AssocOp::DotDot {
2953 RangeLimits::HalfOpen
2958 let r = self.mk_range(Some(lhs), rhs, limits)?;
2959 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2963 let fixity = op.fixity();
2964 let prec_adjustment = match fixity {
2967 // We currently have no non-associative operators that are not handled above by
2968 // the special cases. The code is here only for future convenience.
2971 let rhs = self.with_res(
2972 restrictions - Restrictions::STMT_EXPR,
2973 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
2976 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
2977 // including the attributes.
2981 .filter(|a| a.style == AttrStyle::Outer)
2983 .map_or(lhs_span, |a| a.span);
2984 let span = lhs_span.to(rhs.span);
2986 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2987 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2988 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2989 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2990 AssocOp::Greater | AssocOp::GreaterEqual => {
2991 let ast_op = op.to_ast_binop().unwrap();
2992 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
2993 self.mk_expr(span, binary, ThinVec::new())
2995 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2996 AssocOp::AssignOp(k) => {
2998 token::Plus => BinOpKind::Add,
2999 token::Minus => BinOpKind::Sub,
3000 token::Star => BinOpKind::Mul,
3001 token::Slash => BinOpKind::Div,
3002 token::Percent => BinOpKind::Rem,
3003 token::Caret => BinOpKind::BitXor,
3004 token::And => BinOpKind::BitAnd,
3005 token::Or => BinOpKind::BitOr,
3006 token::Shl => BinOpKind::Shl,
3007 token::Shr => BinOpKind::Shr,
3009 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3010 self.mk_expr(span, aopexpr, ThinVec::new())
3012 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3013 self.bug("AssocOp should have been handled by special case")
3017 if let Fixity::None = fixity { break }
3022 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3023 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3024 -> PResult<'a, P<Expr>> {
3025 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3026 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3029 // Save the state of the parser before parsing type normally, in case there is a
3030 // LessThan comparison after this cast.
3031 let parser_snapshot_before_type = self.clone();
3032 match self.parse_ty_no_plus() {
3034 Ok(mk_expr(self, rhs))
3036 Err(mut type_err) => {
3037 // Rewind to before attempting to parse the type with generics, to recover
3038 // from situations like `x as usize < y` in which we first tried to parse
3039 // `usize < y` as a type with generic arguments.
3040 let parser_snapshot_after_type = self.clone();
3041 mem::replace(self, parser_snapshot_before_type);
3043 match self.parse_path(PathStyle::Expr) {
3045 let (op_noun, op_verb) = match self.token.kind {
3046 token::Lt => ("comparison", "comparing"),
3047 token::BinOp(token::Shl) => ("shift", "shifting"),
3049 // We can end up here even without `<` being the next token, for
3050 // example because `parse_ty_no_plus` returns `Err` on keywords,
3051 // but `parse_path` returns `Ok` on them due to error recovery.
3052 // Return original error and parser state.
3053 mem::replace(self, parser_snapshot_after_type);
3054 return Err(type_err);
3058 // Successfully parsed the type path leaving a `<` yet to parse.
3061 // Report non-fatal diagnostics, keep `x as usize` as an expression
3062 // in AST and continue parsing.
3063 let msg = format!("`<` is interpreted as a start of generic \
3064 arguments for `{}`, not a {}", path, op_noun);
3066 self.sess.span_diagnostic.struct_span_err(self.token.span, &msg);
3067 let span_after_type = parser_snapshot_after_type.token.span;
3068 err.span_label(self.look_ahead(1, |t| t.span).to(span_after_type),
3069 "interpreted as generic arguments");
3070 err.span_label(self.token.span, format!("not interpreted as {}", op_noun));
3072 let expr = mk_expr(self, P(Ty {
3074 node: TyKind::Path(None, path),
3075 id: ast::DUMMY_NODE_ID
3078 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3079 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3080 err.span_suggestion(
3082 &format!("try {} the cast value", op_verb),
3083 format!("({})", expr_str),
3084 Applicability::MachineApplicable
3090 Err(mut path_err) => {
3091 // Couldn't parse as a path, return original error and parser state.
3093 mem::replace(self, parser_snapshot_after_type);
3101 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3102 fn parse_prefix_range_expr(&mut self,
3103 already_parsed_attrs: Option<ThinVec<Attribute>>)
3104 -> PResult<'a, P<Expr>> {
3105 // Check for deprecated `...` syntax
3106 if self.token == token::DotDotDot {
3107 self.err_dotdotdot_syntax(self.token.span);
3110 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
3111 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3113 let tok = self.token.clone();
3114 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3115 let lo = self.token.span;
3116 let mut hi = self.token.span;
3118 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3119 // RHS must be parsed with more associativity than the dots.
3120 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3121 Some(self.parse_assoc_expr_with(next_prec,
3122 LhsExpr::NotYetParsed)
3130 let limits = if tok == token::DotDot {
3131 RangeLimits::HalfOpen
3136 let r = self.mk_range(None, opt_end, limits)?;
3137 Ok(self.mk_expr(lo.to(hi), r, attrs))
3140 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3141 if self.token.can_begin_expr() {
3142 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3143 if self.token == token::OpenDelim(token::Brace) {
3144 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3152 /// Parses an `if` or `if let` expression (`if` token already eaten).
3153 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3154 if self.check_keyword(kw::Let) {
3155 return self.parse_if_let_expr(attrs);
3157 let lo = self.prev_span;
3158 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3160 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3161 // verify that the last statement is either an implicit return (no `;`) or an explicit
3162 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3163 // the dead code lint.
3164 if self.eat_keyword(kw::Else) || !cond.returns() {
3165 let sp = self.sess.source_map().next_point(lo);
3166 let mut err = self.diagnostic()
3167 .struct_span_err(sp, "missing condition for `if` statemement");
3168 err.span_label(sp, "expected if condition here");
3171 let not_block = self.token != token::OpenDelim(token::Brace);
3172 let thn = self.parse_block().map_err(|mut err| {
3174 err.span_label(lo, "this `if` statement has a condition, but no block");
3178 let mut els: Option<P<Expr>> = None;
3179 let mut hi = thn.span;
3180 if self.eat_keyword(kw::Else) {
3181 let elexpr = self.parse_else_expr()?;
3185 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3188 /// Parses an `if let` expression (`if` token already eaten).
3189 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3190 -> PResult<'a, P<Expr>> {
3191 let lo = self.prev_span;
3192 self.expect_keyword(kw::Let)?;
3193 let pats = self.parse_pats()?;
3194 self.expect(&token::Eq)?;
3195 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3196 let thn = self.parse_block()?;
3197 let (hi, els) = if self.eat_keyword(kw::Else) {
3198 let expr = self.parse_else_expr()?;
3199 (expr.span, Some(expr))
3203 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3206 /// Parses `move |args| expr`.
3207 fn parse_lambda_expr(&mut self,
3208 attrs: ThinVec<Attribute>)
3209 -> PResult<'a, P<Expr>>
3211 let lo = self.token.span;
3212 let movability = if self.eat_keyword(kw::Static) {
3217 let asyncness = if self.token.span.rust_2018() {
3218 self.parse_asyncness()
3222 let capture_clause = if self.eat_keyword(kw::Move) {
3227 let decl = self.parse_fn_block_decl()?;
3228 let decl_hi = self.prev_span;
3229 let body = match decl.output {
3230 FunctionRetTy::Default(_) => {
3231 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3232 self.parse_expr_res(restrictions, None)?
3235 // If an explicit return type is given, require a
3236 // block to appear (RFC 968).
3237 let body_lo = self.token.span;
3238 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3244 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3248 // `else` token already eaten
3249 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3250 if self.eat_keyword(kw::If) {
3251 return self.parse_if_expr(ThinVec::new());
3253 let blk = self.parse_block()?;
3254 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3258 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3259 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3261 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3262 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3264 let pat = self.parse_top_level_pat()?;
3265 if !self.eat_keyword(kw::In) {
3266 let in_span = self.prev_span.between(self.token.span);
3267 let mut err = self.sess.span_diagnostic
3268 .struct_span_err(in_span, "missing `in` in `for` loop");
3269 err.span_suggestion_short(
3270 in_span, "try adding `in` here", " in ".into(),
3271 // has been misleading, at least in the past (closed Issue #48492)
3272 Applicability::MaybeIncorrect
3276 let in_span = self.prev_span;
3277 self.check_for_for_in_in_typo(in_span);
3278 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3279 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3280 attrs.extend(iattrs);
3282 let hi = self.prev_span;
3283 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3286 /// Parses a `while` or `while let` expression (`while` token already eaten).
3287 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3289 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3290 if self.token.is_keyword(kw::Let) {
3291 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3293 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3294 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3295 attrs.extend(iattrs);
3296 let span = span_lo.to(body.span);
3297 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3300 /// Parses a `while let` expression (`while` token already eaten).
3301 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3303 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3304 self.expect_keyword(kw::Let)?;
3305 let pats = self.parse_pats()?;
3306 self.expect(&token::Eq)?;
3307 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3308 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3309 attrs.extend(iattrs);
3310 let span = span_lo.to(body.span);
3311 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3314 // parse `loop {...}`, `loop` token already eaten
3315 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3317 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3318 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3319 attrs.extend(iattrs);
3320 let span = span_lo.to(body.span);
3321 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3324 /// Parses an `async move {...}` expression.
3325 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3326 -> PResult<'a, P<Expr>>
3328 let span_lo = self.token.span;
3329 self.expect_keyword(kw::Async)?;
3330 let capture_clause = if self.eat_keyword(kw::Move) {
3335 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3336 attrs.extend(iattrs);
3338 span_lo.to(body.span),
3339 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3342 /// Parses a `try {...}` expression (`try` token already eaten).
3343 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3344 -> PResult<'a, P<Expr>>
3346 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3347 attrs.extend(iattrs);
3348 if self.eat_keyword(kw::Catch) {
3349 let mut error = self.struct_span_err(self.prev_span,
3350 "keyword `catch` cannot follow a `try` block");
3351 error.help("try using `match` on the result of the `try` block instead");
3355 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3359 // `match` token already eaten
3360 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3361 let match_span = self.prev_span;
3362 let lo = self.prev_span;
3363 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3365 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3366 if self.token == token::Semi {
3367 e.span_suggestion_short(
3369 "try removing this `match`",
3371 Applicability::MaybeIncorrect // speculative
3376 attrs.extend(self.parse_inner_attributes()?);
3378 let mut arms: Vec<Arm> = Vec::new();
3379 while self.token != token::CloseDelim(token::Brace) {
3380 match self.parse_arm() {
3381 Ok(arm) => arms.push(arm),
3383 // Recover by skipping to the end of the block.
3385 self.recover_stmt();
3386 let span = lo.to(self.token.span);
3387 if self.token == token::CloseDelim(token::Brace) {
3390 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3394 let hi = self.token.span;
3396 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3399 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3400 let attrs = self.parse_outer_attributes()?;
3401 let lo = self.token.span;
3402 let pats = self.parse_pats()?;
3403 let guard = if self.eat_keyword(kw::If) {
3404 Some(Guard::If(self.parse_expr()?))
3408 let arrow_span = self.token.span;
3409 self.expect(&token::FatArrow)?;
3410 let arm_start_span = self.token.span;
3412 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3413 .map_err(|mut err| {
3414 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3418 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3419 && self.token != token::CloseDelim(token::Brace);
3421 let hi = self.token.span;
3424 let cm = self.sess.source_map();
3425 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3426 .map_err(|mut err| {
3427 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3428 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3429 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3430 && expr_lines.lines.len() == 2
3431 && self.token == token::FatArrow => {
3432 // We check whether there's any trailing code in the parse span,
3433 // if there isn't, we very likely have the following:
3436 // | -- - missing comma
3440 // | - ^^ self.token.span
3442 // | parsed until here as `"y" & X`
3443 err.span_suggestion_short(
3444 cm.next_point(arm_start_span),
3445 "missing a comma here to end this `match` arm",
3447 Applicability::MachineApplicable
3451 err.span_label(arrow_span,
3452 "while parsing the `match` arm starting here");
3458 self.eat(&token::Comma);
3470 /// Parses an expression.
3472 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3473 self.parse_expr_res(Restrictions::empty(), None)
3476 /// Evaluates the closure with restrictions in place.
3478 /// Afters the closure is evaluated, restrictions are reset.
3479 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3480 where F: FnOnce(&mut Self) -> T
3482 let old = self.restrictions;
3483 self.restrictions = r;
3485 self.restrictions = old;
3490 /// Parses an expression, subject to the given restrictions.
3492 fn parse_expr_res(&mut self, r: Restrictions,
3493 already_parsed_attrs: Option<ThinVec<Attribute>>)
3494 -> PResult<'a, P<Expr>> {
3495 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3498 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
3499 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3500 if self.eat(&token::Eq) {
3501 Ok(Some(self.parse_expr()?))
3503 Ok(Some(self.parse_expr()?))
3509 /// Parses patterns, separated by '|' s.
3510 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3511 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
3512 self.eat(&token::BinOp(token::Or));
3514 let mut pats = Vec::new();
3516 pats.push(self.parse_top_level_pat()?);
3518 if self.token == token::OrOr {
3519 let mut err = self.struct_span_err(self.token.span,
3520 "unexpected token `||` after pattern");
3521 err.span_suggestion(
3523 "use a single `|` to specify multiple patterns",
3525 Applicability::MachineApplicable
3529 } else if self.eat(&token::BinOp(token::Or)) {
3530 // This is a No-op. Continue the loop to parse the next
3538 // Parses a parenthesized list of patterns like
3539 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3540 // - a vector of the patterns that were parsed
3541 // - an option indicating the index of the `..` element
3542 // - a boolean indicating whether a trailing comma was present.
3543 // Trailing commas are significant because (p) and (p,) are different patterns.
3544 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3545 self.expect(&token::OpenDelim(token::Paren))?;
3546 let result = match self.parse_pat_list() {
3547 Ok(result) => result,
3548 Err(mut err) => { // recover from parse error in tuple pattern list
3550 self.consume_block(token::Paren);
3551 return Ok((vec![], Some(0), false));
3554 self.expect(&token::CloseDelim(token::Paren))?;
3558 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3559 let mut fields = Vec::new();
3560 let mut ddpos = None;
3561 let mut prev_dd_sp = None;
3562 let mut trailing_comma = false;
3564 if self.eat(&token::DotDot) {
3565 if ddpos.is_none() {
3566 ddpos = Some(fields.len());
3567 prev_dd_sp = Some(self.prev_span);
3569 // Emit a friendly error, ignore `..` and continue parsing
3570 let mut err = self.struct_span_err(
3572 "`..` can only be used once per tuple or tuple struct pattern",
3574 err.span_label(self.prev_span, "can only be used once per pattern");
3575 if let Some(sp) = prev_dd_sp {
3576 err.span_label(sp, "previously present here");
3580 } else if !self.check(&token::CloseDelim(token::Paren)) {
3581 fields.push(self.parse_pat(None)?);
3586 trailing_comma = self.eat(&token::Comma);
3587 if !trailing_comma {
3592 if ddpos == Some(fields.len()) && trailing_comma {
3593 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3594 let msg = "trailing comma is not permitted after `..`";
3595 self.struct_span_err(self.prev_span, msg)
3596 .span_label(self.prev_span, msg)
3600 Ok((fields, ddpos, trailing_comma))
3603 fn parse_pat_vec_elements(
3605 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3606 let mut before = Vec::new();
3607 let mut slice = None;
3608 let mut after = Vec::new();
3609 let mut first = true;
3610 let mut before_slice = true;
3612 while self.token != token::CloseDelim(token::Bracket) {
3616 self.expect(&token::Comma)?;
3618 if self.token == token::CloseDelim(token::Bracket)
3619 && (before_slice || !after.is_empty()) {
3625 if self.eat(&token::DotDot) {
3627 if self.check(&token::Comma) ||
3628 self.check(&token::CloseDelim(token::Bracket)) {
3629 slice = Some(P(Pat {
3630 id: ast::DUMMY_NODE_ID,
3631 node: PatKind::Wild,
3632 span: self.prev_span,
3634 before_slice = false;
3640 let subpat = self.parse_pat(None)?;
3641 if before_slice && self.eat(&token::DotDot) {
3642 slice = Some(subpat);
3643 before_slice = false;
3644 } else if before_slice {
3645 before.push(subpat);
3651 Ok((before, slice, after))
3657 attrs: Vec<Attribute>
3658 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3659 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3661 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3662 // Parsing a pattern of the form "fieldname: pat"
3663 let fieldname = self.parse_field_name()?;
3665 let pat = self.parse_pat(None)?;
3667 (pat, fieldname, false)
3669 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3670 let is_box = self.eat_keyword(kw::Box);
3671 let boxed_span = self.token.span;
3672 let is_ref = self.eat_keyword(kw::Ref);
3673 let is_mut = self.eat_keyword(kw::Mut);
3674 let fieldname = self.parse_ident()?;
3675 hi = self.prev_span;
3677 let bind_type = match (is_ref, is_mut) {
3678 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3679 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3680 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3681 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3683 let fieldpat = P(Pat {
3684 id: ast::DUMMY_NODE_ID,
3685 node: PatKind::Ident(bind_type, fieldname, None),
3686 span: boxed_span.to(hi),
3689 let subpat = if is_box {
3691 id: ast::DUMMY_NODE_ID,
3692 node: PatKind::Box(fieldpat),
3698 (subpat, fieldname, true)
3701 Ok(source_map::Spanned {
3703 node: ast::FieldPat {
3707 attrs: attrs.into(),
3712 /// Parses the fields of a struct-like pattern.
3713 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3714 let mut fields = Vec::new();
3715 let mut etc = false;
3716 let mut ate_comma = true;
3717 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3718 let mut etc_span = None;
3720 while self.token != token::CloseDelim(token::Brace) {
3721 let attrs = self.parse_outer_attributes()?;
3722 let lo = self.token.span;
3724 // check that a comma comes after every field
3726 let err = self.struct_span_err(self.prev_span, "expected `,`");
3727 if let Some(mut delayed) = delayed_err {
3734 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3736 let mut etc_sp = self.token.span;
3738 if self.token == token::DotDotDot { // Issue #46718
3739 // Accept `...` as if it were `..` to avoid further errors
3740 let mut err = self.struct_span_err(self.token.span,
3741 "expected field pattern, found `...`");
3742 err.span_suggestion(
3744 "to omit remaining fields, use one fewer `.`",
3746 Applicability::MachineApplicable
3750 self.bump(); // `..` || `...`
3752 if self.token == token::CloseDelim(token::Brace) {
3753 etc_span = Some(etc_sp);
3756 let token_str = self.this_token_descr();
3757 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3759 err.span_label(self.token.span, "expected `}`");
3760 let mut comma_sp = None;
3761 if self.token == token::Comma { // Issue #49257
3762 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
3763 etc_sp = etc_sp.to(nw_span);
3764 err.span_label(etc_sp,
3765 "`..` must be at the end and cannot have a trailing comma");
3766 comma_sp = Some(self.token.span);
3771 etc_span = Some(etc_sp.until(self.token.span));
3772 if self.token == token::CloseDelim(token::Brace) {
3773 // If the struct looks otherwise well formed, recover and continue.
3774 if let Some(sp) = comma_sp {
3775 err.span_suggestion_short(
3777 "remove this comma",
3779 Applicability::MachineApplicable,
3784 } else if self.token.is_ident() && ate_comma {
3785 // Accept fields coming after `..,`.
3786 // This way we avoid "pattern missing fields" errors afterwards.
3787 // We delay this error until the end in order to have a span for a
3789 if let Some(mut delayed_err) = delayed_err {
3793 delayed_err = Some(err);
3796 if let Some(mut err) = delayed_err {
3803 fields.push(match self.parse_pat_field(lo, attrs) {
3806 if let Some(mut delayed_err) = delayed_err {
3812 ate_comma = self.eat(&token::Comma);
3815 if let Some(mut err) = delayed_err {
3816 if let Some(etc_span) = etc_span {
3817 err.multipart_suggestion(
3818 "move the `..` to the end of the field list",
3820 (etc_span, String::new()),
3821 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3823 Applicability::MachineApplicable,
3828 return Ok((fields, etc));
3831 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3832 if self.token.is_path_start() {
3833 let lo = self.token.span;
3834 let (qself, path) = if self.eat_lt() {
3835 // Parse a qualified path
3836 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3839 // Parse an unqualified path
3840 (None, self.parse_path(PathStyle::Expr)?)
3842 let hi = self.prev_span;
3843 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3845 self.parse_literal_maybe_minus()
3849 // helper function to decide whether to parse as ident binding or to try to do
3850 // something more complex like range patterns
3851 fn parse_as_ident(&mut self) -> bool {
3852 self.look_ahead(1, |t| match t.kind {
3853 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3854 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3855 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3856 // range pattern branch
3857 token::DotDot => None,
3859 }).unwrap_or_else(|| self.look_ahead(2, |t| match t.kind {
3860 token::Comma | token::CloseDelim(token::Bracket) => true,
3865 /// A wrapper around `parse_pat` with some special error handling for the
3866 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3867 /// to subpatterns within such).
3868 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3869 let pat = self.parse_pat(None)?;
3870 if self.token == token::Comma {
3871 // An unexpected comma after a top-level pattern is a clue that the
3872 // user (perhaps more accustomed to some other language) forgot the
3873 // parentheses in what should have been a tuple pattern; return a
3874 // suggestion-enhanced error here rather than choking on the comma
3876 let comma_span = self.token.span;
3878 if let Err(mut err) = self.parse_pat_list() {
3879 // We didn't expect this to work anyway; we just wanted
3880 // to advance to the end of the comma-sequence so we know
3881 // the span to suggest parenthesizing
3884 let seq_span = pat.span.to(self.prev_span);
3885 let mut err = self.struct_span_err(comma_span,
3886 "unexpected `,` in pattern");
3887 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3888 err.span_suggestion(
3890 "try adding parentheses to match on a tuple..",
3891 format!("({})", seq_snippet),
3892 Applicability::MachineApplicable
3895 "..or a vertical bar to match on multiple alternatives",
3896 format!("{}", seq_snippet.replace(",", " |")),
3897 Applicability::MachineApplicable
3905 /// Parses a pattern.
3906 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
3907 self.parse_pat_with_range_pat(true, expected)
3910 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
3912 fn parse_pat_with_range_pat(
3914 allow_range_pat: bool,
3915 expected: Option<&'static str>,
3916 ) -> PResult<'a, P<Pat>> {
3917 maybe_recover_from_interpolated_ty_qpath!(self, true);
3918 maybe_whole!(self, NtPat, |x| x);
3920 let lo = self.token.span;
3922 match self.token.kind {
3923 token::BinOp(token::And) | token::AndAnd => {
3924 // Parse &pat / &mut pat
3926 let mutbl = self.parse_mutability();
3927 if let token::Lifetime(name) = self.token.kind {
3928 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
3929 err.span_label(self.token.span, "unexpected lifetime");
3932 let subpat = self.parse_pat_with_range_pat(false, expected)?;
3933 pat = PatKind::Ref(subpat, mutbl);
3935 token::OpenDelim(token::Paren) => {
3936 // Parse (pat,pat,pat,...) as tuple pattern
3937 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3938 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3939 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3941 PatKind::Tuple(fields, ddpos)
3944 token::OpenDelim(token::Bracket) => {
3945 // Parse [pat,pat,...] as slice pattern
3947 let (before, slice, after) = self.parse_pat_vec_elements()?;
3948 self.expect(&token::CloseDelim(token::Bracket))?;
3949 pat = PatKind::Slice(before, slice, after);
3951 // At this point, token != &, &&, (, [
3952 _ => if self.eat_keyword(kw::Underscore) {
3954 pat = PatKind::Wild;
3955 } else if self.eat_keyword(kw::Mut) {
3956 // Parse mut ident @ pat / mut ref ident @ pat
3957 let mutref_span = self.prev_span.to(self.token.span);
3958 let binding_mode = if self.eat_keyword(kw::Ref) {
3960 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3963 "try switching the order",
3965 Applicability::MachineApplicable
3967 BindingMode::ByRef(Mutability::Mutable)
3969 BindingMode::ByValue(Mutability::Mutable)
3971 pat = self.parse_pat_ident(binding_mode)?;
3972 } else if self.eat_keyword(kw::Ref) {
3973 // Parse ref ident @ pat / ref mut ident @ pat
3974 let mutbl = self.parse_mutability();
3975 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3976 } else if self.eat_keyword(kw::Box) {
3978 let subpat = self.parse_pat_with_range_pat(false, None)?;
3979 pat = PatKind::Box(subpat);
3980 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3981 self.parse_as_ident() {
3982 // Parse ident @ pat
3983 // This can give false positives and parse nullary enums,
3984 // they are dealt with later in resolve
3985 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3986 pat = self.parse_pat_ident(binding_mode)?;
3987 } else if self.token.is_path_start() {
3988 // Parse pattern starting with a path
3989 let (qself, path) = if self.eat_lt() {
3990 // Parse a qualified path
3991 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3994 // Parse an unqualified path
3995 (None, self.parse_path(PathStyle::Expr)?)
3997 match self.token.kind {
3998 token::Not if qself.is_none() => {
3999 // Parse macro invocation
4001 let (delim, tts) = self.expect_delimited_token_tree()?;
4002 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4003 pat = PatKind::Mac(mac);
4005 token::DotDotDot | token::DotDotEq | token::DotDot => {
4006 let end_kind = match self.token.kind {
4007 token::DotDot => RangeEnd::Excluded,
4008 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4009 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4010 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4013 let op_span = self.token.span;
4015 let span = lo.to(self.prev_span);
4016 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4018 let end = self.parse_pat_range_end()?;
4019 let op = Spanned { span: op_span, node: end_kind };
4020 pat = PatKind::Range(begin, end, op);
4022 token::OpenDelim(token::Brace) => {
4023 if qself.is_some() {
4024 let msg = "unexpected `{` after qualified path";
4025 let mut err = self.fatal(msg);
4026 err.span_label(self.token.span, msg);
4029 // Parse struct pattern
4031 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4033 self.recover_stmt();
4037 pat = PatKind::Struct(path, fields, etc);
4039 token::OpenDelim(token::Paren) => {
4040 if qself.is_some() {
4041 let msg = "unexpected `(` after qualified path";
4042 let mut err = self.fatal(msg);
4043 err.span_label(self.token.span, msg);
4046 // Parse tuple struct or enum pattern
4047 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4048 pat = PatKind::TupleStruct(path, fields, ddpos)
4050 _ => pat = PatKind::Path(qself, path),
4053 // Try to parse everything else as literal with optional minus
4054 match self.parse_literal_maybe_minus() {
4056 let op_span = self.token.span;
4057 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4058 self.check(&token::DotDotDot) {
4059 let end_kind = if self.eat(&token::DotDotDot) {
4060 RangeEnd::Included(RangeSyntax::DotDotDot)
4061 } else if self.eat(&token::DotDotEq) {
4062 RangeEnd::Included(RangeSyntax::DotDotEq)
4063 } else if self.eat(&token::DotDot) {
4066 panic!("impossible case: we already matched \
4067 on a range-operator token")
4069 let end = self.parse_pat_range_end()?;
4070 let op = Spanned { span: op_span, node: end_kind };
4071 pat = PatKind::Range(begin, end, op);
4073 pat = PatKind::Lit(begin);
4077 self.cancel(&mut err);
4078 let expected = expected.unwrap_or("pattern");
4080 "expected {}, found {}",
4082 self.this_token_descr(),
4084 let mut err = self.fatal(&msg);
4085 err.span_label(self.token.span, format!("expected {}", expected));
4086 let sp = self.sess.source_map().start_point(self.token.span);
4087 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4088 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4096 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4097 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4099 if !allow_range_pat {
4102 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4104 PatKind::Range(..) => {
4105 let mut err = self.struct_span_err(
4107 "the range pattern here has ambiguous interpretation",
4109 err.span_suggestion(
4111 "add parentheses to clarify the precedence",
4112 format!("({})", pprust::pat_to_string(&pat)),
4113 // "ambiguous interpretation" implies that we have to be guessing
4114 Applicability::MaybeIncorrect
4125 /// Parses `ident` or `ident @ pat`.
4126 /// used by the copy foo and ref foo patterns to give a good
4127 /// error message when parsing mistakes like `ref foo(a, b)`.
4128 fn parse_pat_ident(&mut self,
4129 binding_mode: ast::BindingMode)
4130 -> PResult<'a, PatKind> {
4131 let ident = self.parse_ident()?;
4132 let sub = if self.eat(&token::At) {
4133 Some(self.parse_pat(Some("binding pattern"))?)
4138 // just to be friendly, if they write something like
4140 // we end up here with ( as the current token. This shortly
4141 // leads to a parse error. Note that if there is no explicit
4142 // binding mode then we do not end up here, because the lookahead
4143 // will direct us over to parse_enum_variant()
4144 if self.token == token::OpenDelim(token::Paren) {
4145 return Err(self.span_fatal(
4147 "expected identifier, found enum pattern"))
4150 Ok(PatKind::Ident(binding_mode, ident, sub))
4153 /// Parses a local variable declaration.
4154 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4155 let lo = self.prev_span;
4156 let pat = self.parse_top_level_pat()?;
4158 let (err, ty) = if self.eat(&token::Colon) {
4159 // Save the state of the parser before parsing type normally, in case there is a `:`
4160 // instead of an `=` typo.
4161 let parser_snapshot_before_type = self.clone();
4162 let colon_sp = self.prev_span;
4163 match self.parse_ty() {
4164 Ok(ty) => (None, Some(ty)),
4166 // Rewind to before attempting to parse the type and continue parsing
4167 let parser_snapshot_after_type = self.clone();
4168 mem::replace(self, parser_snapshot_before_type);
4170 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4171 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4172 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4178 let init = match (self.parse_initializer(err.is_some()), err) {
4179 (Ok(init), None) => { // init parsed, ty parsed
4182 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4183 // Could parse the type as if it were the initializer, it is likely there was a
4184 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4185 err.span_suggestion_short(
4187 "use `=` if you meant to assign",
4189 Applicability::MachineApplicable
4192 // As this was parsed successfully, continue as if the code has been fixed for the
4193 // rest of the file. It will still fail due to the emitted error, but we avoid
4197 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4199 // Couldn't parse the type nor the initializer, only raise the type error and
4200 // return to the parser state before parsing the type as the initializer.
4201 // let x: <parse_error>;
4202 mem::replace(self, snapshot);
4205 (Err(err), None) => { // init error, ty parsed
4206 // Couldn't parse the initializer and we're not attempting to recover a failed
4207 // parse of the type, return the error.
4211 let hi = if self.token == token::Semi {
4220 id: ast::DUMMY_NODE_ID,
4226 /// Parses a structure field.
4227 fn parse_name_and_ty(&mut self,
4230 attrs: Vec<Attribute>)
4231 -> PResult<'a, StructField> {
4232 let name = self.parse_ident()?;
4233 self.expect(&token::Colon)?;
4234 let ty = self.parse_ty()?;
4236 span: lo.to(self.prev_span),
4239 id: ast::DUMMY_NODE_ID,
4245 /// Emits an expected-item-after-attributes error.
4246 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4247 let message = match attrs.last() {
4248 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4249 _ => "expected item after attributes",
4252 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4253 if attrs.last().unwrap().is_sugared_doc {
4254 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4259 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4260 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4261 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4262 Ok(self.parse_stmt_(true))
4265 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4266 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4268 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4273 fn is_async_block(&self) -> bool {
4274 self.token.is_keyword(kw::Async) &&
4277 self.is_keyword_ahead(1, &[kw::Move]) &&
4278 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4280 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4285 fn is_async_fn(&self) -> bool {
4286 self.token.is_keyword(kw::Async) &&
4287 self.is_keyword_ahead(1, &[kw::Fn])
4290 fn is_do_catch_block(&self) -> bool {
4291 self.token.is_keyword(kw::Do) &&
4292 self.is_keyword_ahead(1, &[kw::Catch]) &&
4293 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4294 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4297 fn is_try_block(&self) -> bool {
4298 self.token.is_keyword(kw::Try) &&
4299 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4300 self.token.span.rust_2018() &&
4301 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4302 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4305 fn is_union_item(&self) -> bool {
4306 self.token.is_keyword(kw::Union) &&
4307 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4310 fn is_crate_vis(&self) -> bool {
4311 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4314 fn is_existential_type_decl(&self) -> bool {
4315 self.token.is_keyword(kw::Existential) &&
4316 self.is_keyword_ahead(1, &[kw::Type])
4319 fn is_auto_trait_item(&self) -> bool {
4321 (self.token.is_keyword(kw::Auto) &&
4322 self.is_keyword_ahead(1, &[kw::Trait]))
4323 || // unsafe auto trait
4324 (self.token.is_keyword(kw::Unsafe) &&
4325 self.is_keyword_ahead(1, &[kw::Auto]) &&
4326 self.is_keyword_ahead(2, &[kw::Trait]))
4329 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4330 -> PResult<'a, Option<P<Item>>> {
4331 let token_lo = self.token.span;
4332 let (ident, def) = match self.token.kind {
4333 token::Ident(name, false) if name == kw::Macro => {
4335 let ident = self.parse_ident()?;
4336 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4337 match self.parse_token_tree() {
4338 TokenTree::Delimited(_, _, tts) => tts,
4339 _ => unreachable!(),
4341 } else if self.check(&token::OpenDelim(token::Paren)) {
4342 let args = self.parse_token_tree();
4343 let body = if self.check(&token::OpenDelim(token::Brace)) {
4344 self.parse_token_tree()
4349 TokenStream::new(vec![
4351 TokenTree::token(token::FatArrow, token_lo.to(self.prev_span)).into(),
4359 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4361 token::Ident(name, _) if name == sym::macro_rules &&
4362 self.look_ahead(1, |t| *t == token::Not) => {
4363 let prev_span = self.prev_span;
4364 self.complain_if_pub_macro(&vis.node, prev_span);
4368 let ident = self.parse_ident()?;
4369 let (delim, tokens) = self.expect_delimited_token_tree()?;
4370 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
4371 self.report_invalid_macro_expansion_item();
4374 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4376 _ => return Ok(None),
4379 let span = lo.to(self.prev_span);
4380 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4383 fn parse_stmt_without_recovery(&mut self,
4384 macro_legacy_warnings: bool)
4385 -> PResult<'a, Option<Stmt>> {
4386 maybe_whole!(self, NtStmt, |x| Some(x));
4388 let attrs = self.parse_outer_attributes()?;
4389 let lo = self.token.span;
4391 Ok(Some(if self.eat_keyword(kw::Let) {
4393 id: ast::DUMMY_NODE_ID,
4394 node: StmtKind::Local(self.parse_local(attrs.into())?),
4395 span: lo.to(self.prev_span),
4397 } else if let Some(macro_def) = self.eat_macro_def(
4399 &source_map::respan(lo, VisibilityKind::Inherited),
4403 id: ast::DUMMY_NODE_ID,
4404 node: StmtKind::Item(macro_def),
4405 span: lo.to(self.prev_span),
4407 // Starts like a simple path, being careful to avoid contextual keywords
4408 // such as a union items, item with `crate` visibility or auto trait items.
4409 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4410 // like a path (1 token), but it fact not a path.
4411 // `union::b::c` - path, `union U { ... }` - not a path.
4412 // `crate::b::c` - path, `crate struct S;` - not a path.
4413 } else if self.token.is_path_start() &&
4414 !self.token.is_qpath_start() &&
4415 !self.is_union_item() &&
4416 !self.is_crate_vis() &&
4417 !self.is_existential_type_decl() &&
4418 !self.is_auto_trait_item() &&
4419 !self.is_async_fn() {
4420 let pth = self.parse_path(PathStyle::Expr)?;
4422 if !self.eat(&token::Not) {
4423 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4424 self.parse_struct_expr(lo, pth, ThinVec::new())?
4426 let hi = self.prev_span;
4427 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4430 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4431 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4432 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4435 return Ok(Some(Stmt {
4436 id: ast::DUMMY_NODE_ID,
4437 node: StmtKind::Expr(expr),
4438 span: lo.to(self.prev_span),
4442 // it's a macro invocation
4443 let id = match self.token.kind {
4444 token::OpenDelim(_) => Ident::invalid(), // no special identifier
4445 _ => self.parse_ident()?,
4448 // check that we're pointing at delimiters (need to check
4449 // again after the `if`, because of `parse_ident`
4450 // consuming more tokens).
4451 match self.token.kind {
4452 token::OpenDelim(_) => {}
4454 // we only expect an ident if we didn't parse one
4456 let ident_str = if id.name == kw::Invalid {
4461 let tok_str = self.this_token_descr();
4462 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4465 err.span_label(self.token.span, format!("expected {}`(` or `{{`", ident_str));
4470 let (delim, tts) = self.expect_delimited_token_tree()?;
4471 let hi = self.prev_span;
4473 let style = if delim == MacDelimiter::Brace {
4474 MacStmtStyle::Braces
4476 MacStmtStyle::NoBraces
4479 if id.name == kw::Invalid {
4480 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4481 let node = if delim == MacDelimiter::Brace ||
4482 self.token == token::Semi || self.token == token::Eof {
4483 StmtKind::Mac(P((mac, style, attrs.into())))
4485 // We used to incorrectly stop parsing macro-expanded statements here.
4486 // If the next token will be an error anyway but could have parsed with the
4487 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4488 else if macro_legacy_warnings &&
4489 self.token.can_begin_expr() &&
4490 match self.token.kind {
4491 // These can continue an expression, so we can't stop parsing and warn.
4492 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4493 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4494 token::BinOp(token::And) | token::BinOp(token::Or) |
4495 token::AndAnd | token::OrOr |
4496 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4499 self.warn_missing_semicolon();
4500 StmtKind::Mac(P((mac, style, attrs.into())))
4502 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
4503 let e = self.maybe_recover_from_bad_qpath(e, true)?;
4504 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4505 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4509 id: ast::DUMMY_NODE_ID,
4514 // if it has a special ident, it's definitely an item
4516 // Require a semicolon or braces.
4517 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
4518 self.report_invalid_macro_expansion_item();
4520 let span = lo.to(hi);
4522 id: ast::DUMMY_NODE_ID,
4524 node: StmtKind::Item({
4526 span, id /*id is good here*/,
4527 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4528 respan(lo, VisibilityKind::Inherited),
4534 // FIXME: Bad copy of attrs
4535 let old_directory_ownership =
4536 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4537 let item = self.parse_item_(attrs.clone(), false, true)?;
4538 self.directory.ownership = old_directory_ownership;
4542 id: ast::DUMMY_NODE_ID,
4543 span: lo.to(i.span),
4544 node: StmtKind::Item(i),
4547 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4548 if !attrs.is_empty() {
4549 if s.prev_token_kind == PrevTokenKind::DocComment {
4550 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4551 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4553 s.token.span, "expected statement after outer attribute"
4559 // Do not attempt to parse an expression if we're done here.
4560 if self.token == token::Semi {
4561 unused_attrs(&attrs, self);
4566 if self.token == token::CloseDelim(token::Brace) {
4567 unused_attrs(&attrs, self);
4571 // Remainder are line-expr stmts.
4572 let e = self.parse_expr_res(
4573 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4575 id: ast::DUMMY_NODE_ID,
4576 span: lo.to(e.span),
4577 node: StmtKind::Expr(e),
4584 /// Checks if this expression is a successfully parsed statement.
4585 fn expr_is_complete(&self, e: &Expr) -> bool {
4586 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4587 !classify::expr_requires_semi_to_be_stmt(e)
4590 /// Parses a block. No inner attributes are allowed.
4591 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4592 maybe_whole!(self, NtBlock, |x| x);
4594 let lo = self.token.span;
4596 if !self.eat(&token::OpenDelim(token::Brace)) {
4597 let sp = self.token.span;
4598 let tok = self.this_token_descr();
4599 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4600 let do_not_suggest_help =
4601 self.token.is_keyword(kw::In) || self.token == token::Colon;
4603 if self.token.is_ident_named(sym::and) {
4604 e.span_suggestion_short(
4606 "use `&&` instead of `and` for the boolean operator",
4608 Applicability::MaybeIncorrect,
4611 if self.token.is_ident_named(sym::or) {
4612 e.span_suggestion_short(
4614 "use `||` instead of `or` for the boolean operator",
4616 Applicability::MaybeIncorrect,
4620 // Check to see if the user has written something like
4625 // Which is valid in other languages, but not Rust.
4626 match self.parse_stmt_without_recovery(false) {
4628 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4629 || do_not_suggest_help {
4630 // if the next token is an open brace (e.g., `if a b {`), the place-
4631 // inside-a-block suggestion would be more likely wrong than right
4632 e.span_label(sp, "expected `{`");
4635 let mut stmt_span = stmt.span;
4636 // expand the span to include the semicolon, if it exists
4637 if self.eat(&token::Semi) {
4638 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4640 let sugg = pprust::to_string(|s| {
4641 use crate::print::pprust::{PrintState, INDENT_UNIT};
4642 s.ibox(INDENT_UNIT)?;
4644 s.print_stmt(&stmt)?;
4645 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4649 "try placing this code inside a block",
4651 // speculative, has been misleading in the past (closed Issue #46836)
4652 Applicability::MaybeIncorrect
4656 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4657 self.cancel(&mut e);
4661 e.span_label(sp, "expected `{`");
4665 self.parse_block_tail(lo, BlockCheckMode::Default)
4668 /// Parses a block. Inner attributes are allowed.
4669 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4670 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4672 let lo = self.token.span;
4673 self.expect(&token::OpenDelim(token::Brace))?;
4674 Ok((self.parse_inner_attributes()?,
4675 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4678 /// Parses the rest of a block expression or function body.
4679 /// Precondition: already parsed the '{'.
4680 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4681 let mut stmts = vec![];
4682 while !self.eat(&token::CloseDelim(token::Brace)) {
4683 let stmt = match self.parse_full_stmt(false) {
4686 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4688 id: ast::DUMMY_NODE_ID,
4689 node: StmtKind::Expr(DummyResult::raw_expr(self.token.span, true)),
4690 span: self.token.span,
4695 if let Some(stmt) = stmt {
4697 } else if self.token == token::Eof {
4700 // Found only `;` or `}`.
4706 id: ast::DUMMY_NODE_ID,
4708 span: lo.to(self.prev_span),
4712 /// Parses a statement, including the trailing semicolon.
4713 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4714 // skip looking for a trailing semicolon when we have an interpolated statement
4715 maybe_whole!(self, NtStmt, |x| Some(x));
4717 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4719 None => return Ok(None),
4723 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4724 // expression without semicolon
4725 if classify::expr_requires_semi_to_be_stmt(expr) {
4726 // Just check for errors and recover; do not eat semicolon yet.
4728 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4731 self.recover_stmt();
4735 StmtKind::Local(..) => {
4736 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4737 if macro_legacy_warnings && self.token != token::Semi {
4738 self.warn_missing_semicolon();
4740 self.expect_one_of(&[], &[token::Semi])?;
4746 if self.eat(&token::Semi) {
4747 stmt = stmt.add_trailing_semicolon();
4750 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4754 fn warn_missing_semicolon(&self) {
4755 self.diagnostic().struct_span_warn(self.token.span, {
4756 &format!("expected `;`, found {}", self.this_token_descr())
4758 "This was erroneously allowed and will become a hard error in a future release"
4762 fn err_dotdotdot_syntax(&self, span: Span) {
4763 self.diagnostic().struct_span_err(span, {
4764 "unexpected token: `...`"
4766 span, "use `..` for an exclusive range", "..".to_owned(),
4767 Applicability::MaybeIncorrect
4769 span, "or `..=` for an inclusive range", "..=".to_owned(),
4770 Applicability::MaybeIncorrect
4774 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
4777 /// BOUND = TY_BOUND | LT_BOUND
4778 /// LT_BOUND = LIFETIME (e.g., `'a`)
4779 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4780 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
4782 fn parse_generic_bounds_common(&mut self,
4784 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4785 let mut bounds = Vec::new();
4786 let mut negative_bounds = Vec::new();
4787 let mut last_plus_span = None;
4788 let mut was_negative = false;
4790 // This needs to be synchronized with `TokenKind::can_begin_bound`.
4791 let is_bound_start = self.check_path() || self.check_lifetime() ||
4792 self.check(&token::Not) || // used for error reporting only
4793 self.check(&token::Question) ||
4794 self.check_keyword(kw::For) ||
4795 self.check(&token::OpenDelim(token::Paren));
4797 let lo = self.token.span;
4798 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4799 let inner_lo = self.token.span;
4800 let is_negative = self.eat(&token::Not);
4801 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4802 if self.token.is_lifetime() {
4803 if let Some(question_span) = question {
4804 self.span_err(question_span,
4805 "`?` may only modify trait bounds, not lifetime bounds");
4807 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4809 let inner_span = inner_lo.to(self.prev_span);
4810 self.expect(&token::CloseDelim(token::Paren))?;
4811 let mut err = self.struct_span_err(
4812 lo.to(self.prev_span),
4813 "parenthesized lifetime bounds are not supported"
4815 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
4816 err.span_suggestion_short(
4817 lo.to(self.prev_span),
4818 "remove the parentheses",
4820 Applicability::MachineApplicable
4826 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4827 let path = self.parse_path(PathStyle::Type)?;
4829 self.expect(&token::CloseDelim(token::Paren))?;
4831 let poly_span = lo.to(self.prev_span);
4833 was_negative = true;
4834 if let Some(sp) = last_plus_span.or(colon_span) {
4835 negative_bounds.push(sp.to(poly_span));
4838 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
4839 let modifier = if question.is_some() {
4840 TraitBoundModifier::Maybe
4842 TraitBoundModifier::None
4844 bounds.push(GenericBound::Trait(poly_trait, modifier));
4851 if !allow_plus || !self.eat_plus() {
4854 last_plus_span = Some(self.prev_span);
4858 if !negative_bounds.is_empty() || was_negative {
4859 let plural = negative_bounds.len() > 1;
4860 let last_span = negative_bounds.last().map(|sp| *sp);
4861 let mut err = self.struct_span_err(
4863 "negative trait bounds are not supported",
4865 if let Some(sp) = last_span {
4866 err.span_label(sp, "negative trait bounds are not supported");
4868 if let Some(bound_list) = colon_span {
4869 let bound_list = bound_list.to(self.prev_span);
4870 let mut new_bound_list = String::new();
4871 if !bounds.is_empty() {
4872 let mut snippets = bounds.iter().map(|bound| bound.span())
4873 .map(|span| self.sess.source_map().span_to_snippet(span));
4874 while let Some(Ok(snippet)) = snippets.next() {
4875 new_bound_list.push_str(" + ");
4876 new_bound_list.push_str(&snippet);
4878 new_bound_list = new_bound_list.replacen(" +", ":", 1);
4880 err.span_suggestion_hidden(
4882 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
4884 Applicability::MachineApplicable,
4893 crate fn parse_generic_bounds(&mut self,
4894 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4895 self.parse_generic_bounds_common(true, colon_span)
4898 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4901 /// BOUND = LT_BOUND (e.g., `'a`)
4903 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4904 let mut lifetimes = Vec::new();
4905 while self.check_lifetime() {
4906 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4908 if !self.eat_plus() {
4915 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
4916 fn parse_ty_param(&mut self,
4917 preceding_attrs: Vec<Attribute>)
4918 -> PResult<'a, GenericParam> {
4919 let ident = self.parse_ident()?;
4921 // Parse optional colon and param bounds.
4922 let bounds = if self.eat(&token::Colon) {
4923 self.parse_generic_bounds(Some(self.prev_span))?
4928 let default = if self.eat(&token::Eq) {
4929 Some(self.parse_ty()?)
4936 id: ast::DUMMY_NODE_ID,
4937 attrs: preceding_attrs.into(),
4939 kind: GenericParamKind::Type {
4945 /// Parses the following grammar:
4947 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4948 fn parse_trait_item_assoc_ty(&mut self)
4949 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4950 let ident = self.parse_ident()?;
4951 let mut generics = self.parse_generics()?;
4953 // Parse optional colon and param bounds.
4954 let bounds = if self.eat(&token::Colon) {
4955 self.parse_generic_bounds(None)?
4959 generics.where_clause = self.parse_where_clause()?;
4961 let default = if self.eat(&token::Eq) {
4962 Some(self.parse_ty()?)
4966 self.expect(&token::Semi)?;
4968 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4971 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
4972 self.expect_keyword(kw::Const)?;
4973 let ident = self.parse_ident()?;
4974 self.expect(&token::Colon)?;
4975 let ty = self.parse_ty()?;
4979 id: ast::DUMMY_NODE_ID,
4980 attrs: preceding_attrs.into(),
4982 kind: GenericParamKind::Const {
4988 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
4989 /// a trailing comma and erroneous trailing attributes.
4990 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4991 let mut params = Vec::new();
4993 let attrs = self.parse_outer_attributes()?;
4994 if self.check_lifetime() {
4995 let lifetime = self.expect_lifetime();
4996 // Parse lifetime parameter.
4997 let bounds = if self.eat(&token::Colon) {
4998 self.parse_lt_param_bounds()
5002 params.push(ast::GenericParam {
5003 ident: lifetime.ident,
5005 attrs: attrs.into(),
5007 kind: ast::GenericParamKind::Lifetime,
5009 } else if self.check_keyword(kw::Const) {
5010 // Parse const parameter.
5011 params.push(self.parse_const_param(attrs)?);
5012 } else if self.check_ident() {
5013 // Parse type parameter.
5014 params.push(self.parse_ty_param(attrs)?);
5016 // Check for trailing attributes and stop parsing.
5017 if !attrs.is_empty() {
5018 if !params.is_empty() {
5019 self.struct_span_err(
5021 &format!("trailing attribute after generic parameter"),
5023 .span_label(attrs[0].span, "attributes must go before parameters")
5026 self.struct_span_err(
5028 &format!("attribute without generic parameters"),
5032 "attributes are only permitted when preceding parameters",
5040 if !self.eat(&token::Comma) {
5047 /// Parses a set of optional generic type parameter declarations. Where
5048 /// clauses are not parsed here, and must be added later via
5049 /// `parse_where_clause()`.
5051 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5052 /// | ( < lifetimes , typaramseq ( , )? > )
5053 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5054 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5055 let span_lo = self.token.span;
5056 let (params, span) = if self.eat_lt() {
5057 let params = self.parse_generic_params()?;
5059 (params, span_lo.to(self.prev_span))
5061 (vec![], self.prev_span.between(self.token.span))
5065 where_clause: WhereClause {
5066 id: ast::DUMMY_NODE_ID,
5067 predicates: Vec::new(),
5074 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5075 /// For the purposes of understanding the parsing logic of generic arguments, this function
5076 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5077 /// had the correct amount of leading angle brackets.
5079 /// ```ignore (diagnostics)
5080 /// bar::<<<<T as Foo>::Output>();
5081 /// ^^ help: remove extra angle brackets
5083 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5087 ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5088 // We need to detect whether there are extra leading left angle brackets and produce an
5089 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5090 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5091 // then there won't be matching `>` tokens to find.
5093 // To explain how this detection works, consider the following example:
5095 // ```ignore (diagnostics)
5096 // bar::<<<<T as Foo>::Output>();
5097 // ^^ help: remove extra angle brackets
5100 // Parsing of the left angle brackets starts in this function. We start by parsing the
5101 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5104 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5105 // *Unmatched count:* 1
5106 // *`parse_path_segment` calls deep:* 0
5108 // This has the effect of recursing as this function is called if a `<` character
5109 // is found within the expected generic arguments:
5111 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5112 // *Unmatched count:* 2
5113 // *`parse_path_segment` calls deep:* 1
5115 // Eventually we will have recursed until having consumed all of the `<` tokens and
5116 // this will be reflected in the count:
5118 // *Upcoming tokens:* `T as Foo>::Output>;`
5119 // *Unmatched count:* 4
5120 // `parse_path_segment` calls deep:* 3
5122 // The parser will continue until reaching the first `>` - this will decrement the
5123 // unmatched angle bracket count and return to the parent invocation of this function
5124 // having succeeded in parsing:
5126 // *Upcoming tokens:* `::Output>;`
5127 // *Unmatched count:* 3
5128 // *`parse_path_segment` calls deep:* 2
5130 // This will continue until the next `>` character which will also return successfully
5131 // to the parent invocation of this function and decrement the count:
5133 // *Upcoming tokens:* `;`
5134 // *Unmatched count:* 2
5135 // *`parse_path_segment` calls deep:* 1
5137 // At this point, this function will expect to find another matching `>` character but
5138 // won't be able to and will return an error. This will continue all the way up the
5139 // call stack until the first invocation:
5141 // *Upcoming tokens:* `;`
5142 // *Unmatched count:* 2
5143 // *`parse_path_segment` calls deep:* 0
5145 // In doing this, we have managed to work out how many unmatched leading left angle
5146 // brackets there are, but we cannot recover as the unmatched angle brackets have
5147 // already been consumed. To remedy this, we keep a snapshot of the parser state
5148 // before we do the above. We can then inspect whether we ended up with a parsing error
5149 // and unmatched left angle brackets and if so, restore the parser state before we
5150 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5151 // recover by attempting to parse again.
5153 // In practice, the recursion of this function is indirect and there will be other
5154 // locations that consume some `<` characters - as long as we update the count when
5155 // this happens, it isn't an issue.
5157 let is_first_invocation = style == PathStyle::Expr;
5158 // Take a snapshot before attempting to parse - we can restore this later.
5159 let snapshot = if is_first_invocation {
5165 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5166 match self.parse_generic_args() {
5167 Ok(value) => Ok(value),
5168 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5169 // Cancel error from being unable to find `>`. We know the error
5170 // must have been this due to a non-zero unmatched angle bracket
5174 // Swap `self` with our backup of the parser state before attempting to parse
5175 // generic arguments.
5176 let snapshot = mem::replace(self, snapshot.unwrap());
5179 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5180 snapshot.count={:?}",
5181 snapshot.unmatched_angle_bracket_count,
5184 // Eat the unmatched angle brackets.
5185 for _ in 0..snapshot.unmatched_angle_bracket_count {
5189 // Make a span over ${unmatched angle bracket count} characters.
5190 let span = lo.with_hi(
5191 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5193 let plural = snapshot.unmatched_angle_bracket_count > 1;
5198 "unmatched angle bracket{}",
5199 if plural { "s" } else { "" }
5205 "remove extra angle bracket{}",
5206 if plural { "s" } else { "" }
5209 Applicability::MachineApplicable,
5213 // Try again without unmatched angle bracket characters.
5214 self.parse_generic_args()
5220 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5221 /// possibly including trailing comma.
5222 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5223 let mut args = Vec::new();
5224 let mut constraints = Vec::new();
5225 let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new();
5226 let mut assoc_ty_constraints: Vec<Span> = Vec::new();
5228 let args_lo = self.token.span;
5231 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5232 // Parse lifetime argument.
5233 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5234 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5235 } else if self.check_ident() && self.look_ahead(1,
5236 |t| t == &token::Eq || t == &token::Colon) {
5237 // Parse associated type constraint.
5238 let lo = self.token.span;
5239 let ident = self.parse_ident()?;
5240 let kind = if self.eat(&token::Eq) {
5241 AssocTyConstraintKind::Equality {
5242 ty: self.parse_ty()?,
5244 } else if self.eat(&token::Colon) {
5245 AssocTyConstraintKind::Bound {
5246 bounds: self.parse_generic_bounds(Some(self.prev_span))?,
5251 let span = lo.to(self.prev_span);
5252 constraints.push(AssocTyConstraint {
5253 id: ast::DUMMY_NODE_ID,
5258 assoc_ty_constraints.push(span);
5259 } else if self.check_const_arg() {
5260 // Parse const argument.
5261 let expr = if let token::OpenDelim(token::Brace) = self.token.kind {
5262 self.parse_block_expr(
5263 None, self.token.span, BlockCheckMode::Default, ThinVec::new()
5265 } else if self.token.is_ident() {
5266 // FIXME(const_generics): to distinguish between idents for types and consts,
5267 // we should introduce a GenericArg::Ident in the AST and distinguish when
5268 // lowering to the HIR. For now, idents for const args are not permitted.
5269 if self.token.is_keyword(kw::True) || self.token.is_keyword(kw::False) {
5270 self.parse_literal_maybe_minus()?
5273 self.fatal("identifiers may currently not be used for const generics")
5277 self.parse_literal_maybe_minus()?
5279 let value = AnonConst {
5280 id: ast::DUMMY_NODE_ID,
5283 args.push(GenericArg::Const(value));
5284 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5285 } else if self.check_type() {
5286 // Parse type argument.
5287 args.push(GenericArg::Type(self.parse_ty()?));
5288 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5293 if !self.eat(&token::Comma) {
5298 // FIXME: we would like to report this in ast_validation instead, but we currently do not
5299 // preserve ordering of generic parameters with respect to associated type binding, so we
5300 // lose that information after parsing.
5301 if misplaced_assoc_ty_constraints.len() > 0 {
5302 let mut err = self.struct_span_err(
5303 args_lo.to(self.prev_span),
5304 "associated type bindings must be declared after generic parameters",
5306 for span in misplaced_assoc_ty_constraints {
5309 "this associated type binding should be moved after the generic parameters",
5315 Ok((args, constraints))
5318 /// Parses an optional where-clause and places it in `generics`.
5320 /// ```ignore (only-for-syntax-highlight)
5321 /// where T : Trait<U, V> + 'b, 'a : 'b
5323 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5324 let mut where_clause = WhereClause {
5325 id: ast::DUMMY_NODE_ID,
5326 predicates: Vec::new(),
5327 span: self.prev_span.to(self.prev_span),
5330 if !self.eat_keyword(kw::Where) {
5331 return Ok(where_clause);
5333 let lo = self.prev_span;
5335 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5336 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5337 // change we parse those generics now, but report an error.
5338 if self.choose_generics_over_qpath() {
5339 let generics = self.parse_generics()?;
5340 self.struct_span_err(
5342 "generic parameters on `where` clauses are reserved for future use",
5344 .span_label(generics.span, "currently unsupported")
5349 let lo = self.token.span;
5350 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5351 let lifetime = self.expect_lifetime();
5352 // Bounds starting with a colon are mandatory, but possibly empty.
5353 self.expect(&token::Colon)?;
5354 let bounds = self.parse_lt_param_bounds();
5355 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5356 ast::WhereRegionPredicate {
5357 span: lo.to(self.prev_span),
5362 } else if self.check_type() {
5363 // Parse optional `for<'a, 'b>`.
5364 // This `for` is parsed greedily and applies to the whole predicate,
5365 // the bounded type can have its own `for` applying only to it.
5367 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
5368 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
5369 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
5370 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5372 // Parse type with mandatory colon and (possibly empty) bounds,
5373 // or with mandatory equality sign and the second type.
5374 let ty = self.parse_ty()?;
5375 if self.eat(&token::Colon) {
5376 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
5377 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5378 ast::WhereBoundPredicate {
5379 span: lo.to(self.prev_span),
5380 bound_generic_params: lifetime_defs,
5385 // FIXME: Decide what should be used here, `=` or `==`.
5386 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5387 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5388 let rhs_ty = self.parse_ty()?;
5389 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5390 ast::WhereEqPredicate {
5391 span: lo.to(self.prev_span),
5394 id: ast::DUMMY_NODE_ID,
5398 return self.unexpected();
5404 if !self.eat(&token::Comma) {
5409 where_clause.span = lo.to(self.prev_span);
5413 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
5414 -> PResult<'a, (Vec<Arg> , bool)> {
5415 self.expect(&token::OpenDelim(token::Paren))?;
5417 let sp = self.token.span;
5418 let mut c_variadic = false;
5419 let (args, recovered): (Vec<Option<Arg>>, bool) =
5420 self.parse_seq_to_before_end(
5421 &token::CloseDelim(token::Paren),
5422 SeqSep::trailing_allowed(token::Comma),
5424 let do_not_enforce_named_arguments_for_c_variadic =
5425 |token: &token::Token| -> bool {
5426 if token == &token::DotDotDot {
5432 match p.parse_arg_general(
5435 do_not_enforce_named_arguments_for_c_variadic
5438 if let TyKind::CVarArgs = arg.ty.node {
5440 if p.token != token::CloseDelim(token::Paren) {
5441 let span = p.token.span;
5443 "`...` must be the last argument of a C-variadic function");
5454 let lo = p.prev_span;
5455 // Skip every token until next possible arg or end.
5456 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5457 // Create a placeholder argument for proper arg count (issue #34264).
5458 let span = lo.to(p.prev_span);
5459 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
5466 self.eat(&token::CloseDelim(token::Paren));
5469 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5471 if c_variadic && args.is_empty() {
5473 "C-variadic function must be declared with at least one named argument");
5476 Ok((args, c_variadic))
5479 /// Parses the argument list and result type of a function declaration.
5480 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
5481 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
5482 let ret_ty = self.parse_ret_ty(true)?;
5491 /// Returns the parsed optional self argument and whether a self shortcut was used.
5493 /// See `parse_self_arg_with_attrs` to collect attributes.
5494 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5495 let expect_ident = |this: &mut Self| match this.token.kind {
5496 // Preserve hygienic context.
5497 token::Ident(name, _) =>
5498 { let span = this.token.span; this.bump(); Ident::new(name, span) }
5501 let isolated_self = |this: &mut Self, n| {
5502 this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
5503 this.look_ahead(n + 1, |t| t != &token::ModSep)
5506 // Parse optional `self` parameter of a method.
5507 // Only a limited set of initial token sequences is considered `self` parameters; anything
5508 // else is parsed as a normal function parameter list, so some lookahead is required.
5509 let eself_lo = self.token.span;
5510 let (eself, eself_ident, eself_hi) = match self.token.kind {
5511 token::BinOp(token::And) => {
5517 (if isolated_self(self, 1) {
5519 SelfKind::Region(None, Mutability::Immutable)
5520 } else if self.is_keyword_ahead(1, &[kw::Mut]) &&
5521 isolated_self(self, 2) {
5524 SelfKind::Region(None, Mutability::Mutable)
5525 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5526 isolated_self(self, 2) {
5528 let lt = self.expect_lifetime();
5529 SelfKind::Region(Some(lt), Mutability::Immutable)
5530 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5531 self.is_keyword_ahead(2, &[kw::Mut]) &&
5532 isolated_self(self, 3) {
5534 let lt = self.expect_lifetime();
5536 SelfKind::Region(Some(lt), Mutability::Mutable)
5539 }, expect_ident(self), self.prev_span)
5541 token::BinOp(token::Star) => {
5546 // Emit special error for `self` cases.
5547 let msg = "cannot pass `self` by raw pointer";
5548 (if isolated_self(self, 1) {
5550 self.struct_span_err(self.token.span, msg)
5551 .span_label(self.token.span, msg)
5553 SelfKind::Value(Mutability::Immutable)
5554 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5555 isolated_self(self, 2) {
5558 self.struct_span_err(self.token.span, msg)
5559 .span_label(self.token.span, msg)
5561 SelfKind::Value(Mutability::Immutable)
5564 }, expect_ident(self), self.prev_span)
5566 token::Ident(..) => {
5567 if isolated_self(self, 0) {
5570 let eself_ident = expect_ident(self);
5571 let eself_hi = self.prev_span;
5572 (if self.eat(&token::Colon) {
5573 let ty = self.parse_ty()?;
5574 SelfKind::Explicit(ty, Mutability::Immutable)
5576 SelfKind::Value(Mutability::Immutable)
5577 }, eself_ident, eself_hi)
5578 } else if self.token.is_keyword(kw::Mut) &&
5579 isolated_self(self, 1) {
5583 let eself_ident = expect_ident(self);
5584 let eself_hi = self.prev_span;
5585 (if self.eat(&token::Colon) {
5586 let ty = self.parse_ty()?;
5587 SelfKind::Explicit(ty, Mutability::Mutable)
5589 SelfKind::Value(Mutability::Mutable)
5590 }, eself_ident, eself_hi)
5595 _ => return Ok(None),
5598 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5599 Ok(Some(Arg::from_self(ThinVec::default(), eself, eself_ident)))
5602 /// Returns the parsed optional self argument with attributes and whether a self
5603 /// shortcut was used.
5604 fn parse_self_arg_with_attrs(&mut self) -> PResult<'a, Option<Arg>> {
5605 let attrs = self.parse_arg_attributes()?;
5606 let arg_opt = self.parse_self_arg()?;
5607 Ok(arg_opt.map(|mut arg| {
5608 arg.attrs = attrs.into();
5613 /// Parses the parameter list and result type of a function that may have a `self` parameter.
5614 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5615 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5617 self.expect(&token::OpenDelim(token::Paren))?;
5619 // Parse optional self argument.
5620 let self_arg = self.parse_self_arg_with_attrs()?;
5622 // Parse the rest of the function parameter list.
5623 let sep = SeqSep::trailing_allowed(token::Comma);
5624 let (mut fn_inputs, recovered) = if let Some(self_arg) = self_arg {
5625 if self.check(&token::CloseDelim(token::Paren)) {
5626 (vec![self_arg], false)
5627 } else if self.eat(&token::Comma) {
5628 let mut fn_inputs = vec![self_arg];
5629 let (mut input, recovered) = self.parse_seq_to_before_end(
5630 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
5631 fn_inputs.append(&mut input);
5632 (fn_inputs, recovered)
5634 match self.expect_one_of(&[], &[]) {
5635 Err(err) => return Err(err),
5636 Ok(recovered) => (vec![self_arg], recovered),
5640 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5644 // Parse closing paren and return type.
5645 self.expect(&token::CloseDelim(token::Paren))?;
5647 // Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
5648 self.deduplicate_recovered_arg_names(&mut fn_inputs);
5652 output: self.parse_ret_ty(true)?,
5657 /// Parses the `|arg, arg|` header of a closure.
5658 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5659 let inputs_captures = {
5660 if self.eat(&token::OrOr) {
5663 self.expect(&token::BinOp(token::Or))?;
5664 let args = self.parse_seq_to_before_tokens(
5665 &[&token::BinOp(token::Or), &token::OrOr],
5666 SeqSep::trailing_allowed(token::Comma),
5667 TokenExpectType::NoExpect,
5668 |p| p.parse_fn_block_arg()
5674 let output = self.parse_ret_ty(true)?;
5677 inputs: inputs_captures,
5683 /// Parses the name and optional generic types of a function header.
5684 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5685 let id = self.parse_ident()?;
5686 let generics = self.parse_generics()?;
5690 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5691 attrs: Vec<Attribute>) -> P<Item> {
5695 id: ast::DUMMY_NODE_ID,
5703 /// Parses an item-position function declaration.
5704 fn parse_item_fn(&mut self,
5706 asyncness: Spanned<IsAsync>,
5707 constness: Spanned<Constness>,
5709 -> PResult<'a, ItemInfo> {
5710 let (ident, mut generics) = self.parse_fn_header()?;
5711 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
5712 let decl = self.parse_fn_decl(allow_c_variadic)?;
5713 generics.where_clause = self.parse_where_clause()?;
5714 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5715 let header = FnHeader { unsafety, asyncness, constness, abi };
5716 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5719 /// Returns `true` if we are looking at `const ID`
5720 /// (returns `false` for things like `const fn`, etc.).
5721 fn is_const_item(&self) -> bool {
5722 self.token.is_keyword(kw::Const) &&
5723 !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
5726 /// Parses all the "front matter" for a `fn` declaration, up to
5727 /// and including the `fn` keyword:
5731 /// - `const unsafe fn`
5734 fn parse_fn_front_matter(&mut self)
5742 let is_const_fn = self.eat_keyword(kw::Const);
5743 let const_span = self.prev_span;
5744 let unsafety = self.parse_unsafety();
5745 let asyncness = self.parse_asyncness();
5746 let asyncness = respan(self.prev_span, asyncness);
5747 let (constness, unsafety, abi) = if is_const_fn {
5748 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5750 let abi = if self.eat_keyword(kw::Extern) {
5751 self.parse_opt_abi()?.unwrap_or(Abi::C)
5755 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5757 if !self.eat_keyword(kw::Fn) {
5758 // It is possible for `expect_one_of` to recover given the contents of
5759 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
5760 // account for this.
5761 if !self.expect_one_of(&[], &[])? { unreachable!() }
5763 Ok((constness, unsafety, asyncness, abi))
5766 /// Parses an impl item.
5767 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5768 maybe_whole!(self, NtImplItem, |x| x);
5769 let attrs = self.parse_outer_attributes()?;
5770 let mut unclosed_delims = vec![];
5771 let (mut item, tokens) = self.collect_tokens(|this| {
5772 let item = this.parse_impl_item_(at_end, attrs);
5773 unclosed_delims.append(&mut this.unclosed_delims);
5776 self.unclosed_delims.append(&mut unclosed_delims);
5778 // See `parse_item` for why this clause is here.
5779 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5780 item.tokens = Some(tokens);
5785 fn parse_impl_item_(&mut self,
5787 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5788 let lo = self.token.span;
5789 let vis = self.parse_visibility(false)?;
5790 let defaultness = self.parse_defaultness();
5791 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5792 let (name, alias, generics) = type_?;
5793 let kind = match alias {
5794 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5795 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5797 (name, kind, generics)
5798 } else if self.is_const_item() {
5799 // This parses the grammar:
5800 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5801 self.expect_keyword(kw::Const)?;
5802 let name = self.parse_ident()?;
5803 self.expect(&token::Colon)?;
5804 let typ = self.parse_ty()?;
5805 self.expect(&token::Eq)?;
5806 let expr = self.parse_expr()?;
5807 self.expect(&token::Semi)?;
5808 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5810 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5811 attrs.extend(inner_attrs);
5812 (name, node, generics)
5816 id: ast::DUMMY_NODE_ID,
5817 span: lo.to(self.prev_span),
5828 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
5830 VisibilityKind::Inherited => {}
5832 let mut err = if self.token.is_keyword(sym::macro_rules) {
5833 let mut err = self.diagnostic()
5834 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5835 err.span_suggestion(
5837 "try exporting the macro",
5838 "#[macro_export]".to_owned(),
5839 Applicability::MaybeIncorrect // speculative
5843 let mut err = self.diagnostic()
5844 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5845 err.help("try adjusting the macro to put `pub` inside the invocation");
5853 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
5854 -> DiagnosticBuilder<'a>
5856 let expected_kinds = if item_type == "extern" {
5857 "missing `fn`, `type`, or `static`"
5859 "missing `fn`, `type`, or `const`"
5862 // Given this code `path(`, it seems like this is not
5863 // setting the visibility of a macro invocation, but rather
5864 // a mistyped method declaration.
5865 // Create a diagnostic pointing out that `fn` is missing.
5867 // x | pub path(&self) {
5868 // | ^ missing `fn`, `type`, or `const`
5870 // ^^ `sp` below will point to this
5871 let sp = prev_span.between(self.prev_span);
5872 let mut err = self.diagnostic().struct_span_err(
5874 &format!("{} for {}-item declaration",
5875 expected_kinds, item_type));
5876 err.span_label(sp, expected_kinds);
5880 /// Parse a method or a macro invocation in a trait impl.
5881 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5882 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5883 ast::ImplItemKind)> {
5884 // code copied from parse_macro_use_or_failure... abstraction!
5885 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5887 Ok((Ident::invalid(), vec![], ast::Generics::default(),
5888 ast::ImplItemKind::Macro(mac)))
5890 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5891 let ident = self.parse_ident()?;
5892 let mut generics = self.parse_generics()?;
5893 let decl = self.parse_fn_decl_with_self(|p| {
5894 p.parse_arg_general(true, false, |_| true)
5896 generics.where_clause = self.parse_where_clause()?;
5898 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5899 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5900 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5901 ast::MethodSig { header, decl },
5907 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
5908 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5909 let ident = self.parse_ident()?;
5910 let mut tps = self.parse_generics()?;
5912 // Parse optional colon and supertrait bounds.
5913 let bounds = if self.eat(&token::Colon) {
5914 self.parse_generic_bounds(Some(self.prev_span))?
5919 if self.eat(&token::Eq) {
5920 // it's a trait alias
5921 let bounds = self.parse_generic_bounds(None)?;
5922 tps.where_clause = self.parse_where_clause()?;
5923 self.expect(&token::Semi)?;
5924 if is_auto == IsAuto::Yes {
5925 let msg = "trait aliases cannot be `auto`";
5926 self.struct_span_err(self.prev_span, msg)
5927 .span_label(self.prev_span, msg)
5930 if unsafety != Unsafety::Normal {
5931 let msg = "trait aliases cannot be `unsafe`";
5932 self.struct_span_err(self.prev_span, msg)
5933 .span_label(self.prev_span, msg)
5936 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5938 // it's a normal trait
5939 tps.where_clause = self.parse_where_clause()?;
5940 self.expect(&token::OpenDelim(token::Brace))?;
5941 let mut trait_items = vec![];
5942 while !self.eat(&token::CloseDelim(token::Brace)) {
5943 if let token::DocComment(_) = self.token.kind {
5944 if self.look_ahead(1,
5945 |tok| tok == &token::CloseDelim(token::Brace)) {
5946 let mut err = self.diagnostic().struct_span_err_with_code(
5948 "found a documentation comment that doesn't document anything",
5949 DiagnosticId::Error("E0584".into()),
5951 err.help("doc comments must come before what they document, maybe a \
5952 comment was intended with `//`?",
5959 let mut at_end = false;
5960 match self.parse_trait_item(&mut at_end) {
5961 Ok(item) => trait_items.push(item),
5965 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5970 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5974 fn choose_generics_over_qpath(&self) -> bool {
5975 // There's an ambiguity between generic parameters and qualified paths in impls.
5976 // If we see `<` it may start both, so we have to inspect some following tokens.
5977 // The following combinations can only start generics,
5978 // but not qualified paths (with one exception):
5979 // `<` `>` - empty generic parameters
5980 // `<` `#` - generic parameters with attributes
5981 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5982 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5983 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5984 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5985 // `<` const - generic const parameter
5986 // The only truly ambiguous case is
5987 // `<` IDENT `>` `::` IDENT ...
5988 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5989 // because this is what almost always expected in practice, qualified paths in impls
5990 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5991 self.token == token::Lt &&
5992 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5993 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5994 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5995 t == &token::Colon || t == &token::Eq) ||
5996 self.is_keyword_ahead(1, &[kw::Const]))
5999 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6000 self.expect(&token::OpenDelim(token::Brace))?;
6001 let attrs = self.parse_inner_attributes()?;
6003 let mut impl_items = Vec::new();
6004 while !self.eat(&token::CloseDelim(token::Brace)) {
6005 let mut at_end = false;
6006 match self.parse_impl_item(&mut at_end) {
6007 Ok(impl_item) => impl_items.push(impl_item),
6011 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6016 Ok((impl_items, attrs))
6019 /// Parses an implementation item, `impl` keyword is already parsed.
6021 /// impl<'a, T> TYPE { /* impl items */ }
6022 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6023 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6025 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6026 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6027 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6028 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6029 -> PResult<'a, ItemInfo> {
6030 // First, parse generic parameters if necessary.
6031 let mut generics = if self.choose_generics_over_qpath() {
6032 self.parse_generics()?
6034 ast::Generics::default()
6037 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6038 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6040 ast::ImplPolarity::Negative
6042 ast::ImplPolarity::Positive
6045 // Parse both types and traits as a type, then reinterpret if necessary.
6046 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
6047 let ty_first = if self.token.is_keyword(kw::For) &&
6048 self.look_ahead(1, |t| t != &token::Lt) {
6049 let span = self.prev_span.between(self.token.span);
6050 self.struct_span_err(span, "missing trait in a trait impl").emit();
6051 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6056 // If `for` is missing we try to recover.
6057 let has_for = self.eat_keyword(kw::For);
6058 let missing_for_span = self.prev_span.between(self.token.span);
6060 let ty_second = if self.token == token::DotDot {
6061 // We need to report this error after `cfg` expansion for compatibility reasons
6062 self.bump(); // `..`, do not add it to expected tokens
6063 Some(DummyResult::raw_ty(self.prev_span, true))
6064 } else if has_for || self.token.can_begin_type() {
6065 Some(self.parse_ty()?)
6070 generics.where_clause = self.parse_where_clause()?;
6072 let (impl_items, attrs) = self.parse_impl_body()?;
6074 let item_kind = match ty_second {
6075 Some(ty_second) => {
6076 // impl Trait for Type
6078 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6079 .span_suggestion_short(
6082 " for ".to_string(),
6083 Applicability::MachineApplicable,
6087 let ty_first = ty_first.into_inner();
6088 let path = match ty_first.node {
6089 // This notably includes paths passed through `ty` macro fragments (#46438).
6090 TyKind::Path(None, path) => path,
6092 self.span_err(ty_first.span, "expected a trait, found type");
6093 err_path(ty_first.span)
6096 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6098 ItemKind::Impl(unsafety, polarity, defaultness,
6099 generics, Some(trait_ref), ty_second, impl_items)
6103 ItemKind::Impl(unsafety, polarity, defaultness,
6104 generics, None, ty_first, impl_items)
6108 Ok((Ident::invalid(), item_kind, Some(attrs)))
6111 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6112 if self.eat_keyword(kw::For) {
6114 let params = self.parse_generic_params()?;
6116 // We rely on AST validation to rule out invalid cases: There must not be type
6117 // parameters, and the lifetime parameters must not have bounds.
6124 /// Parses `struct Foo { ... }`.
6125 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6126 let class_name = self.parse_ident()?;
6128 let mut generics = self.parse_generics()?;
6130 // There is a special case worth noting here, as reported in issue #17904.
6131 // If we are parsing a tuple struct it is the case that the where clause
6132 // should follow the field list. Like so:
6134 // struct Foo<T>(T) where T: Copy;
6136 // If we are parsing a normal record-style struct it is the case
6137 // that the where clause comes before the body, and after the generics.
6138 // So if we look ahead and see a brace or a where-clause we begin
6139 // parsing a record style struct.
6141 // Otherwise if we look ahead and see a paren we parse a tuple-style
6144 let vdata = if self.token.is_keyword(kw::Where) {
6145 generics.where_clause = self.parse_where_clause()?;
6146 if self.eat(&token::Semi) {
6147 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6148 VariantData::Unit(ast::DUMMY_NODE_ID)
6150 // If we see: `struct Foo<T> where T: Copy { ... }`
6151 let (fields, recovered) = self.parse_record_struct_body()?;
6152 VariantData::Struct(fields, recovered)
6154 // No `where` so: `struct Foo<T>;`
6155 } else if self.eat(&token::Semi) {
6156 VariantData::Unit(ast::DUMMY_NODE_ID)
6157 // Record-style struct definition
6158 } else if self.token == token::OpenDelim(token::Brace) {
6159 let (fields, recovered) = self.parse_record_struct_body()?;
6160 VariantData::Struct(fields, recovered)
6161 // Tuple-style struct definition with optional where-clause.
6162 } else if self.token == token::OpenDelim(token::Paren) {
6163 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6164 generics.where_clause = self.parse_where_clause()?;
6165 self.expect(&token::Semi)?;
6168 let token_str = self.this_token_descr();
6169 let mut err = self.fatal(&format!(
6170 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6173 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
6177 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6180 /// Parses `union Foo { ... }`.
6181 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6182 let class_name = self.parse_ident()?;
6184 let mut generics = self.parse_generics()?;
6186 let vdata = if self.token.is_keyword(kw::Where) {
6187 generics.where_clause = self.parse_where_clause()?;
6188 let (fields, recovered) = self.parse_record_struct_body()?;
6189 VariantData::Struct(fields, recovered)
6190 } else if self.token == token::OpenDelim(token::Brace) {
6191 let (fields, recovered) = self.parse_record_struct_body()?;
6192 VariantData::Struct(fields, recovered)
6194 let token_str = self.this_token_descr();
6195 let mut err = self.fatal(&format!(
6196 "expected `where` or `{{` after union name, found {}", token_str));
6197 err.span_label(self.token.span, "expected `where` or `{` after union name");
6201 Ok((class_name, ItemKind::Union(vdata, generics), None))
6204 fn parse_record_struct_body(
6206 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6207 let mut fields = Vec::new();
6208 let mut recovered = false;
6209 if self.eat(&token::OpenDelim(token::Brace)) {
6210 while self.token != token::CloseDelim(token::Brace) {
6211 let field = self.parse_struct_decl_field().map_err(|e| {
6212 self.recover_stmt();
6217 Ok(field) => fields.push(field),
6223 self.eat(&token::CloseDelim(token::Brace));
6225 let token_str = self.this_token_descr();
6226 let mut err = self.fatal(&format!(
6227 "expected `where`, or `{{` after struct name, found {}", token_str));
6228 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
6232 Ok((fields, recovered))
6235 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6236 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6237 // Unit like structs are handled in parse_item_struct function
6238 let fields = self.parse_unspanned_seq(
6239 &token::OpenDelim(token::Paren),
6240 &token::CloseDelim(token::Paren),
6241 SeqSep::trailing_allowed(token::Comma),
6243 let attrs = p.parse_outer_attributes()?;
6244 let lo = p.token.span;
6245 let vis = p.parse_visibility(true)?;
6246 let ty = p.parse_ty()?;
6248 span: lo.to(ty.span),
6251 id: ast::DUMMY_NODE_ID,
6260 /// Parses a structure field declaration.
6261 fn parse_single_struct_field(&mut self,
6264 attrs: Vec<Attribute> )
6265 -> PResult<'a, StructField> {
6266 let mut seen_comma: bool = false;
6267 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6268 if self.token == token::Comma {
6271 match self.token.kind {
6275 token::CloseDelim(token::Brace) => {}
6276 token::DocComment(_) => {
6277 let previous_span = self.prev_span;
6278 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
6279 self.bump(); // consume the doc comment
6280 let comma_after_doc_seen = self.eat(&token::Comma);
6281 // `seen_comma` is always false, because we are inside doc block
6282 // condition is here to make code more readable
6283 if seen_comma == false && comma_after_doc_seen == true {
6286 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6289 if seen_comma == false {
6290 let sp = self.sess.source_map().next_point(previous_span);
6291 err.span_suggestion(
6293 "missing comma here",
6295 Applicability::MachineApplicable
6302 let sp = self.sess.source_map().next_point(self.prev_span);
6303 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6304 self.this_token_descr()));
6305 if self.token.is_ident() {
6306 // This is likely another field; emit the diagnostic and keep going
6307 err.span_suggestion(
6309 "try adding a comma",
6311 Applicability::MachineApplicable,
6322 /// Parses an element of a struct declaration.
6323 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6324 let attrs = self.parse_outer_attributes()?;
6325 let lo = self.token.span;
6326 let vis = self.parse_visibility(false)?;
6327 self.parse_single_struct_field(lo, vis, attrs)
6330 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6331 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6332 /// If the following element can't be a tuple (i.e., it's a function definition), then
6333 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6334 /// so emit a proper diagnostic.
6335 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6336 maybe_whole!(self, NtVis, |x| x);
6338 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
6339 if self.is_crate_vis() {
6340 self.bump(); // `crate`
6341 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6344 if !self.eat_keyword(kw::Pub) {
6345 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6346 // keyword to grab a span from for inherited visibility; an empty span at the
6347 // beginning of the current token would seem to be the "Schelling span".
6348 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
6350 let lo = self.prev_span;
6352 if self.check(&token::OpenDelim(token::Paren)) {
6353 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6354 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6355 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6356 // by the following tokens.
6357 if self.is_keyword_ahead(1, &[kw::Crate]) &&
6358 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
6362 self.bump(); // `crate`
6363 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6365 lo.to(self.prev_span),
6366 VisibilityKind::Crate(CrateSugar::PubCrate),
6369 } else if self.is_keyword_ahead(1, &[kw::In]) {
6372 self.bump(); // `in`
6373 let path = self.parse_path(PathStyle::Mod)?; // `path`
6374 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6375 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6377 id: ast::DUMMY_NODE_ID,
6380 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6381 self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
6383 // `pub(self)` or `pub(super)`
6385 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6386 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6387 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6389 id: ast::DUMMY_NODE_ID,
6392 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6393 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6395 let msg = "incorrect visibility restriction";
6396 let suggestion = r##"some possible visibility restrictions are:
6397 `pub(crate)`: visible only on the current crate
6398 `pub(super)`: visible only in the current module's parent
6399 `pub(in path::to::module)`: visible only on the specified path"##;
6400 let path = self.parse_path(PathStyle::Mod)?;
6402 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6403 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6404 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6405 err.help(suggestion);
6406 err.span_suggestion(
6407 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6409 err.emit(); // emit diagnostic, but continue with public visibility
6413 Ok(respan(lo, VisibilityKind::Public))
6416 /// Parses defaultness (i.e., `default` or nothing).
6417 fn parse_defaultness(&mut self) -> Defaultness {
6418 // `pub` is included for better error messages
6419 if self.check_keyword(kw::Default) &&
6420 self.is_keyword_ahead(1, &[
6430 self.bump(); // `default`
6431 Defaultness::Default
6437 /// Given a termination token, parses all of the items in a module.
6438 fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
6439 let mut items = vec![];
6440 while let Some(item) = self.parse_item()? {
6442 self.maybe_consume_incorrect_semicolon(&items);
6445 if !self.eat(term) {
6446 let token_str = self.this_token_descr();
6447 if !self.maybe_consume_incorrect_semicolon(&items) {
6448 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6449 err.span_label(self.token.span, "expected item");
6454 let hi = if self.token.span.is_dummy() {
6461 inner: inner_lo.to(hi),
6467 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6468 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6469 self.expect(&token::Colon)?;
6470 let ty = self.parse_ty()?;
6471 self.expect(&token::Eq)?;
6472 let e = self.parse_expr()?;
6473 self.expect(&token::Semi)?;
6474 let item = match m {
6475 Some(m) => ItemKind::Static(ty, m, e),
6476 None => ItemKind::Const(ty, e),
6478 Ok((id, item, None))
6481 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6482 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6483 let (in_cfg, outer_attrs) = {
6484 let mut strip_unconfigured = crate::config::StripUnconfigured {
6486 features: None, // don't perform gated feature checking
6488 let mut outer_attrs = outer_attrs.to_owned();
6489 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
6490 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6493 let id_span = self.token.span;
6494 let id = self.parse_ident()?;
6495 if self.eat(&token::Semi) {
6496 if in_cfg && self.recurse_into_file_modules {
6497 // This mod is in an external file. Let's go get it!
6498 let ModulePathSuccess { path, directory_ownership, warn } =
6499 self.submod_path(id, &outer_attrs, id_span)?;
6500 let (module, mut attrs) =
6501 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6502 // Record that we fetched the mod from an external file
6504 let attr = Attribute {
6505 id: attr::mk_attr_id(),
6506 style: ast::AttrStyle::Outer,
6507 path: ast::Path::from_ident(
6508 Ident::with_empty_ctxt(sym::warn_directory_ownership)),
6509 tokens: TokenStream::empty(),
6510 is_sugared_doc: false,
6513 attr::mark_known(&attr);
6516 Ok((id, ItemKind::Mod(module), Some(attrs)))
6518 let placeholder = ast::Mod {
6523 Ok((id, ItemKind::Mod(placeholder), None))
6526 let old_directory = self.directory.clone();
6527 self.push_directory(id, &outer_attrs);
6529 self.expect(&token::OpenDelim(token::Brace))?;
6530 let mod_inner_lo = self.token.span;
6531 let attrs = self.parse_inner_attributes()?;
6532 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6534 self.directory = old_directory;
6535 Ok((id, ItemKind::Mod(module), Some(attrs)))
6539 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6540 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6541 self.directory.path.to_mut().push(&path.as_str());
6542 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6544 // We have to push on the current module name in the case of relative
6545 // paths in order to ensure that any additional module paths from inline
6546 // `mod x { ... }` come after the relative extension.
6548 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6549 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6550 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6551 if let Some(ident) = relative.take() { // remove the relative offset
6552 self.directory.path.to_mut().push(ident.as_str());
6555 self.directory.path.to_mut().push(&id.as_str());
6559 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6560 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6563 // On windows, the base path might have the form
6564 // `\\?\foo\bar` in which case it does not tolerate
6565 // mixed `/` and `\` separators, so canonicalize
6568 let s = s.replace("/", "\\");
6569 Some(dir_path.join(s))
6575 /// Returns a path to a module.
6576 pub fn default_submod_path(
6578 relative: Option<ast::Ident>,
6580 source_map: &SourceMap) -> ModulePath
6582 // If we're in a foo.rs file instead of a mod.rs file,
6583 // we need to look for submodules in
6584 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6585 // `./<id>.rs` and `./<id>/mod.rs`.
6586 let relative_prefix_string;
6587 let relative_prefix = if let Some(ident) = relative {
6588 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6589 &relative_prefix_string
6594 let mod_name = id.to_string();
6595 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6596 let secondary_path_str = format!("{}{}{}mod.rs",
6597 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6598 let default_path = dir_path.join(&default_path_str);
6599 let secondary_path = dir_path.join(&secondary_path_str);
6600 let default_exists = source_map.file_exists(&default_path);
6601 let secondary_exists = source_map.file_exists(&secondary_path);
6603 let result = match (default_exists, secondary_exists) {
6604 (true, false) => Ok(ModulePathSuccess {
6606 directory_ownership: DirectoryOwnership::Owned {
6611 (false, true) => Ok(ModulePathSuccess {
6612 path: secondary_path,
6613 directory_ownership: DirectoryOwnership::Owned {
6618 (false, false) => Err(Error::FileNotFoundForModule {
6619 mod_name: mod_name.clone(),
6620 default_path: default_path_str,
6621 secondary_path: secondary_path_str,
6622 dir_path: dir_path.display().to_string(),
6624 (true, true) => Err(Error::DuplicatePaths {
6625 mod_name: mod_name.clone(),
6626 default_path: default_path_str,
6627 secondary_path: secondary_path_str,
6633 path_exists: default_exists || secondary_exists,
6638 fn submod_path(&mut self,
6640 outer_attrs: &[Attribute],
6642 -> PResult<'a, ModulePathSuccess> {
6643 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6644 return Ok(ModulePathSuccess {
6645 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6646 // All `#[path]` files are treated as though they are a `mod.rs` file.
6647 // This means that `mod foo;` declarations inside `#[path]`-included
6648 // files are siblings,
6650 // Note that this will produce weirdness when a file named `foo.rs` is
6651 // `#[path]` included and contains a `mod foo;` declaration.
6652 // If you encounter this, it's your own darn fault :P
6653 Some(_) => DirectoryOwnership::Owned { relative: None },
6654 _ => DirectoryOwnership::UnownedViaMod(true),
6661 let relative = match self.directory.ownership {
6662 DirectoryOwnership::Owned { relative } => relative,
6663 DirectoryOwnership::UnownedViaBlock |
6664 DirectoryOwnership::UnownedViaMod(_) => None,
6666 let paths = Parser::default_submod_path(
6667 id, relative, &self.directory.path, self.sess.source_map());
6669 match self.directory.ownership {
6670 DirectoryOwnership::Owned { .. } => {
6671 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6673 DirectoryOwnership::UnownedViaBlock => {
6675 "Cannot declare a non-inline module inside a block \
6676 unless it has a path attribute";
6677 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6678 if paths.path_exists {
6679 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6681 err.span_note(id_sp, &msg);
6685 DirectoryOwnership::UnownedViaMod(warn) => {
6687 if let Ok(result) = paths.result {
6688 return Ok(ModulePathSuccess { warn: true, ..result });
6691 let mut err = self.diagnostic().struct_span_err(id_sp,
6692 "cannot declare a new module at this location");
6693 if !id_sp.is_dummy() {
6694 let src_path = self.sess.source_map().span_to_filename(id_sp);
6695 if let FileName::Real(src_path) = src_path {
6696 if let Some(stem) = src_path.file_stem() {
6697 let mut dest_path = src_path.clone();
6698 dest_path.set_file_name(stem);
6699 dest_path.push("mod.rs");
6700 err.span_note(id_sp,
6701 &format!("maybe move this module `{}` to its own \
6702 directory via `{}`", src_path.display(),
6703 dest_path.display()));
6707 if paths.path_exists {
6708 err.span_note(id_sp,
6709 &format!("... or maybe `use` the module `{}` instead \
6710 of possibly redeclaring it",
6718 /// Reads a module from a source file.
6719 fn eval_src_mod(&mut self,
6721 directory_ownership: DirectoryOwnership,
6724 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6725 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6726 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6727 let mut err = String::from("circular modules: ");
6728 let len = included_mod_stack.len();
6729 for p in &included_mod_stack[i.. len] {
6730 err.push_str(&p.to_string_lossy());
6731 err.push_str(" -> ");
6733 err.push_str(&path.to_string_lossy());
6734 return Err(self.span_fatal(id_sp, &err[..]));
6736 included_mod_stack.push(path.clone());
6737 drop(included_mod_stack);
6740 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6741 p0.cfg_mods = self.cfg_mods;
6742 let mod_inner_lo = p0.token.span;
6743 let mod_attrs = p0.parse_inner_attributes()?;
6744 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6746 self.sess.included_mod_stack.borrow_mut().pop();
6750 /// Parses a function declaration from a foreign module.
6751 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6752 -> PResult<'a, ForeignItem> {
6753 self.expect_keyword(kw::Fn)?;
6755 let (ident, mut generics) = self.parse_fn_header()?;
6756 let decl = self.parse_fn_decl(true)?;
6757 generics.where_clause = self.parse_where_clause()?;
6758 let hi = self.token.span;
6759 self.expect(&token::Semi)?;
6760 Ok(ast::ForeignItem {
6763 node: ForeignItemKind::Fn(decl, generics),
6764 id: ast::DUMMY_NODE_ID,
6770 /// Parses a static item from a foreign module.
6771 /// Assumes that the `static` keyword is already parsed.
6772 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6773 -> PResult<'a, ForeignItem> {
6774 let mutbl = self.parse_mutability();
6775 let ident = self.parse_ident()?;
6776 self.expect(&token::Colon)?;
6777 let ty = self.parse_ty()?;
6778 let hi = self.token.span;
6779 self.expect(&token::Semi)?;
6783 node: ForeignItemKind::Static(ty, mutbl),
6784 id: ast::DUMMY_NODE_ID,
6790 /// Parses a type from a foreign module.
6791 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6792 -> PResult<'a, ForeignItem> {
6793 self.expect_keyword(kw::Type)?;
6795 let ident = self.parse_ident()?;
6796 let hi = self.token.span;
6797 self.expect(&token::Semi)?;
6798 Ok(ast::ForeignItem {
6801 node: ForeignItemKind::Ty,
6802 id: ast::DUMMY_NODE_ID,
6808 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6809 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6810 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6812 let mut ident = if self.token.is_keyword(kw::SelfLower) {
6813 self.parse_path_segment_ident()
6817 let mut idents = vec![];
6818 let mut replacement = vec![];
6819 let mut fixed_crate_name = false;
6820 // Accept `extern crate name-like-this` for better diagnostics
6821 let dash = token::BinOp(token::BinOpToken::Minus);
6822 if self.token == dash { // Do not include `-` as part of the expected tokens list
6823 while self.eat(&dash) {
6824 fixed_crate_name = true;
6825 replacement.push((self.prev_span, "_".to_string()));
6826 idents.push(self.parse_ident()?);
6829 if fixed_crate_name {
6830 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6831 let mut fixed_name = format!("{}", ident.name);
6832 for part in idents {
6833 fixed_name.push_str(&format!("_{}", part.name));
6835 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6837 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6838 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6839 err.multipart_suggestion(
6842 Applicability::MachineApplicable,
6849 /// Parses `extern crate` links.
6854 /// extern crate foo;
6855 /// extern crate bar as foo;
6857 fn parse_item_extern_crate(&mut self,
6859 visibility: Visibility,
6860 attrs: Vec<Attribute>)
6861 -> PResult<'a, P<Item>> {
6862 // Accept `extern crate name-like-this` for better diagnostics
6863 let orig_name = self.parse_crate_name_with_dashes()?;
6864 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6865 (rename, Some(orig_name.name))
6869 self.expect(&token::Semi)?;
6871 let span = lo.to(self.prev_span);
6872 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6875 /// Parses `extern` for foreign ABIs modules.
6877 /// `extern` is expected to have been
6878 /// consumed before calling this method.
6882 /// ```ignore (only-for-syntax-highlight)
6886 fn parse_item_foreign_mod(&mut self,
6888 opt_abi: Option<Abi>,
6889 visibility: Visibility,
6890 mut attrs: Vec<Attribute>)
6891 -> PResult<'a, P<Item>> {
6892 self.expect(&token::OpenDelim(token::Brace))?;
6894 let abi = opt_abi.unwrap_or(Abi::C);
6896 attrs.extend(self.parse_inner_attributes()?);
6898 let mut foreign_items = vec![];
6899 while !self.eat(&token::CloseDelim(token::Brace)) {
6900 foreign_items.push(self.parse_foreign_item()?);
6903 let prev_span = self.prev_span;
6904 let m = ast::ForeignMod {
6906 items: foreign_items
6908 let invalid = Ident::invalid();
6909 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6912 /// Parses `type Foo = Bar;`
6914 /// `existential type Foo: Bar;`
6917 /// without modifying the parser state.
6918 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6919 // This parses the grammar:
6920 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6921 if self.check_keyword(kw::Type) ||
6922 self.check_keyword(kw::Existential) &&
6923 self.is_keyword_ahead(1, &[kw::Type]) {
6924 let existential = self.eat_keyword(kw::Existential);
6925 assert!(self.eat_keyword(kw::Type));
6926 Some(self.parse_existential_or_alias(existential))
6932 /// Parses a type alias or existential type.
6933 fn parse_existential_or_alias(
6936 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6937 let ident = self.parse_ident()?;
6938 let mut tps = self.parse_generics()?;
6939 tps.where_clause = self.parse_where_clause()?;
6940 let alias = if existential {
6941 self.expect(&token::Colon)?;
6942 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6943 AliasKind::Existential(bounds)
6945 self.expect(&token::Eq)?;
6946 let ty = self.parse_ty()?;
6949 self.expect(&token::Semi)?;
6950 Ok((ident, alias, tps))
6953 /// Parses the part of an enum declaration following the `{`.
6954 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6955 let mut variants = Vec::new();
6956 let mut any_disr = vec![];
6957 while self.token != token::CloseDelim(token::Brace) {
6958 let variant_attrs = self.parse_outer_attributes()?;
6959 let vlo = self.token.span;
6962 let mut disr_expr = None;
6964 let ident = self.parse_ident()?;
6965 if self.check(&token::OpenDelim(token::Brace)) {
6966 // Parse a struct variant.
6967 let (fields, recovered) = self.parse_record_struct_body()?;
6968 struct_def = VariantData::Struct(fields, recovered);
6969 } else if self.check(&token::OpenDelim(token::Paren)) {
6970 struct_def = VariantData::Tuple(
6971 self.parse_tuple_struct_body()?,
6974 } else if self.eat(&token::Eq) {
6975 disr_expr = Some(AnonConst {
6976 id: ast::DUMMY_NODE_ID,
6977 value: self.parse_expr()?,
6979 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
6982 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6984 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6987 let vr = ast::Variant_ {
6989 id: ast::DUMMY_NODE_ID,
6990 attrs: variant_attrs,
6994 variants.push(respan(vlo.to(self.prev_span), vr));
6996 if !self.eat(&token::Comma) {
6997 if self.token.is_ident() && !self.token.is_reserved_ident() {
6998 let sp = self.sess.source_map().next_point(self.prev_span);
6999 let mut err = self.struct_span_err(sp, "missing comma");
7000 err.span_suggestion_short(
7004 Applicability::MaybeIncorrect,
7012 self.expect(&token::CloseDelim(token::Brace))?;
7013 self.maybe_report_invalid_custom_discriminants(any_disr, &variants);
7015 Ok(ast::EnumDef { variants })
7018 /// Parses an enum declaration.
7019 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7020 let id = self.parse_ident()?;
7021 let mut generics = self.parse_generics()?;
7022 generics.where_clause = self.parse_where_clause()?;
7023 self.expect(&token::OpenDelim(token::Brace))?;
7025 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7026 self.recover_stmt();
7027 self.eat(&token::CloseDelim(token::Brace));
7030 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7033 /// Parses a string as an ABI spec on an extern type or module. Consumes
7034 /// the `extern` keyword, if one is found.
7035 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7036 match self.token.kind {
7037 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
7038 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
7039 let sp = self.token.span;
7040 self.expect_no_suffix(sp, "an ABI spec", suffix);
7042 match abi::lookup(&symbol.as_str()) {
7043 Some(abi) => Ok(Some(abi)),
7045 let prev_span = self.prev_span;
7046 let mut err = struct_span_err!(
7047 self.sess.span_diagnostic,
7050 "invalid ABI: found `{}`",
7052 err.span_label(prev_span, "invalid ABI");
7053 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7064 fn is_static_global(&mut self) -> bool {
7065 if self.check_keyword(kw::Static) {
7066 // Check if this could be a closure
7067 !self.look_ahead(1, |token| {
7068 if token.is_keyword(kw::Move) {
7072 token::BinOp(token::Or) | token::OrOr => true,
7083 attrs: Vec<Attribute>,
7084 macros_allowed: bool,
7085 attributes_allowed: bool,
7086 ) -> PResult<'a, Option<P<Item>>> {
7087 let mut unclosed_delims = vec![];
7088 let (ret, tokens) = self.collect_tokens(|this| {
7089 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7090 unclosed_delims.append(&mut this.unclosed_delims);
7093 self.unclosed_delims.append(&mut unclosed_delims);
7095 // Once we've parsed an item and recorded the tokens we got while
7096 // parsing we may want to store `tokens` into the item we're about to
7097 // return. Note, though, that we specifically didn't capture tokens
7098 // related to outer attributes. The `tokens` field here may later be
7099 // used with procedural macros to convert this item back into a token
7100 // stream, but during expansion we may be removing attributes as we go
7103 // If we've got inner attributes then the `tokens` we've got above holds
7104 // these inner attributes. If an inner attribute is expanded we won't
7105 // actually remove it from the token stream, so we'll just keep yielding
7106 // it (bad!). To work around this case for now we just avoid recording
7107 // `tokens` if we detect any inner attributes. This should help keep
7108 // expansion correct, but we should fix this bug one day!
7111 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7112 i.tokens = Some(tokens);
7119 /// Parses one of the items allowed by the flags.
7120 fn parse_item_implementation(
7122 attrs: Vec<Attribute>,
7123 macros_allowed: bool,
7124 attributes_allowed: bool,
7125 ) -> PResult<'a, Option<P<Item>>> {
7126 maybe_whole!(self, NtItem, |item| {
7127 let mut item = item.into_inner();
7128 let mut attrs = attrs;
7129 mem::swap(&mut item.attrs, &mut attrs);
7130 item.attrs.extend(attrs);
7134 let lo = self.token.span;
7136 let visibility = self.parse_visibility(false)?;
7138 if self.eat_keyword(kw::Use) {
7140 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7141 self.expect(&token::Semi)?;
7143 let span = lo.to(self.prev_span);
7145 self.mk_item(span, Ident::invalid(), item_, visibility, attrs);
7146 return Ok(Some(item));
7149 if self.eat_keyword(kw::Extern) {
7150 if self.eat_keyword(kw::Crate) {
7151 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7154 let opt_abi = self.parse_opt_abi()?;
7156 if self.eat_keyword(kw::Fn) {
7157 // EXTERN FUNCTION ITEM
7158 let fn_span = self.prev_span;
7159 let abi = opt_abi.unwrap_or(Abi::C);
7160 let (ident, item_, extra_attrs) =
7161 self.parse_item_fn(Unsafety::Normal,
7162 respan(fn_span, IsAsync::NotAsync),
7163 respan(fn_span, Constness::NotConst),
7165 let prev_span = self.prev_span;
7166 let item = self.mk_item(lo.to(prev_span),
7170 maybe_append(attrs, extra_attrs));
7171 return Ok(Some(item));
7172 } else if self.check(&token::OpenDelim(token::Brace)) {
7173 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7179 if self.is_static_global() {
7182 let m = if self.eat_keyword(kw::Mut) {
7185 Mutability::Immutable
7187 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7188 let prev_span = self.prev_span;
7189 let item = self.mk_item(lo.to(prev_span),
7193 maybe_append(attrs, extra_attrs));
7194 return Ok(Some(item));
7196 if self.eat_keyword(kw::Const) {
7197 let const_span = self.prev_span;
7198 if self.check_keyword(kw::Fn)
7199 || (self.check_keyword(kw::Unsafe)
7200 && self.is_keyword_ahead(1, &[kw::Fn])) {
7201 // CONST FUNCTION ITEM
7202 let unsafety = self.parse_unsafety();
7204 let (ident, item_, extra_attrs) =
7205 self.parse_item_fn(unsafety,
7206 respan(const_span, IsAsync::NotAsync),
7207 respan(const_span, Constness::Const),
7209 let prev_span = self.prev_span;
7210 let item = self.mk_item(lo.to(prev_span),
7214 maybe_append(attrs, extra_attrs));
7215 return Ok(Some(item));
7219 if self.eat_keyword(kw::Mut) {
7220 let prev_span = self.prev_span;
7221 let mut err = self.diagnostic()
7222 .struct_span_err(prev_span, "const globals cannot be mutable");
7223 err.span_label(prev_span, "cannot be mutable");
7224 err.span_suggestion(
7226 "you might want to declare a static instead",
7227 "static".to_owned(),
7228 Applicability::MaybeIncorrect,
7232 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7233 let prev_span = self.prev_span;
7234 let item = self.mk_item(lo.to(prev_span),
7238 maybe_append(attrs, extra_attrs));
7239 return Ok(Some(item));
7242 // Parse `async unsafe? fn`.
7243 if self.check_keyword(kw::Async) {
7244 let async_span = self.token.span;
7245 if self.is_keyword_ahead(1, &[kw::Fn])
7246 || self.is_keyword_ahead(2, &[kw::Fn])
7248 // ASYNC FUNCTION ITEM
7249 self.bump(); // `async`
7250 let unsafety = self.parse_unsafety(); // `unsafe`?
7251 self.expect_keyword(kw::Fn)?; // `fn`
7252 let fn_span = self.prev_span;
7253 let (ident, item_, extra_attrs) =
7254 self.parse_item_fn(unsafety,
7255 respan(async_span, IsAsync::Async {
7256 closure_id: ast::DUMMY_NODE_ID,
7257 return_impl_trait_id: ast::DUMMY_NODE_ID,
7259 respan(fn_span, Constness::NotConst),
7261 let prev_span = self.prev_span;
7262 let item = self.mk_item(lo.to(prev_span),
7266 maybe_append(attrs, extra_attrs));
7267 if self.token.span.rust_2015() {
7268 self.diagnostic().struct_span_err_with_code(
7270 "`async fn` is not permitted in the 2015 edition",
7271 DiagnosticId::Error("E0670".into())
7274 return Ok(Some(item));
7277 if self.check_keyword(kw::Unsafe) &&
7278 self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
7280 // UNSAFE TRAIT ITEM
7281 self.bump(); // `unsafe`
7282 let is_auto = if self.eat_keyword(kw::Trait) {
7285 self.expect_keyword(kw::Auto)?;
7286 self.expect_keyword(kw::Trait)?;
7289 let (ident, item_, extra_attrs) =
7290 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7291 let prev_span = self.prev_span;
7292 let item = self.mk_item(lo.to(prev_span),
7296 maybe_append(attrs, extra_attrs));
7297 return Ok(Some(item));
7299 if self.check_keyword(kw::Impl) ||
7300 self.check_keyword(kw::Unsafe) &&
7301 self.is_keyword_ahead(1, &[kw::Impl]) ||
7302 self.check_keyword(kw::Default) &&
7303 self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) {
7305 let defaultness = self.parse_defaultness();
7306 let unsafety = self.parse_unsafety();
7307 self.expect_keyword(kw::Impl)?;
7308 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7309 let span = lo.to(self.prev_span);
7310 return Ok(Some(self.mk_item(span, ident, item, visibility,
7311 maybe_append(attrs, extra_attrs))));
7313 if self.check_keyword(kw::Fn) {
7316 let fn_span = self.prev_span;
7317 let (ident, item_, extra_attrs) =
7318 self.parse_item_fn(Unsafety::Normal,
7319 respan(fn_span, IsAsync::NotAsync),
7320 respan(fn_span, Constness::NotConst),
7322 let prev_span = self.prev_span;
7323 let item = self.mk_item(lo.to(prev_span),
7327 maybe_append(attrs, extra_attrs));
7328 return Ok(Some(item));
7330 if self.check_keyword(kw::Unsafe)
7331 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7332 // UNSAFE FUNCTION ITEM
7333 self.bump(); // `unsafe`
7334 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7335 self.check(&token::OpenDelim(token::Brace));
7336 let abi = if self.eat_keyword(kw::Extern) {
7337 self.parse_opt_abi()?.unwrap_or(Abi::C)
7341 self.expect_keyword(kw::Fn)?;
7342 let fn_span = self.prev_span;
7343 let (ident, item_, extra_attrs) =
7344 self.parse_item_fn(Unsafety::Unsafe,
7345 respan(fn_span, IsAsync::NotAsync),
7346 respan(fn_span, Constness::NotConst),
7348 let prev_span = self.prev_span;
7349 let item = self.mk_item(lo.to(prev_span),
7353 maybe_append(attrs, extra_attrs));
7354 return Ok(Some(item));
7356 if self.eat_keyword(kw::Mod) {
7358 let (ident, item_, extra_attrs) =
7359 self.parse_item_mod(&attrs[..])?;
7360 let prev_span = self.prev_span;
7361 let item = self.mk_item(lo.to(prev_span),
7365 maybe_append(attrs, extra_attrs));
7366 return Ok(Some(item));
7368 if let Some(type_) = self.eat_type() {
7369 let (ident, alias, generics) = type_?;
7371 let item_ = match alias {
7372 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7373 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7375 let prev_span = self.prev_span;
7376 let item = self.mk_item(lo.to(prev_span),
7381 return Ok(Some(item));
7383 if self.eat_keyword(kw::Enum) {
7385 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7386 let prev_span = self.prev_span;
7387 let item = self.mk_item(lo.to(prev_span),
7391 maybe_append(attrs, extra_attrs));
7392 return Ok(Some(item));
7394 if self.check_keyword(kw::Trait)
7395 || (self.check_keyword(kw::Auto)
7396 && self.is_keyword_ahead(1, &[kw::Trait]))
7398 let is_auto = if self.eat_keyword(kw::Trait) {
7401 self.expect_keyword(kw::Auto)?;
7402 self.expect_keyword(kw::Trait)?;
7406 let (ident, item_, extra_attrs) =
7407 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7408 let prev_span = self.prev_span;
7409 let item = self.mk_item(lo.to(prev_span),
7413 maybe_append(attrs, extra_attrs));
7414 return Ok(Some(item));
7416 if self.eat_keyword(kw::Struct) {
7418 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7419 let prev_span = self.prev_span;
7420 let item = self.mk_item(lo.to(prev_span),
7424 maybe_append(attrs, extra_attrs));
7425 return Ok(Some(item));
7427 if self.is_union_item() {
7430 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7431 let prev_span = self.prev_span;
7432 let item = self.mk_item(lo.to(prev_span),
7436 maybe_append(attrs, extra_attrs));
7437 return Ok(Some(item));
7439 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7440 return Ok(Some(macro_def));
7443 // Verify whether we have encountered a struct or method definition where the user forgot to
7444 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7445 if visibility.node.is_pub() &&
7446 self.check_ident() &&
7447 self.look_ahead(1, |t| *t != token::Not)
7449 // Space between `pub` keyword and the identifier
7452 // ^^^ `sp` points here
7453 let sp = self.prev_span.between(self.token.span);
7454 let full_sp = self.prev_span.to(self.token.span);
7455 let ident_sp = self.token.span;
7456 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7457 // possible public struct definition where `struct` was forgotten
7458 let ident = self.parse_ident().unwrap();
7459 let msg = format!("add `struct` here to parse `{}` as a public struct",
7461 let mut err = self.diagnostic()
7462 .struct_span_err(sp, "missing `struct` for struct definition");
7463 err.span_suggestion_short(
7464 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7467 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7468 let ident = self.parse_ident().unwrap();
7470 let kw_name = if let Ok(Some(_)) = self.parse_self_arg_with_attrs() {
7475 self.consume_block(token::Paren);
7476 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7477 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7479 ("fn", kw_name, false)
7480 } else if self.check(&token::OpenDelim(token::Brace)) {
7482 ("fn", kw_name, false)
7483 } else if self.check(&token::Colon) {
7487 ("fn` or `struct", "function or struct", true)
7490 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7491 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7493 self.consume_block(token::Brace);
7494 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7498 err.span_suggestion_short(
7499 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7502 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7503 err.span_suggestion(
7505 "if you meant to call a macro, try",
7506 format!("{}!", snippet),
7507 // this is the `ambiguous` conditional branch
7508 Applicability::MaybeIncorrect
7511 err.help("if you meant to call a macro, remove the `pub` \
7512 and add a trailing `!` after the identifier");
7516 } else if self.look_ahead(1, |t| *t == token::Lt) {
7517 let ident = self.parse_ident().unwrap();
7518 self.eat_to_tokens(&[&token::Gt]);
7520 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7521 if let Ok(Some(_)) = self.parse_self_arg_with_attrs() {
7522 ("fn", "method", false)
7524 ("fn", "function", false)
7526 } else if self.check(&token::OpenDelim(token::Brace)) {
7527 ("struct", "struct", false)
7529 ("fn` or `struct", "function or struct", true)
7531 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7532 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7534 err.span_suggestion_short(
7536 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7537 format!(" {} ", kw),
7538 Applicability::MachineApplicable,
7544 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7547 /// Parses a foreign item.
7548 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7549 maybe_whole!(self, NtForeignItem, |ni| ni);
7551 let attrs = self.parse_outer_attributes()?;
7552 let lo = self.token.span;
7553 let visibility = self.parse_visibility(false)?;
7555 // FOREIGN STATIC ITEM
7556 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7557 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
7558 if self.token.is_keyword(kw::Const) {
7560 .struct_span_err(self.token.span, "extern items cannot be `const`")
7563 "try using a static value",
7564 "static".to_owned(),
7565 Applicability::MachineApplicable
7568 self.bump(); // `static` or `const`
7569 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7571 // FOREIGN FUNCTION ITEM
7572 if self.check_keyword(kw::Fn) {
7573 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7575 // FOREIGN TYPE ITEM
7576 if self.check_keyword(kw::Type) {
7577 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7580 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7584 ident: Ident::invalid(),
7585 span: lo.to(self.prev_span),
7586 id: ast::DUMMY_NODE_ID,
7589 node: ForeignItemKind::Macro(mac),
7594 if !attrs.is_empty() {
7595 self.expected_item_err(&attrs)?;
7603 /// This is the fall-through for parsing items.
7604 fn parse_macro_use_or_failure(
7606 attrs: Vec<Attribute> ,
7607 macros_allowed: bool,
7608 attributes_allowed: bool,
7610 visibility: Visibility
7611 ) -> PResult<'a, Option<P<Item>>> {
7612 if macros_allowed && self.token.is_path_start() &&
7613 !(self.is_async_fn() && self.token.span.rust_2015()) {
7614 // MACRO INVOCATION ITEM
7616 let prev_span = self.prev_span;
7617 self.complain_if_pub_macro(&visibility.node, prev_span);
7619 let mac_lo = self.token.span;
7622 let pth = self.parse_path(PathStyle::Mod)?;
7623 self.expect(&token::Not)?;
7625 // a 'special' identifier (like what `macro_rules!` uses)
7626 // is optional. We should eventually unify invoc syntax
7628 let id = if self.token.is_ident() {
7631 Ident::invalid() // no special identifier
7633 // eat a matched-delimiter token tree:
7634 let (delim, tts) = self.expect_delimited_token_tree()?;
7635 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
7636 self.report_invalid_macro_expansion_item();
7639 let hi = self.prev_span;
7640 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7641 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7642 return Ok(Some(item));
7645 // FAILURE TO PARSE ITEM
7646 match visibility.node {
7647 VisibilityKind::Inherited => {}
7649 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7653 if !attributes_allowed && !attrs.is_empty() {
7654 self.expected_item_err(&attrs)?;
7659 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
7660 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7661 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7663 if self.token.is_path_start() &&
7664 !(self.is_async_fn() && self.token.span.rust_2015()) {
7665 let prev_span = self.prev_span;
7666 let lo = self.token.span;
7667 let pth = self.parse_path(PathStyle::Mod)?;
7669 if pth.segments.len() == 1 {
7670 if !self.eat(&token::Not) {
7671 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7674 self.expect(&token::Not)?;
7677 if let Some(vis) = vis {
7678 self.complain_if_pub_macro(&vis.node, prev_span);
7683 // eat a matched-delimiter token tree:
7684 let (delim, tts) = self.expect_delimited_token_tree()?;
7685 if delim != MacDelimiter::Brace {
7686 self.expect(&token::Semi)?;
7689 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7695 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7696 where F: FnOnce(&mut Self) -> PResult<'a, R>
7698 // Record all tokens we parse when parsing this item.
7699 let mut tokens = Vec::new();
7700 let prev_collecting = match self.token_cursor.frame.last_token {
7701 LastToken::Collecting(ref mut list) => {
7702 Some(mem::replace(list, Vec::new()))
7704 LastToken::Was(ref mut last) => {
7705 tokens.extend(last.take());
7709 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7710 let prev = self.token_cursor.stack.len();
7712 let last_token = if self.token_cursor.stack.len() == prev {
7713 &mut self.token_cursor.frame.last_token
7715 &mut self.token_cursor.stack[prev].last_token
7718 // Pull out the tokens that we've collected from the call to `f` above.
7719 let mut collected_tokens = match *last_token {
7720 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7721 LastToken::Was(_) => panic!("our vector went away?"),
7724 // If we're not at EOF our current token wasn't actually consumed by
7725 // `f`, but it'll still be in our list that we pulled out. In that case
7727 let extra_token = if self.token != token::Eof {
7728 collected_tokens.pop()
7733 // If we were previously collecting tokens, then this was a recursive
7734 // call. In that case we need to record all the tokens we collected in
7735 // our parent list as well. To do that we push a clone of our stream
7736 // onto the previous list.
7737 match prev_collecting {
7739 list.extend(collected_tokens.iter().cloned());
7740 list.extend(extra_token);
7741 *last_token = LastToken::Collecting(list);
7744 *last_token = LastToken::Was(extra_token);
7748 Ok((ret?, TokenStream::new(collected_tokens)))
7751 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7752 let attrs = self.parse_outer_attributes()?;
7753 self.parse_item_(attrs, true, false)
7757 fn is_import_coupler(&mut self) -> bool {
7758 self.check(&token::ModSep) &&
7759 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7760 *t == token::BinOp(token::Star))
7763 /// Parses a `UseTree`.
7766 /// USE_TREE = [`::`] `*` |
7767 /// [`::`] `{` USE_TREE_LIST `}` |
7769 /// PATH `::` `{` USE_TREE_LIST `}` |
7770 /// PATH [`as` IDENT]
7772 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7773 let lo = self.token.span;
7775 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7776 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7777 self.check(&token::BinOp(token::Star)) ||
7778 self.is_import_coupler() {
7779 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7780 let mod_sep_ctxt = self.token.span.ctxt();
7781 if self.eat(&token::ModSep) {
7782 prefix.segments.push(
7783 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7787 if self.eat(&token::BinOp(token::Star)) {
7790 UseTreeKind::Nested(self.parse_use_tree_list()?)
7793 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7794 prefix = self.parse_path(PathStyle::Mod)?;
7796 if self.eat(&token::ModSep) {
7797 if self.eat(&token::BinOp(token::Star)) {
7800 UseTreeKind::Nested(self.parse_use_tree_list()?)
7803 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7807 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7810 /// Parses a `UseTreeKind::Nested(list)`.
7813 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7815 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7816 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7817 &token::CloseDelim(token::Brace),
7818 SeqSep::trailing_allowed(token::Comma), |this| {
7819 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7823 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7824 if self.eat_keyword(kw::As) {
7825 self.parse_ident_or_underscore().map(Some)
7831 /// Parses a source module as a crate. This is the main entry point for the parser.
7832 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7833 let lo = self.token.span;
7834 let krate = Ok(ast::Crate {
7835 attrs: self.parse_inner_attributes()?,
7836 module: self.parse_mod_items(&token::Eof, lo)?,
7837 span: lo.to(self.token.span),
7842 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7843 let ret = match self.token.kind {
7844 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
7845 (symbol, ast::StrStyle::Cooked, suffix),
7846 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
7847 (symbol, ast::StrStyle::Raw(n), suffix),
7854 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7855 match self.parse_optional_str() {
7856 Some((s, style, suf)) => {
7857 let sp = self.prev_span;
7858 self.expect_no_suffix(sp, "a string literal", suf);
7862 let msg = "expected string literal";
7863 let mut err = self.fatal(msg);
7864 err.span_label(self.token.span, msg);
7870 fn report_invalid_macro_expansion_item(&self) {
7871 self.struct_span_err(
7873 "macros that expand to items must be delimited with braces or followed by a semicolon",
7874 ).multipart_suggestion(
7875 "change the delimiters to curly braces",
7877 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
7878 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
7880 Applicability::MaybeIncorrect,
7882 self.sess.source_map.next_point(self.prev_span),
7885 Applicability::MaybeIncorrect,
7890 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
7891 for unmatched in unclosed_delims.iter() {
7892 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
7893 "incorrect close delimiter: `{}`",
7894 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
7896 err.span_label(unmatched.found_span, "incorrect close delimiter");
7897 if let Some(sp) = unmatched.candidate_span {
7898 err.span_label(sp, "close delimiter possibly meant for this");
7900 if let Some(sp) = unmatched.unclosed_span {
7901 err.span_label(sp, "un-closed delimiter");
7905 unclosed_delims.clear();