1 // ignore-tidy-filelength
3 use crate::ast::{AngleBracketedArgs, ParenthesizedArgs, AttrStyle, BareFnTy};
4 use crate::ast::{GenericBound, TraitBoundModifier};
5 use crate::ast::Unsafety;
6 use crate::ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind};
8 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
9 use crate::ast::{Constness, Crate};
10 use crate::ast::Defaultness;
11 use crate::ast::EnumDef;
12 use crate::ast::{Expr, ExprKind, RangeLimits};
13 use crate::ast::{Field, FnDecl, FnHeader};
14 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
15 use crate::ast::{GenericParam, GenericParamKind};
16 use crate::ast::GenericArg;
17 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
18 use crate::ast::{Label, Lifetime};
19 use crate::ast::Local;
20 use crate::ast::MacStmtStyle;
21 use crate::ast::{Mac, Mac_, MacDelimiter};
22 use crate::ast::{MutTy, Mutability};
23 use crate::ast::{Pat, PatKind, PathSegment};
24 use crate::ast::{PolyTraitRef, QSelf};
25 use crate::ast::{Stmt, StmtKind};
26 use crate::ast::{VariantData, StructField};
27 use crate::ast::StrStyle;
28 use crate::ast::SelfKind;
29 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
30 use crate::ast::{Ty, TyKind, AssocTyConstraint, AssocTyConstraintKind, GenericBounds};
31 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
32 use crate::ast::{UseTree, UseTreeKind};
33 use crate::ast::{BinOpKind, UnOp};
34 use crate::ast::{RangeEnd, RangeSyntax};
35 use crate::{ast, attr};
36 use crate::ext::base::DummyResult;
37 use crate::ext::hygiene::SyntaxContext;
38 use crate::source_map::{self, SourceMap, Spanned, respan};
39 use crate::parse::{SeqSep, classify, literal, token};
40 use crate::parse::lexer::UnmatchedBrace;
41 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
42 use crate::parse::token::{Token, TokenKind, DelimToken};
43 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
44 use crate::util::parser::{AssocOp, Fixity, prec_let_scrutinee_needs_par};
45 use crate::print::pprust;
47 use crate::parse::PResult;
49 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
50 use crate::symbol::{kw, sym, Symbol};
51 use crate::parse::diagnostics::{Error, dummy_arg};
53 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
54 use rustc_target::spec::abi::{self, Abi};
55 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
61 use std::path::{self, Path, PathBuf};
65 /// Whether the type alias or associated type is a concrete type or an existential type
67 /// Just a new name for the same type
69 /// Only trait impls of the type will be usable, not the actual type itself
70 Existential(GenericBounds),
74 struct Restrictions: u8 {
75 const STMT_EXPR = 1 << 0;
76 const NO_STRUCT_LITERAL = 1 << 1;
80 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
82 /// Specifies how to parse a path.
83 #[derive(Copy, Clone, PartialEq)]
85 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
86 /// with something else. For example, in expressions `segment < ....` can be interpreted
87 /// as a comparison and `segment ( ....` can be interpreted as a function call.
88 /// In all such contexts the non-path interpretation is preferred by default for practical
89 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
90 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
92 /// In other contexts, notably in types, no ambiguity exists and paths can be written
93 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
94 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
96 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
97 /// visibilities or attributes.
98 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
99 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
100 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
101 /// tokens when something goes wrong.
105 #[derive(Clone, Copy, PartialEq, Debug)]
106 crate enum SemiColonMode {
112 #[derive(Clone, Copy, PartialEq, Debug)]
113 crate enum BlockMode {
118 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
119 /// dropped into the token stream, which happens while parsing the result of
120 /// macro expansion). Placement of these is not as complex as I feared it would
121 /// be. The important thing is to make sure that lookahead doesn't balk at
122 /// `token::Interpolated` tokens.
123 macro_rules! maybe_whole_expr {
125 if let token::Interpolated(nt) = &$p.token.kind {
127 token::NtExpr(e) | token::NtLiteral(e) => {
132 token::NtPath(path) => {
133 let path = path.clone();
135 return Ok($p.mk_expr(
136 $p.token.span, ExprKind::Path(None, path), ThinVec::new()
139 token::NtBlock(block) => {
140 let block = block.clone();
142 return Ok($p.mk_expr(
143 $p.token.span, ExprKind::Block(block, None), ThinVec::new()
152 /// As maybe_whole_expr, but for things other than expressions
153 macro_rules! maybe_whole {
154 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
155 if let token::Interpolated(nt) = &$p.token.kind {
156 if let token::$constructor(x) = &**nt {
165 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
166 macro_rules! maybe_recover_from_interpolated_ty_qpath {
167 ($self: expr, $allow_qpath_recovery: expr) => {
168 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
169 if let token::Interpolated(nt) = &$self.token.kind {
170 if let token::NtTy(ty) = &**nt {
173 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
180 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
181 if let Some(ref mut rhs) = rhs {
187 #[derive(Debug, Clone, Copy, PartialEq)]
199 // NOTE: `Ident`s are handled by `common.rs`.
202 pub struct Parser<'a> {
203 pub sess: &'a ParseSess,
204 /// The current normalized token.
205 /// "Normalized" means that some interpolated tokens
206 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
207 /// with non-interpolated identifier and lifetime tokens they refer to.
208 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
210 /// Span of the current non-normalized token.
211 meta_var_span: Option<Span>,
212 /// Span of the previous non-normalized token.
214 /// Kind of the previous normalized token (in simplified form).
215 prev_token_kind: PrevTokenKind,
216 restrictions: Restrictions,
217 /// Used to determine the path to externally loaded source files.
218 crate directory: Directory<'a>,
219 /// `true` to parse sub-modules in other files.
220 pub recurse_into_file_modules: bool,
221 /// Name of the root module this parser originated from. If `None`, then the
222 /// name is not known. This does not change while the parser is descending
223 /// into modules, and sub-parsers have new values for this name.
224 pub root_module_name: Option<String>,
225 crate expected_tokens: Vec<TokenType>,
226 crate token_cursor: TokenCursor,
227 desugar_doc_comments: bool,
228 /// `true` we should configure out of line modules as we parse.
230 /// This field is used to keep track of how many left angle brackets we have seen. This is
231 /// required in order to detect extra leading left angle brackets (`<` characters) and error
234 /// See the comments in the `parse_path_segment` function for more details.
235 crate unmatched_angle_bracket_count: u32,
236 crate max_angle_bracket_count: u32,
237 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
238 /// it gets removed from here. Every entry left at the end gets emitted as an independent
240 crate unclosed_delims: Vec<UnmatchedBrace>,
241 crate last_unexpected_token_span: Option<Span>,
242 /// 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(span: 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, 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 })
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 macro_rules! parse_lit {
1999 match self.parse_lit() {
2001 hi = self.prev_span;
2002 ex = ExprKind::Lit(literal);
2005 self.cancel(&mut err);
2006 return Err(self.expected_expression_found());
2012 // Note: when adding new syntax here, don't forget to adjust TokenKind::can_begin_expr().
2013 match self.token.kind {
2014 // This match arm is a special-case of the `_` match arm below and
2015 // could be removed without changing functionality, but it's faster
2016 // to have it here, especially for programs with large constants.
2017 token::Literal(_) => {
2020 token::OpenDelim(token::Paren) => {
2023 attrs.extend(self.parse_inner_attributes()?);
2025 // (e) is parenthesized e
2026 // (e,) is a tuple with only one field, e
2027 let mut es = vec![];
2028 let mut trailing_comma = false;
2029 let mut recovered = false;
2030 while self.token != token::CloseDelim(token::Paren) {
2031 es.push(match self.parse_expr() {
2034 // recover from parse error in tuple list
2035 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2038 recovered = self.expect_one_of(
2040 &[token::Comma, token::CloseDelim(token::Paren)],
2042 if self.eat(&token::Comma) {
2043 trailing_comma = true;
2045 trailing_comma = false;
2053 hi = self.prev_span;
2054 ex = if es.len() == 1 && !trailing_comma {
2055 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2060 token::OpenDelim(token::Brace) => {
2061 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2063 token::BinOp(token::Or) | token::OrOr => {
2064 return self.parse_lambda_expr(attrs);
2066 token::OpenDelim(token::Bracket) => {
2069 attrs.extend(self.parse_inner_attributes()?);
2071 if self.eat(&token::CloseDelim(token::Bracket)) {
2073 ex = ExprKind::Array(Vec::new());
2076 let first_expr = self.parse_expr()?;
2077 if self.eat(&token::Semi) {
2078 // Repeating array syntax: [ 0; 512 ]
2079 let count = AnonConst {
2080 id: ast::DUMMY_NODE_ID,
2081 value: self.parse_expr()?,
2083 self.expect(&token::CloseDelim(token::Bracket))?;
2084 ex = ExprKind::Repeat(first_expr, count);
2085 } else if self.eat(&token::Comma) {
2086 // Vector with two or more elements.
2087 let remaining_exprs = self.parse_seq_to_end(
2088 &token::CloseDelim(token::Bracket),
2089 SeqSep::trailing_allowed(token::Comma),
2090 |p| Ok(p.parse_expr()?)
2092 let mut exprs = vec![first_expr];
2093 exprs.extend(remaining_exprs);
2094 ex = ExprKind::Array(exprs);
2096 // Vector with one element.
2097 self.expect(&token::CloseDelim(token::Bracket))?;
2098 ex = ExprKind::Array(vec![first_expr]);
2101 hi = self.prev_span;
2105 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2107 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2109 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
2110 return self.parse_lambda_expr(attrs);
2112 if self.eat_keyword(kw::If) {
2113 return self.parse_if_expr(attrs);
2115 if self.eat_keyword(kw::For) {
2116 let lo = self.prev_span;
2117 return self.parse_for_expr(None, lo, attrs);
2119 if self.eat_keyword(kw::While) {
2120 let lo = self.prev_span;
2121 return self.parse_while_expr(None, lo, attrs);
2123 if let Some(label) = self.eat_label() {
2124 let lo = label.ident.span;
2125 self.expect(&token::Colon)?;
2126 if self.eat_keyword(kw::While) {
2127 return self.parse_while_expr(Some(label), lo, attrs)
2129 if self.eat_keyword(kw::For) {
2130 return self.parse_for_expr(Some(label), lo, attrs)
2132 if self.eat_keyword(kw::Loop) {
2133 return self.parse_loop_expr(Some(label), lo, attrs)
2135 if self.token == token::OpenDelim(token::Brace) {
2136 return self.parse_block_expr(Some(label),
2138 BlockCheckMode::Default,
2141 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2142 let mut err = self.fatal(msg);
2143 err.span_label(self.token.span, msg);
2146 if self.eat_keyword(kw::Loop) {
2147 let lo = self.prev_span;
2148 return self.parse_loop_expr(None, lo, attrs);
2150 if self.eat_keyword(kw::Continue) {
2151 let label = self.eat_label();
2152 let ex = ExprKind::Continue(label);
2153 let hi = self.prev_span;
2154 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2156 if self.eat_keyword(kw::Match) {
2157 let match_sp = self.prev_span;
2158 return self.parse_match_expr(attrs).map_err(|mut err| {
2159 err.span_label(match_sp, "while parsing this match expression");
2163 if self.eat_keyword(kw::Unsafe) {
2164 return self.parse_block_expr(
2167 BlockCheckMode::Unsafe(ast::UserProvided),
2170 if self.is_do_catch_block() {
2171 let mut db = self.fatal("found removed `do catch` syntax");
2172 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2175 if self.is_try_block() {
2176 let lo = self.token.span;
2177 assert!(self.eat_keyword(kw::Try));
2178 return self.parse_try_block(lo, attrs);
2181 // Span::rust_2018() is somewhat expensive; don't get it repeatedly.
2182 let is_span_rust_2018 = self.token.span.rust_2018();
2183 if is_span_rust_2018 && self.check_keyword(kw::Async) {
2184 return if self.is_async_block() { // check for `async {` and `async move {`
2185 self.parse_async_block(attrs)
2187 self.parse_lambda_expr(attrs)
2190 if self.eat_keyword(kw::Return) {
2191 if self.token.can_begin_expr() {
2192 let e = self.parse_expr()?;
2194 ex = ExprKind::Ret(Some(e));
2196 ex = ExprKind::Ret(None);
2198 } else if self.eat_keyword(kw::Break) {
2199 let label = self.eat_label();
2200 let e = if self.token.can_begin_expr()
2201 && !(self.token == token::OpenDelim(token::Brace)
2202 && self.restrictions.contains(
2203 Restrictions::NO_STRUCT_LITERAL)) {
2204 Some(self.parse_expr()?)
2208 ex = ExprKind::Break(label, e);
2209 hi = self.prev_span;
2210 } else if self.eat_keyword(kw::Yield) {
2211 if self.token.can_begin_expr() {
2212 let e = self.parse_expr()?;
2214 ex = ExprKind::Yield(Some(e));
2216 ex = ExprKind::Yield(None);
2218 } else if self.eat_keyword(kw::Let) {
2219 return self.parse_let_expr(attrs);
2220 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
2221 let (await_hi, e_kind) = self.parse_await_macro_or_alt(lo, self.prev_span)?;
2224 } else if self.token.is_path_start() {
2225 let path = self.parse_path(PathStyle::Expr)?;
2227 // `!`, as an operator, is prefix, so we know this isn't that
2228 if self.eat(&token::Not) {
2229 // MACRO INVOCATION expression
2230 let (delim, tts) = self.expect_delimited_token_tree()?;
2231 hi = self.prev_span;
2232 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2233 } else if self.check(&token::OpenDelim(token::Brace)) {
2234 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2238 ex = ExprKind::Path(None, path);
2242 ex = ExprKind::Path(None, path);
2245 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2246 // Don't complain about bare semicolons after unclosed braces
2247 // recovery in order to keep the error count down. Fixing the
2248 // delimiters will possibly also fix the bare semicolon found in
2249 // expression context. For example, silence the following error:
2251 // error: expected expression, found `;`
2255 // | ^ expected expression
2258 return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()));
2265 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2266 self.maybe_recover_from_bad_qpath(expr, true)
2269 /// Parse `await!(<expr>)` calls, or alternatively recover from incorrect but reasonable
2270 /// alternative syntaxes `await <expr>`, `await? <expr>`, `await(<expr>)` and
2271 /// `await { <expr> }`.
2272 fn parse_await_macro_or_alt(
2276 ) -> PResult<'a, (Span, ExprKind)> {
2277 if self.token == token::Not {
2278 // Handle correct `await!(<expr>)`.
2279 // FIXME: make this an error when `await!` is no longer supported
2280 // https://github.com/rust-lang/rust/issues/60610
2281 self.expect(&token::Not)?;
2282 self.expect(&token::OpenDelim(token::Paren))?;
2283 let expr = self.parse_expr().map_err(|mut err| {
2284 err.span_label(await_sp, "while parsing this await macro call");
2287 self.expect(&token::CloseDelim(token::Paren))?;
2288 Ok((self.prev_span, ExprKind::Await(ast::AwaitOrigin::MacroLike, expr)))
2289 } else { // Handle `await <expr>`.
2290 self.parse_incorrect_await_syntax(lo, await_sp)
2294 fn maybe_parse_struct_expr(
2298 attrs: &ThinVec<Attribute>,
2299 ) -> Option<PResult<'a, P<Expr>>> {
2300 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2301 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2302 // `{ ident, ` cannot start a block
2303 self.look_ahead(2, |t| t == &token::Comma) ||
2304 self.look_ahead(2, |t| t == &token::Colon) && (
2305 // `{ ident: token, ` cannot start a block
2306 self.look_ahead(4, |t| t == &token::Comma) ||
2307 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2308 self.look_ahead(3, |t| !t.can_begin_type())
2312 if struct_allowed || certainly_not_a_block() {
2313 // This is a struct literal, but we don't can't accept them here
2314 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2315 if let (Ok(expr), false) = (&expr, struct_allowed) {
2316 let mut err = self.diagnostic().struct_span_err(
2318 "struct literals are not allowed here",
2320 err.multipart_suggestion(
2321 "surround the struct literal with parentheses",
2323 (lo.shrink_to_lo(), "(".to_string()),
2324 (expr.span.shrink_to_hi(), ")".to_string()),
2326 Applicability::MachineApplicable,
2335 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2336 -> PResult<'a, P<Expr>> {
2337 let struct_sp = lo.to(self.prev_span);
2339 let mut fields = Vec::new();
2340 let mut base = None;
2342 attrs.extend(self.parse_inner_attributes()?);
2344 while self.token != token::CloseDelim(token::Brace) {
2345 if self.eat(&token::DotDot) {
2346 let exp_span = self.prev_span;
2347 match self.parse_expr() {
2353 self.recover_stmt();
2356 if self.token == token::Comma {
2357 let mut err = self.sess.span_diagnostic.mut_span_err(
2358 exp_span.to(self.prev_span),
2359 "cannot use a comma after the base struct",
2361 err.span_suggestion_short(
2363 "remove this comma",
2365 Applicability::MachineApplicable
2367 err.note("the base struct must always be the last field");
2369 self.recover_stmt();
2374 let mut recovery_field = None;
2375 if let token::Ident(name, _) = self.token.kind {
2376 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2377 // Use in case of error after field-looking code: `S { foo: () with a }`
2378 recovery_field = Some(ast::Field {
2379 ident: Ident::new(name, self.token.span),
2380 span: self.token.span,
2381 expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
2382 is_shorthand: false,
2383 attrs: ThinVec::new(),
2387 let mut parsed_field = None;
2388 match self.parse_field() {
2389 Ok(f) => parsed_field = Some(f),
2391 e.span_label(struct_sp, "while parsing this struct");
2394 // If the next token is a comma, then try to parse
2395 // what comes next as additional fields, rather than
2396 // bailing out until next `}`.
2397 if self.token != token::Comma {
2398 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2399 if self.token != token::Comma {
2406 match self.expect_one_of(&[token::Comma],
2407 &[token::CloseDelim(token::Brace)]) {
2408 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2409 // only include the field if there's no parse error for the field name
2413 if let Some(f) = recovery_field {
2416 e.span_label(struct_sp, "while parsing this struct");
2418 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2419 self.eat(&token::Comma);
2424 let span = lo.to(self.token.span);
2425 self.expect(&token::CloseDelim(token::Brace))?;
2426 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2429 fn parse_or_use_outer_attributes(&mut self,
2430 already_parsed_attrs: Option<ThinVec<Attribute>>)
2431 -> PResult<'a, ThinVec<Attribute>> {
2432 if let Some(attrs) = already_parsed_attrs {
2435 self.parse_outer_attributes().map(|a| a.into())
2439 /// Parses a block or unsafe block.
2440 crate fn parse_block_expr(
2442 opt_label: Option<Label>,
2444 blk_mode: BlockCheckMode,
2445 outer_attrs: ThinVec<Attribute>,
2446 ) -> PResult<'a, P<Expr>> {
2447 self.expect(&token::OpenDelim(token::Brace))?;
2449 let mut attrs = outer_attrs;
2450 attrs.extend(self.parse_inner_attributes()?);
2452 let blk = self.parse_block_tail(lo, blk_mode)?;
2453 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2456 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2457 fn parse_dot_or_call_expr(&mut self,
2458 already_parsed_attrs: Option<ThinVec<Attribute>>)
2459 -> PResult<'a, P<Expr>> {
2460 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2462 let b = self.parse_bottom_expr();
2463 let (span, b) = self.interpolated_or_expr_span(b)?;
2464 self.parse_dot_or_call_expr_with(b, span, attrs)
2467 fn parse_dot_or_call_expr_with(&mut self,
2470 mut attrs: ThinVec<Attribute>)
2471 -> PResult<'a, P<Expr>> {
2472 // Stitch the list of outer attributes onto the return value.
2473 // A little bit ugly, but the best way given the current code
2475 self.parse_dot_or_call_expr_with_(e0, lo)
2477 expr.map(|mut expr| {
2478 attrs.extend::<Vec<_>>(expr.attrs.into());
2481 ExprKind::If(..) if !expr.attrs.is_empty() => {
2482 // Just point to the first attribute in there...
2483 let span = expr.attrs[0].span;
2486 "attributes are not yet allowed on `if` \
2496 // Assuming we have just parsed `.`, continue parsing into an expression.
2497 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2498 if self.token.span.rust_2018() && self.eat_keyword(kw::Await) {
2499 let span = lo.to(self.prev_span);
2500 let await_expr = self.mk_expr(
2502 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
2505 self.recover_from_await_method_call();
2506 return Ok(await_expr);
2508 let segment = self.parse_path_segment(PathStyle::Expr)?;
2509 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2511 Ok(match self.token.kind {
2512 token::OpenDelim(token::Paren) => {
2513 // Method call `expr.f()`
2514 let mut args = self.parse_unspanned_seq(
2515 &token::OpenDelim(token::Paren),
2516 &token::CloseDelim(token::Paren),
2517 SeqSep::trailing_allowed(token::Comma),
2518 |p| Ok(p.parse_expr()?)
2520 args.insert(0, self_arg);
2522 let span = lo.to(self.prev_span);
2523 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2526 // Field access `expr.f`
2527 if let Some(args) = segment.args {
2528 self.span_err(args.span(),
2529 "field expressions may not have generic arguments");
2532 let span = lo.to(self.prev_span);
2533 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2538 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2543 while self.eat(&token::Question) {
2544 let hi = self.prev_span;
2545 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2549 if self.eat(&token::Dot) {
2550 match self.token.kind {
2551 token::Ident(..) => {
2552 e = self.parse_dot_suffix(e, lo)?;
2554 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
2555 let span = self.token.span;
2557 let field = ExprKind::Field(e, Ident::new(symbol, span));
2558 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2560 self.expect_no_suffix(span, "a tuple index", suffix);
2562 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
2564 let fstr = symbol.as_str();
2565 let msg = format!("unexpected token: `{}`", symbol);
2566 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
2567 err.span_label(self.prev_span, "unexpected token");
2568 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2569 let float = match fstr.parse::<f64>().ok() {
2573 let sugg = pprust::to_string(|s| {
2574 use crate::print::pprust::PrintState;
2578 s.print_usize(float.trunc() as usize)?;
2581 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2583 err.span_suggestion(
2584 lo.to(self.prev_span),
2585 "try parenthesizing the first index",
2587 Applicability::MachineApplicable
2594 // FIXME Could factor this out into non_fatal_unexpected or something.
2595 let actual = self.this_token_to_string();
2596 self.span_err(self.token.span, &format!("unexpected token: `{}`", actual));
2601 if self.expr_is_complete(&e) { break; }
2602 match self.token.kind {
2604 token::OpenDelim(token::Paren) => {
2605 let seq = self.parse_unspanned_seq(
2606 &token::OpenDelim(token::Paren),
2607 &token::CloseDelim(token::Paren),
2608 SeqSep::trailing_allowed(token::Comma),
2609 |p| Ok(p.parse_expr()?)
2611 let nd = self.mk_call(e, es);
2612 let hi = self.prev_span;
2613 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2615 e = self.recover_seq_parse_error(token::Paren, lo, seq);
2619 // Could be either an index expression or a slicing expression.
2620 token::OpenDelim(token::Bracket) => {
2622 let ix = self.parse_expr()?;
2623 hi = self.token.span;
2624 self.expect(&token::CloseDelim(token::Bracket))?;
2625 let index = self.mk_index(e, ix);
2626 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2634 crate fn process_potential_macro_variable(&mut self) {
2635 self.token = match self.token.kind {
2636 token::Dollar if self.token.span.ctxt() != SyntaxContext::empty() &&
2637 self.look_ahead(1, |t| t.is_ident()) => {
2639 let name = match self.token.kind {
2640 token::Ident(name, _) => name,
2643 let span = self.prev_span.to(self.token.span);
2645 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
2646 .span_label(span, "unknown macro variable")
2651 token::Interpolated(ref nt) => {
2652 self.meta_var_span = Some(self.token.span);
2653 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2654 // and lifetime tokens, so the former are never encountered during normal parsing.
2656 token::NtIdent(ident, is_raw) =>
2657 Token::new(token::Ident(ident.name, is_raw), ident.span),
2658 token::NtLifetime(ident) =>
2659 Token::new(token::Lifetime(ident.name), ident.span),
2667 /// Parses a single token tree from the input.
2668 crate fn parse_token_tree(&mut self) -> TokenTree {
2669 match self.token.kind {
2670 token::OpenDelim(..) => {
2671 let frame = mem::replace(&mut self.token_cursor.frame,
2672 self.token_cursor.stack.pop().unwrap());
2673 self.token.span = frame.span.entire();
2675 TokenTree::Delimited(
2678 frame.tree_cursor.stream.into(),
2681 token::CloseDelim(_) | token::Eof => unreachable!(),
2683 let token = self.token.take();
2685 TokenTree::Token(token)
2690 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
2691 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2692 let mut tts = Vec::new();
2693 while self.token != token::Eof {
2694 tts.push(self.parse_token_tree());
2699 pub fn parse_tokens(&mut self) -> TokenStream {
2700 let mut result = Vec::new();
2702 match self.token.kind {
2703 token::Eof | token::CloseDelim(..) => break,
2704 _ => result.push(self.parse_token_tree().into()),
2707 TokenStream::new(result)
2710 /// Parse a prefix-unary-operator expr
2711 fn parse_prefix_expr(&mut self,
2712 already_parsed_attrs: Option<ThinVec<Attribute>>)
2713 -> PResult<'a, P<Expr>> {
2714 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2715 let lo = self.token.span;
2716 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
2717 let (hi, ex) = match self.token.kind {
2720 let e = self.parse_prefix_expr(None);
2721 let (span, e) = self.interpolated_or_expr_span(e)?;
2722 (lo.to(span), self.mk_unary(UnOp::Not, e))
2724 // Suggest `!` for bitwise negation when encountering a `~`
2727 let e = self.parse_prefix_expr(None);
2728 let (span, e) = self.interpolated_or_expr_span(e)?;
2729 let span_of_tilde = lo;
2730 let mut err = self.diagnostic()
2731 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2732 err.span_suggestion_short(
2734 "use `!` to perform bitwise negation",
2736 Applicability::MachineApplicable
2739 (lo.to(span), self.mk_unary(UnOp::Not, e))
2741 token::BinOp(token::Minus) => {
2743 let e = self.parse_prefix_expr(None);
2744 let (span, e) = self.interpolated_or_expr_span(e)?;
2745 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2747 token::BinOp(token::Star) => {
2749 let e = self.parse_prefix_expr(None);
2750 let (span, e) = self.interpolated_or_expr_span(e)?;
2751 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2753 token::BinOp(token::And) | token::AndAnd => {
2755 let m = self.parse_mutability();
2756 let e = self.parse_prefix_expr(None);
2757 let (span, e) = self.interpolated_or_expr_span(e)?;
2758 (lo.to(span), ExprKind::AddrOf(m, e))
2760 token::Ident(..) if self.token.is_keyword(kw::Box) => {
2762 let e = self.parse_prefix_expr(None);
2763 let (span, e) = self.interpolated_or_expr_span(e)?;
2764 (lo.to(span), ExprKind::Box(e))
2766 token::Ident(..) if self.token.is_ident_named(sym::not) => {
2767 // `not` is just an ordinary identifier in Rust-the-language,
2768 // but as `rustc`-the-compiler, we can issue clever diagnostics
2769 // for confused users who really want to say `!`
2770 let token_cannot_continue_expr = |t: &Token| match t.kind {
2771 // These tokens can start an expression after `!`, but
2772 // can't continue an expression after an ident
2773 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
2774 token::Literal(..) | token::Pound => true,
2775 token::Interpolated(ref nt) => match **nt {
2776 token::NtIdent(..) | token::NtExpr(..) |
2777 token::NtBlock(..) | token::NtPath(..) => true,
2782 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2783 if cannot_continue_expr {
2785 // Emit the error ...
2786 let mut err = self.diagnostic()
2787 .struct_span_err(self.token.span,
2788 &format!("unexpected {} after identifier",
2789 self.this_token_descr()));
2790 // span the `not` plus trailing whitespace to avoid
2791 // trailing whitespace after the `!` in our suggestion
2792 let to_replace = self.sess.source_map()
2793 .span_until_non_whitespace(lo.to(self.token.span));
2794 err.span_suggestion_short(
2796 "use `!` to perform logical negation",
2798 Applicability::MachineApplicable
2801 // —and recover! (just as if we were in the block
2802 // for the `token::Not` arm)
2803 let e = self.parse_prefix_expr(None);
2804 let (span, e) = self.interpolated_or_expr_span(e)?;
2805 (lo.to(span), self.mk_unary(UnOp::Not, e))
2807 return self.parse_dot_or_call_expr(Some(attrs));
2810 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2812 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2815 /// Parses an associative expression.
2817 /// This parses an expression accounting for associativity and precedence of the operators in
2820 fn parse_assoc_expr(&mut self,
2821 already_parsed_attrs: Option<ThinVec<Attribute>>)
2822 -> PResult<'a, P<Expr>> {
2823 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2826 /// Parses an associative expression with operators of at least `min_prec` precedence.
2827 fn parse_assoc_expr_with(&mut self,
2830 -> PResult<'a, P<Expr>> {
2831 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2834 let attrs = match lhs {
2835 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2838 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
2839 return self.parse_prefix_range_expr(attrs);
2841 self.parse_prefix_expr(attrs)?
2845 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
2847 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2850 (false, _) => {} // continue parsing the expression
2851 // An exhaustive check is done in the following block, but these are checked first
2852 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
2853 // want to keep their span info to improve diagnostics in these cases in a later stage.
2854 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
2855 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
2856 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
2857 (true, Some(AssocOp::Add)) // `{ 42 } + 42
2858 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
2859 // `if x { a } else { b } && if y { c } else { d }`
2860 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
2861 // These cases are ambiguous and can't be identified in the parser alone
2862 let sp = self.sess.source_map().start_point(self.token.span);
2863 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
2866 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
2869 (true, Some(_)) => {
2870 // We've found an expression that would be parsed as a statement, but the next
2871 // token implies this should be parsed as an expression.
2872 // For example: `if let Some(x) = x { x } else { 0 } / 2`
2873 let mut err = self.sess.span_diagnostic.struct_span_err(self.token.span, &format!(
2874 "expected expression, found `{}`",
2875 pprust::token_to_string(&self.token),
2877 err.span_label(self.token.span, "expected expression");
2878 self.sess.expr_parentheses_needed(
2881 Some(pprust::expr_to_string(&lhs),
2886 self.expected_tokens.push(TokenType::Operator);
2887 while let Some(op) = AssocOp::from_token(&self.token) {
2889 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2890 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2891 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2892 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2893 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2894 (PrevTokenKind::Interpolated, _) => self.prev_span,
2895 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2896 if path.segments.len() == 1 => self.prev_span,
2900 let cur_op_span = self.token.span;
2901 let restrictions = if op.is_assign_like() {
2902 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2906 let prec = op.precedence();
2907 if prec < min_prec {
2910 // Check for deprecated `...` syntax
2911 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2912 self.err_dotdotdot_syntax(self.token.span);
2916 if op.is_comparison() {
2917 self.check_no_chained_comparison(&lhs, &op);
2920 if op == AssocOp::As {
2921 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2923 } else if op == AssocOp::Colon {
2924 let maybe_path = self.could_ascription_be_path(&lhs.node);
2925 let next_sp = self.token.span;
2927 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2930 self.bad_type_ascription(
2941 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2942 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2943 // generalise it to the Fixity::None code.
2945 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2946 // two variants are handled with `parse_prefix_range_expr` call above.
2947 let rhs = if self.is_at_start_of_range_notation_rhs() {
2948 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
2952 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2957 let limits = if op == AssocOp::DotDot {
2958 RangeLimits::HalfOpen
2963 let r = self.mk_range(Some(lhs), rhs, limits)?;
2964 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2968 let fixity = op.fixity();
2969 let prec_adjustment = match fixity {
2972 // We currently have no non-associative operators that are not handled above by
2973 // the special cases. The code is here only for future convenience.
2976 let rhs = self.with_res(
2977 restrictions - Restrictions::STMT_EXPR,
2978 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
2981 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
2982 // including the attributes.
2986 .filter(|a| a.style == AttrStyle::Outer)
2988 .map_or(lhs_span, |a| a.span);
2989 let span = lhs_span.to(rhs.span);
2991 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2992 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2993 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2994 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2995 AssocOp::Greater | AssocOp::GreaterEqual => {
2996 let ast_op = op.to_ast_binop().unwrap();
2997 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
2998 self.mk_expr(span, binary, ThinVec::new())
3000 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3001 AssocOp::AssignOp(k) => {
3003 token::Plus => BinOpKind::Add,
3004 token::Minus => BinOpKind::Sub,
3005 token::Star => BinOpKind::Mul,
3006 token::Slash => BinOpKind::Div,
3007 token::Percent => BinOpKind::Rem,
3008 token::Caret => BinOpKind::BitXor,
3009 token::And => BinOpKind::BitAnd,
3010 token::Or => BinOpKind::BitOr,
3011 token::Shl => BinOpKind::Shl,
3012 token::Shr => BinOpKind::Shr,
3014 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3015 self.mk_expr(span, aopexpr, ThinVec::new())
3017 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3018 self.bug("AssocOp should have been handled by special case")
3022 if let Fixity::None = fixity { break }
3027 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3028 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3029 -> PResult<'a, P<Expr>> {
3030 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3031 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3034 // Save the state of the parser before parsing type normally, in case there is a
3035 // LessThan comparison after this cast.
3036 let parser_snapshot_before_type = self.clone();
3037 match self.parse_ty_no_plus() {
3039 Ok(mk_expr(self, rhs))
3041 Err(mut type_err) => {
3042 // Rewind to before attempting to parse the type with generics, to recover
3043 // from situations like `x as usize < y` in which we first tried to parse
3044 // `usize < y` as a type with generic arguments.
3045 let parser_snapshot_after_type = self.clone();
3046 mem::replace(self, parser_snapshot_before_type);
3048 match self.parse_path(PathStyle::Expr) {
3050 let (op_noun, op_verb) = match self.token.kind {
3051 token::Lt => ("comparison", "comparing"),
3052 token::BinOp(token::Shl) => ("shift", "shifting"),
3054 // We can end up here even without `<` being the next token, for
3055 // example because `parse_ty_no_plus` returns `Err` on keywords,
3056 // but `parse_path` returns `Ok` on them due to error recovery.
3057 // Return original error and parser state.
3058 mem::replace(self, parser_snapshot_after_type);
3059 return Err(type_err);
3063 // Successfully parsed the type path leaving a `<` yet to parse.
3066 // Report non-fatal diagnostics, keep `x as usize` as an expression
3067 // in AST and continue parsing.
3068 let msg = format!("`<` is interpreted as a start of generic \
3069 arguments for `{}`, not a {}", path, op_noun);
3071 self.sess.span_diagnostic.struct_span_err(self.token.span, &msg);
3072 let span_after_type = parser_snapshot_after_type.token.span;
3073 err.span_label(self.look_ahead(1, |t| t.span).to(span_after_type),
3074 "interpreted as generic arguments");
3075 err.span_label(self.token.span, format!("not interpreted as {}", op_noun));
3077 let expr = mk_expr(self, P(Ty {
3079 node: TyKind::Path(None, path),
3080 id: ast::DUMMY_NODE_ID
3083 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3084 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3085 err.span_suggestion(
3087 &format!("try {} the cast value", op_verb),
3088 format!("({})", expr_str),
3089 Applicability::MachineApplicable
3095 Err(mut path_err) => {
3096 // Couldn't parse as a path, return original error and parser state.
3098 mem::replace(self, parser_snapshot_after_type);
3106 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3107 fn parse_prefix_range_expr(&mut self,
3108 already_parsed_attrs: Option<ThinVec<Attribute>>)
3109 -> PResult<'a, P<Expr>> {
3110 // Check for deprecated `...` syntax
3111 if self.token == token::DotDotDot {
3112 self.err_dotdotdot_syntax(self.token.span);
3115 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
3116 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3118 let tok = self.token.clone();
3119 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3120 let lo = self.token.span;
3121 let mut hi = self.token.span;
3123 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3124 // RHS must be parsed with more associativity than the dots.
3125 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3126 Some(self.parse_assoc_expr_with(next_prec,
3127 LhsExpr::NotYetParsed)
3135 let limits = if tok == token::DotDot {
3136 RangeLimits::HalfOpen
3141 let r = self.mk_range(None, opt_end, limits)?;
3142 Ok(self.mk_expr(lo.to(hi), r, attrs))
3145 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3146 if self.token.can_begin_expr() {
3147 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3148 if self.token == token::OpenDelim(token::Brace) {
3149 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3157 /// Parses an `if` expression (`if` token already eaten).
3158 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3159 let lo = self.prev_span;
3160 let cond = self.parse_cond_expr()?;
3162 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3163 // verify that the last statement is either an implicit return (no `;`) or an explicit
3164 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3165 // the dead code lint.
3166 if self.eat_keyword(kw::Else) || !cond.returns() {
3167 let sp = self.sess.source_map().next_point(lo);
3168 let mut err = self.diagnostic()
3169 .struct_span_err(sp, "missing condition for `if` statemement");
3170 err.span_label(sp, "expected if condition here");
3173 let not_block = self.token != token::OpenDelim(token::Brace);
3174 let thn = self.parse_block().map_err(|mut err| {
3176 err.span_label(lo, "this `if` statement has a condition, but no block");
3180 let mut els: Option<P<Expr>> = None;
3181 let mut hi = thn.span;
3182 if self.eat_keyword(kw::Else) {
3183 let elexpr = self.parse_else_expr()?;
3187 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3190 /// Parse the condition of a `if`- or `while`-expression
3191 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
3192 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3194 if let ExprKind::Let(..) = cond.node {
3195 // Remove the last feature gating of a `let` expression since it's stable.
3196 let last = self.sess.let_chains_spans.borrow_mut().pop();
3197 debug_assert_eq!(cond.span, last.unwrap());
3203 /// Parses a `let $pats = $expr` pseudo-expression.
3204 /// The `let` token has already been eaten.
3205 fn parse_let_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3206 let lo = self.prev_span;
3207 let pats = self.parse_pats()?;
3208 self.expect(&token::Eq)?;
3209 let expr = self.with_res(
3210 Restrictions::NO_STRUCT_LITERAL,
3211 |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
3213 let span = lo.to(expr.span);
3214 self.sess.let_chains_spans.borrow_mut().push(span);
3215 Ok(self.mk_expr(span, ExprKind::Let(pats, expr), attrs))
3218 /// Parses `move |args| expr`.
3219 fn parse_lambda_expr(&mut self,
3220 attrs: ThinVec<Attribute>)
3221 -> PResult<'a, P<Expr>>
3223 let lo = self.token.span;
3224 let movability = if self.eat_keyword(kw::Static) {
3229 let asyncness = if self.token.span.rust_2018() {
3230 self.parse_asyncness()
3234 let capture_clause = if self.eat_keyword(kw::Move) {
3239 let decl = self.parse_fn_block_decl()?;
3240 let decl_hi = self.prev_span;
3241 let body = match decl.output {
3242 FunctionRetTy::Default(_) => {
3243 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3244 self.parse_expr_res(restrictions, None)?
3247 // If an explicit return type is given, require a
3248 // block to appear (RFC 968).
3249 let body_lo = self.token.span;
3250 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3256 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3260 // `else` token already eaten
3261 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3262 if self.eat_keyword(kw::If) {
3263 return self.parse_if_expr(ThinVec::new());
3265 let blk = self.parse_block()?;
3266 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3270 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3271 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3273 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3274 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3276 let pat = self.parse_top_level_pat()?;
3277 if !self.eat_keyword(kw::In) {
3278 let in_span = self.prev_span.between(self.token.span);
3279 let mut err = self.sess.span_diagnostic
3280 .struct_span_err(in_span, "missing `in` in `for` loop");
3281 err.span_suggestion_short(
3282 in_span, "try adding `in` here", " in ".into(),
3283 // has been misleading, at least in the past (closed Issue #48492)
3284 Applicability::MaybeIncorrect
3288 let in_span = self.prev_span;
3289 self.check_for_for_in_in_typo(in_span);
3290 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3291 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3292 attrs.extend(iattrs);
3294 let hi = self.prev_span;
3295 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3298 /// Parses a `while` or `while let` expression (`while` token already eaten).
3299 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3301 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3302 let cond = self.parse_cond_expr()?;
3303 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3304 attrs.extend(iattrs);
3305 let span = span_lo.to(body.span);
3306 Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs))
3309 // parse `loop {...}`, `loop` token already eaten
3310 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3312 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3313 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3314 attrs.extend(iattrs);
3315 let span = span_lo.to(body.span);
3316 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3319 /// Parses an `async move {...}` expression.
3320 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3321 -> PResult<'a, P<Expr>>
3323 let span_lo = self.token.span;
3324 self.expect_keyword(kw::Async)?;
3325 let capture_clause = if self.eat_keyword(kw::Move) {
3330 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3331 attrs.extend(iattrs);
3333 span_lo.to(body.span),
3334 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3337 /// Parses a `try {...}` expression (`try` token already eaten).
3338 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3339 -> PResult<'a, P<Expr>>
3341 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3342 attrs.extend(iattrs);
3343 if self.eat_keyword(kw::Catch) {
3344 let mut error = self.struct_span_err(self.prev_span,
3345 "keyword `catch` cannot follow a `try` block");
3346 error.help("try using `match` on the result of the `try` block instead");
3350 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3354 // `match` token already eaten
3355 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3356 let match_span = self.prev_span;
3357 let lo = self.prev_span;
3358 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3360 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3361 if self.token == token::Semi {
3362 e.span_suggestion_short(
3364 "try removing this `match`",
3366 Applicability::MaybeIncorrect // speculative
3371 attrs.extend(self.parse_inner_attributes()?);
3373 let mut arms: Vec<Arm> = Vec::new();
3374 while self.token != token::CloseDelim(token::Brace) {
3375 match self.parse_arm() {
3376 Ok(arm) => arms.push(arm),
3378 // Recover by skipping to the end of the block.
3380 self.recover_stmt();
3381 let span = lo.to(self.token.span);
3382 if self.token == token::CloseDelim(token::Brace) {
3385 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3389 let hi = self.token.span;
3391 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3394 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3395 let attrs = self.parse_outer_attributes()?;
3396 let lo = self.token.span;
3397 let pats = self.parse_pats()?;
3398 let guard = if self.eat_keyword(kw::If) {
3399 Some(self.parse_expr()?)
3403 let arrow_span = self.token.span;
3404 self.expect(&token::FatArrow)?;
3405 let arm_start_span = self.token.span;
3407 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3408 .map_err(|mut err| {
3409 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3413 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3414 && self.token != token::CloseDelim(token::Brace);
3416 let hi = self.token.span;
3419 let cm = self.sess.source_map();
3420 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3421 .map_err(|mut err| {
3422 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3423 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3424 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3425 && expr_lines.lines.len() == 2
3426 && self.token == token::FatArrow => {
3427 // We check whether there's any trailing code in the parse span,
3428 // if there isn't, we very likely have the following:
3431 // | -- - missing comma
3435 // | - ^^ self.token.span
3437 // | parsed until here as `"y" & X`
3438 err.span_suggestion_short(
3439 cm.next_point(arm_start_span),
3440 "missing a comma here to end this `match` arm",
3442 Applicability::MachineApplicable
3446 err.span_label(arrow_span,
3447 "while parsing the `match` arm starting here");
3453 self.eat(&token::Comma);
3465 /// Parses an expression.
3467 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3468 self.parse_expr_res(Restrictions::empty(), None)
3471 /// Evaluates the closure with restrictions in place.
3473 /// Afters the closure is evaluated, restrictions are reset.
3474 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3475 where F: FnOnce(&mut Self) -> T
3477 let old = self.restrictions;
3478 self.restrictions = r;
3480 self.restrictions = old;
3485 /// Parses an expression, subject to the given restrictions.
3487 fn parse_expr_res(&mut self, r: Restrictions,
3488 already_parsed_attrs: Option<ThinVec<Attribute>>)
3489 -> PResult<'a, P<Expr>> {
3490 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3493 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
3494 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3495 if self.eat(&token::Eq) {
3496 Ok(Some(self.parse_expr()?))
3498 Ok(Some(self.parse_expr()?))
3504 /// Parses patterns, separated by '|' s.
3505 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3506 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
3507 self.eat(&token::BinOp(token::Or));
3509 let mut pats = Vec::new();
3511 pats.push(self.parse_top_level_pat()?);
3513 if self.token == token::OrOr {
3514 let mut err = self.struct_span_err(self.token.span,
3515 "unexpected token `||` after pattern");
3516 err.span_suggestion(
3518 "use a single `|` to specify multiple patterns",
3520 Applicability::MachineApplicable
3524 } else if self.eat(&token::BinOp(token::Or)) {
3525 // This is a No-op. Continue the loop to parse the next
3533 // Parses a parenthesized list of patterns like
3534 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3535 // - a vector of the patterns that were parsed
3536 // - an option indicating the index of the `..` element
3537 // - a boolean indicating whether a trailing comma was present.
3538 // Trailing commas are significant because (p) and (p,) are different patterns.
3539 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3540 self.expect(&token::OpenDelim(token::Paren))?;
3541 let result = match self.parse_pat_list() {
3542 Ok(result) => result,
3543 Err(mut err) => { // recover from parse error in tuple pattern list
3545 self.consume_block(token::Paren);
3546 return Ok((vec![], Some(0), false));
3549 self.expect(&token::CloseDelim(token::Paren))?;
3553 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3554 let mut fields = Vec::new();
3555 let mut ddpos = None;
3556 let mut prev_dd_sp = None;
3557 let mut trailing_comma = false;
3559 if self.eat(&token::DotDot) {
3560 if ddpos.is_none() {
3561 ddpos = Some(fields.len());
3562 prev_dd_sp = Some(self.prev_span);
3564 // Emit a friendly error, ignore `..` and continue parsing
3565 let mut err = self.struct_span_err(
3567 "`..` can only be used once per tuple or tuple struct pattern",
3569 err.span_label(self.prev_span, "can only be used once per pattern");
3570 if let Some(sp) = prev_dd_sp {
3571 err.span_label(sp, "previously present here");
3575 } else if !self.check(&token::CloseDelim(token::Paren)) {
3576 fields.push(self.parse_pat(None)?);
3581 trailing_comma = self.eat(&token::Comma);
3582 if !trailing_comma {
3587 if ddpos == Some(fields.len()) && trailing_comma {
3588 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3589 let msg = "trailing comma is not permitted after `..`";
3590 self.struct_span_err(self.prev_span, msg)
3591 .span_label(self.prev_span, msg)
3595 Ok((fields, ddpos, trailing_comma))
3598 fn parse_pat_vec_elements(
3600 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3601 let mut before = Vec::new();
3602 let mut slice = None;
3603 let mut after = Vec::new();
3604 let mut first = true;
3605 let mut before_slice = true;
3607 while self.token != token::CloseDelim(token::Bracket) {
3611 self.expect(&token::Comma)?;
3613 if self.token == token::CloseDelim(token::Bracket)
3614 && (before_slice || !after.is_empty()) {
3620 if self.eat(&token::DotDot) {
3622 if self.check(&token::Comma) ||
3623 self.check(&token::CloseDelim(token::Bracket)) {
3624 slice = Some(P(Pat {
3625 id: ast::DUMMY_NODE_ID,
3626 node: PatKind::Wild,
3627 span: self.prev_span,
3629 before_slice = false;
3635 let subpat = self.parse_pat(None)?;
3636 if before_slice && self.eat(&token::DotDot) {
3637 slice = Some(subpat);
3638 before_slice = false;
3639 } else if before_slice {
3640 before.push(subpat);
3646 Ok((before, slice, after))
3652 attrs: Vec<Attribute>
3653 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3654 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3656 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3657 // Parsing a pattern of the form "fieldname: pat"
3658 let fieldname = self.parse_field_name()?;
3660 let pat = self.parse_pat(None)?;
3662 (pat, fieldname, false)
3664 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3665 let is_box = self.eat_keyword(kw::Box);
3666 let boxed_span = self.token.span;
3667 let is_ref = self.eat_keyword(kw::Ref);
3668 let is_mut = self.eat_keyword(kw::Mut);
3669 let fieldname = self.parse_ident()?;
3670 hi = self.prev_span;
3672 let bind_type = match (is_ref, is_mut) {
3673 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3674 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3675 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3676 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3678 let fieldpat = P(Pat {
3679 id: ast::DUMMY_NODE_ID,
3680 node: PatKind::Ident(bind_type, fieldname, None),
3681 span: boxed_span.to(hi),
3684 let subpat = if is_box {
3686 id: ast::DUMMY_NODE_ID,
3687 node: PatKind::Box(fieldpat),
3693 (subpat, fieldname, true)
3696 Ok(source_map::Spanned {
3698 node: ast::FieldPat {
3702 attrs: attrs.into(),
3707 /// Parses the fields of a struct-like pattern.
3708 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3709 let mut fields = Vec::new();
3710 let mut etc = false;
3711 let mut ate_comma = true;
3712 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3713 let mut etc_span = None;
3715 while self.token != token::CloseDelim(token::Brace) {
3716 let attrs = self.parse_outer_attributes()?;
3717 let lo = self.token.span;
3719 // check that a comma comes after every field
3721 let err = self.struct_span_err(self.prev_span, "expected `,`");
3722 if let Some(mut delayed) = delayed_err {
3729 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3731 let mut etc_sp = self.token.span;
3733 if self.token == token::DotDotDot { // Issue #46718
3734 // Accept `...` as if it were `..` to avoid further errors
3735 let mut err = self.struct_span_err(self.token.span,
3736 "expected field pattern, found `...`");
3737 err.span_suggestion(
3739 "to omit remaining fields, use one fewer `.`",
3741 Applicability::MachineApplicable
3745 self.bump(); // `..` || `...`
3747 if self.token == token::CloseDelim(token::Brace) {
3748 etc_span = Some(etc_sp);
3751 let token_str = self.this_token_descr();
3752 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3754 err.span_label(self.token.span, "expected `}`");
3755 let mut comma_sp = None;
3756 if self.token == token::Comma { // Issue #49257
3757 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
3758 etc_sp = etc_sp.to(nw_span);
3759 err.span_label(etc_sp,
3760 "`..` must be at the end and cannot have a trailing comma");
3761 comma_sp = Some(self.token.span);
3766 etc_span = Some(etc_sp.until(self.token.span));
3767 if self.token == token::CloseDelim(token::Brace) {
3768 // If the struct looks otherwise well formed, recover and continue.
3769 if let Some(sp) = comma_sp {
3770 err.span_suggestion_short(
3772 "remove this comma",
3774 Applicability::MachineApplicable,
3779 } else if self.token.is_ident() && ate_comma {
3780 // Accept fields coming after `..,`.
3781 // This way we avoid "pattern missing fields" errors afterwards.
3782 // We delay this error until the end in order to have a span for a
3784 if let Some(mut delayed_err) = delayed_err {
3788 delayed_err = Some(err);
3791 if let Some(mut err) = delayed_err {
3798 fields.push(match self.parse_pat_field(lo, attrs) {
3801 if let Some(mut delayed_err) = delayed_err {
3807 ate_comma = self.eat(&token::Comma);
3810 if let Some(mut err) = delayed_err {
3811 if let Some(etc_span) = etc_span {
3812 err.multipart_suggestion(
3813 "move the `..` to the end of the field list",
3815 (etc_span, String::new()),
3816 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3818 Applicability::MachineApplicable,
3823 return Ok((fields, etc));
3826 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3827 if self.token.is_path_start() {
3828 let lo = self.token.span;
3829 let (qself, path) = if self.eat_lt() {
3830 // Parse a qualified path
3831 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3834 // Parse an unqualified path
3835 (None, self.parse_path(PathStyle::Expr)?)
3837 let hi = self.prev_span;
3838 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3840 self.parse_literal_maybe_minus()
3844 // helper function to decide whether to parse as ident binding or to try to do
3845 // something more complex like range patterns
3846 fn parse_as_ident(&mut self) -> bool {
3847 self.look_ahead(1, |t| match t.kind {
3848 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3849 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3850 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3851 // range pattern branch
3852 token::DotDot => None,
3854 }).unwrap_or_else(|| self.look_ahead(2, |t| match t.kind {
3855 token::Comma | token::CloseDelim(token::Bracket) => true,
3860 /// A wrapper around `parse_pat` with some special error handling for the
3861 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3862 /// to subpatterns within such).
3863 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3864 let pat = self.parse_pat(None)?;
3865 if self.token == token::Comma {
3866 // An unexpected comma after a top-level pattern is a clue that the
3867 // user (perhaps more accustomed to some other language) forgot the
3868 // parentheses in what should have been a tuple pattern; return a
3869 // suggestion-enhanced error here rather than choking on the comma
3871 let comma_span = self.token.span;
3873 if let Err(mut err) = self.parse_pat_list() {
3874 // We didn't expect this to work anyway; we just wanted
3875 // to advance to the end of the comma-sequence so we know
3876 // the span to suggest parenthesizing
3879 let seq_span = pat.span.to(self.prev_span);
3880 let mut err = self.struct_span_err(comma_span,
3881 "unexpected `,` in pattern");
3882 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3883 err.span_suggestion(
3885 "try adding parentheses to match on a tuple..",
3886 format!("({})", seq_snippet),
3887 Applicability::MachineApplicable
3890 "..or a vertical bar to match on multiple alternatives",
3891 format!("{}", seq_snippet.replace(",", " |")),
3892 Applicability::MachineApplicable
3900 /// Parses a pattern.
3901 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
3902 self.parse_pat_with_range_pat(true, expected)
3905 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
3907 fn parse_pat_with_range_pat(
3909 allow_range_pat: bool,
3910 expected: Option<&'static str>,
3911 ) -> PResult<'a, P<Pat>> {
3912 maybe_recover_from_interpolated_ty_qpath!(self, true);
3913 maybe_whole!(self, NtPat, |x| x);
3915 let lo = self.token.span;
3917 match self.token.kind {
3918 token::BinOp(token::And) | token::AndAnd => {
3919 // Parse &pat / &mut pat
3921 let mutbl = self.parse_mutability();
3922 if let token::Lifetime(name) = self.token.kind {
3923 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
3924 err.span_label(self.token.span, "unexpected lifetime");
3927 let subpat = self.parse_pat_with_range_pat(false, expected)?;
3928 pat = PatKind::Ref(subpat, mutbl);
3930 token::OpenDelim(token::Paren) => {
3931 // Parse (pat,pat,pat,...) as tuple pattern
3932 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3933 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3934 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3936 PatKind::Tuple(fields, ddpos)
3939 token::OpenDelim(token::Bracket) => {
3940 // Parse [pat,pat,...] as slice pattern
3942 let (before, slice, after) = self.parse_pat_vec_elements()?;
3943 self.expect(&token::CloseDelim(token::Bracket))?;
3944 pat = PatKind::Slice(before, slice, after);
3946 // At this point, token != &, &&, (, [
3947 _ => if self.eat_keyword(kw::Underscore) {
3949 pat = PatKind::Wild;
3950 } else if self.eat_keyword(kw::Mut) {
3951 // Parse mut ident @ pat / mut ref ident @ pat
3952 let mutref_span = self.prev_span.to(self.token.span);
3953 let binding_mode = if self.eat_keyword(kw::Ref) {
3955 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3958 "try switching the order",
3960 Applicability::MachineApplicable
3962 BindingMode::ByRef(Mutability::Mutable)
3964 BindingMode::ByValue(Mutability::Mutable)
3966 pat = self.parse_pat_ident(binding_mode)?;
3967 } else if self.eat_keyword(kw::Ref) {
3968 // Parse ref ident @ pat / ref mut ident @ pat
3969 let mutbl = self.parse_mutability();
3970 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3971 } else if self.eat_keyword(kw::Box) {
3973 let subpat = self.parse_pat_with_range_pat(false, None)?;
3974 pat = PatKind::Box(subpat);
3975 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3976 self.parse_as_ident() {
3977 // Parse ident @ pat
3978 // This can give false positives and parse nullary enums,
3979 // they are dealt with later in resolve
3980 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3981 pat = self.parse_pat_ident(binding_mode)?;
3982 } else if self.token.is_path_start() {
3983 // Parse pattern starting with a path
3984 let (qself, path) = if self.eat_lt() {
3985 // Parse a qualified path
3986 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3989 // Parse an unqualified path
3990 (None, self.parse_path(PathStyle::Expr)?)
3992 match self.token.kind {
3993 token::Not if qself.is_none() => {
3994 // Parse macro invocation
3996 let (delim, tts) = self.expect_delimited_token_tree()?;
3997 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
3998 pat = PatKind::Mac(mac);
4000 token::DotDotDot | token::DotDotEq | token::DotDot => {
4001 let end_kind = match self.token.kind {
4002 token::DotDot => RangeEnd::Excluded,
4003 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4004 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4005 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4008 let op_span = self.token.span;
4010 let span = lo.to(self.prev_span);
4011 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4013 let end = self.parse_pat_range_end()?;
4014 let op = Spanned { span: op_span, node: end_kind };
4015 pat = PatKind::Range(begin, end, op);
4017 token::OpenDelim(token::Brace) => {
4018 if qself.is_some() {
4019 let msg = "unexpected `{` after qualified path";
4020 let mut err = self.fatal(msg);
4021 err.span_label(self.token.span, msg);
4024 // Parse struct pattern
4026 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4028 self.recover_stmt();
4032 pat = PatKind::Struct(path, fields, etc);
4034 token::OpenDelim(token::Paren) => {
4035 if qself.is_some() {
4036 let msg = "unexpected `(` after qualified path";
4037 let mut err = self.fatal(msg);
4038 err.span_label(self.token.span, msg);
4041 // Parse tuple struct or enum pattern
4042 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4043 pat = PatKind::TupleStruct(path, fields, ddpos)
4045 _ => pat = PatKind::Path(qself, path),
4048 // Try to parse everything else as literal with optional minus
4049 match self.parse_literal_maybe_minus() {
4051 let op_span = self.token.span;
4052 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4053 self.check(&token::DotDotDot) {
4054 let end_kind = if self.eat(&token::DotDotDot) {
4055 RangeEnd::Included(RangeSyntax::DotDotDot)
4056 } else if self.eat(&token::DotDotEq) {
4057 RangeEnd::Included(RangeSyntax::DotDotEq)
4058 } else if self.eat(&token::DotDot) {
4061 panic!("impossible case: we already matched \
4062 on a range-operator token")
4064 let end = self.parse_pat_range_end()?;
4065 let op = Spanned { span: op_span, node: end_kind };
4066 pat = PatKind::Range(begin, end, op);
4068 pat = PatKind::Lit(begin);
4072 self.cancel(&mut err);
4073 let expected = expected.unwrap_or("pattern");
4075 "expected {}, found {}",
4077 self.this_token_descr(),
4079 let mut err = self.fatal(&msg);
4080 err.span_label(self.token.span, format!("expected {}", expected));
4081 let sp = self.sess.source_map().start_point(self.token.span);
4082 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4083 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4091 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4092 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4094 if !allow_range_pat {
4097 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4099 PatKind::Range(..) => {
4100 let mut err = self.struct_span_err(
4102 "the range pattern here has ambiguous interpretation",
4104 err.span_suggestion(
4106 "add parentheses to clarify the precedence",
4107 format!("({})", pprust::pat_to_string(&pat)),
4108 // "ambiguous interpretation" implies that we have to be guessing
4109 Applicability::MaybeIncorrect
4120 /// Parses `ident` or `ident @ pat`.
4121 /// used by the copy foo and ref foo patterns to give a good
4122 /// error message when parsing mistakes like `ref foo(a, b)`.
4123 fn parse_pat_ident(&mut self,
4124 binding_mode: ast::BindingMode)
4125 -> PResult<'a, PatKind> {
4126 let ident = self.parse_ident()?;
4127 let sub = if self.eat(&token::At) {
4128 Some(self.parse_pat(Some("binding pattern"))?)
4133 // just to be friendly, if they write something like
4135 // we end up here with ( as the current token. This shortly
4136 // leads to a parse error. Note that if there is no explicit
4137 // binding mode then we do not end up here, because the lookahead
4138 // will direct us over to parse_enum_variant()
4139 if self.token == token::OpenDelim(token::Paren) {
4140 return Err(self.span_fatal(
4142 "expected identifier, found enum pattern"))
4145 Ok(PatKind::Ident(binding_mode, ident, sub))
4148 /// Parses a local variable declaration.
4149 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4150 let lo = self.prev_span;
4151 let pat = self.parse_top_level_pat()?;
4153 let (err, ty) = if self.eat(&token::Colon) {
4154 // Save the state of the parser before parsing type normally, in case there is a `:`
4155 // instead of an `=` typo.
4156 let parser_snapshot_before_type = self.clone();
4157 let colon_sp = self.prev_span;
4158 match self.parse_ty() {
4159 Ok(ty) => (None, Some(ty)),
4161 // Rewind to before attempting to parse the type and continue parsing
4162 let parser_snapshot_after_type = self.clone();
4163 mem::replace(self, parser_snapshot_before_type);
4165 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4166 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4167 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4173 let init = match (self.parse_initializer(err.is_some()), err) {
4174 (Ok(init), None) => { // init parsed, ty parsed
4177 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4178 // Could parse the type as if it were the initializer, it is likely there was a
4179 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4180 err.span_suggestion_short(
4182 "use `=` if you meant to assign",
4184 Applicability::MachineApplicable
4187 // As this was parsed successfully, continue as if the code has been fixed for the
4188 // rest of the file. It will still fail due to the emitted error, but we avoid
4192 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4194 // Couldn't parse the type nor the initializer, only raise the type error and
4195 // return to the parser state before parsing the type as the initializer.
4196 // let x: <parse_error>;
4197 mem::replace(self, snapshot);
4200 (Err(err), None) => { // init error, ty parsed
4201 // Couldn't parse the initializer and we're not attempting to recover a failed
4202 // parse of the type, return the error.
4206 let hi = if self.token == token::Semi {
4215 id: ast::DUMMY_NODE_ID,
4221 /// Parses a structure field.
4222 fn parse_name_and_ty(&mut self,
4225 attrs: Vec<Attribute>)
4226 -> PResult<'a, StructField> {
4227 let name = self.parse_ident()?;
4228 self.expect(&token::Colon)?;
4229 let ty = self.parse_ty()?;
4231 span: lo.to(self.prev_span),
4234 id: ast::DUMMY_NODE_ID,
4240 /// Emits an expected-item-after-attributes error.
4241 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4242 let message = match attrs.last() {
4243 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4244 _ => "expected item after attributes",
4247 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4248 if attrs.last().unwrap().is_sugared_doc {
4249 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4254 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4255 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4256 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4257 Ok(self.parse_stmt_(true))
4260 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4261 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4263 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4268 fn is_async_block(&self) -> bool {
4269 self.token.is_keyword(kw::Async) &&
4272 self.is_keyword_ahead(1, &[kw::Move]) &&
4273 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4275 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4280 fn is_async_fn(&self) -> bool {
4281 self.token.is_keyword(kw::Async) &&
4282 self.is_keyword_ahead(1, &[kw::Fn])
4285 fn is_do_catch_block(&self) -> bool {
4286 self.token.is_keyword(kw::Do) &&
4287 self.is_keyword_ahead(1, &[kw::Catch]) &&
4288 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4289 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4292 fn is_try_block(&self) -> bool {
4293 self.token.is_keyword(kw::Try) &&
4294 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4295 self.token.span.rust_2018() &&
4296 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4297 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4300 fn is_union_item(&self) -> bool {
4301 self.token.is_keyword(kw::Union) &&
4302 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4305 fn is_crate_vis(&self) -> bool {
4306 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4309 fn is_existential_type_decl(&self) -> bool {
4310 self.token.is_keyword(kw::Existential) &&
4311 self.is_keyword_ahead(1, &[kw::Type])
4314 fn is_auto_trait_item(&self) -> bool {
4316 (self.token.is_keyword(kw::Auto) &&
4317 self.is_keyword_ahead(1, &[kw::Trait]))
4318 || // unsafe auto trait
4319 (self.token.is_keyword(kw::Unsafe) &&
4320 self.is_keyword_ahead(1, &[kw::Auto]) &&
4321 self.is_keyword_ahead(2, &[kw::Trait]))
4324 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4325 -> PResult<'a, Option<P<Item>>> {
4326 let token_lo = self.token.span;
4327 let (ident, def) = match self.token.kind {
4328 token::Ident(name, false) if name == kw::Macro => {
4330 let ident = self.parse_ident()?;
4331 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4332 match self.parse_token_tree() {
4333 TokenTree::Delimited(_, _, tts) => tts,
4334 _ => unreachable!(),
4336 } else if self.check(&token::OpenDelim(token::Paren)) {
4337 let args = self.parse_token_tree();
4338 let body = if self.check(&token::OpenDelim(token::Brace)) {
4339 self.parse_token_tree()
4344 TokenStream::new(vec![
4346 TokenTree::token(token::FatArrow, token_lo.to(self.prev_span)).into(),
4354 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4356 token::Ident(name, _) if name == sym::macro_rules &&
4357 self.look_ahead(1, |t| *t == token::Not) => {
4358 let prev_span = self.prev_span;
4359 self.complain_if_pub_macro(&vis.node, prev_span);
4363 let ident = self.parse_ident()?;
4364 let (delim, tokens) = self.expect_delimited_token_tree()?;
4365 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
4366 self.report_invalid_macro_expansion_item();
4369 (ident, ast::MacroDef { tokens, legacy: true })
4371 _ => return Ok(None),
4374 let span = lo.to(self.prev_span);
4375 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4378 fn parse_stmt_without_recovery(&mut self,
4379 macro_legacy_warnings: bool)
4380 -> PResult<'a, Option<Stmt>> {
4381 maybe_whole!(self, NtStmt, |x| Some(x));
4383 let attrs = self.parse_outer_attributes()?;
4384 let lo = self.token.span;
4386 Ok(Some(if self.eat_keyword(kw::Let) {
4388 id: ast::DUMMY_NODE_ID,
4389 node: StmtKind::Local(self.parse_local(attrs.into())?),
4390 span: lo.to(self.prev_span),
4392 } else if let Some(macro_def) = self.eat_macro_def(
4394 &source_map::respan(lo, VisibilityKind::Inherited),
4398 id: ast::DUMMY_NODE_ID,
4399 node: StmtKind::Item(macro_def),
4400 span: lo.to(self.prev_span),
4402 // Starts like a simple path, being careful to avoid contextual keywords
4403 // such as a union items, item with `crate` visibility or auto trait items.
4404 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4405 // like a path (1 token), but it fact not a path.
4406 // `union::b::c` - path, `union U { ... }` - not a path.
4407 // `crate::b::c` - path, `crate struct S;` - not a path.
4408 } else if self.token.is_path_start() &&
4409 !self.token.is_qpath_start() &&
4410 !self.is_union_item() &&
4411 !self.is_crate_vis() &&
4412 !self.is_existential_type_decl() &&
4413 !self.is_auto_trait_item() &&
4414 !self.is_async_fn() {
4415 let pth = self.parse_path(PathStyle::Expr)?;
4417 if !self.eat(&token::Not) {
4418 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4419 self.parse_struct_expr(lo, pth, ThinVec::new())?
4421 let hi = self.prev_span;
4422 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4425 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4426 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4427 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4430 return Ok(Some(Stmt {
4431 id: ast::DUMMY_NODE_ID,
4432 node: StmtKind::Expr(expr),
4433 span: lo.to(self.prev_span),
4437 // it's a macro invocation
4438 let id = match self.token.kind {
4439 token::OpenDelim(_) => Ident::invalid(), // no special identifier
4440 _ => self.parse_ident()?,
4443 // check that we're pointing at delimiters (need to check
4444 // again after the `if`, because of `parse_ident`
4445 // consuming more tokens).
4446 match self.token.kind {
4447 token::OpenDelim(_) => {}
4449 // we only expect an ident if we didn't parse one
4451 let ident_str = if id.name == kw::Invalid {
4456 let tok_str = self.this_token_descr();
4457 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4460 err.span_label(self.token.span, format!("expected {}`(` or `{{`", ident_str));
4465 let (delim, tts) = self.expect_delimited_token_tree()?;
4466 let hi = self.prev_span;
4468 let style = if delim == MacDelimiter::Brace {
4469 MacStmtStyle::Braces
4471 MacStmtStyle::NoBraces
4474 if id.name == kw::Invalid {
4475 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4476 let node = if delim == MacDelimiter::Brace ||
4477 self.token == token::Semi || self.token == token::Eof {
4478 StmtKind::Mac(P((mac, style, attrs.into())))
4480 // We used to incorrectly stop parsing macro-expanded statements here.
4481 // If the next token will be an error anyway but could have parsed with the
4482 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4483 else if macro_legacy_warnings &&
4484 self.token.can_begin_expr() &&
4485 match self.token.kind {
4486 // These can continue an expression, so we can't stop parsing and warn.
4487 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4488 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4489 token::BinOp(token::And) | token::BinOp(token::Or) |
4490 token::AndAnd | token::OrOr |
4491 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4494 self.warn_missing_semicolon();
4495 StmtKind::Mac(P((mac, style, attrs.into())))
4497 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
4498 let e = self.maybe_recover_from_bad_qpath(e, true)?;
4499 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4500 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4504 id: ast::DUMMY_NODE_ID,
4509 // if it has a special ident, it's definitely an item
4511 // Require a semicolon or braces.
4512 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
4513 self.report_invalid_macro_expansion_item();
4515 let span = lo.to(hi);
4517 id: ast::DUMMY_NODE_ID,
4519 node: StmtKind::Item({
4521 span, id /*id is good here*/,
4522 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4523 respan(lo, VisibilityKind::Inherited),
4529 // FIXME: Bad copy of attrs
4530 let old_directory_ownership =
4531 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4532 let item = self.parse_item_(attrs.clone(), false, true)?;
4533 self.directory.ownership = old_directory_ownership;
4537 id: ast::DUMMY_NODE_ID,
4538 span: lo.to(i.span),
4539 node: StmtKind::Item(i),
4542 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4543 if !attrs.is_empty() {
4544 if s.prev_token_kind == PrevTokenKind::DocComment {
4545 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4546 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4548 s.token.span, "expected statement after outer attribute"
4554 // Do not attempt to parse an expression if we're done here.
4555 if self.token == token::Semi {
4556 unused_attrs(&attrs, self);
4561 if self.token == token::CloseDelim(token::Brace) {
4562 unused_attrs(&attrs, self);
4566 // Remainder are line-expr stmts.
4567 let e = self.parse_expr_res(
4568 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4570 id: ast::DUMMY_NODE_ID,
4571 span: lo.to(e.span),
4572 node: StmtKind::Expr(e),
4579 /// Checks if this expression is a successfully parsed statement.
4580 fn expr_is_complete(&self, e: &Expr) -> bool {
4581 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4582 !classify::expr_requires_semi_to_be_stmt(e)
4585 /// Parses a block. No inner attributes are allowed.
4586 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4587 maybe_whole!(self, NtBlock, |x| x);
4589 let lo = self.token.span;
4591 if !self.eat(&token::OpenDelim(token::Brace)) {
4592 let sp = self.token.span;
4593 let tok = self.this_token_descr();
4594 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4595 let do_not_suggest_help =
4596 self.token.is_keyword(kw::In) || self.token == token::Colon;
4598 if self.token.is_ident_named(sym::and) {
4599 e.span_suggestion_short(
4601 "use `&&` instead of `and` for the boolean operator",
4603 Applicability::MaybeIncorrect,
4606 if self.token.is_ident_named(sym::or) {
4607 e.span_suggestion_short(
4609 "use `||` instead of `or` for the boolean operator",
4611 Applicability::MaybeIncorrect,
4615 // Check to see if the user has written something like
4620 // Which is valid in other languages, but not Rust.
4621 match self.parse_stmt_without_recovery(false) {
4623 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4624 || do_not_suggest_help {
4625 // if the next token is an open brace (e.g., `if a b {`), the place-
4626 // inside-a-block suggestion would be more likely wrong than right
4627 e.span_label(sp, "expected `{`");
4630 let mut stmt_span = stmt.span;
4631 // expand the span to include the semicolon, if it exists
4632 if self.eat(&token::Semi) {
4633 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4635 let sugg = pprust::to_string(|s| {
4636 use crate::print::pprust::{PrintState, INDENT_UNIT};
4637 s.ibox(INDENT_UNIT)?;
4639 s.print_stmt(&stmt)?;
4640 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4644 "try placing this code inside a block",
4646 // speculative, has been misleading in the past (closed Issue #46836)
4647 Applicability::MaybeIncorrect
4651 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4652 self.cancel(&mut e);
4656 e.span_label(sp, "expected `{`");
4660 self.parse_block_tail(lo, BlockCheckMode::Default)
4663 /// Parses a block. Inner attributes are allowed.
4664 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4665 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4667 let lo = self.token.span;
4668 self.expect(&token::OpenDelim(token::Brace))?;
4669 Ok((self.parse_inner_attributes()?,
4670 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4673 /// Parses the rest of a block expression or function body.
4674 /// Precondition: already parsed the '{'.
4675 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4676 let mut stmts = vec![];
4677 while !self.eat(&token::CloseDelim(token::Brace)) {
4678 let stmt = match self.parse_full_stmt(false) {
4681 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4683 id: ast::DUMMY_NODE_ID,
4684 node: StmtKind::Expr(DummyResult::raw_expr(self.token.span, true)),
4685 span: self.token.span,
4690 if let Some(stmt) = stmt {
4692 } else if self.token == token::Eof {
4695 // Found only `;` or `}`.
4701 id: ast::DUMMY_NODE_ID,
4703 span: lo.to(self.prev_span),
4707 /// Parses a statement, including the trailing semicolon.
4708 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4709 // skip looking for a trailing semicolon when we have an interpolated statement
4710 maybe_whole!(self, NtStmt, |x| Some(x));
4712 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4714 None => return Ok(None),
4718 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4719 // expression without semicolon
4720 if classify::expr_requires_semi_to_be_stmt(expr) {
4721 // Just check for errors and recover; do not eat semicolon yet.
4723 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4726 self.recover_stmt();
4730 StmtKind::Local(..) => {
4731 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4732 if macro_legacy_warnings && self.token != token::Semi {
4733 self.warn_missing_semicolon();
4735 self.expect_one_of(&[], &[token::Semi])?;
4741 if self.eat(&token::Semi) {
4742 stmt = stmt.add_trailing_semicolon();
4745 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4749 fn warn_missing_semicolon(&self) {
4750 self.diagnostic().struct_span_warn(self.token.span, {
4751 &format!("expected `;`, found {}", self.this_token_descr())
4753 "This was erroneously allowed and will become a hard error in a future release"
4757 fn err_dotdotdot_syntax(&self, span: Span) {
4758 self.diagnostic().struct_span_err(span, {
4759 "unexpected token: `...`"
4761 span, "use `..` for an exclusive range", "..".to_owned(),
4762 Applicability::MaybeIncorrect
4764 span, "or `..=` for an inclusive range", "..=".to_owned(),
4765 Applicability::MaybeIncorrect
4769 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
4772 /// BOUND = TY_BOUND | LT_BOUND
4773 /// LT_BOUND = LIFETIME (e.g., `'a`)
4774 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4775 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
4777 fn parse_generic_bounds_common(&mut self,
4779 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4780 let mut bounds = Vec::new();
4781 let mut negative_bounds = Vec::new();
4782 let mut last_plus_span = None;
4783 let mut was_negative = false;
4785 // This needs to be synchronized with `TokenKind::can_begin_bound`.
4786 let is_bound_start = self.check_path() || self.check_lifetime() ||
4787 self.check(&token::Not) || // used for error reporting only
4788 self.check(&token::Question) ||
4789 self.check_keyword(kw::For) ||
4790 self.check(&token::OpenDelim(token::Paren));
4792 let lo = self.token.span;
4793 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4794 let inner_lo = self.token.span;
4795 let is_negative = self.eat(&token::Not);
4796 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4797 if self.token.is_lifetime() {
4798 if let Some(question_span) = question {
4799 self.span_err(question_span,
4800 "`?` may only modify trait bounds, not lifetime bounds");
4802 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4804 let inner_span = inner_lo.to(self.prev_span);
4805 self.expect(&token::CloseDelim(token::Paren))?;
4806 let mut err = self.struct_span_err(
4807 lo.to(self.prev_span),
4808 "parenthesized lifetime bounds are not supported"
4810 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
4811 err.span_suggestion_short(
4812 lo.to(self.prev_span),
4813 "remove the parentheses",
4815 Applicability::MachineApplicable
4821 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4822 let path = self.parse_path(PathStyle::Type)?;
4824 self.expect(&token::CloseDelim(token::Paren))?;
4826 let poly_span = lo.to(self.prev_span);
4828 was_negative = true;
4829 if let Some(sp) = last_plus_span.or(colon_span) {
4830 negative_bounds.push(sp.to(poly_span));
4833 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
4834 let modifier = if question.is_some() {
4835 TraitBoundModifier::Maybe
4837 TraitBoundModifier::None
4839 bounds.push(GenericBound::Trait(poly_trait, modifier));
4846 if !allow_plus || !self.eat_plus() {
4849 last_plus_span = Some(self.prev_span);
4853 if !negative_bounds.is_empty() || was_negative {
4854 let plural = negative_bounds.len() > 1;
4855 let last_span = negative_bounds.last().map(|sp| *sp);
4856 let mut err = self.struct_span_err(
4858 "negative trait bounds are not supported",
4860 if let Some(sp) = last_span {
4861 err.span_label(sp, "negative trait bounds are not supported");
4863 if let Some(bound_list) = colon_span {
4864 let bound_list = bound_list.to(self.prev_span);
4865 let mut new_bound_list = String::new();
4866 if !bounds.is_empty() {
4867 let mut snippets = bounds.iter().map(|bound| bound.span())
4868 .map(|span| self.sess.source_map().span_to_snippet(span));
4869 while let Some(Ok(snippet)) = snippets.next() {
4870 new_bound_list.push_str(" + ");
4871 new_bound_list.push_str(&snippet);
4873 new_bound_list = new_bound_list.replacen(" +", ":", 1);
4875 err.span_suggestion_hidden(
4877 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
4879 Applicability::MachineApplicable,
4888 crate fn parse_generic_bounds(&mut self,
4889 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4890 self.parse_generic_bounds_common(true, colon_span)
4893 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4896 /// BOUND = LT_BOUND (e.g., `'a`)
4898 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4899 let mut lifetimes = Vec::new();
4900 while self.check_lifetime() {
4901 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4903 if !self.eat_plus() {
4910 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
4911 fn parse_ty_param(&mut self,
4912 preceding_attrs: Vec<Attribute>)
4913 -> PResult<'a, GenericParam> {
4914 let ident = self.parse_ident()?;
4916 // Parse optional colon and param bounds.
4917 let bounds = if self.eat(&token::Colon) {
4918 self.parse_generic_bounds(Some(self.prev_span))?
4923 let default = if self.eat(&token::Eq) {
4924 Some(self.parse_ty()?)
4931 id: ast::DUMMY_NODE_ID,
4932 attrs: preceding_attrs.into(),
4934 kind: GenericParamKind::Type {
4940 /// Parses the following grammar:
4942 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4943 fn parse_trait_item_assoc_ty(&mut self)
4944 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4945 let ident = self.parse_ident()?;
4946 let mut generics = self.parse_generics()?;
4948 // Parse optional colon and param bounds.
4949 let bounds = if self.eat(&token::Colon) {
4950 self.parse_generic_bounds(None)?
4954 generics.where_clause = self.parse_where_clause()?;
4956 let default = if self.eat(&token::Eq) {
4957 Some(self.parse_ty()?)
4961 self.expect(&token::Semi)?;
4963 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4966 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
4967 self.expect_keyword(kw::Const)?;
4968 let ident = self.parse_ident()?;
4969 self.expect(&token::Colon)?;
4970 let ty = self.parse_ty()?;
4974 id: ast::DUMMY_NODE_ID,
4975 attrs: preceding_attrs.into(),
4977 kind: GenericParamKind::Const {
4983 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
4984 /// a trailing comma and erroneous trailing attributes.
4985 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4986 let mut params = Vec::new();
4988 let attrs = self.parse_outer_attributes()?;
4989 if self.check_lifetime() {
4990 let lifetime = self.expect_lifetime();
4991 // Parse lifetime parameter.
4992 let bounds = if self.eat(&token::Colon) {
4993 self.parse_lt_param_bounds()
4997 params.push(ast::GenericParam {
4998 ident: lifetime.ident,
5000 attrs: attrs.into(),
5002 kind: ast::GenericParamKind::Lifetime,
5004 } else if self.check_keyword(kw::Const) {
5005 // Parse const parameter.
5006 params.push(self.parse_const_param(attrs)?);
5007 } else if self.check_ident() {
5008 // Parse type parameter.
5009 params.push(self.parse_ty_param(attrs)?);
5011 // Check for trailing attributes and stop parsing.
5012 if !attrs.is_empty() {
5013 if !params.is_empty() {
5014 self.struct_span_err(
5016 &format!("trailing attribute after generic parameter"),
5018 .span_label(attrs[0].span, "attributes must go before parameters")
5021 self.struct_span_err(
5023 &format!("attribute without generic parameters"),
5027 "attributes are only permitted when preceding parameters",
5035 if !self.eat(&token::Comma) {
5042 /// Parses a set of optional generic type parameter declarations. Where
5043 /// clauses are not parsed here, and must be added later via
5044 /// `parse_where_clause()`.
5046 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5047 /// | ( < lifetimes , typaramseq ( , )? > )
5048 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5049 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5050 let span_lo = self.token.span;
5051 let (params, span) = if self.eat_lt() {
5052 let params = self.parse_generic_params()?;
5054 (params, span_lo.to(self.prev_span))
5056 (vec![], self.prev_span.between(self.token.span))
5060 where_clause: WhereClause {
5061 predicates: Vec::new(),
5068 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5069 /// For the purposes of understanding the parsing logic of generic arguments, this function
5070 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5071 /// had the correct amount of leading angle brackets.
5073 /// ```ignore (diagnostics)
5074 /// bar::<<<<T as Foo>::Output>();
5075 /// ^^ help: remove extra angle brackets
5077 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5081 ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5082 // We need to detect whether there are extra leading left angle brackets and produce an
5083 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5084 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5085 // then there won't be matching `>` tokens to find.
5087 // To explain how this detection works, consider the following example:
5089 // ```ignore (diagnostics)
5090 // bar::<<<<T as Foo>::Output>();
5091 // ^^ help: remove extra angle brackets
5094 // Parsing of the left angle brackets starts in this function. We start by parsing the
5095 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5098 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5099 // *Unmatched count:* 1
5100 // *`parse_path_segment` calls deep:* 0
5102 // This has the effect of recursing as this function is called if a `<` character
5103 // is found within the expected generic arguments:
5105 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5106 // *Unmatched count:* 2
5107 // *`parse_path_segment` calls deep:* 1
5109 // Eventually we will have recursed until having consumed all of the `<` tokens and
5110 // this will be reflected in the count:
5112 // *Upcoming tokens:* `T as Foo>::Output>;`
5113 // *Unmatched count:* 4
5114 // `parse_path_segment` calls deep:* 3
5116 // The parser will continue until reaching the first `>` - this will decrement the
5117 // unmatched angle bracket count and return to the parent invocation of this function
5118 // having succeeded in parsing:
5120 // *Upcoming tokens:* `::Output>;`
5121 // *Unmatched count:* 3
5122 // *`parse_path_segment` calls deep:* 2
5124 // This will continue until the next `>` character which will also return successfully
5125 // to the parent invocation of this function and decrement the count:
5127 // *Upcoming tokens:* `;`
5128 // *Unmatched count:* 2
5129 // *`parse_path_segment` calls deep:* 1
5131 // At this point, this function will expect to find another matching `>` character but
5132 // won't be able to and will return an error. This will continue all the way up the
5133 // call stack until the first invocation:
5135 // *Upcoming tokens:* `;`
5136 // *Unmatched count:* 2
5137 // *`parse_path_segment` calls deep:* 0
5139 // In doing this, we have managed to work out how many unmatched leading left angle
5140 // brackets there are, but we cannot recover as the unmatched angle brackets have
5141 // already been consumed. To remedy this, we keep a snapshot of the parser state
5142 // before we do the above. We can then inspect whether we ended up with a parsing error
5143 // and unmatched left angle brackets and if so, restore the parser state before we
5144 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5145 // recover by attempting to parse again.
5147 // In practice, the recursion of this function is indirect and there will be other
5148 // locations that consume some `<` characters - as long as we update the count when
5149 // this happens, it isn't an issue.
5151 let is_first_invocation = style == PathStyle::Expr;
5152 // Take a snapshot before attempting to parse - we can restore this later.
5153 let snapshot = if is_first_invocation {
5159 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5160 match self.parse_generic_args() {
5161 Ok(value) => Ok(value),
5162 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5163 // Cancel error from being unable to find `>`. We know the error
5164 // must have been this due to a non-zero unmatched angle bracket
5168 // Swap `self` with our backup of the parser state before attempting to parse
5169 // generic arguments.
5170 let snapshot = mem::replace(self, snapshot.unwrap());
5173 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5174 snapshot.count={:?}",
5175 snapshot.unmatched_angle_bracket_count,
5178 // Eat the unmatched angle brackets.
5179 for _ in 0..snapshot.unmatched_angle_bracket_count {
5183 // Make a span over ${unmatched angle bracket count} characters.
5184 let span = lo.with_hi(
5185 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5187 let plural = snapshot.unmatched_angle_bracket_count > 1;
5192 "unmatched angle bracket{}",
5193 if plural { "s" } else { "" }
5199 "remove extra angle bracket{}",
5200 if plural { "s" } else { "" }
5203 Applicability::MachineApplicable,
5207 // Try again without unmatched angle bracket characters.
5208 self.parse_generic_args()
5214 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5215 /// possibly including trailing comma.
5216 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5217 let mut args = Vec::new();
5218 let mut constraints = Vec::new();
5219 let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new();
5220 let mut assoc_ty_constraints: Vec<Span> = Vec::new();
5222 let args_lo = self.token.span;
5225 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5226 // Parse lifetime argument.
5227 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5228 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5229 } else if self.check_ident() && self.look_ahead(1,
5230 |t| t == &token::Eq || t == &token::Colon) {
5231 // Parse associated type constraint.
5232 let lo = self.token.span;
5233 let ident = self.parse_ident()?;
5234 let kind = if self.eat(&token::Eq) {
5235 AssocTyConstraintKind::Equality {
5236 ty: self.parse_ty()?,
5238 } else if self.eat(&token::Colon) {
5239 AssocTyConstraintKind::Bound {
5240 bounds: self.parse_generic_bounds(Some(self.prev_span))?,
5245 let span = lo.to(self.prev_span);
5246 constraints.push(AssocTyConstraint {
5247 id: ast::DUMMY_NODE_ID,
5252 assoc_ty_constraints.push(span);
5253 } else if self.check_const_arg() {
5254 // Parse const argument.
5255 let expr = if let token::OpenDelim(token::Brace) = self.token.kind {
5256 self.parse_block_expr(
5257 None, self.token.span, BlockCheckMode::Default, ThinVec::new()
5259 } else if self.token.is_ident() {
5260 // FIXME(const_generics): to distinguish between idents for types and consts,
5261 // we should introduce a GenericArg::Ident in the AST and distinguish when
5262 // lowering to the HIR. For now, idents for const args are not permitted.
5263 if self.token.is_keyword(kw::True) || self.token.is_keyword(kw::False) {
5264 self.parse_literal_maybe_minus()?
5267 self.fatal("identifiers may currently not be used for const generics")
5271 self.parse_literal_maybe_minus()?
5273 let value = AnonConst {
5274 id: ast::DUMMY_NODE_ID,
5277 args.push(GenericArg::Const(value));
5278 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5279 } else if self.check_type() {
5280 // Parse type argument.
5281 args.push(GenericArg::Type(self.parse_ty()?));
5282 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5287 if !self.eat(&token::Comma) {
5292 // FIXME: we would like to report this in ast_validation instead, but we currently do not
5293 // preserve ordering of generic parameters with respect to associated type binding, so we
5294 // lose that information after parsing.
5295 if misplaced_assoc_ty_constraints.len() > 0 {
5296 let mut err = self.struct_span_err(
5297 args_lo.to(self.prev_span),
5298 "associated type bindings must be declared after generic parameters",
5300 for span in misplaced_assoc_ty_constraints {
5303 "this associated type binding should be moved after the generic parameters",
5309 Ok((args, constraints))
5312 /// Parses an optional where-clause and places it in `generics`.
5314 /// ```ignore (only-for-syntax-highlight)
5315 /// where T : Trait<U, V> + 'b, 'a : 'b
5317 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5318 let mut where_clause = WhereClause {
5319 predicates: Vec::new(),
5320 span: self.prev_span.to(self.prev_span),
5323 if !self.eat_keyword(kw::Where) {
5324 return Ok(where_clause);
5326 let lo = self.prev_span;
5328 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5329 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5330 // change we parse those generics now, but report an error.
5331 if self.choose_generics_over_qpath() {
5332 let generics = self.parse_generics()?;
5333 self.struct_span_err(
5335 "generic parameters on `where` clauses are reserved for future use",
5337 .span_label(generics.span, "currently unsupported")
5342 let lo = self.token.span;
5343 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5344 let lifetime = self.expect_lifetime();
5345 // Bounds starting with a colon are mandatory, but possibly empty.
5346 self.expect(&token::Colon)?;
5347 let bounds = self.parse_lt_param_bounds();
5348 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5349 ast::WhereRegionPredicate {
5350 span: lo.to(self.prev_span),
5355 } else if self.check_type() {
5356 // Parse optional `for<'a, 'b>`.
5357 // This `for` is parsed greedily and applies to the whole predicate,
5358 // the bounded type can have its own `for` applying only to it.
5360 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
5361 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
5362 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
5363 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5365 // Parse type with mandatory colon and (possibly empty) bounds,
5366 // or with mandatory equality sign and the second type.
5367 let ty = self.parse_ty()?;
5368 if self.eat(&token::Colon) {
5369 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
5370 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5371 ast::WhereBoundPredicate {
5372 span: lo.to(self.prev_span),
5373 bound_generic_params: lifetime_defs,
5378 // FIXME: Decide what should be used here, `=` or `==`.
5379 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5380 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5381 let rhs_ty = self.parse_ty()?;
5382 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5383 ast::WhereEqPredicate {
5384 span: lo.to(self.prev_span),
5387 id: ast::DUMMY_NODE_ID,
5391 return self.unexpected();
5397 if !self.eat(&token::Comma) {
5402 where_clause.span = lo.to(self.prev_span);
5406 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
5407 -> PResult<'a, (Vec<Arg> , bool)> {
5408 self.expect(&token::OpenDelim(token::Paren))?;
5410 let sp = self.token.span;
5411 let mut c_variadic = false;
5412 let (args, recovered): (Vec<Option<Arg>>, bool) =
5413 self.parse_seq_to_before_end(
5414 &token::CloseDelim(token::Paren),
5415 SeqSep::trailing_allowed(token::Comma),
5417 let do_not_enforce_named_arguments_for_c_variadic =
5418 |token: &token::Token| -> bool {
5419 if token == &token::DotDotDot {
5425 match p.parse_arg_general(
5428 do_not_enforce_named_arguments_for_c_variadic
5431 if let TyKind::CVarArgs = arg.ty.node {
5433 if p.token != token::CloseDelim(token::Paren) {
5434 let span = p.token.span;
5436 "`...` must be the last argument of a C-variadic function");
5447 let lo = p.prev_span;
5448 // Skip every token until next possible arg or end.
5449 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5450 // Create a placeholder argument for proper arg count (issue #34264).
5451 let span = lo.to(p.prev_span);
5452 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
5459 self.eat(&token::CloseDelim(token::Paren));
5462 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5464 if c_variadic && args.is_empty() {
5466 "C-variadic function must be declared with at least one named argument");
5469 Ok((args, c_variadic))
5472 /// Parses the argument list and result type of a function declaration.
5473 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
5474 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
5475 let ret_ty = self.parse_ret_ty(true)?;
5484 /// Returns the parsed optional self argument and whether a self shortcut was used.
5486 /// See `parse_self_arg_with_attrs` to collect attributes.
5487 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5488 let expect_ident = |this: &mut Self| match this.token.kind {
5489 // Preserve hygienic context.
5490 token::Ident(name, _) =>
5491 { let span = this.token.span; this.bump(); Ident::new(name, span) }
5494 let isolated_self = |this: &mut Self, n| {
5495 this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
5496 this.look_ahead(n + 1, |t| t != &token::ModSep)
5499 // Parse optional `self` parameter of a method.
5500 // Only a limited set of initial token sequences is considered `self` parameters; anything
5501 // else is parsed as a normal function parameter list, so some lookahead is required.
5502 let eself_lo = self.token.span;
5503 let (eself, eself_ident, eself_hi) = match self.token.kind {
5504 token::BinOp(token::And) => {
5510 (if isolated_self(self, 1) {
5512 SelfKind::Region(None, Mutability::Immutable)
5513 } else if self.is_keyword_ahead(1, &[kw::Mut]) &&
5514 isolated_self(self, 2) {
5517 SelfKind::Region(None, Mutability::Mutable)
5518 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5519 isolated_self(self, 2) {
5521 let lt = self.expect_lifetime();
5522 SelfKind::Region(Some(lt), Mutability::Immutable)
5523 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5524 self.is_keyword_ahead(2, &[kw::Mut]) &&
5525 isolated_self(self, 3) {
5527 let lt = self.expect_lifetime();
5529 SelfKind::Region(Some(lt), Mutability::Mutable)
5532 }, expect_ident(self), self.prev_span)
5534 token::BinOp(token::Star) => {
5539 // Emit special error for `self` cases.
5540 let msg = "cannot pass `self` by raw pointer";
5541 (if isolated_self(self, 1) {
5543 self.struct_span_err(self.token.span, msg)
5544 .span_label(self.token.span, msg)
5546 SelfKind::Value(Mutability::Immutable)
5547 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5548 isolated_self(self, 2) {
5551 self.struct_span_err(self.token.span, msg)
5552 .span_label(self.token.span, msg)
5554 SelfKind::Value(Mutability::Immutable)
5557 }, expect_ident(self), self.prev_span)
5559 token::Ident(..) => {
5560 if isolated_self(self, 0) {
5563 let eself_ident = expect_ident(self);
5564 let eself_hi = self.prev_span;
5565 (if self.eat(&token::Colon) {
5566 let ty = self.parse_ty()?;
5567 SelfKind::Explicit(ty, Mutability::Immutable)
5569 SelfKind::Value(Mutability::Immutable)
5570 }, eself_ident, eself_hi)
5571 } else if self.token.is_keyword(kw::Mut) &&
5572 isolated_self(self, 1) {
5576 let eself_ident = expect_ident(self);
5577 let eself_hi = self.prev_span;
5578 (if self.eat(&token::Colon) {
5579 let ty = self.parse_ty()?;
5580 SelfKind::Explicit(ty, Mutability::Mutable)
5582 SelfKind::Value(Mutability::Mutable)
5583 }, eself_ident, eself_hi)
5588 _ => return Ok(None),
5591 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5592 Ok(Some(Arg::from_self(ThinVec::default(), eself, eself_ident)))
5595 /// Returns the parsed optional self argument with attributes and whether a self
5596 /// shortcut was used.
5597 fn parse_self_arg_with_attrs(&mut self) -> PResult<'a, Option<Arg>> {
5598 let attrs = self.parse_arg_attributes()?;
5599 let arg_opt = self.parse_self_arg()?;
5600 Ok(arg_opt.map(|mut arg| {
5601 arg.attrs = attrs.into();
5606 /// Parses the parameter list and result type of a function that may have a `self` parameter.
5607 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5608 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5610 self.expect(&token::OpenDelim(token::Paren))?;
5612 // Parse optional self argument.
5613 let self_arg = self.parse_self_arg_with_attrs()?;
5615 // Parse the rest of the function parameter list.
5616 let sep = SeqSep::trailing_allowed(token::Comma);
5617 let (mut fn_inputs, recovered) = if let Some(self_arg) = self_arg {
5618 if self.check(&token::CloseDelim(token::Paren)) {
5619 (vec![self_arg], false)
5620 } else if self.eat(&token::Comma) {
5621 let mut fn_inputs = vec![self_arg];
5622 let (mut input, recovered) = self.parse_seq_to_before_end(
5623 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
5624 fn_inputs.append(&mut input);
5625 (fn_inputs, recovered)
5627 match self.expect_one_of(&[], &[]) {
5628 Err(err) => return Err(err),
5629 Ok(recovered) => (vec![self_arg], recovered),
5633 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5637 // Parse closing paren and return type.
5638 self.expect(&token::CloseDelim(token::Paren))?;
5640 // Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
5641 self.deduplicate_recovered_arg_names(&mut fn_inputs);
5645 output: self.parse_ret_ty(true)?,
5650 /// Parses the `|arg, arg|` header of a closure.
5651 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5652 let inputs_captures = {
5653 if self.eat(&token::OrOr) {
5656 self.expect(&token::BinOp(token::Or))?;
5657 let args = self.parse_seq_to_before_tokens(
5658 &[&token::BinOp(token::Or), &token::OrOr],
5659 SeqSep::trailing_allowed(token::Comma),
5660 TokenExpectType::NoExpect,
5661 |p| p.parse_fn_block_arg()
5667 let output = self.parse_ret_ty(true)?;
5670 inputs: inputs_captures,
5676 /// Parses the name and optional generic types of a function header.
5677 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5678 let id = self.parse_ident()?;
5679 let generics = self.parse_generics()?;
5683 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5684 attrs: Vec<Attribute>) -> P<Item> {
5688 id: ast::DUMMY_NODE_ID,
5696 /// Parses an item-position function declaration.
5697 fn parse_item_fn(&mut self,
5699 asyncness: Spanned<IsAsync>,
5700 constness: Spanned<Constness>,
5702 -> PResult<'a, ItemInfo> {
5703 let (ident, mut generics) = self.parse_fn_header()?;
5704 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
5705 let decl = self.parse_fn_decl(allow_c_variadic)?;
5706 generics.where_clause = self.parse_where_clause()?;
5707 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5708 let header = FnHeader { unsafety, asyncness, constness, abi };
5709 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5712 /// Returns `true` if we are looking at `const ID`
5713 /// (returns `false` for things like `const fn`, etc.).
5714 fn is_const_item(&self) -> bool {
5715 self.token.is_keyword(kw::Const) &&
5716 !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
5719 /// Parses all the "front matter" for a `fn` declaration, up to
5720 /// and including the `fn` keyword:
5724 /// - `const unsafe fn`
5727 fn parse_fn_front_matter(&mut self)
5735 let is_const_fn = self.eat_keyword(kw::Const);
5736 let const_span = self.prev_span;
5737 let asyncness = self.parse_asyncness();
5738 if let IsAsync::Async { .. } = asyncness {
5739 self.ban_async_in_2015(self.prev_span);
5741 let asyncness = respan(self.prev_span, asyncness);
5742 let unsafety = self.parse_unsafety();
5743 let (constness, unsafety, abi) = if is_const_fn {
5744 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5746 let abi = if self.eat_keyword(kw::Extern) {
5747 self.parse_opt_abi()?.unwrap_or(Abi::C)
5751 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5753 if !self.eat_keyword(kw::Fn) {
5754 // It is possible for `expect_one_of` to recover given the contents of
5755 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
5756 // account for this.
5757 if !self.expect_one_of(&[], &[])? { unreachable!() }
5759 Ok((constness, unsafety, asyncness, abi))
5762 /// Parses an impl item.
5763 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5764 maybe_whole!(self, NtImplItem, |x| x);
5765 let attrs = self.parse_outer_attributes()?;
5766 let mut unclosed_delims = vec![];
5767 let (mut item, tokens) = self.collect_tokens(|this| {
5768 let item = this.parse_impl_item_(at_end, attrs);
5769 unclosed_delims.append(&mut this.unclosed_delims);
5772 self.unclosed_delims.append(&mut unclosed_delims);
5774 // See `parse_item` for why this clause is here.
5775 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5776 item.tokens = Some(tokens);
5781 fn parse_impl_item_(&mut self,
5783 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5784 let lo = self.token.span;
5785 let vis = self.parse_visibility(false)?;
5786 let defaultness = self.parse_defaultness();
5787 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5788 let (name, alias, generics) = type_?;
5789 let kind = match alias {
5790 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5791 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5793 (name, kind, generics)
5794 } else if self.is_const_item() {
5795 // This parses the grammar:
5796 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5797 self.expect_keyword(kw::Const)?;
5798 let name = self.parse_ident()?;
5799 self.expect(&token::Colon)?;
5800 let typ = self.parse_ty()?;
5801 self.expect(&token::Eq)?;
5802 let expr = self.parse_expr()?;
5803 self.expect(&token::Semi)?;
5804 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5806 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5807 attrs.extend(inner_attrs);
5808 (name, node, generics)
5812 id: ast::DUMMY_NODE_ID,
5813 span: lo.to(self.prev_span),
5824 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
5826 VisibilityKind::Inherited => {}
5828 let mut err = if self.token.is_keyword(sym::macro_rules) {
5829 let mut err = self.diagnostic()
5830 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5831 err.span_suggestion(
5833 "try exporting the macro",
5834 "#[macro_export]".to_owned(),
5835 Applicability::MaybeIncorrect // speculative
5839 let mut err = self.diagnostic()
5840 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5841 err.help("try adjusting the macro to put `pub` inside the invocation");
5849 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
5850 -> DiagnosticBuilder<'a>
5852 let expected_kinds = if item_type == "extern" {
5853 "missing `fn`, `type`, or `static`"
5855 "missing `fn`, `type`, or `const`"
5858 // Given this code `path(`, it seems like this is not
5859 // setting the visibility of a macro invocation, but rather
5860 // a mistyped method declaration.
5861 // Create a diagnostic pointing out that `fn` is missing.
5863 // x | pub path(&self) {
5864 // | ^ missing `fn`, `type`, or `const`
5866 // ^^ `sp` below will point to this
5867 let sp = prev_span.between(self.prev_span);
5868 let mut err = self.diagnostic().struct_span_err(
5870 &format!("{} for {}-item declaration",
5871 expected_kinds, item_type));
5872 err.span_label(sp, expected_kinds);
5876 /// Parse a method or a macro invocation in a trait impl.
5877 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5878 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5879 ast::ImplItemKind)> {
5880 // code copied from parse_macro_use_or_failure... abstraction!
5881 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5883 Ok((Ident::invalid(), vec![], ast::Generics::default(),
5884 ast::ImplItemKind::Macro(mac)))
5886 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5887 let ident = self.parse_ident()?;
5888 let mut generics = self.parse_generics()?;
5889 let decl = self.parse_fn_decl_with_self(|p| {
5890 p.parse_arg_general(true, false, |_| true)
5892 generics.where_clause = self.parse_where_clause()?;
5894 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5895 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5896 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5897 ast::MethodSig { header, decl },
5903 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
5904 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5905 let ident = self.parse_ident()?;
5906 let mut tps = self.parse_generics()?;
5908 // Parse optional colon and supertrait bounds.
5909 let bounds = if self.eat(&token::Colon) {
5910 self.parse_generic_bounds(Some(self.prev_span))?
5915 if self.eat(&token::Eq) {
5916 // it's a trait alias
5917 let bounds = self.parse_generic_bounds(None)?;
5918 tps.where_clause = self.parse_where_clause()?;
5919 self.expect(&token::Semi)?;
5920 if is_auto == IsAuto::Yes {
5921 let msg = "trait aliases cannot be `auto`";
5922 self.struct_span_err(self.prev_span, msg)
5923 .span_label(self.prev_span, msg)
5926 if unsafety != Unsafety::Normal {
5927 let msg = "trait aliases cannot be `unsafe`";
5928 self.struct_span_err(self.prev_span, msg)
5929 .span_label(self.prev_span, msg)
5932 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5934 // it's a normal trait
5935 tps.where_clause = self.parse_where_clause()?;
5936 self.expect(&token::OpenDelim(token::Brace))?;
5937 let mut trait_items = vec![];
5938 while !self.eat(&token::CloseDelim(token::Brace)) {
5939 if let token::DocComment(_) = self.token.kind {
5940 if self.look_ahead(1,
5941 |tok| tok == &token::CloseDelim(token::Brace)) {
5942 let mut err = self.diagnostic().struct_span_err_with_code(
5944 "found a documentation comment that doesn't document anything",
5945 DiagnosticId::Error("E0584".into()),
5947 err.help("doc comments must come before what they document, maybe a \
5948 comment was intended with `//`?",
5955 let mut at_end = false;
5956 match self.parse_trait_item(&mut at_end) {
5957 Ok(item) => trait_items.push(item),
5961 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5966 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5970 fn choose_generics_over_qpath(&self) -> bool {
5971 // There's an ambiguity between generic parameters and qualified paths in impls.
5972 // If we see `<` it may start both, so we have to inspect some following tokens.
5973 // The following combinations can only start generics,
5974 // but not qualified paths (with one exception):
5975 // `<` `>` - empty generic parameters
5976 // `<` `#` - generic parameters with attributes
5977 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5978 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5979 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5980 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5981 // `<` const - generic const parameter
5982 // The only truly ambiguous case is
5983 // `<` IDENT `>` `::` IDENT ...
5984 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5985 // because this is what almost always expected in practice, qualified paths in impls
5986 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5987 self.token == token::Lt &&
5988 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5989 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5990 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5991 t == &token::Colon || t == &token::Eq) ||
5992 self.is_keyword_ahead(1, &[kw::Const]))
5995 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5996 self.expect(&token::OpenDelim(token::Brace))?;
5997 let attrs = self.parse_inner_attributes()?;
5999 let mut impl_items = Vec::new();
6000 while !self.eat(&token::CloseDelim(token::Brace)) {
6001 let mut at_end = false;
6002 match self.parse_impl_item(&mut at_end) {
6003 Ok(impl_item) => impl_items.push(impl_item),
6007 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6012 Ok((impl_items, attrs))
6015 /// Parses an implementation item, `impl` keyword is already parsed.
6017 /// impl<'a, T> TYPE { /* impl items */ }
6018 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6019 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6021 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6022 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6023 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6024 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6025 -> PResult<'a, ItemInfo> {
6026 // First, parse generic parameters if necessary.
6027 let mut generics = if self.choose_generics_over_qpath() {
6028 self.parse_generics()?
6030 ast::Generics::default()
6033 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6034 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6036 ast::ImplPolarity::Negative
6038 ast::ImplPolarity::Positive
6041 // Parse both types and traits as a type, then reinterpret if necessary.
6042 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
6043 let ty_first = if self.token.is_keyword(kw::For) &&
6044 self.look_ahead(1, |t| t != &token::Lt) {
6045 let span = self.prev_span.between(self.token.span);
6046 self.struct_span_err(span, "missing trait in a trait impl").emit();
6047 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6052 // If `for` is missing we try to recover.
6053 let has_for = self.eat_keyword(kw::For);
6054 let missing_for_span = self.prev_span.between(self.token.span);
6056 let ty_second = if self.token == token::DotDot {
6057 // We need to report this error after `cfg` expansion for compatibility reasons
6058 self.bump(); // `..`, do not add it to expected tokens
6059 Some(DummyResult::raw_ty(self.prev_span, true))
6060 } else if has_for || self.token.can_begin_type() {
6061 Some(self.parse_ty()?)
6066 generics.where_clause = self.parse_where_clause()?;
6068 let (impl_items, attrs) = self.parse_impl_body()?;
6070 let item_kind = match ty_second {
6071 Some(ty_second) => {
6072 // impl Trait for Type
6074 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6075 .span_suggestion_short(
6078 " for ".to_string(),
6079 Applicability::MachineApplicable,
6083 let ty_first = ty_first.into_inner();
6084 let path = match ty_first.node {
6085 // This notably includes paths passed through `ty` macro fragments (#46438).
6086 TyKind::Path(None, path) => path,
6088 self.span_err(ty_first.span, "expected a trait, found type");
6089 err_path(ty_first.span)
6092 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6094 ItemKind::Impl(unsafety, polarity, defaultness,
6095 generics, Some(trait_ref), ty_second, impl_items)
6099 ItemKind::Impl(unsafety, polarity, defaultness,
6100 generics, None, ty_first, impl_items)
6104 Ok((Ident::invalid(), item_kind, Some(attrs)))
6107 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6108 if self.eat_keyword(kw::For) {
6110 let params = self.parse_generic_params()?;
6112 // We rely on AST validation to rule out invalid cases: There must not be type
6113 // parameters, and the lifetime parameters must not have bounds.
6120 /// Parses `struct Foo { ... }`.
6121 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6122 let class_name = self.parse_ident()?;
6124 let mut generics = self.parse_generics()?;
6126 // There is a special case worth noting here, as reported in issue #17904.
6127 // If we are parsing a tuple struct it is the case that the where clause
6128 // should follow the field list. Like so:
6130 // struct Foo<T>(T) where T: Copy;
6132 // If we are parsing a normal record-style struct it is the case
6133 // that the where clause comes before the body, and after the generics.
6134 // So if we look ahead and see a brace or a where-clause we begin
6135 // parsing a record style struct.
6137 // Otherwise if we look ahead and see a paren we parse a tuple-style
6140 let vdata = if self.token.is_keyword(kw::Where) {
6141 generics.where_clause = self.parse_where_clause()?;
6142 if self.eat(&token::Semi) {
6143 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6144 VariantData::Unit(ast::DUMMY_NODE_ID)
6146 // If we see: `struct Foo<T> where T: Copy { ... }`
6147 let (fields, recovered) = self.parse_record_struct_body()?;
6148 VariantData::Struct(fields, recovered)
6150 // No `where` so: `struct Foo<T>;`
6151 } else if self.eat(&token::Semi) {
6152 VariantData::Unit(ast::DUMMY_NODE_ID)
6153 // Record-style struct definition
6154 } else if self.token == token::OpenDelim(token::Brace) {
6155 let (fields, recovered) = self.parse_record_struct_body()?;
6156 VariantData::Struct(fields, recovered)
6157 // Tuple-style struct definition with optional where-clause.
6158 } else if self.token == token::OpenDelim(token::Paren) {
6159 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6160 generics.where_clause = self.parse_where_clause()?;
6161 self.expect(&token::Semi)?;
6164 let token_str = self.this_token_descr();
6165 let mut err = self.fatal(&format!(
6166 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6169 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
6173 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6176 /// Parses `union Foo { ... }`.
6177 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6178 let class_name = self.parse_ident()?;
6180 let mut generics = self.parse_generics()?;
6182 let vdata = if self.token.is_keyword(kw::Where) {
6183 generics.where_clause = self.parse_where_clause()?;
6184 let (fields, recovered) = self.parse_record_struct_body()?;
6185 VariantData::Struct(fields, recovered)
6186 } else if self.token == token::OpenDelim(token::Brace) {
6187 let (fields, recovered) = self.parse_record_struct_body()?;
6188 VariantData::Struct(fields, recovered)
6190 let token_str = self.this_token_descr();
6191 let mut err = self.fatal(&format!(
6192 "expected `where` or `{{` after union name, found {}", token_str));
6193 err.span_label(self.token.span, "expected `where` or `{` after union name");
6197 Ok((class_name, ItemKind::Union(vdata, generics), None))
6200 fn parse_record_struct_body(
6202 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6203 let mut fields = Vec::new();
6204 let mut recovered = false;
6205 if self.eat(&token::OpenDelim(token::Brace)) {
6206 while self.token != token::CloseDelim(token::Brace) {
6207 let field = self.parse_struct_decl_field().map_err(|e| {
6208 self.recover_stmt();
6213 Ok(field) => fields.push(field),
6219 self.eat(&token::CloseDelim(token::Brace));
6221 let token_str = self.this_token_descr();
6222 let mut err = self.fatal(&format!(
6223 "expected `where`, or `{{` after struct name, found {}", token_str));
6224 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
6228 Ok((fields, recovered))
6231 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6232 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6233 // Unit like structs are handled in parse_item_struct function
6234 let fields = self.parse_unspanned_seq(
6235 &token::OpenDelim(token::Paren),
6236 &token::CloseDelim(token::Paren),
6237 SeqSep::trailing_allowed(token::Comma),
6239 let attrs = p.parse_outer_attributes()?;
6240 let lo = p.token.span;
6241 let vis = p.parse_visibility(true)?;
6242 let ty = p.parse_ty()?;
6244 span: lo.to(ty.span),
6247 id: ast::DUMMY_NODE_ID,
6256 /// Parses a structure field declaration.
6257 fn parse_single_struct_field(&mut self,
6260 attrs: Vec<Attribute> )
6261 -> PResult<'a, StructField> {
6262 let mut seen_comma: bool = false;
6263 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6264 if self.token == token::Comma {
6267 match self.token.kind {
6271 token::CloseDelim(token::Brace) => {}
6272 token::DocComment(_) => {
6273 let previous_span = self.prev_span;
6274 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
6275 self.bump(); // consume the doc comment
6276 let comma_after_doc_seen = self.eat(&token::Comma);
6277 // `seen_comma` is always false, because we are inside doc block
6278 // condition is here to make code more readable
6279 if seen_comma == false && comma_after_doc_seen == true {
6282 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6285 if seen_comma == false {
6286 let sp = self.sess.source_map().next_point(previous_span);
6287 err.span_suggestion(
6289 "missing comma here",
6291 Applicability::MachineApplicable
6298 let sp = self.sess.source_map().next_point(self.prev_span);
6299 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6300 self.this_token_descr()));
6301 if self.token.is_ident() {
6302 // This is likely another field; emit the diagnostic and keep going
6303 err.span_suggestion(
6305 "try adding a comma",
6307 Applicability::MachineApplicable,
6318 /// Parses an element of a struct declaration.
6319 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6320 let attrs = self.parse_outer_attributes()?;
6321 let lo = self.token.span;
6322 let vis = self.parse_visibility(false)?;
6323 self.parse_single_struct_field(lo, vis, attrs)
6326 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6327 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6328 /// If the following element can't be a tuple (i.e., it's a function definition), then
6329 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6330 /// so emit a proper diagnostic.
6331 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6332 maybe_whole!(self, NtVis, |x| x);
6334 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
6335 if self.is_crate_vis() {
6336 self.bump(); // `crate`
6337 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6340 if !self.eat_keyword(kw::Pub) {
6341 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6342 // keyword to grab a span from for inherited visibility; an empty span at the
6343 // beginning of the current token would seem to be the "Schelling span".
6344 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
6346 let lo = self.prev_span;
6348 if self.check(&token::OpenDelim(token::Paren)) {
6349 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6350 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6351 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6352 // by the following tokens.
6353 if self.is_keyword_ahead(1, &[kw::Crate]) &&
6354 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
6358 self.bump(); // `crate`
6359 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6361 lo.to(self.prev_span),
6362 VisibilityKind::Crate(CrateSugar::PubCrate),
6365 } else if self.is_keyword_ahead(1, &[kw::In]) {
6368 self.bump(); // `in`
6369 let path = self.parse_path(PathStyle::Mod)?; // `path`
6370 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6371 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6373 id: ast::DUMMY_NODE_ID,
6376 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6377 self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
6379 // `pub(self)` or `pub(super)`
6381 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6382 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6383 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6385 id: ast::DUMMY_NODE_ID,
6388 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6389 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6391 let msg = "incorrect visibility restriction";
6392 let suggestion = r##"some possible visibility restrictions are:
6393 `pub(crate)`: visible only on the current crate
6394 `pub(super)`: visible only in the current module's parent
6395 `pub(in path::to::module)`: visible only on the specified path"##;
6396 let path = self.parse_path(PathStyle::Mod)?;
6398 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6399 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6400 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6401 err.help(suggestion);
6402 err.span_suggestion(
6403 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6405 err.emit(); // emit diagnostic, but continue with public visibility
6409 Ok(respan(lo, VisibilityKind::Public))
6412 /// Parses defaultness (i.e., `default` or nothing).
6413 fn parse_defaultness(&mut self) -> Defaultness {
6414 // `pub` is included for better error messages
6415 if self.check_keyword(kw::Default) &&
6416 self.is_keyword_ahead(1, &[
6426 self.bump(); // `default`
6427 Defaultness::Default
6433 /// Given a termination token, parses all of the items in a module.
6434 fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
6435 let mut items = vec![];
6436 while let Some(item) = self.parse_item()? {
6438 self.maybe_consume_incorrect_semicolon(&items);
6441 if !self.eat(term) {
6442 let token_str = self.this_token_descr();
6443 if !self.maybe_consume_incorrect_semicolon(&items) {
6444 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6445 err.span_label(self.token.span, "expected item");
6450 let hi = if self.token.span.is_dummy() {
6457 inner: inner_lo.to(hi),
6463 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6464 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6465 self.expect(&token::Colon)?;
6466 let ty = self.parse_ty()?;
6467 self.expect(&token::Eq)?;
6468 let e = self.parse_expr()?;
6469 self.expect(&token::Semi)?;
6470 let item = match m {
6471 Some(m) => ItemKind::Static(ty, m, e),
6472 None => ItemKind::Const(ty, e),
6474 Ok((id, item, None))
6477 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6478 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6479 let (in_cfg, outer_attrs) = {
6480 let mut strip_unconfigured = crate::config::StripUnconfigured {
6482 features: None, // don't perform gated feature checking
6484 let mut outer_attrs = outer_attrs.to_owned();
6485 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
6486 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6489 let id_span = self.token.span;
6490 let id = self.parse_ident()?;
6491 if self.eat(&token::Semi) {
6492 if in_cfg && self.recurse_into_file_modules {
6493 // This mod is in an external file. Let's go get it!
6494 let ModulePathSuccess { path, directory_ownership, warn } =
6495 self.submod_path(id, &outer_attrs, id_span)?;
6496 let (module, mut attrs) =
6497 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6498 // Record that we fetched the mod from an external file
6500 let attr = Attribute {
6501 id: attr::mk_attr_id(),
6502 style: ast::AttrStyle::Outer,
6503 path: ast::Path::from_ident(
6504 Ident::with_empty_ctxt(sym::warn_directory_ownership)),
6505 tokens: TokenStream::empty(),
6506 is_sugared_doc: false,
6509 attr::mark_known(&attr);
6512 Ok((id, ItemKind::Mod(module), Some(attrs)))
6514 let placeholder = ast::Mod {
6519 Ok((id, ItemKind::Mod(placeholder), None))
6522 let old_directory = self.directory.clone();
6523 self.push_directory(id, &outer_attrs);
6525 self.expect(&token::OpenDelim(token::Brace))?;
6526 let mod_inner_lo = self.token.span;
6527 let attrs = self.parse_inner_attributes()?;
6528 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6530 self.directory = old_directory;
6531 Ok((id, ItemKind::Mod(module), Some(attrs)))
6535 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6536 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6537 self.directory.path.to_mut().push(&path.as_str());
6538 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6540 // We have to push on the current module name in the case of relative
6541 // paths in order to ensure that any additional module paths from inline
6542 // `mod x { ... }` come after the relative extension.
6544 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6545 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6546 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6547 if let Some(ident) = relative.take() { // remove the relative offset
6548 self.directory.path.to_mut().push(ident.as_str());
6551 self.directory.path.to_mut().push(&id.as_str());
6555 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6556 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6559 // On windows, the base path might have the form
6560 // `\\?\foo\bar` in which case it does not tolerate
6561 // mixed `/` and `\` separators, so canonicalize
6564 let s = s.replace("/", "\\");
6565 Some(dir_path.join(s))
6571 /// Returns a path to a module.
6572 pub fn default_submod_path(
6574 relative: Option<ast::Ident>,
6576 source_map: &SourceMap) -> ModulePath
6578 // If we're in a foo.rs file instead of a mod.rs file,
6579 // we need to look for submodules in
6580 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6581 // `./<id>.rs` and `./<id>/mod.rs`.
6582 let relative_prefix_string;
6583 let relative_prefix = if let Some(ident) = relative {
6584 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6585 &relative_prefix_string
6590 let mod_name = id.to_string();
6591 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6592 let secondary_path_str = format!("{}{}{}mod.rs",
6593 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6594 let default_path = dir_path.join(&default_path_str);
6595 let secondary_path = dir_path.join(&secondary_path_str);
6596 let default_exists = source_map.file_exists(&default_path);
6597 let secondary_exists = source_map.file_exists(&secondary_path);
6599 let result = match (default_exists, secondary_exists) {
6600 (true, false) => Ok(ModulePathSuccess {
6602 directory_ownership: DirectoryOwnership::Owned {
6607 (false, true) => Ok(ModulePathSuccess {
6608 path: secondary_path,
6609 directory_ownership: DirectoryOwnership::Owned {
6614 (false, false) => Err(Error::FileNotFoundForModule {
6615 mod_name: mod_name.clone(),
6616 default_path: default_path_str,
6617 secondary_path: secondary_path_str,
6618 dir_path: dir_path.display().to_string(),
6620 (true, true) => Err(Error::DuplicatePaths {
6621 mod_name: mod_name.clone(),
6622 default_path: default_path_str,
6623 secondary_path: secondary_path_str,
6629 path_exists: default_exists || secondary_exists,
6634 fn submod_path(&mut self,
6636 outer_attrs: &[Attribute],
6638 -> PResult<'a, ModulePathSuccess> {
6639 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6640 return Ok(ModulePathSuccess {
6641 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6642 // All `#[path]` files are treated as though they are a `mod.rs` file.
6643 // This means that `mod foo;` declarations inside `#[path]`-included
6644 // files are siblings,
6646 // Note that this will produce weirdness when a file named `foo.rs` is
6647 // `#[path]` included and contains a `mod foo;` declaration.
6648 // If you encounter this, it's your own darn fault :P
6649 Some(_) => DirectoryOwnership::Owned { relative: None },
6650 _ => DirectoryOwnership::UnownedViaMod(true),
6657 let relative = match self.directory.ownership {
6658 DirectoryOwnership::Owned { relative } => relative,
6659 DirectoryOwnership::UnownedViaBlock |
6660 DirectoryOwnership::UnownedViaMod(_) => None,
6662 let paths = Parser::default_submod_path(
6663 id, relative, &self.directory.path, self.sess.source_map());
6665 match self.directory.ownership {
6666 DirectoryOwnership::Owned { .. } => {
6667 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6669 DirectoryOwnership::UnownedViaBlock => {
6671 "Cannot declare a non-inline module inside a block \
6672 unless it has a path attribute";
6673 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6674 if paths.path_exists {
6675 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6677 err.span_note(id_sp, &msg);
6681 DirectoryOwnership::UnownedViaMod(warn) => {
6683 if let Ok(result) = paths.result {
6684 return Ok(ModulePathSuccess { warn: true, ..result });
6687 let mut err = self.diagnostic().struct_span_err(id_sp,
6688 "cannot declare a new module at this location");
6689 if !id_sp.is_dummy() {
6690 let src_path = self.sess.source_map().span_to_filename(id_sp);
6691 if let FileName::Real(src_path) = src_path {
6692 if let Some(stem) = src_path.file_stem() {
6693 let mut dest_path = src_path.clone();
6694 dest_path.set_file_name(stem);
6695 dest_path.push("mod.rs");
6696 err.span_note(id_sp,
6697 &format!("maybe move this module `{}` to its own \
6698 directory via `{}`", src_path.display(),
6699 dest_path.display()));
6703 if paths.path_exists {
6704 err.span_note(id_sp,
6705 &format!("... or maybe `use` the module `{}` instead \
6706 of possibly redeclaring it",
6714 /// Reads a module from a source file.
6715 fn eval_src_mod(&mut self,
6717 directory_ownership: DirectoryOwnership,
6720 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6721 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6722 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6723 let mut err = String::from("circular modules: ");
6724 let len = included_mod_stack.len();
6725 for p in &included_mod_stack[i.. len] {
6726 err.push_str(&p.to_string_lossy());
6727 err.push_str(" -> ");
6729 err.push_str(&path.to_string_lossy());
6730 return Err(self.span_fatal(id_sp, &err[..]));
6732 included_mod_stack.push(path.clone());
6733 drop(included_mod_stack);
6736 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6737 p0.cfg_mods = self.cfg_mods;
6738 let mod_inner_lo = p0.token.span;
6739 let mod_attrs = p0.parse_inner_attributes()?;
6740 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6742 self.sess.included_mod_stack.borrow_mut().pop();
6746 /// Parses a function declaration from a foreign module.
6747 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6748 -> PResult<'a, ForeignItem> {
6749 self.expect_keyword(kw::Fn)?;
6751 let (ident, mut generics) = self.parse_fn_header()?;
6752 let decl = self.parse_fn_decl(true)?;
6753 generics.where_clause = self.parse_where_clause()?;
6754 let hi = self.token.span;
6755 self.expect(&token::Semi)?;
6756 Ok(ast::ForeignItem {
6759 node: ForeignItemKind::Fn(decl, generics),
6760 id: ast::DUMMY_NODE_ID,
6766 /// Parses a static item from a foreign module.
6767 /// Assumes that the `static` keyword is already parsed.
6768 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6769 -> PResult<'a, ForeignItem> {
6770 let mutbl = self.parse_mutability();
6771 let ident = self.parse_ident()?;
6772 self.expect(&token::Colon)?;
6773 let ty = self.parse_ty()?;
6774 let hi = self.token.span;
6775 self.expect(&token::Semi)?;
6779 node: ForeignItemKind::Static(ty, mutbl),
6780 id: ast::DUMMY_NODE_ID,
6786 /// Parses a type from a foreign module.
6787 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6788 -> PResult<'a, ForeignItem> {
6789 self.expect_keyword(kw::Type)?;
6791 let ident = self.parse_ident()?;
6792 let hi = self.token.span;
6793 self.expect(&token::Semi)?;
6794 Ok(ast::ForeignItem {
6797 node: ForeignItemKind::Ty,
6798 id: ast::DUMMY_NODE_ID,
6804 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6805 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6806 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6808 let mut ident = if self.token.is_keyword(kw::SelfLower) {
6809 self.parse_path_segment_ident()
6813 let mut idents = vec![];
6814 let mut replacement = vec![];
6815 let mut fixed_crate_name = false;
6816 // Accept `extern crate name-like-this` for better diagnostics
6817 let dash = token::BinOp(token::BinOpToken::Minus);
6818 if self.token == dash { // Do not include `-` as part of the expected tokens list
6819 while self.eat(&dash) {
6820 fixed_crate_name = true;
6821 replacement.push((self.prev_span, "_".to_string()));
6822 idents.push(self.parse_ident()?);
6825 if fixed_crate_name {
6826 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6827 let mut fixed_name = format!("{}", ident.name);
6828 for part in idents {
6829 fixed_name.push_str(&format!("_{}", part.name));
6831 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6833 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6834 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6835 err.multipart_suggestion(
6838 Applicability::MachineApplicable,
6845 /// Parses `extern crate` links.
6850 /// extern crate foo;
6851 /// extern crate bar as foo;
6853 fn parse_item_extern_crate(&mut self,
6855 visibility: Visibility,
6856 attrs: Vec<Attribute>)
6857 -> PResult<'a, P<Item>> {
6858 // Accept `extern crate name-like-this` for better diagnostics
6859 let orig_name = self.parse_crate_name_with_dashes()?;
6860 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6861 (rename, Some(orig_name.name))
6865 self.expect(&token::Semi)?;
6867 let span = lo.to(self.prev_span);
6868 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6871 /// Parses `extern` for foreign ABIs modules.
6873 /// `extern` is expected to have been
6874 /// consumed before calling this method.
6878 /// ```ignore (only-for-syntax-highlight)
6882 fn parse_item_foreign_mod(&mut self,
6884 opt_abi: Option<Abi>,
6885 visibility: Visibility,
6886 mut attrs: Vec<Attribute>)
6887 -> PResult<'a, P<Item>> {
6888 self.expect(&token::OpenDelim(token::Brace))?;
6890 let abi = opt_abi.unwrap_or(Abi::C);
6892 attrs.extend(self.parse_inner_attributes()?);
6894 let mut foreign_items = vec![];
6895 while !self.eat(&token::CloseDelim(token::Brace)) {
6896 foreign_items.push(self.parse_foreign_item()?);
6899 let prev_span = self.prev_span;
6900 let m = ast::ForeignMod {
6902 items: foreign_items
6904 let invalid = Ident::invalid();
6905 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6908 /// Parses `type Foo = Bar;`
6910 /// `existential type Foo: Bar;`
6913 /// without modifying the parser state.
6914 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6915 // This parses the grammar:
6916 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6917 if self.check_keyword(kw::Type) ||
6918 self.check_keyword(kw::Existential) &&
6919 self.is_keyword_ahead(1, &[kw::Type]) {
6920 let existential = self.eat_keyword(kw::Existential);
6921 assert!(self.eat_keyword(kw::Type));
6922 Some(self.parse_existential_or_alias(existential))
6928 /// Parses a type alias or existential type.
6929 fn parse_existential_or_alias(
6932 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6933 let ident = self.parse_ident()?;
6934 let mut tps = self.parse_generics()?;
6935 tps.where_clause = self.parse_where_clause()?;
6936 let alias = if existential {
6937 self.expect(&token::Colon)?;
6938 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6939 AliasKind::Existential(bounds)
6941 self.expect(&token::Eq)?;
6942 let ty = self.parse_ty()?;
6945 self.expect(&token::Semi)?;
6946 Ok((ident, alias, tps))
6949 /// Parses the part of an enum declaration following the `{`.
6950 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6951 let mut variants = Vec::new();
6952 while self.token != token::CloseDelim(token::Brace) {
6953 let variant_attrs = self.parse_outer_attributes()?;
6954 let vlo = self.token.span;
6957 let ident = self.parse_ident()?;
6959 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
6960 // Parse a struct variant.
6961 let (fields, recovered) = self.parse_record_struct_body()?;
6962 VariantData::Struct(fields, recovered)
6963 } else if self.check(&token::OpenDelim(token::Paren)) {
6965 self.parse_tuple_struct_body()?,
6969 VariantData::Unit(ast::DUMMY_NODE_ID)
6972 let disr_expr = if self.eat(&token::Eq) {
6974 id: ast::DUMMY_NODE_ID,
6975 value: self.parse_expr()?,
6981 let vr = ast::Variant_ {
6983 id: ast::DUMMY_NODE_ID,
6984 attrs: variant_attrs,
6988 variants.push(respan(vlo.to(self.prev_span), vr));
6990 if !self.eat(&token::Comma) {
6991 if self.token.is_ident() && !self.token.is_reserved_ident() {
6992 let sp = self.sess.source_map().next_point(self.prev_span);
6993 let mut err = self.struct_span_err(sp, "missing comma");
6994 err.span_suggestion_short(
6998 Applicability::MaybeIncorrect,
7006 self.expect(&token::CloseDelim(token::Brace))?;
7008 Ok(ast::EnumDef { variants })
7011 /// Parses an enum declaration.
7012 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7013 let id = self.parse_ident()?;
7014 let mut generics = self.parse_generics()?;
7015 generics.where_clause = self.parse_where_clause()?;
7016 self.expect(&token::OpenDelim(token::Brace))?;
7018 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7019 self.recover_stmt();
7020 self.eat(&token::CloseDelim(token::Brace));
7023 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7026 /// Parses a string as an ABI spec on an extern type or module. Consumes
7027 /// the `extern` keyword, if one is found.
7028 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7029 match self.token.kind {
7030 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
7031 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
7032 let sp = self.token.span;
7033 self.expect_no_suffix(sp, "an ABI spec", suffix);
7035 match abi::lookup(&symbol.as_str()) {
7036 Some(abi) => Ok(Some(abi)),
7038 let prev_span = self.prev_span;
7039 let mut err = struct_span_err!(
7040 self.sess.span_diagnostic,
7043 "invalid ABI: found `{}`",
7045 err.span_label(prev_span, "invalid ABI");
7046 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7057 fn is_static_global(&mut self) -> bool {
7058 if self.check_keyword(kw::Static) {
7059 // Check if this could be a closure
7060 !self.look_ahead(1, |token| {
7061 if token.is_keyword(kw::Move) {
7065 token::BinOp(token::Or) | token::OrOr => true,
7076 attrs: Vec<Attribute>,
7077 macros_allowed: bool,
7078 attributes_allowed: bool,
7079 ) -> PResult<'a, Option<P<Item>>> {
7080 let mut unclosed_delims = vec![];
7081 let (ret, tokens) = self.collect_tokens(|this| {
7082 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7083 unclosed_delims.append(&mut this.unclosed_delims);
7086 self.unclosed_delims.append(&mut unclosed_delims);
7088 // Once we've parsed an item and recorded the tokens we got while
7089 // parsing we may want to store `tokens` into the item we're about to
7090 // return. Note, though, that we specifically didn't capture tokens
7091 // related to outer attributes. The `tokens` field here may later be
7092 // used with procedural macros to convert this item back into a token
7093 // stream, but during expansion we may be removing attributes as we go
7096 // If we've got inner attributes then the `tokens` we've got above holds
7097 // these inner attributes. If an inner attribute is expanded we won't
7098 // actually remove it from the token stream, so we'll just keep yielding
7099 // it (bad!). To work around this case for now we just avoid recording
7100 // `tokens` if we detect any inner attributes. This should help keep
7101 // expansion correct, but we should fix this bug one day!
7104 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7105 i.tokens = Some(tokens);
7112 /// Parses one of the items allowed by the flags.
7113 fn parse_item_implementation(
7115 attrs: Vec<Attribute>,
7116 macros_allowed: bool,
7117 attributes_allowed: bool,
7118 ) -> PResult<'a, Option<P<Item>>> {
7119 maybe_whole!(self, NtItem, |item| {
7120 let mut item = item.into_inner();
7121 let mut attrs = attrs;
7122 mem::swap(&mut item.attrs, &mut attrs);
7123 item.attrs.extend(attrs);
7127 let lo = self.token.span;
7129 let visibility = self.parse_visibility(false)?;
7131 if self.eat_keyword(kw::Use) {
7133 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7134 self.expect(&token::Semi)?;
7136 let span = lo.to(self.prev_span);
7138 self.mk_item(span, Ident::invalid(), item_, visibility, attrs);
7139 return Ok(Some(item));
7142 if self.eat_keyword(kw::Extern) {
7143 if self.eat_keyword(kw::Crate) {
7144 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7147 let opt_abi = self.parse_opt_abi()?;
7149 if self.eat_keyword(kw::Fn) {
7150 // EXTERN FUNCTION ITEM
7151 let fn_span = self.prev_span;
7152 let abi = opt_abi.unwrap_or(Abi::C);
7153 let (ident, item_, extra_attrs) =
7154 self.parse_item_fn(Unsafety::Normal,
7155 respan(fn_span, IsAsync::NotAsync),
7156 respan(fn_span, Constness::NotConst),
7158 let prev_span = self.prev_span;
7159 let item = self.mk_item(lo.to(prev_span),
7163 maybe_append(attrs, extra_attrs));
7164 return Ok(Some(item));
7165 } else if self.check(&token::OpenDelim(token::Brace)) {
7166 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7172 if self.is_static_global() {
7175 let m = if self.eat_keyword(kw::Mut) {
7178 Mutability::Immutable
7180 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7181 let prev_span = self.prev_span;
7182 let item = self.mk_item(lo.to(prev_span),
7186 maybe_append(attrs, extra_attrs));
7187 return Ok(Some(item));
7189 if self.eat_keyword(kw::Const) {
7190 let const_span = self.prev_span;
7191 if self.check_keyword(kw::Fn)
7192 || (self.check_keyword(kw::Unsafe)
7193 && self.is_keyword_ahead(1, &[kw::Fn])) {
7194 // CONST FUNCTION ITEM
7195 let unsafety = self.parse_unsafety();
7197 let (ident, item_, extra_attrs) =
7198 self.parse_item_fn(unsafety,
7199 respan(const_span, IsAsync::NotAsync),
7200 respan(const_span, Constness::Const),
7202 let prev_span = self.prev_span;
7203 let item = self.mk_item(lo.to(prev_span),
7207 maybe_append(attrs, extra_attrs));
7208 return Ok(Some(item));
7212 if self.eat_keyword(kw::Mut) {
7213 let prev_span = self.prev_span;
7214 let mut err = self.diagnostic()
7215 .struct_span_err(prev_span, "const globals cannot be mutable");
7216 err.span_label(prev_span, "cannot be mutable");
7217 err.span_suggestion(
7219 "you might want to declare a static instead",
7220 "static".to_owned(),
7221 Applicability::MaybeIncorrect,
7225 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7226 let prev_span = self.prev_span;
7227 let item = self.mk_item(lo.to(prev_span),
7231 maybe_append(attrs, extra_attrs));
7232 return Ok(Some(item));
7235 // Parse `async unsafe? fn`.
7236 if self.check_keyword(kw::Async) {
7237 let async_span = self.token.span;
7238 if self.is_keyword_ahead(1, &[kw::Fn])
7239 || self.is_keyword_ahead(2, &[kw::Fn])
7241 // ASYNC FUNCTION ITEM
7242 self.bump(); // `async`
7243 let unsafety = self.parse_unsafety(); // `unsafe`?
7244 self.expect_keyword(kw::Fn)?; // `fn`
7245 let fn_span = self.prev_span;
7246 let (ident, item_, extra_attrs) =
7247 self.parse_item_fn(unsafety,
7248 respan(async_span, IsAsync::Async {
7249 closure_id: ast::DUMMY_NODE_ID,
7250 return_impl_trait_id: ast::DUMMY_NODE_ID,
7252 respan(fn_span, Constness::NotConst),
7254 let prev_span = self.prev_span;
7255 let item = self.mk_item(lo.to(prev_span),
7259 maybe_append(attrs, extra_attrs));
7260 self.ban_async_in_2015(async_span);
7261 return Ok(Some(item));
7264 if self.check_keyword(kw::Unsafe) &&
7265 self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
7267 // UNSAFE TRAIT ITEM
7268 self.bump(); // `unsafe`
7269 let is_auto = if self.eat_keyword(kw::Trait) {
7272 self.expect_keyword(kw::Auto)?;
7273 self.expect_keyword(kw::Trait)?;
7276 let (ident, item_, extra_attrs) =
7277 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7278 let prev_span = self.prev_span;
7279 let item = self.mk_item(lo.to(prev_span),
7283 maybe_append(attrs, extra_attrs));
7284 return Ok(Some(item));
7286 if self.check_keyword(kw::Impl) ||
7287 self.check_keyword(kw::Unsafe) &&
7288 self.is_keyword_ahead(1, &[kw::Impl]) ||
7289 self.check_keyword(kw::Default) &&
7290 self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) {
7292 let defaultness = self.parse_defaultness();
7293 let unsafety = self.parse_unsafety();
7294 self.expect_keyword(kw::Impl)?;
7295 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7296 let span = lo.to(self.prev_span);
7297 return Ok(Some(self.mk_item(span, ident, item, visibility,
7298 maybe_append(attrs, extra_attrs))));
7300 if self.check_keyword(kw::Fn) {
7303 let fn_span = self.prev_span;
7304 let (ident, item_, extra_attrs) =
7305 self.parse_item_fn(Unsafety::Normal,
7306 respan(fn_span, IsAsync::NotAsync),
7307 respan(fn_span, Constness::NotConst),
7309 let prev_span = self.prev_span;
7310 let item = self.mk_item(lo.to(prev_span),
7314 maybe_append(attrs, extra_attrs));
7315 return Ok(Some(item));
7317 if self.check_keyword(kw::Unsafe)
7318 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7319 // UNSAFE FUNCTION ITEM
7320 self.bump(); // `unsafe`
7321 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7322 self.check(&token::OpenDelim(token::Brace));
7323 let abi = if self.eat_keyword(kw::Extern) {
7324 self.parse_opt_abi()?.unwrap_or(Abi::C)
7328 self.expect_keyword(kw::Fn)?;
7329 let fn_span = self.prev_span;
7330 let (ident, item_, extra_attrs) =
7331 self.parse_item_fn(Unsafety::Unsafe,
7332 respan(fn_span, IsAsync::NotAsync),
7333 respan(fn_span, Constness::NotConst),
7335 let prev_span = self.prev_span;
7336 let item = self.mk_item(lo.to(prev_span),
7340 maybe_append(attrs, extra_attrs));
7341 return Ok(Some(item));
7343 if self.eat_keyword(kw::Mod) {
7345 let (ident, item_, extra_attrs) =
7346 self.parse_item_mod(&attrs[..])?;
7347 let prev_span = self.prev_span;
7348 let item = self.mk_item(lo.to(prev_span),
7352 maybe_append(attrs, extra_attrs));
7353 return Ok(Some(item));
7355 if let Some(type_) = self.eat_type() {
7356 let (ident, alias, generics) = type_?;
7358 let item_ = match alias {
7359 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7360 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7362 let prev_span = self.prev_span;
7363 let item = self.mk_item(lo.to(prev_span),
7368 return Ok(Some(item));
7370 if self.eat_keyword(kw::Enum) {
7372 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7373 let prev_span = self.prev_span;
7374 let item = self.mk_item(lo.to(prev_span),
7378 maybe_append(attrs, extra_attrs));
7379 return Ok(Some(item));
7381 if self.check_keyword(kw::Trait)
7382 || (self.check_keyword(kw::Auto)
7383 && self.is_keyword_ahead(1, &[kw::Trait]))
7385 let is_auto = if self.eat_keyword(kw::Trait) {
7388 self.expect_keyword(kw::Auto)?;
7389 self.expect_keyword(kw::Trait)?;
7393 let (ident, item_, extra_attrs) =
7394 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7395 let prev_span = self.prev_span;
7396 let item = self.mk_item(lo.to(prev_span),
7400 maybe_append(attrs, extra_attrs));
7401 return Ok(Some(item));
7403 if self.eat_keyword(kw::Struct) {
7405 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7406 let prev_span = self.prev_span;
7407 let item = self.mk_item(lo.to(prev_span),
7411 maybe_append(attrs, extra_attrs));
7412 return Ok(Some(item));
7414 if self.is_union_item() {
7417 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7418 let prev_span = self.prev_span;
7419 let item = self.mk_item(lo.to(prev_span),
7423 maybe_append(attrs, extra_attrs));
7424 return Ok(Some(item));
7426 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7427 return Ok(Some(macro_def));
7430 // Verify whether we have encountered a struct or method definition where the user forgot to
7431 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7432 if visibility.node.is_pub() &&
7433 self.check_ident() &&
7434 self.look_ahead(1, |t| *t != token::Not)
7436 // Space between `pub` keyword and the identifier
7439 // ^^^ `sp` points here
7440 let sp = self.prev_span.between(self.token.span);
7441 let full_sp = self.prev_span.to(self.token.span);
7442 let ident_sp = self.token.span;
7443 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7444 // possible public struct definition where `struct` was forgotten
7445 let ident = self.parse_ident().unwrap();
7446 let msg = format!("add `struct` here to parse `{}` as a public struct",
7448 let mut err = self.diagnostic()
7449 .struct_span_err(sp, "missing `struct` for struct definition");
7450 err.span_suggestion_short(
7451 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7454 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7455 let ident = self.parse_ident().unwrap();
7457 let kw_name = if let Ok(Some(_)) = self.parse_self_arg_with_attrs() {
7462 self.consume_block(token::Paren);
7463 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7464 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7466 ("fn", kw_name, false)
7467 } else if self.check(&token::OpenDelim(token::Brace)) {
7469 ("fn", kw_name, false)
7470 } else if self.check(&token::Colon) {
7474 ("fn` or `struct", "function or struct", true)
7477 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7478 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7480 self.consume_block(token::Brace);
7481 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7485 err.span_suggestion_short(
7486 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7489 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7490 err.span_suggestion(
7492 "if you meant to call a macro, try",
7493 format!("{}!", snippet),
7494 // this is the `ambiguous` conditional branch
7495 Applicability::MaybeIncorrect
7498 err.help("if you meant to call a macro, remove the `pub` \
7499 and add a trailing `!` after the identifier");
7503 } else if self.look_ahead(1, |t| *t == token::Lt) {
7504 let ident = self.parse_ident().unwrap();
7505 self.eat_to_tokens(&[&token::Gt]);
7507 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7508 if let Ok(Some(_)) = self.parse_self_arg_with_attrs() {
7509 ("fn", "method", false)
7511 ("fn", "function", false)
7513 } else if self.check(&token::OpenDelim(token::Brace)) {
7514 ("struct", "struct", false)
7516 ("fn` or `struct", "function or struct", true)
7518 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7519 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7521 err.span_suggestion_short(
7523 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7524 format!(" {} ", kw),
7525 Applicability::MachineApplicable,
7531 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7534 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
7535 fn ban_async_in_2015(&self, async_span: Span) {
7536 if async_span.rust_2015() {
7538 .struct_span_err_with_code(
7540 "`async fn` is not permitted in the 2015 edition",
7541 DiagnosticId::Error("E0670".into())
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::take(list))
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::take(v),
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();