1 // ignore-tidy-filelength
3 use crate::ast::{AngleBracketedArgs, ParenthesizedArgs, AttrStyle, BareFnTy};
4 use crate::ast::{GenericBound, TraitBoundModifier};
5 use crate::ast::Unsafety;
6 use crate::ast::{Mod, AnonConst, Arg, Arm, Guard, Attribute, BindingMode, TraitItemKind};
8 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
9 use crate::ast::{Constness, Crate};
10 use crate::ast::Defaultness;
11 use crate::ast::EnumDef;
12 use crate::ast::{Expr, ExprKind, RangeLimits};
13 use crate::ast::{Field, FnDecl, FnHeader};
14 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
15 use crate::ast::{GenericParam, GenericParamKind};
16 use crate::ast::GenericArg;
17 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
18 use crate::ast::{Label, Lifetime};
19 use crate::ast::Local;
20 use crate::ast::MacStmtStyle;
21 use crate::ast::{Mac, Mac_, MacDelimiter};
22 use crate::ast::{MutTy, Mutability};
23 use crate::ast::{Pat, PatKind, PathSegment};
24 use crate::ast::{PolyTraitRef, QSelf};
25 use crate::ast::{Stmt, StmtKind};
26 use crate::ast::{VariantData, StructField};
27 use crate::ast::StrStyle;
28 use crate::ast::SelfKind;
29 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
30 use crate::ast::{Ty, TyKind, AssocTyConstraint, AssocTyConstraintKind, GenericBounds};
31 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
32 use crate::ast::{UseTree, UseTreeKind};
33 use crate::ast::{BinOpKind, UnOp};
34 use crate::ast::{RangeEnd, RangeSyntax};
35 use crate::{ast, attr};
36 use crate::ext::base::DummyResult;
37 use crate::ext::hygiene::SyntaxContext;
38 use crate::source_map::{self, SourceMap, Spanned, respan};
39 use crate::parse::{SeqSep, classify, literal, token};
40 use crate::parse::lexer::UnmatchedBrace;
41 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
42 use crate::parse::token::{Token, TokenKind, DelimToken};
43 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
44 use crate::util::parser::{AssocOp, Fixity};
45 use crate::print::pprust;
47 use crate::parse::PResult;
49 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
50 use crate::symbol::{kw, sym, Symbol};
51 use crate::parse::diagnostics::{Error, dummy_arg};
53 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
54 use rustc_target::spec::abi::{self, Abi};
55 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
61 use std::path::{self, Path, PathBuf};
65 /// Whether the type alias or associated type is a concrete type or an existential type
67 /// Just a new name for the same type
69 /// Only trait impls of the type will be usable, not the actual type itself
70 Existential(GenericBounds),
74 struct Restrictions: u8 {
75 const STMT_EXPR = 1 << 0;
76 const NO_STRUCT_LITERAL = 1 << 1;
80 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
82 /// Specifies how to parse a path.
83 #[derive(Copy, Clone, PartialEq)]
85 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
86 /// with something else. For example, in expressions `segment < ....` can be interpreted
87 /// as a comparison and `segment ( ....` can be interpreted as a function call.
88 /// In all such contexts the non-path interpretation is preferred by default for practical
89 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
90 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
92 /// In other contexts, notably in types, no ambiguity exists and paths can be written
93 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
94 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
96 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
97 /// visibilities or attributes.
98 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
99 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
100 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
101 /// tokens when something goes wrong.
105 #[derive(Clone, Copy, PartialEq, Debug)]
106 crate enum SemiColonMode {
112 #[derive(Clone, Copy, PartialEq, Debug)]
113 crate enum BlockMode {
118 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
119 /// dropped into the token stream, which happens while parsing the result of
120 /// macro expansion). Placement of these is not as complex as I feared it would
121 /// be. The important thing is to make sure that lookahead doesn't balk at
122 /// `token::Interpolated` tokens.
123 macro_rules! maybe_whole_expr {
125 if let token::Interpolated(nt) = &$p.token.kind {
127 token::NtExpr(e) | token::NtLiteral(e) => {
132 token::NtPath(path) => {
133 let path = path.clone();
135 return Ok($p.mk_expr(
136 $p.token.span, ExprKind::Path(None, path), ThinVec::new()
139 token::NtBlock(block) => {
140 let block = block.clone();
142 return Ok($p.mk_expr(
143 $p.token.span, ExprKind::Block(block, None), ThinVec::new()
152 /// As maybe_whole_expr, but for things other than expressions
153 macro_rules! maybe_whole {
154 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
155 if let token::Interpolated(nt) = &$p.token.kind {
156 if let token::$constructor(x) = &**nt {
165 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
166 macro_rules! maybe_recover_from_interpolated_ty_qpath {
167 ($self: expr, $allow_qpath_recovery: expr) => {
168 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
169 if let token::Interpolated(nt) = &$self.token.kind {
170 if let token::NtTy(ty) = &**nt {
173 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
180 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
181 if let Some(ref mut rhs) = rhs {
187 #[derive(Debug, Clone, Copy, PartialEq)]
199 // NOTE: `Ident`s are handled by `common.rs`.
202 pub struct Parser<'a> {
203 pub sess: &'a ParseSess,
204 /// The current normalized token.
205 /// "Normalized" means that some interpolated tokens
206 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
207 /// with non-interpolated identifier and lifetime tokens they refer to.
208 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
210 /// Span of the current non-normalized token.
211 meta_var_span: Option<Span>,
212 /// Span of the previous non-normalized token.
214 /// Kind of the previous normalized token (in simplified form).
215 prev_token_kind: PrevTokenKind,
216 restrictions: Restrictions,
217 /// Used to determine the path to externally loaded source files.
218 crate directory: Directory<'a>,
219 /// `true` to parse sub-modules in other files.
220 pub recurse_into_file_modules: bool,
221 /// Name of the root module this parser originated from. If `None`, then the
222 /// name is not known. This does not change while the parser is descending
223 /// into modules, and sub-parsers have new values for this name.
224 pub root_module_name: Option<String>,
225 crate expected_tokens: Vec<TokenType>,
226 crate token_cursor: TokenCursor,
227 desugar_doc_comments: bool,
228 /// `true` we should configure out of line modules as we parse.
230 /// This field is used to keep track of how many left angle brackets we have seen. This is
231 /// required in order to detect extra leading left angle brackets (`<` characters) and error
234 /// See the comments in the `parse_path_segment` function for more details.
235 crate unmatched_angle_bracket_count: u32,
236 crate max_angle_bracket_count: u32,
237 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
238 /// it gets removed from here. Every entry left at the end gets emitted as an independent
240 crate unclosed_delims: Vec<UnmatchedBrace>,
241 crate last_unexpected_token_span: Option<Span>,
242 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
243 crate subparser_name: Option<&'static str>,
246 impl<'a> Drop for Parser<'a> {
248 let diag = self.diagnostic();
249 emit_unclosed_delims(&mut self.unclosed_delims, diag);
254 crate struct TokenCursor {
255 crate frame: TokenCursorFrame,
256 crate stack: Vec<TokenCursorFrame>,
260 crate struct TokenCursorFrame {
261 crate delim: token::DelimToken,
262 crate span: DelimSpan,
263 crate open_delim: bool,
264 crate tree_cursor: tokenstream::Cursor,
265 crate close_delim: bool,
266 crate last_token: LastToken,
269 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
270 /// by the parser, and then that's transitively used to record the tokens that
271 /// each parse AST item is created with.
273 /// Right now this has two states, either collecting tokens or not collecting
274 /// tokens. If we're collecting tokens we just save everything off into a local
275 /// `Vec`. This should eventually though likely save tokens from the original
276 /// token stream and just use slicing of token streams to avoid creation of a
277 /// whole new vector.
279 /// The second state is where we're passively not recording tokens, but the last
280 /// token is still tracked for when we want to start recording tokens. This
281 /// "last token" means that when we start recording tokens we'll want to ensure
282 /// that this, the first token, is included in the output.
284 /// You can find some more example usage of this in the `collect_tokens` method
287 crate enum LastToken {
288 Collecting(Vec<TreeAndJoint>),
289 Was(Option<TreeAndJoint>),
292 impl TokenCursorFrame {
293 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
297 open_delim: delim == token::NoDelim,
298 tree_cursor: tts.clone().into_trees(),
299 close_delim: delim == token::NoDelim,
300 last_token: LastToken::Was(None),
306 fn next(&mut self) -> Token {
308 let tree = if !self.frame.open_delim {
309 self.frame.open_delim = true;
310 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
311 } else if let Some(tree) = self.frame.tree_cursor.next() {
313 } else if !self.frame.close_delim {
314 self.frame.close_delim = true;
315 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
316 } else if let Some(frame) = self.stack.pop() {
320 return Token::new(token::Eof, DUMMY_SP);
323 match self.frame.last_token {
324 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
325 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
329 TokenTree::Token(token) => return token,
330 TokenTree::Delimited(sp, delim, tts) => {
331 let frame = TokenCursorFrame::new(sp, delim, &tts);
332 self.stack.push(mem::replace(&mut self.frame, frame));
338 fn next_desugared(&mut self) -> Token {
339 let (name, sp) = match self.next() {
340 Token { kind: token::DocComment(name), span } => (name, span),
344 let stripped = strip_doc_comment_decoration(&name.as_str());
346 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
347 // required to wrap the text.
348 let mut num_of_hashes = 0;
350 for ch in stripped.chars() {
353 '#' if count > 0 => count + 1,
356 num_of_hashes = cmp::max(num_of_hashes, count);
359 let delim_span = DelimSpan::from_single(sp);
360 let body = TokenTree::Delimited(
364 TokenTree::token(token::Ident(sym::doc, false), sp),
365 TokenTree::token(token::Eq, sp),
366 TokenTree::token(TokenKind::lit(
367 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
370 .iter().cloned().collect::<TokenStream>().into(),
373 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
376 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
377 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
378 .iter().cloned().collect::<TokenStream>().into()
380 [TokenTree::token(token::Pound, sp), body]
381 .iter().cloned().collect::<TokenStream>().into()
389 #[derive(Clone, PartialEq)]
390 crate enum TokenType {
402 crate fn to_string(&self) -> String {
404 TokenType::Token(ref t) => format!("`{}`", pprust::token_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: &TokenKind) -> 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) {
592 } else if inedible.contains(&self.token) {
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) {
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 crate fn look_ahead_span(&self, dist: usize) -> Span {
1069 return self.token.span
1072 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1073 Some(TokenTree::Token(token)) => token.span,
1074 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1075 None => self.look_ahead_span(dist - 1),
1079 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1080 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1081 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1084 /// Is the current token one of the keywords that signals a bare function type?
1085 fn token_is_bare_fn_keyword(&mut self) -> bool {
1086 self.check_keyword(kw::Fn) ||
1087 self.check_keyword(kw::Unsafe) ||
1088 self.check_keyword(kw::Extern)
1091 /// Parses a `TyKind::BareFn` type.
1092 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1095 [unsafe] [extern "ABI"] fn (S) -> T
1105 let unsafety = self.parse_unsafety();
1106 let abi = if self.eat_keyword(kw::Extern) {
1107 self.parse_opt_abi()?.unwrap_or(Abi::C)
1112 self.expect_keyword(kw::Fn)?;
1113 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1114 let ret_ty = self.parse_ret_ty(false)?;
1115 let decl = P(FnDecl {
1120 Ok(TyKind::BareFn(P(BareFnTy {
1128 /// Parses asyncness: `async` or nothing.
1129 fn parse_asyncness(&mut self) -> IsAsync {
1130 if self.eat_keyword(kw::Async) {
1132 closure_id: ast::DUMMY_NODE_ID,
1133 return_impl_trait_id: ast::DUMMY_NODE_ID,
1140 /// Parses unsafety: `unsafe` or nothing.
1141 fn parse_unsafety(&mut self) -> Unsafety {
1142 if self.eat_keyword(kw::Unsafe) {
1149 /// Parses the items in a trait declaration.
1150 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1151 maybe_whole!(self, NtTraitItem, |x| x);
1152 let attrs = self.parse_outer_attributes()?;
1153 let mut unclosed_delims = vec![];
1154 let (mut item, tokens) = self.collect_tokens(|this| {
1155 let item = this.parse_trait_item_(at_end, attrs);
1156 unclosed_delims.append(&mut this.unclosed_delims);
1159 self.unclosed_delims.append(&mut unclosed_delims);
1160 // See `parse_item` for why this clause is here.
1161 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1162 item.tokens = Some(tokens);
1167 fn parse_trait_item_(&mut self,
1169 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1170 let lo = self.token.span;
1172 let (name, node, generics) = if self.eat_keyword(kw::Type) {
1173 self.parse_trait_item_assoc_ty()?
1174 } else if self.is_const_item() {
1175 self.expect_keyword(kw::Const)?;
1176 let ident = self.parse_ident()?;
1177 self.expect(&token::Colon)?;
1178 let ty = self.parse_ty()?;
1179 let default = if self.eat(&token::Eq) {
1180 let expr = self.parse_expr()?;
1181 self.expect(&token::Semi)?;
1184 self.expect(&token::Semi)?;
1187 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1188 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1189 // trait item macro.
1190 (Ident::invalid(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1192 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1194 let ident = self.parse_ident()?;
1195 let mut generics = self.parse_generics()?;
1197 let decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1198 // This is somewhat dubious; We don't want to allow
1199 // argument names to be left off if there is a
1202 // We don't allow argument names to be left off in edition 2018.
1203 p.parse_arg_general(p.token.span.rust_2018(), true, false)
1205 generics.where_clause = self.parse_where_clause()?;
1207 let sig = ast::MethodSig {
1217 let body = match self.token.kind {
1221 debug!("parse_trait_methods(): parsing required method");
1224 token::OpenDelim(token::Brace) => {
1225 debug!("parse_trait_methods(): parsing provided method");
1227 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1228 attrs.extend(inner_attrs.iter().cloned());
1231 token::Interpolated(ref nt) => {
1233 token::NtBlock(..) => {
1235 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1236 attrs.extend(inner_attrs.iter().cloned());
1240 return self.expected_semi_or_open_brace();
1245 return self.expected_semi_or_open_brace();
1248 (ident, ast::TraitItemKind::Method(sig, body), generics)
1252 id: ast::DUMMY_NODE_ID,
1257 span: lo.to(self.prev_span),
1262 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1263 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1264 if self.eat(&token::RArrow) {
1265 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1267 Ok(FunctionRetTy::Default(self.token.span.shrink_to_lo()))
1272 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1273 self.parse_ty_common(true, true, false)
1276 /// Parses a type in restricted contexts where `+` is not permitted.
1278 /// Example 1: `&'a TYPE`
1279 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1280 /// Example 2: `value1 as TYPE + value2`
1281 /// `+` is prohibited to avoid interactions with expression grammar.
1282 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1283 self.parse_ty_common(false, true, false)
1286 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1287 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1288 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1289 maybe_whole!(self, NtTy, |x| x);
1291 let lo = self.token.span;
1292 let mut impl_dyn_multi = false;
1293 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1294 // `(TYPE)` is a parenthesized type.
1295 // `(TYPE,)` is a tuple with a single field of type TYPE.
1296 let mut ts = vec![];
1297 let mut last_comma = false;
1298 while self.token != token::CloseDelim(token::Paren) {
1299 ts.push(self.parse_ty()?);
1300 if self.eat(&token::Comma) {
1307 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1308 self.expect(&token::CloseDelim(token::Paren))?;
1310 if ts.len() == 1 && !last_comma {
1311 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1312 let maybe_bounds = allow_plus && self.token.is_like_plus();
1314 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1315 TyKind::Path(None, ref path) if maybe_bounds => {
1316 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1318 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1319 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1320 let path = match bounds[0] {
1321 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1322 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1324 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1327 _ => TyKind::Paren(P(ty))
1332 } else if self.eat(&token::Not) {
1335 } else if self.eat(&token::BinOp(token::Star)) {
1337 TyKind::Ptr(self.parse_ptr()?)
1338 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1340 let t = self.parse_ty()?;
1341 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1342 let t = match self.maybe_parse_fixed_length_of_vec()? {
1343 None => TyKind::Slice(t),
1344 Some(length) => TyKind::Array(t, AnonConst {
1345 id: ast::DUMMY_NODE_ID,
1349 self.expect(&token::CloseDelim(token::Bracket))?;
1351 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1354 self.parse_borrowed_pointee()?
1355 } else if self.eat_keyword_noexpect(kw::Typeof) {
1357 // In order to not be ambiguous, the type must be surrounded by parens.
1358 self.expect(&token::OpenDelim(token::Paren))?;
1360 id: ast::DUMMY_NODE_ID,
1361 value: self.parse_expr()?,
1363 self.expect(&token::CloseDelim(token::Paren))?;
1365 } else if self.eat_keyword(kw::Underscore) {
1366 // A type to be inferred `_`
1368 } else if self.token_is_bare_fn_keyword() {
1369 // Function pointer type
1370 self.parse_ty_bare_fn(Vec::new())?
1371 } else if self.check_keyword(kw::For) {
1372 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1373 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1374 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1375 let lo = self.token.span;
1376 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1377 if self.token_is_bare_fn_keyword() {
1378 self.parse_ty_bare_fn(lifetime_defs)?
1380 let path = self.parse_path(PathStyle::Type)?;
1381 let parse_plus = allow_plus && self.check_plus();
1382 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1384 } else if self.eat_keyword(kw::Impl) {
1385 // Always parse bounds greedily for better error recovery.
1386 let bounds = self.parse_generic_bounds(None)?;
1387 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1388 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1389 } else if self.check_keyword(kw::Dyn) &&
1390 (self.token.span.rust_2018() ||
1391 self.look_ahead(1, |t| t.can_begin_bound() &&
1392 !can_continue_type_after_non_fn_ident(t))) {
1393 self.bump(); // `dyn`
1394 // Always parse bounds greedily for better error recovery.
1395 let bounds = self.parse_generic_bounds(None)?;
1396 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1397 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1398 } else if self.check(&token::Question) ||
1399 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1400 // Bound list (trait object type)
1401 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1402 TraitObjectSyntax::None)
1403 } else if self.eat_lt() {
1405 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1406 TyKind::Path(Some(qself), path)
1407 } else if self.token.is_path_start() {
1409 let path = self.parse_path(PathStyle::Type)?;
1410 if self.eat(&token::Not) {
1411 // Macro invocation in type position
1412 let (delim, tts) = self.expect_delimited_token_tree()?;
1413 let node = Mac_ { path, tts, delim };
1414 TyKind::Mac(respan(lo.to(self.prev_span), node))
1416 // Just a type path or bound list (trait object type) starting with a trait.
1418 // `Trait1 + Trait2 + 'a`
1419 if allow_plus && self.check_plus() {
1420 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1422 TyKind::Path(None, path)
1425 } else if self.check(&token::DotDotDot) {
1426 if allow_c_variadic {
1427 self.eat(&token::DotDotDot);
1430 return Err(self.fatal(
1431 "only foreign functions are allowed to be C-variadic"
1435 let msg = format!("expected type, found {}", self.this_token_descr());
1436 return Err(self.fatal(&msg));
1439 let span = lo.to(self.prev_span);
1440 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1442 // Try to recover from use of `+` with incorrect priority.
1443 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1444 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1445 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1448 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1449 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1450 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1451 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1453 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1454 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1456 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1459 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1460 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1461 let mutbl = self.parse_mutability();
1462 let ty = self.parse_ty_no_plus()?;
1463 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1466 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1467 let mutbl = if self.eat_keyword(kw::Mut) {
1469 } else if self.eat_keyword(kw::Const) {
1470 Mutability::Immutable
1472 let span = self.prev_span;
1473 let msg = "expected mut or const in raw pointer type";
1474 self.struct_span_err(span, msg)
1475 .span_label(span, msg)
1476 .help("use `*mut T` or `*const T` as appropriate")
1478 Mutability::Immutable
1480 let t = self.parse_ty_no_plus()?;
1481 Ok(MutTy { ty: t, mutbl: mutbl })
1484 fn is_named_argument(&self) -> bool {
1485 let offset = match self.token.kind {
1486 token::Interpolated(ref nt) => match **nt {
1487 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1490 token::BinOp(token::And) | token::AndAnd => 1,
1491 _ if self.token.is_keyword(kw::Mut) => 1,
1495 self.look_ahead(offset, |t| t.is_ident()) &&
1496 self.look_ahead(offset + 1, |t| t == &token::Colon)
1499 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1501 /// This version of parse arg doesn't necessarily require identifier names.
1502 fn parse_arg_general(
1505 is_trait_item: bool,
1506 allow_c_variadic: bool,
1507 ) -> PResult<'a, Arg> {
1508 if let Ok(Some(arg)) = self.parse_self_arg() {
1509 return self.recover_bad_self_arg(arg, is_trait_item);
1512 let (pat, ty) = if require_name || self.is_named_argument() {
1513 debug!("parse_arg_general parse_pat (require_name:{})", require_name);
1514 self.eat_incorrect_doc_comment("method arguments");
1515 let pat = self.parse_pat(Some("argument name"))?;
1517 if let Err(mut err) = self.expect(&token::Colon) {
1518 if let Some(ident) = self.argument_without_type(
1525 return Ok(dummy_arg(ident));
1531 self.eat_incorrect_doc_comment("a method argument's type");
1532 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1534 debug!("parse_arg_general ident_to_pat");
1535 let parser_snapshot_before_ty = self.clone();
1536 self.eat_incorrect_doc_comment("a method argument's type");
1537 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1538 if ty.is_ok() && self.token != token::Comma &&
1539 self.token != token::CloseDelim(token::Paren) {
1540 // This wasn't actually a type, but a pattern looking like a type,
1541 // so we are going to rollback and re-parse for recovery.
1542 ty = self.unexpected();
1546 let ident = Ident::new(kw::Invalid, self.prev_span);
1548 id: ast::DUMMY_NODE_ID,
1549 node: PatKind::Ident(
1550 BindingMode::ByValue(Mutability::Immutable), ident, None),
1556 // If this is a C-variadic argument and we hit an error, return the
1558 if self.token == token::DotDotDot {
1561 // Recover from attempting to parse the argument as a type without pattern.
1563 mem::replace(self, parser_snapshot_before_ty);
1564 self.recover_arg_parse()?
1569 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1572 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
1573 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1574 let pat = self.parse_pat(Some("argument name"))?;
1575 let t = if self.eat(&token::Colon) {
1579 id: ast::DUMMY_NODE_ID,
1580 node: TyKind::Infer,
1581 span: self.prev_span,
1587 id: ast::DUMMY_NODE_ID
1591 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1592 if self.eat(&token::Semi) {
1593 Ok(Some(self.parse_expr()?))
1599 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1600 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1601 maybe_whole_expr!(self);
1603 let minus_lo = self.token.span;
1604 let minus_present = self.eat(&token::BinOp(token::Minus));
1605 let lo = self.token.span;
1606 let literal = self.parse_lit()?;
1607 let hi = self.prev_span;
1608 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1611 let minus_hi = self.prev_span;
1612 let unary = self.mk_unary(UnOp::Neg, expr);
1613 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1619 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1620 match self.token.kind {
1621 token::Ident(name, _) if name.is_path_segment_keyword() => {
1622 let span = self.token.span;
1624 Ok(Ident::new(name, span))
1626 _ => self.parse_ident(),
1630 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
1631 match self.token.kind {
1632 token::Ident(name, false) if name == kw::Underscore => {
1633 let span = self.token.span;
1635 Ok(Ident::new(name, span))
1637 _ => self.parse_ident(),
1641 /// Parses a qualified path.
1642 /// Assumes that the leading `<` has been parsed already.
1644 /// `qualified_path = <type [as trait_ref]>::path`
1649 /// `<T as U>::F::a<S>` (without disambiguator)
1650 /// `<T as U>::F::a::<S>` (with disambiguator)
1651 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1652 let lo = self.prev_span;
1653 let ty = self.parse_ty()?;
1655 // `path` will contain the prefix of the path up to the `>`,
1656 // if any (e.g., `U` in the `<T as U>::*` examples
1657 // above). `path_span` has the span of that path, or an empty
1658 // span in the case of something like `<T>::Bar`.
1659 let (mut path, path_span);
1660 if self.eat_keyword(kw::As) {
1661 let path_lo = self.token.span;
1662 path = self.parse_path(PathStyle::Type)?;
1663 path_span = path_lo.to(self.prev_span);
1665 path_span = self.token.span.to(self.token.span);
1666 path = ast::Path { segments: Vec::new(), span: path_span };
1669 // See doc comment for `unmatched_angle_bracket_count`.
1670 self.expect(&token::Gt)?;
1671 if self.unmatched_angle_bracket_count > 0 {
1672 self.unmatched_angle_bracket_count -= 1;
1673 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1676 self.expect(&token::ModSep)?;
1678 let qself = QSelf { ty, path_span, position: path.segments.len() };
1679 self.parse_path_segments(&mut path.segments, style)?;
1681 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1684 /// Parses simple paths.
1686 /// `path = [::] segment+`
1687 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1690 /// `a::b::C<D>` (without disambiguator)
1691 /// `a::b::C::<D>` (with disambiguator)
1692 /// `Fn(Args)` (without disambiguator)
1693 /// `Fn::(Args)` (with disambiguator)
1694 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1695 maybe_whole!(self, NtPath, |path| {
1696 if style == PathStyle::Mod &&
1697 path.segments.iter().any(|segment| segment.args.is_some()) {
1698 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1703 let lo = self.meta_var_span.unwrap_or(self.token.span);
1704 let mut segments = Vec::new();
1705 let mod_sep_ctxt = self.token.span.ctxt();
1706 if self.eat(&token::ModSep) {
1707 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
1709 self.parse_path_segments(&mut segments, style)?;
1711 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1714 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
1715 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
1717 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1718 let meta_ident = match self.token.kind {
1719 token::Interpolated(ref nt) => match **nt {
1720 token::NtMeta(ref meta) => match meta.node {
1721 ast::MetaItemKind::Word => Some(meta.path.clone()),
1728 if let Some(path) = meta_ident {
1732 self.parse_path(style)
1735 crate fn parse_path_segments(&mut self,
1736 segments: &mut Vec<PathSegment>,
1738 -> PResult<'a, ()> {
1740 let segment = self.parse_path_segment(style)?;
1741 if style == PathStyle::Expr {
1742 // In order to check for trailing angle brackets, we must have finished
1743 // recursing (`parse_path_segment` can indirectly call this function),
1744 // that is, the next token must be the highlighted part of the below example:
1746 // `Foo::<Bar as Baz<T>>::Qux`
1749 // As opposed to the below highlight (if we had only finished the first
1752 // `Foo::<Bar as Baz<T>>::Qux`
1755 // `PathStyle::Expr` is only provided at the root invocation and never in
1756 // `parse_path_segment` to recurse and therefore can be checked to maintain
1758 self.check_trailing_angle_brackets(&segment, token::ModSep);
1760 segments.push(segment);
1762 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1768 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
1769 let ident = self.parse_path_segment_ident()?;
1771 let is_args_start = |token: &TokenKind| match *token {
1772 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
1773 | token::LArrow => true,
1776 let check_args_start = |this: &mut Self| {
1777 this.expected_tokens.extend_from_slice(
1778 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1780 is_args_start(&this.token)
1783 Ok(if style == PathStyle::Type && check_args_start(self) ||
1784 style != PathStyle::Mod && self.check(&token::ModSep)
1785 && self.look_ahead(1, |t| is_args_start(t)) {
1786 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
1787 // it isn't, then we reset the unmatched angle bracket count as we're about to start
1788 // parsing a new path.
1789 if style == PathStyle::Expr {
1790 self.unmatched_angle_bracket_count = 0;
1791 self.max_angle_bracket_count = 0;
1794 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1795 self.eat(&token::ModSep);
1796 let lo = self.token.span;
1797 let args = if self.eat_lt() {
1799 let (args, constraints) =
1800 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
1802 let span = lo.to(self.prev_span);
1803 AngleBracketedArgs { args, constraints, span }.into()
1807 let (inputs, recovered) = self.parse_seq_to_before_tokens(
1808 &[&token::CloseDelim(token::Paren)],
1809 SeqSep::trailing_allowed(token::Comma),
1810 TokenExpectType::Expect,
1815 let span = lo.to(self.prev_span);
1816 let output = if self.eat(&token::RArrow) {
1817 Some(self.parse_ty_common(false, false, false)?)
1821 ParenthesizedArgs { inputs, output, span }.into()
1824 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
1826 // Generic arguments are not found.
1827 PathSegment::from_ident(ident)
1831 crate fn check_lifetime(&mut self) -> bool {
1832 self.expected_tokens.push(TokenType::Lifetime);
1833 self.token.is_lifetime()
1836 /// Parses a single lifetime `'a` or panics.
1837 crate fn expect_lifetime(&mut self) -> Lifetime {
1838 if let Some(ident) = self.token.lifetime() {
1839 let span = self.token.span;
1841 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
1843 self.span_bug(self.token.span, "not a lifetime")
1847 fn eat_label(&mut self) -> Option<Label> {
1848 if let Some(ident) = self.token.lifetime() {
1849 let span = self.token.span;
1851 Some(Label { ident: Ident::new(ident.name, span) })
1857 /// Parses mutability (`mut` or nothing).
1858 fn parse_mutability(&mut self) -> Mutability {
1859 if self.eat_keyword(kw::Mut) {
1862 Mutability::Immutable
1866 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1867 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1869 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1871 Ok(Ident::new(symbol, self.prev_span))
1873 self.parse_ident_common(false)
1877 /// Parse ident (COLON expr)?
1878 fn parse_field(&mut self) -> PResult<'a, Field> {
1879 let attrs = self.parse_outer_attributes()?;
1880 let lo = self.token.span;
1882 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1883 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1884 t == &token::Colon || t == &token::Eq
1886 let fieldname = self.parse_field_name()?;
1888 // Check for an equals token. This means the source incorrectly attempts to
1889 // initialize a field with an eq rather than a colon.
1890 if self.token == token::Eq {
1892 .struct_span_err(self.token.span, "expected `:`, found `=`")
1894 fieldname.span.shrink_to_hi().to(self.token.span),
1895 "replace equals symbol with a colon",
1897 Applicability::MachineApplicable,
1902 (fieldname, self.parse_expr()?, false)
1904 let fieldname = self.parse_ident_common(false)?;
1906 // Mimic `x: x` for the `x` field shorthand.
1907 let path = ast::Path::from_ident(fieldname);
1908 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1909 (fieldname, expr, true)
1913 span: lo.to(expr.span),
1916 attrs: attrs.into(),
1920 crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1921 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
1924 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1925 ExprKind::Unary(unop, expr)
1928 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1929 ExprKind::Binary(binop, lhs, rhs)
1932 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1933 ExprKind::Call(f, args)
1936 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1937 ExprKind::Index(expr, idx)
1941 start: Option<P<Expr>>,
1942 end: Option<P<Expr>>,
1943 limits: RangeLimits)
1944 -> PResult<'a, ast::ExprKind> {
1945 if end.is_none() && limits == RangeLimits::Closed {
1946 Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
1948 Ok(ExprKind::Range(start, end, limits))
1952 fn mk_assign_op(&self, binop: ast::BinOp,
1953 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1954 ExprKind::AssignOp(binop, lhs, rhs)
1957 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
1958 let delim = match self.token.kind {
1959 token::OpenDelim(delim) => delim,
1961 let msg = "expected open delimiter";
1962 let mut err = self.fatal(msg);
1963 err.span_label(self.token.span, msg);
1967 let tts = match self.parse_token_tree() {
1968 TokenTree::Delimited(_, _, tts) => tts,
1969 _ => unreachable!(),
1971 let delim = match delim {
1972 token::Paren => MacDelimiter::Parenthesis,
1973 token::Bracket => MacDelimiter::Bracket,
1974 token::Brace => MacDelimiter::Brace,
1975 token::NoDelim => self.bug("unexpected no delimiter"),
1977 Ok((delim, tts.into()))
1980 /// At the bottom (top?) of the precedence hierarchy,
1981 /// Parses things like parenthesized exprs, macros, `return`, etc.
1983 /// N.B., this does not parse outer attributes, and is private because it only works
1984 /// correctly if called from `parse_dot_or_call_expr()`.
1985 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1986 maybe_recover_from_interpolated_ty_qpath!(self, true);
1987 maybe_whole_expr!(self);
1989 // Outer attributes are already parsed and will be
1990 // added to the return value after the fact.
1992 // Therefore, prevent sub-parser from parsing
1993 // attributes by giving them a empty "already parsed" list.
1994 let mut attrs = ThinVec::new();
1996 let lo = self.token.span;
1997 let mut hi = self.token.span;
2001 // Note: when adding new syntax here, don't forget to adjust TokenKind::can_begin_expr().
2002 match self.token.kind {
2003 token::OpenDelim(token::Paren) => {
2006 attrs.extend(self.parse_inner_attributes()?);
2008 // (e) is parenthesized e
2009 // (e,) is a tuple with only one field, e
2010 let mut es = vec![];
2011 let mut trailing_comma = false;
2012 let mut recovered = false;
2013 while self.token != token::CloseDelim(token::Paren) {
2014 es.push(match self.parse_expr() {
2017 // recover from parse error in tuple list
2018 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2021 recovered = self.expect_one_of(
2023 &[token::Comma, token::CloseDelim(token::Paren)],
2025 if self.eat(&token::Comma) {
2026 trailing_comma = true;
2028 trailing_comma = false;
2036 hi = self.prev_span;
2037 ex = if es.len() == 1 && !trailing_comma {
2038 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2043 token::OpenDelim(token::Brace) => {
2044 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2046 token::BinOp(token::Or) | token::OrOr => {
2047 return self.parse_lambda_expr(attrs);
2049 token::OpenDelim(token::Bracket) => {
2052 attrs.extend(self.parse_inner_attributes()?);
2054 if self.eat(&token::CloseDelim(token::Bracket)) {
2056 ex = ExprKind::Array(Vec::new());
2059 let first_expr = self.parse_expr()?;
2060 if self.eat(&token::Semi) {
2061 // Repeating array syntax: [ 0; 512 ]
2062 let count = AnonConst {
2063 id: ast::DUMMY_NODE_ID,
2064 value: self.parse_expr()?,
2066 self.expect(&token::CloseDelim(token::Bracket))?;
2067 ex = ExprKind::Repeat(first_expr, count);
2068 } else if self.eat(&token::Comma) {
2069 // Vector with two or more elements.
2070 let remaining_exprs = self.parse_seq_to_end(
2071 &token::CloseDelim(token::Bracket),
2072 SeqSep::trailing_allowed(token::Comma),
2073 |p| Ok(p.parse_expr()?)
2075 let mut exprs = vec![first_expr];
2076 exprs.extend(remaining_exprs);
2077 ex = ExprKind::Array(exprs);
2079 // Vector with one element.
2080 self.expect(&token::CloseDelim(token::Bracket))?;
2081 ex = ExprKind::Array(vec![first_expr]);
2084 hi = self.prev_span;
2088 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2090 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2092 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
2093 return self.parse_lambda_expr(attrs);
2095 if self.eat_keyword(kw::If) {
2096 return self.parse_if_expr(attrs);
2098 if self.eat_keyword(kw::For) {
2099 let lo = self.prev_span;
2100 return self.parse_for_expr(None, lo, attrs);
2102 if self.eat_keyword(kw::While) {
2103 let lo = self.prev_span;
2104 return self.parse_while_expr(None, lo, attrs);
2106 if let Some(label) = self.eat_label() {
2107 let lo = label.ident.span;
2108 self.expect(&token::Colon)?;
2109 if self.eat_keyword(kw::While) {
2110 return self.parse_while_expr(Some(label), lo, attrs)
2112 if self.eat_keyword(kw::For) {
2113 return self.parse_for_expr(Some(label), lo, attrs)
2115 if self.eat_keyword(kw::Loop) {
2116 return self.parse_loop_expr(Some(label), lo, attrs)
2118 if self.token == token::OpenDelim(token::Brace) {
2119 return self.parse_block_expr(Some(label),
2121 BlockCheckMode::Default,
2124 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2125 let mut err = self.fatal(msg);
2126 err.span_label(self.token.span, msg);
2129 if self.eat_keyword(kw::Loop) {
2130 let lo = self.prev_span;
2131 return self.parse_loop_expr(None, lo, attrs);
2133 if self.eat_keyword(kw::Continue) {
2134 let label = self.eat_label();
2135 let ex = ExprKind::Continue(label);
2136 let hi = self.prev_span;
2137 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2139 if self.eat_keyword(kw::Match) {
2140 let match_sp = self.prev_span;
2141 return self.parse_match_expr(attrs).map_err(|mut err| {
2142 err.span_label(match_sp, "while parsing this match expression");
2146 if self.eat_keyword(kw::Unsafe) {
2147 return self.parse_block_expr(
2150 BlockCheckMode::Unsafe(ast::UserProvided),
2153 if self.is_do_catch_block() {
2154 let mut db = self.fatal("found removed `do catch` syntax");
2155 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2158 if self.is_try_block() {
2159 let lo = self.token.span;
2160 assert!(self.eat_keyword(kw::Try));
2161 return self.parse_try_block(lo, attrs);
2164 // Span::rust_2018() is somewhat expensive; don't get it repeatedly.
2165 let is_span_rust_2018 = self.token.span.rust_2018();
2166 if is_span_rust_2018 && self.check_keyword(kw::Async) {
2167 return if self.is_async_block() { // check for `async {` and `async move {`
2168 self.parse_async_block(attrs)
2170 self.parse_lambda_expr(attrs)
2173 if self.eat_keyword(kw::Return) {
2174 if self.token.can_begin_expr() {
2175 let e = self.parse_expr()?;
2177 ex = ExprKind::Ret(Some(e));
2179 ex = ExprKind::Ret(None);
2181 } else if self.eat_keyword(kw::Break) {
2182 let label = self.eat_label();
2183 let e = if self.token.can_begin_expr()
2184 && !(self.token == token::OpenDelim(token::Brace)
2185 && self.restrictions.contains(
2186 Restrictions::NO_STRUCT_LITERAL)) {
2187 Some(self.parse_expr()?)
2191 ex = ExprKind::Break(label, e);
2192 hi = self.prev_span;
2193 } else if self.eat_keyword(kw::Yield) {
2194 if self.token.can_begin_expr() {
2195 let e = self.parse_expr()?;
2197 ex = ExprKind::Yield(Some(e));
2199 ex = ExprKind::Yield(None);
2201 } else if self.token.is_keyword(kw::Let) {
2202 // Catch this syntax error here, instead of in `parse_ident`, so
2203 // that we can explicitly mention that let is not to be used as an expression
2204 let mut db = self.fatal("expected expression, found statement (`let`)");
2205 db.span_label(self.token.span, "expected expression");
2206 db.note("variable declaration using `let` is a statement");
2208 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
2209 let (await_hi, e_kind) = self.parse_await_macro_or_alt(lo, self.prev_span)?;
2212 } else if self.token.is_path_start() {
2213 let path = self.parse_path(PathStyle::Expr)?;
2215 // `!`, as an operator, is prefix, so we know this isn't that
2216 if self.eat(&token::Not) {
2217 // MACRO INVOCATION expression
2218 let (delim, tts) = self.expect_delimited_token_tree()?;
2219 hi = self.prev_span;
2220 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2221 } else if self.check(&token::OpenDelim(token::Brace)) {
2222 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2226 ex = ExprKind::Path(None, path);
2230 ex = ExprKind::Path(None, path);
2233 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2234 // Don't complain about bare semicolons after unclosed braces
2235 // recovery in order to keep the error count down. Fixing the
2236 // delimiters will possibly also fix the bare semicolon found in
2237 // expression context. For example, silence the following error:
2239 // error: expected expression, found `;`
2243 // | ^ expected expression
2246 return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()));
2248 match self.parse_literal_maybe_minus() {
2251 ex = expr.node.clone();
2254 self.cancel(&mut err);
2255 return Err(self.expected_expression_found());
2262 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2263 self.maybe_recover_from_bad_qpath(expr, true)
2266 /// Parse `await!(<expr>)` calls, or alternatively recover from incorrect but reasonable
2267 /// alternative syntaxes `await <expr>`, `await? <expr>`, `await(<expr>)` and
2268 /// `await { <expr> }`.
2269 fn parse_await_macro_or_alt(
2273 ) -> PResult<'a, (Span, ExprKind)> {
2274 if self.token == token::Not {
2275 // Handle correct `await!(<expr>)`.
2276 // FIXME: make this an error when `await!` is no longer supported
2277 // https://github.com/rust-lang/rust/issues/60610
2278 self.expect(&token::Not)?;
2279 self.expect(&token::OpenDelim(token::Paren))?;
2280 let expr = self.parse_expr().map_err(|mut err| {
2281 err.span_label(await_sp, "while parsing this await macro call");
2284 self.expect(&token::CloseDelim(token::Paren))?;
2285 Ok((self.prev_span, ExprKind::Await(ast::AwaitOrigin::MacroLike, expr)))
2286 } else { // Handle `await <expr>`.
2287 self.parse_incorrect_await_syntax(lo, await_sp)
2291 fn maybe_parse_struct_expr(
2295 attrs: &ThinVec<Attribute>,
2296 ) -> Option<PResult<'a, P<Expr>>> {
2297 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2298 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2299 // `{ ident, ` cannot start a block
2300 self.look_ahead(2, |t| t == &token::Comma) ||
2301 self.look_ahead(2, |t| t == &token::Colon) && (
2302 // `{ ident: token, ` cannot start a block
2303 self.look_ahead(4, |t| t == &token::Comma) ||
2304 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2305 self.look_ahead(3, |t| !t.can_begin_type())
2309 if struct_allowed || certainly_not_a_block() {
2310 // This is a struct literal, but we don't can't accept them here
2311 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2312 if let (Ok(expr), false) = (&expr, struct_allowed) {
2313 let mut err = self.diagnostic().struct_span_err(
2315 "struct literals are not allowed here",
2317 err.multipart_suggestion(
2318 "surround the struct literal with parentheses",
2320 (lo.shrink_to_lo(), "(".to_string()),
2321 (expr.span.shrink_to_hi(), ")".to_string()),
2323 Applicability::MachineApplicable,
2332 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2333 -> PResult<'a, P<Expr>> {
2334 let struct_sp = lo.to(self.prev_span);
2336 let mut fields = Vec::new();
2337 let mut base = None;
2339 attrs.extend(self.parse_inner_attributes()?);
2341 while self.token != token::CloseDelim(token::Brace) {
2342 if self.eat(&token::DotDot) {
2343 let exp_span = self.prev_span;
2344 match self.parse_expr() {
2350 self.recover_stmt();
2353 if self.token == token::Comma {
2354 let mut err = self.sess.span_diagnostic.mut_span_err(
2355 exp_span.to(self.prev_span),
2356 "cannot use a comma after the base struct",
2358 err.span_suggestion_short(
2360 "remove this comma",
2362 Applicability::MachineApplicable
2364 err.note("the base struct must always be the last field");
2366 self.recover_stmt();
2371 let mut recovery_field = None;
2372 if let token::Ident(name, _) = self.token.kind {
2373 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2374 // Use in case of error after field-looking code: `S { foo: () with a }`
2375 recovery_field = Some(ast::Field {
2376 ident: Ident::new(name, self.token.span),
2377 span: self.token.span,
2378 expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
2379 is_shorthand: false,
2380 attrs: ThinVec::new(),
2384 let mut parsed_field = None;
2385 match self.parse_field() {
2386 Ok(f) => parsed_field = Some(f),
2388 e.span_label(struct_sp, "while parsing this struct");
2391 // If the next token is a comma, then try to parse
2392 // what comes next as additional fields, rather than
2393 // bailing out until next `}`.
2394 if self.token != token::Comma {
2395 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2396 if self.token != token::Comma {
2403 match self.expect_one_of(&[token::Comma],
2404 &[token::CloseDelim(token::Brace)]) {
2405 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2406 // only include the field if there's no parse error for the field name
2410 if let Some(f) = recovery_field {
2413 e.span_label(struct_sp, "while parsing this struct");
2415 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2416 self.eat(&token::Comma);
2421 let span = lo.to(self.token.span);
2422 self.expect(&token::CloseDelim(token::Brace))?;
2423 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2426 fn parse_or_use_outer_attributes(&mut self,
2427 already_parsed_attrs: Option<ThinVec<Attribute>>)
2428 -> PResult<'a, ThinVec<Attribute>> {
2429 if let Some(attrs) = already_parsed_attrs {
2432 self.parse_outer_attributes().map(|a| a.into())
2436 /// Parses a block or unsafe block.
2437 crate fn parse_block_expr(
2439 opt_label: Option<Label>,
2441 blk_mode: BlockCheckMode,
2442 outer_attrs: ThinVec<Attribute>,
2443 ) -> PResult<'a, P<Expr>> {
2444 self.expect(&token::OpenDelim(token::Brace))?;
2446 let mut attrs = outer_attrs;
2447 attrs.extend(self.parse_inner_attributes()?);
2449 let blk = self.parse_block_tail(lo, blk_mode)?;
2450 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2453 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2454 fn parse_dot_or_call_expr(&mut self,
2455 already_parsed_attrs: Option<ThinVec<Attribute>>)
2456 -> PResult<'a, P<Expr>> {
2457 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2459 let b = self.parse_bottom_expr();
2460 let (span, b) = self.interpolated_or_expr_span(b)?;
2461 self.parse_dot_or_call_expr_with(b, span, attrs)
2464 fn parse_dot_or_call_expr_with(&mut self,
2467 mut attrs: ThinVec<Attribute>)
2468 -> PResult<'a, P<Expr>> {
2469 // Stitch the list of outer attributes onto the return value.
2470 // A little bit ugly, but the best way given the current code
2472 self.parse_dot_or_call_expr_with_(e0, lo)
2474 expr.map(|mut expr| {
2475 attrs.extend::<Vec<_>>(expr.attrs.into());
2478 ExprKind::If(..) | ExprKind::IfLet(..) => {
2479 if !expr.attrs.is_empty() {
2480 // Just point to the first attribute in there...
2481 let span = expr.attrs[0].span;
2484 "attributes are not yet allowed on `if` \
2495 // Assuming we have just parsed `.`, continue parsing into an expression.
2496 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2497 if self.token.span.rust_2018() && self.eat_keyword(kw::Await) {
2498 let span = lo.to(self.prev_span);
2499 let await_expr = self.mk_expr(
2501 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
2504 self.recover_from_await_method_call();
2505 return Ok(await_expr);
2507 let segment = self.parse_path_segment(PathStyle::Expr)?;
2508 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2510 Ok(match self.token.kind {
2511 token::OpenDelim(token::Paren) => {
2512 // Method call `expr.f()`
2513 let mut args = self.parse_unspanned_seq(
2514 &token::OpenDelim(token::Paren),
2515 &token::CloseDelim(token::Paren),
2516 SeqSep::trailing_allowed(token::Comma),
2517 |p| Ok(p.parse_expr()?)
2519 args.insert(0, self_arg);
2521 let span = lo.to(self.prev_span);
2522 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2525 // Field access `expr.f`
2526 if let Some(args) = segment.args {
2527 self.span_err(args.span(),
2528 "field expressions may not have generic arguments");
2531 let span = lo.to(self.prev_span);
2532 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2537 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2542 while self.eat(&token::Question) {
2543 let hi = self.prev_span;
2544 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2548 if self.eat(&token::Dot) {
2549 match self.token.kind {
2550 token::Ident(..) => {
2551 e = self.parse_dot_suffix(e, lo)?;
2553 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
2554 let span = self.token.span;
2556 let field = ExprKind::Field(e, Ident::new(symbol, span));
2557 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2559 self.expect_no_suffix(span, "a tuple index", suffix);
2561 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
2563 let fstr = symbol.as_str();
2564 let msg = format!("unexpected token: `{}`", symbol);
2565 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
2566 err.span_label(self.prev_span, "unexpected token");
2567 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2568 let float = match fstr.parse::<f64>().ok() {
2572 let sugg = pprust::to_string(|s| {
2573 use crate::print::pprust::PrintState;
2577 s.print_usize(float.trunc() as usize)?;
2580 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2582 err.span_suggestion(
2583 lo.to(self.prev_span),
2584 "try parenthesizing the first index",
2586 Applicability::MachineApplicable
2593 // FIXME Could factor this out into non_fatal_unexpected or something.
2594 let actual = self.this_token_to_string();
2595 self.span_err(self.token.span, &format!("unexpected token: `{}`", actual));
2600 if self.expr_is_complete(&e) { break; }
2601 match self.token.kind {
2603 token::OpenDelim(token::Paren) => {
2604 let seq = self.parse_unspanned_seq(
2605 &token::OpenDelim(token::Paren),
2606 &token::CloseDelim(token::Paren),
2607 SeqSep::trailing_allowed(token::Comma),
2608 |p| Ok(p.parse_expr()?)
2610 let nd = self.mk_call(e, es);
2611 let hi = self.prev_span;
2612 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2614 e = self.recover_seq_parse_error(token::Paren, lo, seq);
2618 // Could be either an index expression or a slicing expression.
2619 token::OpenDelim(token::Bracket) => {
2621 let ix = self.parse_expr()?;
2622 hi = self.token.span;
2623 self.expect(&token::CloseDelim(token::Bracket))?;
2624 let index = self.mk_index(e, ix);
2625 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2633 crate fn process_potential_macro_variable(&mut self) {
2634 self.token = match self.token.kind {
2635 token::Dollar if self.token.span.ctxt() != SyntaxContext::empty() &&
2636 self.look_ahead(1, |t| t.is_ident()) => {
2638 let name = match self.token.kind {
2639 token::Ident(name, _) => name,
2642 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2643 err.span_label(self.token.span, "unknown macro variable");
2648 token::Interpolated(ref nt) => {
2649 self.meta_var_span = Some(self.token.span);
2650 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2651 // and lifetime tokens, so the former are never encountered during normal parsing.
2653 token::NtIdent(ident, is_raw) =>
2654 Token::new(token::Ident(ident.name, is_raw), ident.span),
2655 token::NtLifetime(ident) =>
2656 Token::new(token::Lifetime(ident.name), ident.span),
2664 /// Parses a single token tree from the input.
2665 crate fn parse_token_tree(&mut self) -> TokenTree {
2666 match self.token.kind {
2667 token::OpenDelim(..) => {
2668 let frame = mem::replace(&mut self.token_cursor.frame,
2669 self.token_cursor.stack.pop().unwrap());
2670 self.token.span = frame.span.entire();
2672 TokenTree::Delimited(
2675 frame.tree_cursor.stream.into(),
2678 token::CloseDelim(_) | token::Eof => unreachable!(),
2680 let token = self.token.take();
2682 TokenTree::Token(token)
2687 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
2688 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2689 let mut tts = Vec::new();
2690 while self.token != token::Eof {
2691 tts.push(self.parse_token_tree());
2696 pub fn parse_tokens(&mut self) -> TokenStream {
2697 let mut result = Vec::new();
2699 match self.token.kind {
2700 token::Eof | token::CloseDelim(..) => break,
2701 _ => result.push(self.parse_token_tree().into()),
2704 TokenStream::new(result)
2707 /// Parse a prefix-unary-operator expr
2708 fn parse_prefix_expr(&mut self,
2709 already_parsed_attrs: Option<ThinVec<Attribute>>)
2710 -> PResult<'a, P<Expr>> {
2711 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2712 let lo = self.token.span;
2713 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
2714 let (hi, ex) = match self.token.kind {
2717 let e = self.parse_prefix_expr(None);
2718 let (span, e) = self.interpolated_or_expr_span(e)?;
2719 (lo.to(span), self.mk_unary(UnOp::Not, e))
2721 // Suggest `!` for bitwise negation when encountering a `~`
2724 let e = self.parse_prefix_expr(None);
2725 let (span, e) = self.interpolated_or_expr_span(e)?;
2726 let span_of_tilde = lo;
2727 let mut err = self.diagnostic()
2728 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2729 err.span_suggestion_short(
2731 "use `!` to perform bitwise negation",
2733 Applicability::MachineApplicable
2736 (lo.to(span), self.mk_unary(UnOp::Not, e))
2738 token::BinOp(token::Minus) => {
2740 let e = self.parse_prefix_expr(None);
2741 let (span, e) = self.interpolated_or_expr_span(e)?;
2742 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2744 token::BinOp(token::Star) => {
2746 let e = self.parse_prefix_expr(None);
2747 let (span, e) = self.interpolated_or_expr_span(e)?;
2748 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2750 token::BinOp(token::And) | token::AndAnd => {
2752 let m = self.parse_mutability();
2753 let e = self.parse_prefix_expr(None);
2754 let (span, e) = self.interpolated_or_expr_span(e)?;
2755 (lo.to(span), ExprKind::AddrOf(m, e))
2757 token::Ident(..) if self.token.is_keyword(kw::Box) => {
2759 let e = self.parse_prefix_expr(None);
2760 let (span, e) = self.interpolated_or_expr_span(e)?;
2761 (lo.to(span), ExprKind::Box(e))
2763 token::Ident(..) if self.token.is_ident_named(sym::not) => {
2764 // `not` is just an ordinary identifier in Rust-the-language,
2765 // but as `rustc`-the-compiler, we can issue clever diagnostics
2766 // for confused users who really want to say `!`
2767 let token_cannot_continue_expr = |t: &Token| match t.kind {
2768 // These tokens can start an expression after `!`, but
2769 // can't continue an expression after an ident
2770 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
2771 token::Literal(..) | token::Pound => true,
2772 token::Interpolated(ref nt) => match **nt {
2773 token::NtIdent(..) | token::NtExpr(..) |
2774 token::NtBlock(..) | token::NtPath(..) => true,
2779 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2780 if cannot_continue_expr {
2782 // Emit the error ...
2783 let mut err = self.diagnostic()
2784 .struct_span_err(self.token.span,
2785 &format!("unexpected {} after identifier",
2786 self.this_token_descr()));
2787 // span the `not` plus trailing whitespace to avoid
2788 // trailing whitespace after the `!` in our suggestion
2789 let to_replace = self.sess.source_map()
2790 .span_until_non_whitespace(lo.to(self.token.span));
2791 err.span_suggestion_short(
2793 "use `!` to perform logical negation",
2795 Applicability::MachineApplicable
2798 // —and recover! (just as if we were in the block
2799 // for the `token::Not` arm)
2800 let e = self.parse_prefix_expr(None);
2801 let (span, e) = self.interpolated_or_expr_span(e)?;
2802 (lo.to(span), self.mk_unary(UnOp::Not, e))
2804 return self.parse_dot_or_call_expr(Some(attrs));
2807 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2809 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2812 /// Parses an associative expression.
2814 /// This parses an expression accounting for associativity and precedence of the operators in
2817 fn parse_assoc_expr(&mut self,
2818 already_parsed_attrs: Option<ThinVec<Attribute>>)
2819 -> PResult<'a, P<Expr>> {
2820 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2823 /// Parses an associative expression with operators of at least `min_prec` precedence.
2824 fn parse_assoc_expr_with(&mut self,
2827 -> PResult<'a, P<Expr>> {
2828 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2831 let attrs = match lhs {
2832 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2835 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2836 return self.parse_prefix_range_expr(attrs);
2838 self.parse_prefix_expr(attrs)?
2842 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
2844 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2847 (false, _) => {} // continue parsing the expression
2848 // An exhaustive check is done in the following block, but these are checked first
2849 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
2850 // want to keep their span info to improve diagnostics in these cases in a later stage.
2851 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
2852 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
2853 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
2854 (true, Some(AssocOp::Add)) // `{ 42 } + 42
2855 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
2856 // `if x { a } else { b } && if y { c } else { d }`
2857 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
2858 // These cases are ambiguous and can't be identified in the parser alone
2859 let sp = self.sess.source_map().start_point(self.token.span);
2860 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
2863 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
2866 (true, Some(_)) => {
2867 // We've found an expression that would be parsed as a statement, but the next
2868 // token implies this should be parsed as an expression.
2869 // For example: `if let Some(x) = x { x } else { 0 } / 2`
2870 let mut err = self.sess.span_diagnostic.struct_span_err(self.token.span, &format!(
2871 "expected expression, found `{}`",
2872 pprust::token_to_string(&self.token),
2874 err.span_label(self.token.span, "expected expression");
2875 self.sess.expr_parentheses_needed(
2878 Some(pprust::expr_to_string(&lhs),
2883 self.expected_tokens.push(TokenType::Operator);
2884 while let Some(op) = AssocOp::from_token(&self.token) {
2886 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2887 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2888 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2889 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2890 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2891 (PrevTokenKind::Interpolated, _) => self.prev_span,
2892 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2893 if path.segments.len() == 1 => self.prev_span,
2897 let cur_op_span = self.token.span;
2898 let restrictions = if op.is_assign_like() {
2899 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2903 let prec = op.precedence();
2904 if prec < min_prec {
2907 // Check for deprecated `...` syntax
2908 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2909 self.err_dotdotdot_syntax(self.token.span);
2913 if op.is_comparison() {
2914 self.check_no_chained_comparison(&lhs, &op);
2917 if op == AssocOp::As {
2918 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2920 } else if op == AssocOp::Colon {
2921 let maybe_path = self.could_ascription_be_path(&lhs.node);
2922 let next_sp = self.token.span;
2924 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2927 self.bad_type_ascription(
2938 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2939 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2940 // generalise it to the Fixity::None code.
2942 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2943 // two variants are handled with `parse_prefix_range_expr` call above.
2944 let rhs = if self.is_at_start_of_range_notation_rhs() {
2945 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
2949 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2954 let limits = if op == AssocOp::DotDot {
2955 RangeLimits::HalfOpen
2960 let r = self.mk_range(Some(lhs), rhs, limits)?;
2961 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2965 let fixity = op.fixity();
2966 let prec_adjustment = match fixity {
2969 // We currently have no non-associative operators that are not handled above by
2970 // the special cases. The code is here only for future convenience.
2973 let rhs = self.with_res(
2974 restrictions - Restrictions::STMT_EXPR,
2975 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
2978 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
2979 // including the attributes.
2983 .filter(|a| a.style == AttrStyle::Outer)
2985 .map_or(lhs_span, |a| a.span);
2986 let span = lhs_span.to(rhs.span);
2988 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2989 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2990 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2991 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2992 AssocOp::Greater | AssocOp::GreaterEqual => {
2993 let ast_op = op.to_ast_binop().unwrap();
2994 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
2995 self.mk_expr(span, binary, ThinVec::new())
2997 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2998 AssocOp::AssignOp(k) => {
3000 token::Plus => BinOpKind::Add,
3001 token::Minus => BinOpKind::Sub,
3002 token::Star => BinOpKind::Mul,
3003 token::Slash => BinOpKind::Div,
3004 token::Percent => BinOpKind::Rem,
3005 token::Caret => BinOpKind::BitXor,
3006 token::And => BinOpKind::BitAnd,
3007 token::Or => BinOpKind::BitOr,
3008 token::Shl => BinOpKind::Shl,
3009 token::Shr => BinOpKind::Shr,
3011 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3012 self.mk_expr(span, aopexpr, ThinVec::new())
3014 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3015 self.bug("AssocOp should have been handled by special case")
3019 if let Fixity::None = fixity { break }
3024 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3025 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3026 -> PResult<'a, P<Expr>> {
3027 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3028 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3031 // Save the state of the parser before parsing type normally, in case there is a
3032 // LessThan comparison after this cast.
3033 let parser_snapshot_before_type = self.clone();
3034 match self.parse_ty_no_plus() {
3036 Ok(mk_expr(self, rhs))
3038 Err(mut type_err) => {
3039 // Rewind to before attempting to parse the type with generics, to recover
3040 // from situations like `x as usize < y` in which we first tried to parse
3041 // `usize < y` as a type with generic arguments.
3042 let parser_snapshot_after_type = self.clone();
3043 mem::replace(self, parser_snapshot_before_type);
3045 match self.parse_path(PathStyle::Expr) {
3047 let (op_noun, op_verb) = match self.token.kind {
3048 token::Lt => ("comparison", "comparing"),
3049 token::BinOp(token::Shl) => ("shift", "shifting"),
3051 // We can end up here even without `<` being the next token, for
3052 // example because `parse_ty_no_plus` returns `Err` on keywords,
3053 // but `parse_path` returns `Ok` on them due to error recovery.
3054 // Return original error and parser state.
3055 mem::replace(self, parser_snapshot_after_type);
3056 return Err(type_err);
3060 // Successfully parsed the type path leaving a `<` yet to parse.
3063 // Report non-fatal diagnostics, keep `x as usize` as an expression
3064 // in AST and continue parsing.
3065 let msg = format!("`<` is interpreted as a start of generic \
3066 arguments for `{}`, not a {}", path, op_noun);
3068 self.sess.span_diagnostic.struct_span_err(self.token.span, &msg);
3069 let span_after_type = parser_snapshot_after_type.token.span;
3070 err.span_label(self.look_ahead_span(1).to(span_after_type),
3071 "interpreted as generic arguments");
3072 err.span_label(self.token.span, format!("not interpreted as {}", op_noun));
3074 let expr = mk_expr(self, P(Ty {
3076 node: TyKind::Path(None, path),
3077 id: ast::DUMMY_NODE_ID
3080 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3081 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3082 err.span_suggestion(
3084 &format!("try {} the cast value", op_verb),
3085 format!("({})", expr_str),
3086 Applicability::MachineApplicable
3092 Err(mut path_err) => {
3093 // Couldn't parse as a path, return original error and parser state.
3095 mem::replace(self, parser_snapshot_after_type);
3103 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3104 fn parse_prefix_range_expr(&mut self,
3105 already_parsed_attrs: Option<ThinVec<Attribute>>)
3106 -> PResult<'a, P<Expr>> {
3107 // Check for deprecated `...` syntax
3108 if self.token == token::DotDotDot {
3109 self.err_dotdotdot_syntax(self.token.span);
3112 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3113 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3115 let tok = self.token.clone();
3116 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3117 let lo = self.token.span;
3118 let mut hi = self.token.span;
3120 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3121 // RHS must be parsed with more associativity than the dots.
3122 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3123 Some(self.parse_assoc_expr_with(next_prec,
3124 LhsExpr::NotYetParsed)
3132 let limits = if tok == token::DotDot {
3133 RangeLimits::HalfOpen
3138 let r = self.mk_range(None, opt_end, limits)?;
3139 Ok(self.mk_expr(lo.to(hi), r, attrs))
3142 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3143 if self.token.can_begin_expr() {
3144 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3145 if self.token == token::OpenDelim(token::Brace) {
3146 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3154 /// Parses an `if` or `if let` expression (`if` token already eaten).
3155 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3156 if self.check_keyword(kw::Let) {
3157 return self.parse_if_let_expr(attrs);
3159 let lo = self.prev_span;
3160 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
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 /// Parses an `if let` expression (`if` token already eaten).
3191 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3192 -> PResult<'a, P<Expr>> {
3193 let lo = self.prev_span;
3194 self.expect_keyword(kw::Let)?;
3195 let pats = self.parse_pats()?;
3196 self.expect(&token::Eq)?;
3197 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3198 let thn = self.parse_block()?;
3199 let (hi, els) = if self.eat_keyword(kw::Else) {
3200 let expr = self.parse_else_expr()?;
3201 (expr.span, Some(expr))
3205 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3208 /// Parses `move |args| expr`.
3209 fn parse_lambda_expr(&mut self,
3210 attrs: ThinVec<Attribute>)
3211 -> PResult<'a, P<Expr>>
3213 let lo = self.token.span;
3214 let movability = if self.eat_keyword(kw::Static) {
3219 let asyncness = if self.token.span.rust_2018() {
3220 self.parse_asyncness()
3224 let capture_clause = if self.eat_keyword(kw::Move) {
3229 let decl = self.parse_fn_block_decl()?;
3230 let decl_hi = self.prev_span;
3231 let body = match decl.output {
3232 FunctionRetTy::Default(_) => {
3233 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3234 self.parse_expr_res(restrictions, None)?
3237 // If an explicit return type is given, require a
3238 // block to appear (RFC 968).
3239 let body_lo = self.token.span;
3240 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3246 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3250 // `else` token already eaten
3251 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3252 if self.eat_keyword(kw::If) {
3253 return self.parse_if_expr(ThinVec::new());
3255 let blk = self.parse_block()?;
3256 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3260 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3261 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3263 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3264 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3266 let pat = self.parse_top_level_pat()?;
3267 if !self.eat_keyword(kw::In) {
3268 let in_span = self.prev_span.between(self.token.span);
3269 let mut err = self.sess.span_diagnostic
3270 .struct_span_err(in_span, "missing `in` in `for` loop");
3271 err.span_suggestion_short(
3272 in_span, "try adding `in` here", " in ".into(),
3273 // has been misleading, at least in the past (closed Issue #48492)
3274 Applicability::MaybeIncorrect
3278 let in_span = self.prev_span;
3279 self.check_for_for_in_in_typo(in_span);
3280 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3281 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3282 attrs.extend(iattrs);
3284 let hi = self.prev_span;
3285 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3288 /// Parses a `while` or `while let` expression (`while` token already eaten).
3289 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3291 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3292 if self.token.is_keyword(kw::Let) {
3293 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3295 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3296 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3297 attrs.extend(iattrs);
3298 let span = span_lo.to(body.span);
3299 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3302 /// Parses a `while let` expression (`while` token already eaten).
3303 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3305 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3306 self.expect_keyword(kw::Let)?;
3307 let pats = self.parse_pats()?;
3308 self.expect(&token::Eq)?;
3309 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3310 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3311 attrs.extend(iattrs);
3312 let span = span_lo.to(body.span);
3313 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3316 // parse `loop {...}`, `loop` token already eaten
3317 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3319 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3320 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3321 attrs.extend(iattrs);
3322 let span = span_lo.to(body.span);
3323 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3326 /// Parses an `async move {...}` expression.
3327 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3328 -> PResult<'a, P<Expr>>
3330 let span_lo = self.token.span;
3331 self.expect_keyword(kw::Async)?;
3332 let capture_clause = if self.eat_keyword(kw::Move) {
3337 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3338 attrs.extend(iattrs);
3340 span_lo.to(body.span),
3341 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3344 /// Parses a `try {...}` expression (`try` token already eaten).
3345 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3346 -> PResult<'a, P<Expr>>
3348 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3349 attrs.extend(iattrs);
3350 if self.eat_keyword(kw::Catch) {
3351 let mut error = self.struct_span_err(self.prev_span,
3352 "keyword `catch` cannot follow a `try` block");
3353 error.help("try using `match` on the result of the `try` block instead");
3357 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3361 // `match` token already eaten
3362 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3363 let match_span = self.prev_span;
3364 let lo = self.prev_span;
3365 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3367 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3368 if self.token == token::Semi {
3369 e.span_suggestion_short(
3371 "try removing this `match`",
3373 Applicability::MaybeIncorrect // speculative
3378 attrs.extend(self.parse_inner_attributes()?);
3380 let mut arms: Vec<Arm> = Vec::new();
3381 while self.token != token::CloseDelim(token::Brace) {
3382 match self.parse_arm() {
3383 Ok(arm) => arms.push(arm),
3385 // Recover by skipping to the end of the block.
3387 self.recover_stmt();
3388 let span = lo.to(self.token.span);
3389 if self.token == token::CloseDelim(token::Brace) {
3392 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3396 let hi = self.token.span;
3398 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3401 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3402 let attrs = self.parse_outer_attributes()?;
3403 let lo = self.token.span;
3404 let pats = self.parse_pats()?;
3405 let guard = if self.eat_keyword(kw::If) {
3406 Some(Guard::If(self.parse_expr()?))
3410 let arrow_span = self.token.span;
3411 self.expect(&token::FatArrow)?;
3412 let arm_start_span = self.token.span;
3414 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3415 .map_err(|mut err| {
3416 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3420 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3421 && self.token != token::CloseDelim(token::Brace);
3423 let hi = self.token.span;
3426 let cm = self.sess.source_map();
3427 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3428 .map_err(|mut err| {
3429 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3430 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3431 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3432 && expr_lines.lines.len() == 2
3433 && self.token == token::FatArrow => {
3434 // We check whether there's any trailing code in the parse span,
3435 // if there isn't, we very likely have the following:
3438 // | -- - missing comma
3442 // | - ^^ self.token.span
3444 // | parsed until here as `"y" & X`
3445 err.span_suggestion_short(
3446 cm.next_point(arm_start_span),
3447 "missing a comma here to end this `match` arm",
3449 Applicability::MachineApplicable
3453 err.span_label(arrow_span,
3454 "while parsing the `match` arm starting here");
3460 self.eat(&token::Comma);
3472 /// Parses an expression.
3474 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3475 self.parse_expr_res(Restrictions::empty(), None)
3478 /// Evaluates the closure with restrictions in place.
3480 /// Afters the closure is evaluated, restrictions are reset.
3481 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3482 where F: FnOnce(&mut Self) -> T
3484 let old = self.restrictions;
3485 self.restrictions = r;
3487 self.restrictions = old;
3492 /// Parses an expression, subject to the given restrictions.
3494 fn parse_expr_res(&mut self, r: Restrictions,
3495 already_parsed_attrs: Option<ThinVec<Attribute>>)
3496 -> PResult<'a, P<Expr>> {
3497 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3500 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
3501 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3502 if self.eat(&token::Eq) {
3503 Ok(Some(self.parse_expr()?))
3505 Ok(Some(self.parse_expr()?))
3511 /// Parses patterns, separated by '|' s.
3512 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3513 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
3514 self.eat(&token::BinOp(token::Or));
3516 let mut pats = Vec::new();
3518 pats.push(self.parse_top_level_pat()?);
3520 if self.token == token::OrOr {
3521 let mut err = self.struct_span_err(self.token.span,
3522 "unexpected token `||` after pattern");
3523 err.span_suggestion(
3525 "use a single `|` to specify multiple patterns",
3527 Applicability::MachineApplicable
3531 } else if self.eat(&token::BinOp(token::Or)) {
3532 // This is a No-op. Continue the loop to parse the next
3540 // Parses a parenthesized list of patterns like
3541 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3542 // - a vector of the patterns that were parsed
3543 // - an option indicating the index of the `..` element
3544 // - a boolean indicating whether a trailing comma was present.
3545 // Trailing commas are significant because (p) and (p,) are different patterns.
3546 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3547 self.expect(&token::OpenDelim(token::Paren))?;
3548 let result = match self.parse_pat_list() {
3549 Ok(result) => result,
3550 Err(mut err) => { // recover from parse error in tuple pattern list
3552 self.consume_block(token::Paren);
3553 return Ok((vec![], Some(0), false));
3556 self.expect(&token::CloseDelim(token::Paren))?;
3560 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3561 let mut fields = Vec::new();
3562 let mut ddpos = None;
3563 let mut prev_dd_sp = None;
3564 let mut trailing_comma = false;
3566 if self.eat(&token::DotDot) {
3567 if ddpos.is_none() {
3568 ddpos = Some(fields.len());
3569 prev_dd_sp = Some(self.prev_span);
3571 // Emit a friendly error, ignore `..` and continue parsing
3572 let mut err = self.struct_span_err(
3574 "`..` can only be used once per tuple or tuple struct pattern",
3576 err.span_label(self.prev_span, "can only be used once per pattern");
3577 if let Some(sp) = prev_dd_sp {
3578 err.span_label(sp, "previously present here");
3582 } else if !self.check(&token::CloseDelim(token::Paren)) {
3583 fields.push(self.parse_pat(None)?);
3588 trailing_comma = self.eat(&token::Comma);
3589 if !trailing_comma {
3594 if ddpos == Some(fields.len()) && trailing_comma {
3595 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3596 let msg = "trailing comma is not permitted after `..`";
3597 self.struct_span_err(self.prev_span, msg)
3598 .span_label(self.prev_span, msg)
3602 Ok((fields, ddpos, trailing_comma))
3605 fn parse_pat_vec_elements(
3607 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3608 let mut before = Vec::new();
3609 let mut slice = None;
3610 let mut after = Vec::new();
3611 let mut first = true;
3612 let mut before_slice = true;
3614 while self.token != token::CloseDelim(token::Bracket) {
3618 self.expect(&token::Comma)?;
3620 if self.token == token::CloseDelim(token::Bracket)
3621 && (before_slice || !after.is_empty()) {
3627 if self.eat(&token::DotDot) {
3629 if self.check(&token::Comma) ||
3630 self.check(&token::CloseDelim(token::Bracket)) {
3631 slice = Some(P(Pat {
3632 id: ast::DUMMY_NODE_ID,
3633 node: PatKind::Wild,
3634 span: self.prev_span,
3636 before_slice = false;
3642 let subpat = self.parse_pat(None)?;
3643 if before_slice && self.eat(&token::DotDot) {
3644 slice = Some(subpat);
3645 before_slice = false;
3646 } else if before_slice {
3647 before.push(subpat);
3653 Ok((before, slice, after))
3659 attrs: Vec<Attribute>
3660 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3661 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3663 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3664 // Parsing a pattern of the form "fieldname: pat"
3665 let fieldname = self.parse_field_name()?;
3667 let pat = self.parse_pat(None)?;
3669 (pat, fieldname, false)
3671 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3672 let is_box = self.eat_keyword(kw::Box);
3673 let boxed_span = self.token.span;
3674 let is_ref = self.eat_keyword(kw::Ref);
3675 let is_mut = self.eat_keyword(kw::Mut);
3676 let fieldname = self.parse_ident()?;
3677 hi = self.prev_span;
3679 let bind_type = match (is_ref, is_mut) {
3680 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3681 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3682 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3683 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3685 let fieldpat = P(Pat {
3686 id: ast::DUMMY_NODE_ID,
3687 node: PatKind::Ident(bind_type, fieldname, None),
3688 span: boxed_span.to(hi),
3691 let subpat = if is_box {
3693 id: ast::DUMMY_NODE_ID,
3694 node: PatKind::Box(fieldpat),
3700 (subpat, fieldname, true)
3703 Ok(source_map::Spanned {
3705 node: ast::FieldPat {
3709 attrs: attrs.into(),
3714 /// Parses the fields of a struct-like pattern.
3715 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3716 let mut fields = Vec::new();
3717 let mut etc = false;
3718 let mut ate_comma = true;
3719 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3720 let mut etc_span = None;
3722 while self.token != token::CloseDelim(token::Brace) {
3723 let attrs = self.parse_outer_attributes()?;
3724 let lo = self.token.span;
3726 // check that a comma comes after every field
3728 let err = self.struct_span_err(self.prev_span, "expected `,`");
3729 if let Some(mut delayed) = delayed_err {
3736 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3738 let mut etc_sp = self.token.span;
3740 if self.token == token::DotDotDot { // Issue #46718
3741 // Accept `...` as if it were `..` to avoid further errors
3742 let mut err = self.struct_span_err(self.token.span,
3743 "expected field pattern, found `...`");
3744 err.span_suggestion(
3746 "to omit remaining fields, use one fewer `.`",
3748 Applicability::MachineApplicable
3752 self.bump(); // `..` || `...`
3754 if self.token == token::CloseDelim(token::Brace) {
3755 etc_span = Some(etc_sp);
3758 let token_str = self.this_token_descr();
3759 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3761 err.span_label(self.token.span, "expected `}`");
3762 let mut comma_sp = None;
3763 if self.token == token::Comma { // Issue #49257
3764 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
3765 etc_sp = etc_sp.to(nw_span);
3766 err.span_label(etc_sp,
3767 "`..` must be at the end and cannot have a trailing comma");
3768 comma_sp = Some(self.token.span);
3773 etc_span = Some(etc_sp.until(self.token.span));
3774 if self.token == token::CloseDelim(token::Brace) {
3775 // If the struct looks otherwise well formed, recover and continue.
3776 if let Some(sp) = comma_sp {
3777 err.span_suggestion_short(
3779 "remove this comma",
3781 Applicability::MachineApplicable,
3786 } else if self.token.is_ident() && ate_comma {
3787 // Accept fields coming after `..,`.
3788 // This way we avoid "pattern missing fields" errors afterwards.
3789 // We delay this error until the end in order to have a span for a
3791 if let Some(mut delayed_err) = delayed_err {
3795 delayed_err = Some(err);
3798 if let Some(mut err) = delayed_err {
3805 fields.push(match self.parse_pat_field(lo, attrs) {
3808 if let Some(mut delayed_err) = delayed_err {
3814 ate_comma = self.eat(&token::Comma);
3817 if let Some(mut err) = delayed_err {
3818 if let Some(etc_span) = etc_span {
3819 err.multipart_suggestion(
3820 "move the `..` to the end of the field list",
3822 (etc_span, String::new()),
3823 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3825 Applicability::MachineApplicable,
3830 return Ok((fields, etc));
3833 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3834 if self.token.is_path_start() {
3835 let lo = self.token.span;
3836 let (qself, path) = if self.eat_lt() {
3837 // Parse a qualified path
3838 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3841 // Parse an unqualified path
3842 (None, self.parse_path(PathStyle::Expr)?)
3844 let hi = self.prev_span;
3845 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3847 self.parse_literal_maybe_minus()
3851 // helper function to decide whether to parse as ident binding or to try to do
3852 // something more complex like range patterns
3853 fn parse_as_ident(&mut self) -> bool {
3854 self.look_ahead(1, |t| match t.kind {
3855 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3856 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3857 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3858 // range pattern branch
3859 token::DotDot => None,
3861 }).unwrap_or_else(|| self.look_ahead(2, |t| match t.kind {
3862 token::Comma | token::CloseDelim(token::Bracket) => true,
3867 /// A wrapper around `parse_pat` with some special error handling for the
3868 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3869 /// to subpatterns within such).
3870 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3871 let pat = self.parse_pat(None)?;
3872 if self.token == token::Comma {
3873 // An unexpected comma after a top-level pattern is a clue that the
3874 // user (perhaps more accustomed to some other language) forgot the
3875 // parentheses in what should have been a tuple pattern; return a
3876 // suggestion-enhanced error here rather than choking on the comma
3878 let comma_span = self.token.span;
3880 if let Err(mut err) = self.parse_pat_list() {
3881 // We didn't expect this to work anyway; we just wanted
3882 // to advance to the end of the comma-sequence so we know
3883 // the span to suggest parenthesizing
3886 let seq_span = pat.span.to(self.prev_span);
3887 let mut err = self.struct_span_err(comma_span,
3888 "unexpected `,` in pattern");
3889 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3890 err.span_suggestion(
3892 "try adding parentheses to match on a tuple..",
3893 format!("({})", seq_snippet),
3894 Applicability::MachineApplicable
3897 "..or a vertical bar to match on multiple alternatives",
3898 format!("{}", seq_snippet.replace(",", " |")),
3899 Applicability::MachineApplicable
3907 /// Parses a pattern.
3908 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
3909 self.parse_pat_with_range_pat(true, expected)
3912 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
3914 fn parse_pat_with_range_pat(
3916 allow_range_pat: bool,
3917 expected: Option<&'static str>,
3918 ) -> PResult<'a, P<Pat>> {
3919 maybe_recover_from_interpolated_ty_qpath!(self, true);
3920 maybe_whole!(self, NtPat, |x| x);
3922 let lo = self.token.span;
3924 match self.token.kind {
3925 token::BinOp(token::And) | token::AndAnd => {
3926 // Parse &pat / &mut pat
3928 let mutbl = self.parse_mutability();
3929 if let token::Lifetime(name) = self.token.kind {
3930 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
3931 err.span_label(self.token.span, "unexpected lifetime");
3934 let subpat = self.parse_pat_with_range_pat(false, expected)?;
3935 pat = PatKind::Ref(subpat, mutbl);
3937 token::OpenDelim(token::Paren) => {
3938 // Parse (pat,pat,pat,...) as tuple pattern
3939 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3940 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3941 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3943 PatKind::Tuple(fields, ddpos)
3946 token::OpenDelim(token::Bracket) => {
3947 // Parse [pat,pat,...] as slice pattern
3949 let (before, slice, after) = self.parse_pat_vec_elements()?;
3950 self.expect(&token::CloseDelim(token::Bracket))?;
3951 pat = PatKind::Slice(before, slice, after);
3953 // At this point, token != &, &&, (, [
3954 _ => if self.eat_keyword(kw::Underscore) {
3956 pat = PatKind::Wild;
3957 } else if self.eat_keyword(kw::Mut) {
3958 // Parse mut ident @ pat / mut ref ident @ pat
3959 let mutref_span = self.prev_span.to(self.token.span);
3960 let binding_mode = if self.eat_keyword(kw::Ref) {
3962 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3965 "try switching the order",
3967 Applicability::MachineApplicable
3969 BindingMode::ByRef(Mutability::Mutable)
3971 BindingMode::ByValue(Mutability::Mutable)
3973 pat = self.parse_pat_ident(binding_mode)?;
3974 } else if self.eat_keyword(kw::Ref) {
3975 // Parse ref ident @ pat / ref mut ident @ pat
3976 let mutbl = self.parse_mutability();
3977 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3978 } else if self.eat_keyword(kw::Box) {
3980 let subpat = self.parse_pat_with_range_pat(false, None)?;
3981 pat = PatKind::Box(subpat);
3982 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3983 self.parse_as_ident() {
3984 // Parse ident @ pat
3985 // This can give false positives and parse nullary enums,
3986 // they are dealt with later in resolve
3987 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3988 pat = self.parse_pat_ident(binding_mode)?;
3989 } else if self.token.is_path_start() {
3990 // Parse pattern starting with a path
3991 let (qself, path) = if self.eat_lt() {
3992 // Parse a qualified path
3993 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3996 // Parse an unqualified path
3997 (None, self.parse_path(PathStyle::Expr)?)
3999 match self.token.kind {
4000 token::Not if qself.is_none() => {
4001 // Parse macro invocation
4003 let (delim, tts) = self.expect_delimited_token_tree()?;
4004 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4005 pat = PatKind::Mac(mac);
4007 token::DotDotDot | token::DotDotEq | token::DotDot => {
4008 let end_kind = match self.token.kind {
4009 token::DotDot => RangeEnd::Excluded,
4010 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4011 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4012 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4015 let op_span = self.token.span;
4017 let span = lo.to(self.prev_span);
4018 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4020 let end = self.parse_pat_range_end()?;
4021 let op = Spanned { span: op_span, node: end_kind };
4022 pat = PatKind::Range(begin, end, op);
4024 token::OpenDelim(token::Brace) => {
4025 if qself.is_some() {
4026 let msg = "unexpected `{` after qualified path";
4027 let mut err = self.fatal(msg);
4028 err.span_label(self.token.span, msg);
4031 // Parse struct pattern
4033 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4035 self.recover_stmt();
4039 pat = PatKind::Struct(path, fields, etc);
4041 token::OpenDelim(token::Paren) => {
4042 if qself.is_some() {
4043 let msg = "unexpected `(` after qualified path";
4044 let mut err = self.fatal(msg);
4045 err.span_label(self.token.span, msg);
4048 // Parse tuple struct or enum pattern
4049 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4050 pat = PatKind::TupleStruct(path, fields, ddpos)
4052 _ => pat = PatKind::Path(qself, path),
4055 // Try to parse everything else as literal with optional minus
4056 match self.parse_literal_maybe_minus() {
4058 let op_span = self.token.span;
4059 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4060 self.check(&token::DotDotDot) {
4061 let end_kind = if self.eat(&token::DotDotDot) {
4062 RangeEnd::Included(RangeSyntax::DotDotDot)
4063 } else if self.eat(&token::DotDotEq) {
4064 RangeEnd::Included(RangeSyntax::DotDotEq)
4065 } else if self.eat(&token::DotDot) {
4068 panic!("impossible case: we already matched \
4069 on a range-operator token")
4071 let end = self.parse_pat_range_end()?;
4072 let op = Spanned { span: op_span, node: end_kind };
4073 pat = PatKind::Range(begin, end, op);
4075 pat = PatKind::Lit(begin);
4079 self.cancel(&mut err);
4080 let expected = expected.unwrap_or("pattern");
4082 "expected {}, found {}",
4084 self.this_token_descr(),
4086 let mut err = self.fatal(&msg);
4087 err.span_label(self.token.span, format!("expected {}", expected));
4088 let sp = self.sess.source_map().start_point(self.token.span);
4089 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4090 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4098 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4099 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4101 if !allow_range_pat {
4104 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4106 PatKind::Range(..) => {
4107 let mut err = self.struct_span_err(
4109 "the range pattern here has ambiguous interpretation",
4111 err.span_suggestion(
4113 "add parentheses to clarify the precedence",
4114 format!("({})", pprust::pat_to_string(&pat)),
4115 // "ambiguous interpretation" implies that we have to be guessing
4116 Applicability::MaybeIncorrect
4127 /// Parses `ident` or `ident @ pat`.
4128 /// used by the copy foo and ref foo patterns to give a good
4129 /// error message when parsing mistakes like `ref foo(a, b)`.
4130 fn parse_pat_ident(&mut self,
4131 binding_mode: ast::BindingMode)
4132 -> PResult<'a, PatKind> {
4133 let ident = self.parse_ident()?;
4134 let sub = if self.eat(&token::At) {
4135 Some(self.parse_pat(Some("binding pattern"))?)
4140 // just to be friendly, if they write something like
4142 // we end up here with ( as the current token. This shortly
4143 // leads to a parse error. Note that if there is no explicit
4144 // binding mode then we do not end up here, because the lookahead
4145 // will direct us over to parse_enum_variant()
4146 if self.token == token::OpenDelim(token::Paren) {
4147 return Err(self.span_fatal(
4149 "expected identifier, found enum pattern"))
4152 Ok(PatKind::Ident(binding_mode, ident, sub))
4155 /// Parses a local variable declaration.
4156 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4157 let lo = self.prev_span;
4158 let pat = self.parse_top_level_pat()?;
4160 let (err, ty) = if self.eat(&token::Colon) {
4161 // Save the state of the parser before parsing type normally, in case there is a `:`
4162 // instead of an `=` typo.
4163 let parser_snapshot_before_type = self.clone();
4164 let colon_sp = self.prev_span;
4165 match self.parse_ty() {
4166 Ok(ty) => (None, Some(ty)),
4168 // Rewind to before attempting to parse the type and continue parsing
4169 let parser_snapshot_after_type = self.clone();
4170 mem::replace(self, parser_snapshot_before_type);
4172 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4173 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4174 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4180 let init = match (self.parse_initializer(err.is_some()), err) {
4181 (Ok(init), None) => { // init parsed, ty parsed
4184 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4185 // Could parse the type as if it were the initializer, it is likely there was a
4186 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4187 err.span_suggestion_short(
4189 "use `=` if you meant to assign",
4191 Applicability::MachineApplicable
4194 // As this was parsed successfully, continue as if the code has been fixed for the
4195 // rest of the file. It will still fail due to the emitted error, but we avoid
4199 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4201 // Couldn't parse the type nor the initializer, only raise the type error and
4202 // return to the parser state before parsing the type as the initializer.
4203 // let x: <parse_error>;
4204 mem::replace(self, snapshot);
4207 (Err(err), None) => { // init error, ty parsed
4208 // Couldn't parse the initializer and we're not attempting to recover a failed
4209 // parse of the type, return the error.
4213 let hi = if self.token == token::Semi {
4222 id: ast::DUMMY_NODE_ID,
4228 /// Parses a structure field.
4229 fn parse_name_and_ty(&mut self,
4232 attrs: Vec<Attribute>)
4233 -> PResult<'a, StructField> {
4234 let name = self.parse_ident()?;
4235 self.expect(&token::Colon)?;
4236 let ty = self.parse_ty()?;
4238 span: lo.to(self.prev_span),
4241 id: ast::DUMMY_NODE_ID,
4247 /// Emits an expected-item-after-attributes error.
4248 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4249 let message = match attrs.last() {
4250 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4251 _ => "expected item after attributes",
4254 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4255 if attrs.last().unwrap().is_sugared_doc {
4256 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4261 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4262 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4263 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4264 Ok(self.parse_stmt_(true))
4267 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4268 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4270 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4275 fn is_async_block(&self) -> bool {
4276 self.token.is_keyword(kw::Async) &&
4279 self.is_keyword_ahead(1, &[kw::Move]) &&
4280 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4282 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4287 fn is_async_fn(&self) -> bool {
4288 self.token.is_keyword(kw::Async) &&
4289 self.is_keyword_ahead(1, &[kw::Fn])
4292 fn is_do_catch_block(&self) -> bool {
4293 self.token.is_keyword(kw::Do) &&
4294 self.is_keyword_ahead(1, &[kw::Catch]) &&
4295 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4296 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4299 fn is_try_block(&self) -> bool {
4300 self.token.is_keyword(kw::Try) &&
4301 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4302 self.token.span.rust_2018() &&
4303 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4304 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4307 fn is_union_item(&self) -> bool {
4308 self.token.is_keyword(kw::Union) &&
4309 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4312 fn is_crate_vis(&self) -> bool {
4313 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4316 fn is_existential_type_decl(&self) -> bool {
4317 self.token.is_keyword(kw::Existential) &&
4318 self.is_keyword_ahead(1, &[kw::Type])
4321 fn is_auto_trait_item(&self) -> bool {
4323 (self.token.is_keyword(kw::Auto) &&
4324 self.is_keyword_ahead(1, &[kw::Trait]))
4325 || // unsafe auto trait
4326 (self.token.is_keyword(kw::Unsafe) &&
4327 self.is_keyword_ahead(1, &[kw::Auto]) &&
4328 self.is_keyword_ahead(2, &[kw::Trait]))
4331 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4332 -> PResult<'a, Option<P<Item>>> {
4333 let token_lo = self.token.span;
4334 let (ident, def) = match self.token.kind {
4335 token::Ident(name, false) if name == kw::Macro => {
4337 let ident = self.parse_ident()?;
4338 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4339 match self.parse_token_tree() {
4340 TokenTree::Delimited(_, _, tts) => tts,
4341 _ => unreachable!(),
4343 } else if self.check(&token::OpenDelim(token::Paren)) {
4344 let args = self.parse_token_tree();
4345 let body = if self.check(&token::OpenDelim(token::Brace)) {
4346 self.parse_token_tree()
4351 TokenStream::new(vec![
4353 TokenTree::token(token::FatArrow, token_lo.to(self.prev_span)).into(),
4361 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4363 token::Ident(name, _) if name == sym::macro_rules &&
4364 self.look_ahead(1, |t| *t == token::Not) => {
4365 let prev_span = self.prev_span;
4366 self.complain_if_pub_macro(&vis.node, prev_span);
4370 let ident = self.parse_ident()?;
4371 let (delim, tokens) = self.expect_delimited_token_tree()?;
4372 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
4373 self.report_invalid_macro_expansion_item();
4376 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4378 _ => return Ok(None),
4381 let span = lo.to(self.prev_span);
4382 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4385 fn parse_stmt_without_recovery(&mut self,
4386 macro_legacy_warnings: bool)
4387 -> PResult<'a, Option<Stmt>> {
4388 maybe_whole!(self, NtStmt, |x| Some(x));
4390 let attrs = self.parse_outer_attributes()?;
4391 let lo = self.token.span;
4393 Ok(Some(if self.eat_keyword(kw::Let) {
4395 id: ast::DUMMY_NODE_ID,
4396 node: StmtKind::Local(self.parse_local(attrs.into())?),
4397 span: lo.to(self.prev_span),
4399 } else if let Some(macro_def) = self.eat_macro_def(
4401 &source_map::respan(lo, VisibilityKind::Inherited),
4405 id: ast::DUMMY_NODE_ID,
4406 node: StmtKind::Item(macro_def),
4407 span: lo.to(self.prev_span),
4409 // Starts like a simple path, being careful to avoid contextual keywords
4410 // such as a union items, item with `crate` visibility or auto trait items.
4411 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4412 // like a path (1 token), but it fact not a path.
4413 // `union::b::c` - path, `union U { ... }` - not a path.
4414 // `crate::b::c` - path, `crate struct S;` - not a path.
4415 } else if self.token.is_path_start() &&
4416 !self.token.is_qpath_start() &&
4417 !self.is_union_item() &&
4418 !self.is_crate_vis() &&
4419 !self.is_existential_type_decl() &&
4420 !self.is_auto_trait_item() &&
4421 !self.is_async_fn() {
4422 let pth = self.parse_path(PathStyle::Expr)?;
4424 if !self.eat(&token::Not) {
4425 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4426 self.parse_struct_expr(lo, pth, ThinVec::new())?
4428 let hi = self.prev_span;
4429 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4432 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4433 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4434 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4437 return Ok(Some(Stmt {
4438 id: ast::DUMMY_NODE_ID,
4439 node: StmtKind::Expr(expr),
4440 span: lo.to(self.prev_span),
4444 // it's a macro invocation
4445 let id = match self.token.kind {
4446 token::OpenDelim(_) => Ident::invalid(), // no special identifier
4447 _ => self.parse_ident()?,
4450 // check that we're pointing at delimiters (need to check
4451 // again after the `if`, because of `parse_ident`
4452 // consuming more tokens).
4453 match self.token.kind {
4454 token::OpenDelim(_) => {}
4456 // we only expect an ident if we didn't parse one
4458 let ident_str = if id.name == kw::Invalid {
4463 let tok_str = self.this_token_descr();
4464 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4467 err.span_label(self.token.span, format!("expected {}`(` or `{{`", ident_str));
4472 let (delim, tts) = self.expect_delimited_token_tree()?;
4473 let hi = self.prev_span;
4475 let style = if delim == MacDelimiter::Brace {
4476 MacStmtStyle::Braces
4478 MacStmtStyle::NoBraces
4481 if id.name == kw::Invalid {
4482 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4483 let node = if delim == MacDelimiter::Brace ||
4484 self.token == token::Semi || self.token == token::Eof {
4485 StmtKind::Mac(P((mac, style, attrs.into())))
4487 // We used to incorrectly stop parsing macro-expanded statements here.
4488 // If the next token will be an error anyway but could have parsed with the
4489 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4490 else if macro_legacy_warnings &&
4491 self.token.can_begin_expr() &&
4492 match self.token.kind {
4493 // These can continue an expression, so we can't stop parsing and warn.
4494 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4495 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4496 token::BinOp(token::And) | token::BinOp(token::Or) |
4497 token::AndAnd | token::OrOr |
4498 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4501 self.warn_missing_semicolon();
4502 StmtKind::Mac(P((mac, style, attrs.into())))
4504 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
4505 let e = self.maybe_recover_from_bad_qpath(e, true)?;
4506 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4507 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4511 id: ast::DUMMY_NODE_ID,
4516 // if it has a special ident, it's definitely an item
4518 // Require a semicolon or braces.
4519 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
4520 self.report_invalid_macro_expansion_item();
4522 let span = lo.to(hi);
4524 id: ast::DUMMY_NODE_ID,
4526 node: StmtKind::Item({
4528 span, id /*id is good here*/,
4529 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4530 respan(lo, VisibilityKind::Inherited),
4536 // FIXME: Bad copy of attrs
4537 let old_directory_ownership =
4538 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4539 let item = self.parse_item_(attrs.clone(), false, true)?;
4540 self.directory.ownership = old_directory_ownership;
4544 id: ast::DUMMY_NODE_ID,
4545 span: lo.to(i.span),
4546 node: StmtKind::Item(i),
4549 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4550 if !attrs.is_empty() {
4551 if s.prev_token_kind == PrevTokenKind::DocComment {
4552 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4553 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4555 s.token.span, "expected statement after outer attribute"
4561 // Do not attempt to parse an expression if we're done here.
4562 if self.token == token::Semi {
4563 unused_attrs(&attrs, self);
4568 if self.token == token::CloseDelim(token::Brace) {
4569 unused_attrs(&attrs, self);
4573 // Remainder are line-expr stmts.
4574 let e = self.parse_expr_res(
4575 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4577 id: ast::DUMMY_NODE_ID,
4578 span: lo.to(e.span),
4579 node: StmtKind::Expr(e),
4586 /// Checks if this expression is a successfully parsed statement.
4587 fn expr_is_complete(&self, e: &Expr) -> bool {
4588 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4589 !classify::expr_requires_semi_to_be_stmt(e)
4592 /// Parses a block. No inner attributes are allowed.
4593 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4594 maybe_whole!(self, NtBlock, |x| x);
4596 let lo = self.token.span;
4598 if !self.eat(&token::OpenDelim(token::Brace)) {
4599 let sp = self.token.span;
4600 let tok = self.this_token_descr();
4601 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4602 let do_not_suggest_help =
4603 self.token.is_keyword(kw::In) || self.token == token::Colon;
4605 if self.token.is_ident_named(sym::and) {
4606 e.span_suggestion_short(
4608 "use `&&` instead of `and` for the boolean operator",
4610 Applicability::MaybeIncorrect,
4613 if self.token.is_ident_named(sym::or) {
4614 e.span_suggestion_short(
4616 "use `||` instead of `or` for the boolean operator",
4618 Applicability::MaybeIncorrect,
4622 // Check to see if the user has written something like
4627 // Which is valid in other languages, but not Rust.
4628 match self.parse_stmt_without_recovery(false) {
4630 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4631 || do_not_suggest_help {
4632 // if the next token is an open brace (e.g., `if a b {`), the place-
4633 // inside-a-block suggestion would be more likely wrong than right
4634 e.span_label(sp, "expected `{`");
4637 let mut stmt_span = stmt.span;
4638 // expand the span to include the semicolon, if it exists
4639 if self.eat(&token::Semi) {
4640 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4642 let sugg = pprust::to_string(|s| {
4643 use crate::print::pprust::{PrintState, INDENT_UNIT};
4644 s.ibox(INDENT_UNIT)?;
4646 s.print_stmt(&stmt)?;
4647 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4651 "try placing this code inside a block",
4653 // speculative, has been misleading in the past (closed Issue #46836)
4654 Applicability::MaybeIncorrect
4658 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4659 self.cancel(&mut e);
4663 e.span_label(sp, "expected `{`");
4667 self.parse_block_tail(lo, BlockCheckMode::Default)
4670 /// Parses a block. Inner attributes are allowed.
4671 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4672 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4674 let lo = self.token.span;
4675 self.expect(&token::OpenDelim(token::Brace))?;
4676 Ok((self.parse_inner_attributes()?,
4677 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4680 /// Parses the rest of a block expression or function body.
4681 /// Precondition: already parsed the '{'.
4682 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4683 let mut stmts = vec![];
4684 while !self.eat(&token::CloseDelim(token::Brace)) {
4685 let stmt = match self.parse_full_stmt(false) {
4688 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4690 id: ast::DUMMY_NODE_ID,
4691 node: StmtKind::Expr(DummyResult::raw_expr(self.token.span, true)),
4692 span: self.token.span,
4697 if let Some(stmt) = stmt {
4699 } else if self.token == token::Eof {
4702 // Found only `;` or `}`.
4708 id: ast::DUMMY_NODE_ID,
4710 span: lo.to(self.prev_span),
4714 /// Parses a statement, including the trailing semicolon.
4715 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4716 // skip looking for a trailing semicolon when we have an interpolated statement
4717 maybe_whole!(self, NtStmt, |x| Some(x));
4719 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4721 None => return Ok(None),
4725 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4726 // expression without semicolon
4727 if classify::expr_requires_semi_to_be_stmt(expr) {
4728 // Just check for errors and recover; do not eat semicolon yet.
4730 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4733 self.recover_stmt();
4737 StmtKind::Local(..) => {
4738 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4739 if macro_legacy_warnings && self.token != token::Semi {
4740 self.warn_missing_semicolon();
4742 self.expect_one_of(&[], &[token::Semi])?;
4748 if self.eat(&token::Semi) {
4749 stmt = stmt.add_trailing_semicolon();
4752 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4756 fn warn_missing_semicolon(&self) {
4757 self.diagnostic().struct_span_warn(self.token.span, {
4758 &format!("expected `;`, found {}", self.this_token_descr())
4760 "This was erroneously allowed and will become a hard error in a future release"
4764 fn err_dotdotdot_syntax(&self, span: Span) {
4765 self.diagnostic().struct_span_err(span, {
4766 "unexpected token: `...`"
4768 span, "use `..` for an exclusive range", "..".to_owned(),
4769 Applicability::MaybeIncorrect
4771 span, "or `..=` for an inclusive range", "..=".to_owned(),
4772 Applicability::MaybeIncorrect
4776 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
4779 /// BOUND = TY_BOUND | LT_BOUND
4780 /// LT_BOUND = LIFETIME (e.g., `'a`)
4781 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4782 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
4784 fn parse_generic_bounds_common(&mut self,
4786 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4787 let mut bounds = Vec::new();
4788 let mut negative_bounds = Vec::new();
4789 let mut last_plus_span = None;
4790 let mut was_negative = false;
4792 // This needs to be synchronized with `TokenKind::can_begin_bound`.
4793 let is_bound_start = self.check_path() || self.check_lifetime() ||
4794 self.check(&token::Not) || // used for error reporting only
4795 self.check(&token::Question) ||
4796 self.check_keyword(kw::For) ||
4797 self.check(&token::OpenDelim(token::Paren));
4799 let lo = self.token.span;
4800 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4801 let inner_lo = self.token.span;
4802 let is_negative = self.eat(&token::Not);
4803 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4804 if self.token.is_lifetime() {
4805 if let Some(question_span) = question {
4806 self.span_err(question_span,
4807 "`?` may only modify trait bounds, not lifetime bounds");
4809 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4811 let inner_span = inner_lo.to(self.prev_span);
4812 self.expect(&token::CloseDelim(token::Paren))?;
4813 let mut err = self.struct_span_err(
4814 lo.to(self.prev_span),
4815 "parenthesized lifetime bounds are not supported"
4817 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
4818 err.span_suggestion_short(
4819 lo.to(self.prev_span),
4820 "remove the parentheses",
4822 Applicability::MachineApplicable
4828 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4829 let path = self.parse_path(PathStyle::Type)?;
4831 self.expect(&token::CloseDelim(token::Paren))?;
4833 let poly_span = lo.to(self.prev_span);
4835 was_negative = true;
4836 if let Some(sp) = last_plus_span.or(colon_span) {
4837 negative_bounds.push(sp.to(poly_span));
4840 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
4841 let modifier = if question.is_some() {
4842 TraitBoundModifier::Maybe
4844 TraitBoundModifier::None
4846 bounds.push(GenericBound::Trait(poly_trait, modifier));
4853 if !allow_plus || !self.eat_plus() {
4856 last_plus_span = Some(self.prev_span);
4860 if !negative_bounds.is_empty() || was_negative {
4861 let plural = negative_bounds.len() > 1;
4862 let last_span = negative_bounds.last().map(|sp| *sp);
4863 let mut err = self.struct_span_err(
4865 "negative trait bounds are not supported",
4867 if let Some(sp) = last_span {
4868 err.span_label(sp, "negative trait bounds are not supported");
4870 if let Some(bound_list) = colon_span {
4871 let bound_list = bound_list.to(self.prev_span);
4872 let mut new_bound_list = String::new();
4873 if !bounds.is_empty() {
4874 let mut snippets = bounds.iter().map(|bound| bound.span())
4875 .map(|span| self.sess.source_map().span_to_snippet(span));
4876 while let Some(Ok(snippet)) = snippets.next() {
4877 new_bound_list.push_str(" + ");
4878 new_bound_list.push_str(&snippet);
4880 new_bound_list = new_bound_list.replacen(" +", ":", 1);
4882 err.span_suggestion_hidden(
4884 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
4886 Applicability::MachineApplicable,
4895 crate fn parse_generic_bounds(&mut self,
4896 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4897 self.parse_generic_bounds_common(true, colon_span)
4900 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4903 /// BOUND = LT_BOUND (e.g., `'a`)
4905 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4906 let mut lifetimes = Vec::new();
4907 while self.check_lifetime() {
4908 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4910 if !self.eat_plus() {
4917 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
4918 fn parse_ty_param(&mut self,
4919 preceding_attrs: Vec<Attribute>)
4920 -> PResult<'a, GenericParam> {
4921 let ident = self.parse_ident()?;
4923 // Parse optional colon and param bounds.
4924 let bounds = if self.eat(&token::Colon) {
4925 self.parse_generic_bounds(Some(self.prev_span))?
4930 let default = if self.eat(&token::Eq) {
4931 Some(self.parse_ty()?)
4938 id: ast::DUMMY_NODE_ID,
4939 attrs: preceding_attrs.into(),
4941 kind: GenericParamKind::Type {
4947 /// Parses the following grammar:
4949 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4950 fn parse_trait_item_assoc_ty(&mut self)
4951 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4952 let ident = self.parse_ident()?;
4953 let mut generics = self.parse_generics()?;
4955 // Parse optional colon and param bounds.
4956 let bounds = if self.eat(&token::Colon) {
4957 self.parse_generic_bounds(None)?
4961 generics.where_clause = self.parse_where_clause()?;
4963 let default = if self.eat(&token::Eq) {
4964 Some(self.parse_ty()?)
4968 self.expect(&token::Semi)?;
4970 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4973 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
4974 self.expect_keyword(kw::Const)?;
4975 let ident = self.parse_ident()?;
4976 self.expect(&token::Colon)?;
4977 let ty = self.parse_ty()?;
4981 id: ast::DUMMY_NODE_ID,
4982 attrs: preceding_attrs.into(),
4984 kind: GenericParamKind::Const {
4990 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
4991 /// a trailing comma and erroneous trailing attributes.
4992 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4993 let mut params = Vec::new();
4995 let attrs = self.parse_outer_attributes()?;
4996 if self.check_lifetime() {
4997 let lifetime = self.expect_lifetime();
4998 // Parse lifetime parameter.
4999 let bounds = if self.eat(&token::Colon) {
5000 self.parse_lt_param_bounds()
5004 params.push(ast::GenericParam {
5005 ident: lifetime.ident,
5007 attrs: attrs.into(),
5009 kind: ast::GenericParamKind::Lifetime,
5011 } else if self.check_keyword(kw::Const) {
5012 // Parse const parameter.
5013 params.push(self.parse_const_param(attrs)?);
5014 } else if self.check_ident() {
5015 // Parse type parameter.
5016 params.push(self.parse_ty_param(attrs)?);
5018 // Check for trailing attributes and stop parsing.
5019 if !attrs.is_empty() {
5020 if !params.is_empty() {
5021 self.struct_span_err(
5023 &format!("trailing attribute after generic parameter"),
5025 .span_label(attrs[0].span, "attributes must go before parameters")
5028 self.struct_span_err(
5030 &format!("attribute without generic parameters"),
5034 "attributes are only permitted when preceding parameters",
5042 if !self.eat(&token::Comma) {
5049 /// Parses a set of optional generic type parameter declarations. Where
5050 /// clauses are not parsed here, and must be added later via
5051 /// `parse_where_clause()`.
5053 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5054 /// | ( < lifetimes , typaramseq ( , )? > )
5055 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5056 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5057 let span_lo = self.token.span;
5058 let (params, span) = if self.eat_lt() {
5059 let params = self.parse_generic_params()?;
5061 (params, span_lo.to(self.prev_span))
5063 (vec![], self.prev_span.between(self.token.span))
5067 where_clause: WhereClause {
5068 id: ast::DUMMY_NODE_ID,
5069 predicates: Vec::new(),
5076 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5077 /// For the purposes of understanding the parsing logic of generic arguments, this function
5078 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5079 /// had the correct amount of leading angle brackets.
5081 /// ```ignore (diagnostics)
5082 /// bar::<<<<T as Foo>::Output>();
5083 /// ^^ help: remove extra angle brackets
5085 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5089 ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5090 // We need to detect whether there are extra leading left angle brackets and produce an
5091 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5092 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5093 // then there won't be matching `>` tokens to find.
5095 // To explain how this detection works, consider the following example:
5097 // ```ignore (diagnostics)
5098 // bar::<<<<T as Foo>::Output>();
5099 // ^^ help: remove extra angle brackets
5102 // Parsing of the left angle brackets starts in this function. We start by parsing the
5103 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5106 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5107 // *Unmatched count:* 1
5108 // *`parse_path_segment` calls deep:* 0
5110 // This has the effect of recursing as this function is called if a `<` character
5111 // is found within the expected generic arguments:
5113 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5114 // *Unmatched count:* 2
5115 // *`parse_path_segment` calls deep:* 1
5117 // Eventually we will have recursed until having consumed all of the `<` tokens and
5118 // this will be reflected in the count:
5120 // *Upcoming tokens:* `T as Foo>::Output>;`
5121 // *Unmatched count:* 4
5122 // `parse_path_segment` calls deep:* 3
5124 // The parser will continue until reaching the first `>` - this will decrement the
5125 // unmatched angle bracket count and return to the parent invocation of this function
5126 // having succeeded in parsing:
5128 // *Upcoming tokens:* `::Output>;`
5129 // *Unmatched count:* 3
5130 // *`parse_path_segment` calls deep:* 2
5132 // This will continue until the next `>` character which will also return successfully
5133 // to the parent invocation of this function and decrement the count:
5135 // *Upcoming tokens:* `;`
5136 // *Unmatched count:* 2
5137 // *`parse_path_segment` calls deep:* 1
5139 // At this point, this function will expect to find another matching `>` character but
5140 // won't be able to and will return an error. This will continue all the way up the
5141 // call stack until the first invocation:
5143 // *Upcoming tokens:* `;`
5144 // *Unmatched count:* 2
5145 // *`parse_path_segment` calls deep:* 0
5147 // In doing this, we have managed to work out how many unmatched leading left angle
5148 // brackets there are, but we cannot recover as the unmatched angle brackets have
5149 // already been consumed. To remedy this, we keep a snapshot of the parser state
5150 // before we do the above. We can then inspect whether we ended up with a parsing error
5151 // and unmatched left angle brackets and if so, restore the parser state before we
5152 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5153 // recover by attempting to parse again.
5155 // In practice, the recursion of this function is indirect and there will be other
5156 // locations that consume some `<` characters - as long as we update the count when
5157 // this happens, it isn't an issue.
5159 let is_first_invocation = style == PathStyle::Expr;
5160 // Take a snapshot before attempting to parse - we can restore this later.
5161 let snapshot = if is_first_invocation {
5167 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5168 match self.parse_generic_args() {
5169 Ok(value) => Ok(value),
5170 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5171 // Cancel error from being unable to find `>`. We know the error
5172 // must have been this due to a non-zero unmatched angle bracket
5176 // Swap `self` with our backup of the parser state before attempting to parse
5177 // generic arguments.
5178 let snapshot = mem::replace(self, snapshot.unwrap());
5181 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5182 snapshot.count={:?}",
5183 snapshot.unmatched_angle_bracket_count,
5186 // Eat the unmatched angle brackets.
5187 for _ in 0..snapshot.unmatched_angle_bracket_count {
5191 // Make a span over ${unmatched angle bracket count} characters.
5192 let span = lo.with_hi(
5193 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5195 let plural = snapshot.unmatched_angle_bracket_count > 1;
5200 "unmatched angle bracket{}",
5201 if plural { "s" } else { "" }
5207 "remove extra angle bracket{}",
5208 if plural { "s" } else { "" }
5211 Applicability::MachineApplicable,
5215 // Try again without unmatched angle bracket characters.
5216 self.parse_generic_args()
5222 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5223 /// possibly including trailing comma.
5224 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5225 let mut args = Vec::new();
5226 let mut constraints = Vec::new();
5227 let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new();
5228 let mut assoc_ty_constraints: Vec<Span> = Vec::new();
5230 let args_lo = self.token.span;
5233 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5234 // Parse lifetime argument.
5235 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5236 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5237 } else if self.check_ident() && self.look_ahead(1,
5238 |t| t == &token::Eq || t == &token::Colon) {
5239 // Parse associated type constraint.
5240 let lo = self.token.span;
5241 let ident = self.parse_ident()?;
5242 let kind = if self.eat(&token::Eq) {
5243 AssocTyConstraintKind::Equality {
5244 ty: self.parse_ty()?,
5246 } else if self.eat(&token::Colon) {
5247 AssocTyConstraintKind::Bound {
5248 bounds: self.parse_generic_bounds(Some(self.prev_span))?,
5253 let span = lo.to(self.prev_span);
5254 constraints.push(AssocTyConstraint {
5255 id: ast::DUMMY_NODE_ID,
5260 assoc_ty_constraints.push(span);
5261 } else if self.check_const_arg() {
5262 // Parse const argument.
5263 let expr = if let token::OpenDelim(token::Brace) = self.token.kind {
5264 self.parse_block_expr(
5265 None, self.token.span, BlockCheckMode::Default, ThinVec::new()
5267 } else if self.token.is_ident() {
5268 // FIXME(const_generics): to distinguish between idents for types and consts,
5269 // we should introduce a GenericArg::Ident in the AST and distinguish when
5270 // lowering to the HIR. For now, idents for const args are not permitted.
5271 if self.token.is_keyword(kw::True) || self.token.is_keyword(kw::False) {
5272 self.parse_literal_maybe_minus()?
5275 self.fatal("identifiers may currently not be used for const generics")
5279 self.parse_literal_maybe_minus()?
5281 let value = AnonConst {
5282 id: ast::DUMMY_NODE_ID,
5285 args.push(GenericArg::Const(value));
5286 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5287 } else if self.check_type() {
5288 // Parse type argument.
5289 args.push(GenericArg::Type(self.parse_ty()?));
5290 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5295 if !self.eat(&token::Comma) {
5300 // FIXME: we would like to report this in ast_validation instead, but we currently do not
5301 // preserve ordering of generic parameters with respect to associated type binding, so we
5302 // lose that information after parsing.
5303 if misplaced_assoc_ty_constraints.len() > 0 {
5304 let mut err = self.struct_span_err(
5305 args_lo.to(self.prev_span),
5306 "associated type bindings must be declared after generic parameters",
5308 for span in misplaced_assoc_ty_constraints {
5311 "this associated type binding should be moved after the generic parameters",
5317 Ok((args, constraints))
5320 /// Parses an optional where-clause and places it in `generics`.
5322 /// ```ignore (only-for-syntax-highlight)
5323 /// where T : Trait<U, V> + 'b, 'a : 'b
5325 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5326 let mut where_clause = WhereClause {
5327 id: ast::DUMMY_NODE_ID,
5328 predicates: Vec::new(),
5329 span: self.prev_span.to(self.prev_span),
5332 if !self.eat_keyword(kw::Where) {
5333 return Ok(where_clause);
5335 let lo = self.prev_span;
5337 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5338 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5339 // change we parse those generics now, but report an error.
5340 if self.choose_generics_over_qpath() {
5341 let generics = self.parse_generics()?;
5342 self.struct_span_err(
5344 "generic parameters on `where` clauses are reserved for future use",
5346 .span_label(generics.span, "currently unsupported")
5351 let lo = self.token.span;
5352 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5353 let lifetime = self.expect_lifetime();
5354 // Bounds starting with a colon are mandatory, but possibly empty.
5355 self.expect(&token::Colon)?;
5356 let bounds = self.parse_lt_param_bounds();
5357 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5358 ast::WhereRegionPredicate {
5359 span: lo.to(self.prev_span),
5364 } else if self.check_type() {
5365 // Parse optional `for<'a, 'b>`.
5366 // This `for` is parsed greedily and applies to the whole predicate,
5367 // the bounded type can have its own `for` applying only to it.
5369 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
5370 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
5371 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
5372 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5374 // Parse type with mandatory colon and (possibly empty) bounds,
5375 // or with mandatory equality sign and the second type.
5376 let ty = self.parse_ty()?;
5377 if self.eat(&token::Colon) {
5378 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
5379 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5380 ast::WhereBoundPredicate {
5381 span: lo.to(self.prev_span),
5382 bound_generic_params: lifetime_defs,
5387 // FIXME: Decide what should be used here, `=` or `==`.
5388 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5389 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5390 let rhs_ty = self.parse_ty()?;
5391 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5392 ast::WhereEqPredicate {
5393 span: lo.to(self.prev_span),
5396 id: ast::DUMMY_NODE_ID,
5400 return self.unexpected();
5406 if !self.eat(&token::Comma) {
5411 where_clause.span = lo.to(self.prev_span);
5415 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
5416 -> PResult<'a, (Vec<Arg> , bool)> {
5417 self.expect(&token::OpenDelim(token::Paren))?;
5419 let sp = self.token.span;
5420 let mut c_variadic = false;
5421 let (args, recovered): (Vec<Option<Arg>>, bool) =
5422 self.parse_seq_to_before_end(
5423 &token::CloseDelim(token::Paren),
5424 SeqSep::trailing_allowed(token::Comma),
5426 // If the argument is a C-variadic argument we should not
5427 // enforce named arguments.
5428 let enforce_named_args = if p.token == token::DotDotDot {
5433 match p.parse_arg_general(enforce_named_args, false,
5436 if let TyKind::CVarArgs = arg.ty.node {
5438 if p.token != token::CloseDelim(token::Paren) {
5439 let span = p.token.span;
5441 "`...` must be the last argument of a C-variadic function");
5452 let lo = p.prev_span;
5453 // Skip every token until next possible arg or end.
5454 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5455 // Create a placeholder argument for proper arg count (issue #34264).
5456 let span = lo.to(p.prev_span);
5457 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
5464 self.eat(&token::CloseDelim(token::Paren));
5467 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5469 if c_variadic && args.is_empty() {
5471 "C-variadic function must be declared with at least one named argument");
5474 Ok((args, c_variadic))
5477 /// Parses the argument list and result type of a function declaration.
5478 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
5480 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
5481 let ret_ty = self.parse_ret_ty(true)?;
5490 /// Returns the parsed optional self argument and whether a self shortcut was used.
5491 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5492 let expect_ident = |this: &mut Self| match this.token.kind {
5493 // Preserve hygienic context.
5494 token::Ident(name, _) =>
5495 { let span = this.token.span; this.bump(); Ident::new(name, span) }
5498 let isolated_self = |this: &mut Self, n| {
5499 this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
5500 this.look_ahead(n + 1, |t| t != &token::ModSep)
5503 // Parse optional `self` parameter of a method.
5504 // Only a limited set of initial token sequences is considered `self` parameters; anything
5505 // else is parsed as a normal function parameter list, so some lookahead is required.
5506 let eself_lo = self.token.span;
5507 let (eself, eself_ident, eself_hi) = match self.token.kind {
5508 token::BinOp(token::And) => {
5514 (if isolated_self(self, 1) {
5516 SelfKind::Region(None, Mutability::Immutable)
5517 } else if self.is_keyword_ahead(1, &[kw::Mut]) &&
5518 isolated_self(self, 2) {
5521 SelfKind::Region(None, Mutability::Mutable)
5522 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5523 isolated_self(self, 2) {
5525 let lt = self.expect_lifetime();
5526 SelfKind::Region(Some(lt), Mutability::Immutable)
5527 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5528 self.is_keyword_ahead(2, &[kw::Mut]) &&
5529 isolated_self(self, 3) {
5531 let lt = self.expect_lifetime();
5533 SelfKind::Region(Some(lt), Mutability::Mutable)
5536 }, expect_ident(self), self.prev_span)
5538 token::BinOp(token::Star) => {
5543 // Emit special error for `self` cases.
5544 let msg = "cannot pass `self` by raw pointer";
5545 (if isolated_self(self, 1) {
5547 self.struct_span_err(self.token.span, msg)
5548 .span_label(self.token.span, msg)
5550 SelfKind::Value(Mutability::Immutable)
5551 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5552 isolated_self(self, 2) {
5555 self.struct_span_err(self.token.span, msg)
5556 .span_label(self.token.span, msg)
5558 SelfKind::Value(Mutability::Immutable)
5561 }, expect_ident(self), self.prev_span)
5563 token::Ident(..) => {
5564 if isolated_self(self, 0) {
5567 let eself_ident = expect_ident(self);
5568 let eself_hi = self.prev_span;
5569 (if self.eat(&token::Colon) {
5570 let ty = self.parse_ty()?;
5571 SelfKind::Explicit(ty, Mutability::Immutable)
5573 SelfKind::Value(Mutability::Immutable)
5574 }, eself_ident, eself_hi)
5575 } else if self.token.is_keyword(kw::Mut) &&
5576 isolated_self(self, 1) {
5580 let eself_ident = expect_ident(self);
5581 let eself_hi = self.prev_span;
5582 (if self.eat(&token::Colon) {
5583 let ty = self.parse_ty()?;
5584 SelfKind::Explicit(ty, Mutability::Mutable)
5586 SelfKind::Value(Mutability::Mutable)
5587 }, eself_ident, eself_hi)
5592 _ => return Ok(None),
5595 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5596 Ok(Some(Arg::from_self(eself, eself_ident)))
5599 /// Parses the parameter list and result type of a function that may have a `self` parameter.
5600 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5601 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5603 self.expect(&token::OpenDelim(token::Paren))?;
5605 // Parse optional self argument.
5606 let self_arg = self.parse_self_arg()?;
5608 // Parse the rest of the function parameter list.
5609 let sep = SeqSep::trailing_allowed(token::Comma);
5610 let (mut fn_inputs, recovered) = if let Some(self_arg) = self_arg {
5611 if self.check(&token::CloseDelim(token::Paren)) {
5612 (vec![self_arg], false)
5613 } else if self.eat(&token::Comma) {
5614 let mut fn_inputs = vec![self_arg];
5615 let (mut input, recovered) = self.parse_seq_to_before_end(
5616 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
5617 fn_inputs.append(&mut input);
5618 (fn_inputs, recovered)
5620 match self.expect_one_of(&[], &[]) {
5621 Err(err) => return Err(err),
5622 Ok(recovered) => (vec![self_arg], recovered),
5626 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5630 // Parse closing paren and return type.
5631 self.expect(&token::CloseDelim(token::Paren))?;
5633 // Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
5634 self.deduplicate_recovered_arg_names(&mut fn_inputs);
5638 output: self.parse_ret_ty(true)?,
5643 /// Parses the `|arg, arg|` header of a closure.
5644 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5645 let inputs_captures = {
5646 if self.eat(&token::OrOr) {
5649 self.expect(&token::BinOp(token::Or))?;
5650 let args = self.parse_seq_to_before_tokens(
5651 &[&token::BinOp(token::Or), &token::OrOr],
5652 SeqSep::trailing_allowed(token::Comma),
5653 TokenExpectType::NoExpect,
5654 |p| p.parse_fn_block_arg()
5660 let output = self.parse_ret_ty(true)?;
5663 inputs: inputs_captures,
5669 /// Parses the name and optional generic types of a function header.
5670 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5671 let id = self.parse_ident()?;
5672 let generics = self.parse_generics()?;
5676 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5677 attrs: Vec<Attribute>) -> P<Item> {
5681 id: ast::DUMMY_NODE_ID,
5689 /// Parses an item-position function declaration.
5690 fn parse_item_fn(&mut self,
5692 asyncness: Spanned<IsAsync>,
5693 constness: Spanned<Constness>,
5695 -> PResult<'a, ItemInfo> {
5696 let (ident, mut generics) = self.parse_fn_header()?;
5697 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
5698 let decl = self.parse_fn_decl(allow_c_variadic)?;
5699 generics.where_clause = self.parse_where_clause()?;
5700 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5701 let header = FnHeader { unsafety, asyncness, constness, abi };
5702 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5705 /// Returns `true` if we are looking at `const ID`
5706 /// (returns `false` for things like `const fn`, etc.).
5707 fn is_const_item(&self) -> bool {
5708 self.token.is_keyword(kw::Const) &&
5709 !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
5712 /// Parses all the "front matter" for a `fn` declaration, up to
5713 /// and including the `fn` keyword:
5717 /// - `const unsafe fn`
5720 fn parse_fn_front_matter(&mut self)
5728 let is_const_fn = self.eat_keyword(kw::Const);
5729 let const_span = self.prev_span;
5730 let unsafety = self.parse_unsafety();
5731 let asyncness = self.parse_asyncness();
5732 let asyncness = respan(self.prev_span, asyncness);
5733 let (constness, unsafety, abi) = if is_const_fn {
5734 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5736 let abi = if self.eat_keyword(kw::Extern) {
5737 self.parse_opt_abi()?.unwrap_or(Abi::C)
5741 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5743 if !self.eat_keyword(kw::Fn) {
5744 // It is possible for `expect_one_of` to recover given the contents of
5745 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
5746 // account for this.
5747 if !self.expect_one_of(&[], &[])? { unreachable!() }
5749 Ok((constness, unsafety, asyncness, abi))
5752 /// Parses an impl item.
5753 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5754 maybe_whole!(self, NtImplItem, |x| x);
5755 let attrs = self.parse_outer_attributes()?;
5756 let mut unclosed_delims = vec![];
5757 let (mut item, tokens) = self.collect_tokens(|this| {
5758 let item = this.parse_impl_item_(at_end, attrs);
5759 unclosed_delims.append(&mut this.unclosed_delims);
5762 self.unclosed_delims.append(&mut unclosed_delims);
5764 // See `parse_item` for why this clause is here.
5765 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5766 item.tokens = Some(tokens);
5771 fn parse_impl_item_(&mut self,
5773 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5774 let lo = self.token.span;
5775 let vis = self.parse_visibility(false)?;
5776 let defaultness = self.parse_defaultness();
5777 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5778 let (name, alias, generics) = type_?;
5779 let kind = match alias {
5780 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5781 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5783 (name, kind, generics)
5784 } else if self.is_const_item() {
5785 // This parses the grammar:
5786 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5787 self.expect_keyword(kw::Const)?;
5788 let name = self.parse_ident()?;
5789 self.expect(&token::Colon)?;
5790 let typ = self.parse_ty()?;
5791 self.expect(&token::Eq)?;
5792 let expr = self.parse_expr()?;
5793 self.expect(&token::Semi)?;
5794 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5796 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5797 attrs.extend(inner_attrs);
5798 (name, node, generics)
5802 id: ast::DUMMY_NODE_ID,
5803 span: lo.to(self.prev_span),
5814 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
5816 VisibilityKind::Inherited => {}
5818 let mut err = if self.token.is_keyword(sym::macro_rules) {
5819 let mut err = self.diagnostic()
5820 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5821 err.span_suggestion(
5823 "try exporting the macro",
5824 "#[macro_export]".to_owned(),
5825 Applicability::MaybeIncorrect // speculative
5829 let mut err = self.diagnostic()
5830 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5831 err.help("try adjusting the macro to put `pub` inside the invocation");
5839 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
5840 -> DiagnosticBuilder<'a>
5842 let expected_kinds = if item_type == "extern" {
5843 "missing `fn`, `type`, or `static`"
5845 "missing `fn`, `type`, or `const`"
5848 // Given this code `path(`, it seems like this is not
5849 // setting the visibility of a macro invocation, but rather
5850 // a mistyped method declaration.
5851 // Create a diagnostic pointing out that `fn` is missing.
5853 // x | pub path(&self) {
5854 // | ^ missing `fn`, `type`, or `const`
5856 // ^^ `sp` below will point to this
5857 let sp = prev_span.between(self.prev_span);
5858 let mut err = self.diagnostic().struct_span_err(
5860 &format!("{} for {}-item declaration",
5861 expected_kinds, item_type));
5862 err.span_label(sp, expected_kinds);
5866 /// Parse a method or a macro invocation in a trait impl.
5867 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5868 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5869 ast::ImplItemKind)> {
5870 // code copied from parse_macro_use_or_failure... abstraction!
5871 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5873 Ok((Ident::invalid(), vec![], ast::Generics::default(),
5874 ast::ImplItemKind::Macro(mac)))
5876 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5877 let ident = self.parse_ident()?;
5878 let mut generics = self.parse_generics()?;
5879 let decl = self.parse_fn_decl_with_self(|p| {
5880 p.parse_arg_general(true, true, false)
5882 generics.where_clause = self.parse_where_clause()?;
5884 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5885 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5886 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5887 ast::MethodSig { header, decl },
5893 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
5894 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5895 let ident = self.parse_ident()?;
5896 let mut tps = self.parse_generics()?;
5898 // Parse optional colon and supertrait bounds.
5899 let bounds = if self.eat(&token::Colon) {
5900 self.parse_generic_bounds(Some(self.prev_span))?
5905 if self.eat(&token::Eq) {
5906 // it's a trait alias
5907 let bounds = self.parse_generic_bounds(None)?;
5908 tps.where_clause = self.parse_where_clause()?;
5909 self.expect(&token::Semi)?;
5910 if is_auto == IsAuto::Yes {
5911 let msg = "trait aliases cannot be `auto`";
5912 self.struct_span_err(self.prev_span, msg)
5913 .span_label(self.prev_span, msg)
5916 if unsafety != Unsafety::Normal {
5917 let msg = "trait aliases cannot be `unsafe`";
5918 self.struct_span_err(self.prev_span, msg)
5919 .span_label(self.prev_span, msg)
5922 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5924 // it's a normal trait
5925 tps.where_clause = self.parse_where_clause()?;
5926 self.expect(&token::OpenDelim(token::Brace))?;
5927 let mut trait_items = vec![];
5928 while !self.eat(&token::CloseDelim(token::Brace)) {
5929 if let token::DocComment(_) = self.token.kind {
5930 if self.look_ahead(1,
5931 |tok| tok == &token::CloseDelim(token::Brace)) {
5932 let mut err = self.diagnostic().struct_span_err_with_code(
5934 "found a documentation comment that doesn't document anything",
5935 DiagnosticId::Error("E0584".into()),
5937 err.help("doc comments must come before what they document, maybe a \
5938 comment was intended with `//`?",
5945 let mut at_end = false;
5946 match self.parse_trait_item(&mut at_end) {
5947 Ok(item) => trait_items.push(item),
5951 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5956 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5960 fn choose_generics_over_qpath(&self) -> bool {
5961 // There's an ambiguity between generic parameters and qualified paths in impls.
5962 // If we see `<` it may start both, so we have to inspect some following tokens.
5963 // The following combinations can only start generics,
5964 // but not qualified paths (with one exception):
5965 // `<` `>` - empty generic parameters
5966 // `<` `#` - generic parameters with attributes
5967 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5968 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5969 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5970 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5971 // `<` const - generic const parameter
5972 // The only truly ambiguous case is
5973 // `<` IDENT `>` `::` IDENT ...
5974 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5975 // because this is what almost always expected in practice, qualified paths in impls
5976 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5977 self.token == token::Lt &&
5978 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5979 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5980 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5981 t == &token::Colon || t == &token::Eq) ||
5982 self.is_keyword_ahead(1, &[kw::Const]))
5985 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5986 self.expect(&token::OpenDelim(token::Brace))?;
5987 let attrs = self.parse_inner_attributes()?;
5989 let mut impl_items = Vec::new();
5990 while !self.eat(&token::CloseDelim(token::Brace)) {
5991 let mut at_end = false;
5992 match self.parse_impl_item(&mut at_end) {
5993 Ok(impl_item) => impl_items.push(impl_item),
5997 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6002 Ok((impl_items, attrs))
6005 /// Parses an implementation item, `impl` keyword is already parsed.
6007 /// impl<'a, T> TYPE { /* impl items */ }
6008 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6009 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6011 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6012 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6013 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6014 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6015 -> PResult<'a, ItemInfo> {
6016 // First, parse generic parameters if necessary.
6017 let mut generics = if self.choose_generics_over_qpath() {
6018 self.parse_generics()?
6020 ast::Generics::default()
6023 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6024 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6026 ast::ImplPolarity::Negative
6028 ast::ImplPolarity::Positive
6031 // Parse both types and traits as a type, then reinterpret if necessary.
6032 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
6033 let ty_first = if self.token.is_keyword(kw::For) &&
6034 self.look_ahead(1, |t| t != &token::Lt) {
6035 let span = self.prev_span.between(self.token.span);
6036 self.struct_span_err(span, "missing trait in a trait impl").emit();
6037 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6042 // If `for` is missing we try to recover.
6043 let has_for = self.eat_keyword(kw::For);
6044 let missing_for_span = self.prev_span.between(self.token.span);
6046 let ty_second = if self.token == token::DotDot {
6047 // We need to report this error after `cfg` expansion for compatibility reasons
6048 self.bump(); // `..`, do not add it to expected tokens
6049 Some(DummyResult::raw_ty(self.prev_span, true))
6050 } else if has_for || self.token.can_begin_type() {
6051 Some(self.parse_ty()?)
6056 generics.where_clause = self.parse_where_clause()?;
6058 let (impl_items, attrs) = self.parse_impl_body()?;
6060 let item_kind = match ty_second {
6061 Some(ty_second) => {
6062 // impl Trait for Type
6064 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6065 .span_suggestion_short(
6068 " for ".to_string(),
6069 Applicability::MachineApplicable,
6073 let ty_first = ty_first.into_inner();
6074 let path = match ty_first.node {
6075 // This notably includes paths passed through `ty` macro fragments (#46438).
6076 TyKind::Path(None, path) => path,
6078 self.span_err(ty_first.span, "expected a trait, found type");
6079 err_path(ty_first.span)
6082 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6084 ItemKind::Impl(unsafety, polarity, defaultness,
6085 generics, Some(trait_ref), ty_second, impl_items)
6089 ItemKind::Impl(unsafety, polarity, defaultness,
6090 generics, None, ty_first, impl_items)
6094 Ok((Ident::invalid(), item_kind, Some(attrs)))
6097 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6098 if self.eat_keyword(kw::For) {
6100 let params = self.parse_generic_params()?;
6102 // We rely on AST validation to rule out invalid cases: There must not be type
6103 // parameters, and the lifetime parameters must not have bounds.
6110 /// Parses `struct Foo { ... }`.
6111 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6112 let class_name = self.parse_ident()?;
6114 let mut generics = self.parse_generics()?;
6116 // There is a special case worth noting here, as reported in issue #17904.
6117 // If we are parsing a tuple struct it is the case that the where clause
6118 // should follow the field list. Like so:
6120 // struct Foo<T>(T) where T: Copy;
6122 // If we are parsing a normal record-style struct it is the case
6123 // that the where clause comes before the body, and after the generics.
6124 // So if we look ahead and see a brace or a where-clause we begin
6125 // parsing a record style struct.
6127 // Otherwise if we look ahead and see a paren we parse a tuple-style
6130 let vdata = if self.token.is_keyword(kw::Where) {
6131 generics.where_clause = self.parse_where_clause()?;
6132 if self.eat(&token::Semi) {
6133 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6134 VariantData::Unit(ast::DUMMY_NODE_ID)
6136 // If we see: `struct Foo<T> where T: Copy { ... }`
6137 let (fields, recovered) = self.parse_record_struct_body()?;
6138 VariantData::Struct(fields, recovered)
6140 // No `where` so: `struct Foo<T>;`
6141 } else if self.eat(&token::Semi) {
6142 VariantData::Unit(ast::DUMMY_NODE_ID)
6143 // Record-style struct definition
6144 } else if self.token == token::OpenDelim(token::Brace) {
6145 let (fields, recovered) = self.parse_record_struct_body()?;
6146 VariantData::Struct(fields, recovered)
6147 // Tuple-style struct definition with optional where-clause.
6148 } else if self.token == token::OpenDelim(token::Paren) {
6149 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6150 generics.where_clause = self.parse_where_clause()?;
6151 self.expect(&token::Semi)?;
6154 let token_str = self.this_token_descr();
6155 let mut err = self.fatal(&format!(
6156 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6159 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
6163 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6166 /// Parses `union Foo { ... }`.
6167 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6168 let class_name = self.parse_ident()?;
6170 let mut generics = self.parse_generics()?;
6172 let vdata = if self.token.is_keyword(kw::Where) {
6173 generics.where_clause = self.parse_where_clause()?;
6174 let (fields, recovered) = self.parse_record_struct_body()?;
6175 VariantData::Struct(fields, recovered)
6176 } else if self.token == token::OpenDelim(token::Brace) {
6177 let (fields, recovered) = self.parse_record_struct_body()?;
6178 VariantData::Struct(fields, recovered)
6180 let token_str = self.this_token_descr();
6181 let mut err = self.fatal(&format!(
6182 "expected `where` or `{{` after union name, found {}", token_str));
6183 err.span_label(self.token.span, "expected `where` or `{` after union name");
6187 Ok((class_name, ItemKind::Union(vdata, generics), None))
6190 fn parse_record_struct_body(
6192 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6193 let mut fields = Vec::new();
6194 let mut recovered = false;
6195 if self.eat(&token::OpenDelim(token::Brace)) {
6196 while self.token != token::CloseDelim(token::Brace) {
6197 let field = self.parse_struct_decl_field().map_err(|e| {
6198 self.recover_stmt();
6203 Ok(field) => fields.push(field),
6209 self.eat(&token::CloseDelim(token::Brace));
6211 let token_str = self.this_token_descr();
6212 let mut err = self.fatal(&format!(
6213 "expected `where`, or `{{` after struct name, found {}", token_str));
6214 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
6218 Ok((fields, recovered))
6221 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6222 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6223 // Unit like structs are handled in parse_item_struct function
6224 let fields = self.parse_unspanned_seq(
6225 &token::OpenDelim(token::Paren),
6226 &token::CloseDelim(token::Paren),
6227 SeqSep::trailing_allowed(token::Comma),
6229 let attrs = p.parse_outer_attributes()?;
6230 let lo = p.token.span;
6231 let vis = p.parse_visibility(true)?;
6232 let ty = p.parse_ty()?;
6234 span: lo.to(ty.span),
6237 id: ast::DUMMY_NODE_ID,
6246 /// Parses a structure field declaration.
6247 fn parse_single_struct_field(&mut self,
6250 attrs: Vec<Attribute> )
6251 -> PResult<'a, StructField> {
6252 let mut seen_comma: bool = false;
6253 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6254 if self.token == token::Comma {
6257 match self.token.kind {
6261 token::CloseDelim(token::Brace) => {}
6262 token::DocComment(_) => {
6263 let previous_span = self.prev_span;
6264 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
6265 self.bump(); // consume the doc comment
6266 let comma_after_doc_seen = self.eat(&token::Comma);
6267 // `seen_comma` is always false, because we are inside doc block
6268 // condition is here to make code more readable
6269 if seen_comma == false && comma_after_doc_seen == true {
6272 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6275 if seen_comma == false {
6276 let sp = self.sess.source_map().next_point(previous_span);
6277 err.span_suggestion(
6279 "missing comma here",
6281 Applicability::MachineApplicable
6288 let sp = self.sess.source_map().next_point(self.prev_span);
6289 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6290 self.this_token_descr()));
6291 if self.token.is_ident() {
6292 // This is likely another field; emit the diagnostic and keep going
6293 err.span_suggestion(
6295 "try adding a comma",
6297 Applicability::MachineApplicable,
6308 /// Parses an element of a struct declaration.
6309 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6310 let attrs = self.parse_outer_attributes()?;
6311 let lo = self.token.span;
6312 let vis = self.parse_visibility(false)?;
6313 self.parse_single_struct_field(lo, vis, attrs)
6316 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6317 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6318 /// If the following element can't be a tuple (i.e., it's a function definition), then
6319 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6320 /// so emit a proper diagnostic.
6321 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6322 maybe_whole!(self, NtVis, |x| x);
6324 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
6325 if self.is_crate_vis() {
6326 self.bump(); // `crate`
6327 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6330 if !self.eat_keyword(kw::Pub) {
6331 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6332 // keyword to grab a span from for inherited visibility; an empty span at the
6333 // beginning of the current token would seem to be the "Schelling span".
6334 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
6336 let lo = self.prev_span;
6338 if self.check(&token::OpenDelim(token::Paren)) {
6339 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6340 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6341 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6342 // by the following tokens.
6343 if self.is_keyword_ahead(1, &[kw::Crate]) &&
6344 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
6348 self.bump(); // `crate`
6349 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6351 lo.to(self.prev_span),
6352 VisibilityKind::Crate(CrateSugar::PubCrate),
6355 } else if self.is_keyword_ahead(1, &[kw::In]) {
6358 self.bump(); // `in`
6359 let path = self.parse_path(PathStyle::Mod)?; // `path`
6360 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6361 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6363 id: ast::DUMMY_NODE_ID,
6366 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6367 self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
6369 // `pub(self)` or `pub(super)`
6371 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6372 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6373 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6375 id: ast::DUMMY_NODE_ID,
6378 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6379 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6381 let msg = "incorrect visibility restriction";
6382 let suggestion = r##"some possible visibility restrictions are:
6383 `pub(crate)`: visible only on the current crate
6384 `pub(super)`: visible only in the current module's parent
6385 `pub(in path::to::module)`: visible only on the specified path"##;
6386 let path = self.parse_path(PathStyle::Mod)?;
6388 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6389 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6390 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6391 err.help(suggestion);
6392 err.span_suggestion(
6393 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6395 err.emit(); // emit diagnostic, but continue with public visibility
6399 Ok(respan(lo, VisibilityKind::Public))
6402 /// Parses defaultness (i.e., `default` or nothing).
6403 fn parse_defaultness(&mut self) -> Defaultness {
6404 // `pub` is included for better error messages
6405 if self.check_keyword(kw::Default) &&
6406 self.is_keyword_ahead(1, &[
6416 self.bump(); // `default`
6417 Defaultness::Default
6423 /// Given a termination token, parses all of the items in a module.
6424 fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
6425 let mut items = vec![];
6426 while let Some(item) = self.parse_item()? {
6428 self.maybe_consume_incorrect_semicolon(&items);
6431 if !self.eat(term) {
6432 let token_str = self.this_token_descr();
6433 if !self.maybe_consume_incorrect_semicolon(&items) {
6434 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6435 err.span_label(self.token.span, "expected item");
6440 let hi = if self.token.span.is_dummy() {
6447 inner: inner_lo.to(hi),
6453 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6454 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6455 self.expect(&token::Colon)?;
6456 let ty = self.parse_ty()?;
6457 self.expect(&token::Eq)?;
6458 let e = self.parse_expr()?;
6459 self.expect(&token::Semi)?;
6460 let item = match m {
6461 Some(m) => ItemKind::Static(ty, m, e),
6462 None => ItemKind::Const(ty, e),
6464 Ok((id, item, None))
6467 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6468 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6469 let (in_cfg, outer_attrs) = {
6470 let mut strip_unconfigured = crate::config::StripUnconfigured {
6472 features: None, // don't perform gated feature checking
6474 let mut outer_attrs = outer_attrs.to_owned();
6475 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
6476 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6479 let id_span = self.token.span;
6480 let id = self.parse_ident()?;
6481 if self.eat(&token::Semi) {
6482 if in_cfg && self.recurse_into_file_modules {
6483 // This mod is in an external file. Let's go get it!
6484 let ModulePathSuccess { path, directory_ownership, warn } =
6485 self.submod_path(id, &outer_attrs, id_span)?;
6486 let (module, mut attrs) =
6487 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6488 // Record that we fetched the mod from an external file
6490 let attr = Attribute {
6491 id: attr::mk_attr_id(),
6492 style: ast::AttrStyle::Outer,
6493 path: ast::Path::from_ident(
6494 Ident::with_empty_ctxt(sym::warn_directory_ownership)),
6495 tokens: TokenStream::empty(),
6496 is_sugared_doc: false,
6499 attr::mark_known(&attr);
6502 Ok((id, ItemKind::Mod(module), Some(attrs)))
6504 let placeholder = ast::Mod {
6509 Ok((id, ItemKind::Mod(placeholder), None))
6512 let old_directory = self.directory.clone();
6513 self.push_directory(id, &outer_attrs);
6515 self.expect(&token::OpenDelim(token::Brace))?;
6516 let mod_inner_lo = self.token.span;
6517 let attrs = self.parse_inner_attributes()?;
6518 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6520 self.directory = old_directory;
6521 Ok((id, ItemKind::Mod(module), Some(attrs)))
6525 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6526 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6527 self.directory.path.to_mut().push(&path.as_str());
6528 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6530 // We have to push on the current module name in the case of relative
6531 // paths in order to ensure that any additional module paths from inline
6532 // `mod x { ... }` come after the relative extension.
6534 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6535 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6536 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6537 if let Some(ident) = relative.take() { // remove the relative offset
6538 self.directory.path.to_mut().push(ident.as_str());
6541 self.directory.path.to_mut().push(&id.as_str());
6545 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6546 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6549 // On windows, the base path might have the form
6550 // `\\?\foo\bar` in which case it does not tolerate
6551 // mixed `/` and `\` separators, so canonicalize
6554 let s = s.replace("/", "\\");
6555 Some(dir_path.join(s))
6561 /// Returns a path to a module.
6562 pub fn default_submod_path(
6564 relative: Option<ast::Ident>,
6566 source_map: &SourceMap) -> ModulePath
6568 // If we're in a foo.rs file instead of a mod.rs file,
6569 // we need to look for submodules in
6570 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6571 // `./<id>.rs` and `./<id>/mod.rs`.
6572 let relative_prefix_string;
6573 let relative_prefix = if let Some(ident) = relative {
6574 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6575 &relative_prefix_string
6580 let mod_name = id.to_string();
6581 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6582 let secondary_path_str = format!("{}{}{}mod.rs",
6583 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6584 let default_path = dir_path.join(&default_path_str);
6585 let secondary_path = dir_path.join(&secondary_path_str);
6586 let default_exists = source_map.file_exists(&default_path);
6587 let secondary_exists = source_map.file_exists(&secondary_path);
6589 let result = match (default_exists, secondary_exists) {
6590 (true, false) => Ok(ModulePathSuccess {
6592 directory_ownership: DirectoryOwnership::Owned {
6597 (false, true) => Ok(ModulePathSuccess {
6598 path: secondary_path,
6599 directory_ownership: DirectoryOwnership::Owned {
6604 (false, false) => Err(Error::FileNotFoundForModule {
6605 mod_name: mod_name.clone(),
6606 default_path: default_path_str,
6607 secondary_path: secondary_path_str,
6608 dir_path: dir_path.display().to_string(),
6610 (true, true) => Err(Error::DuplicatePaths {
6611 mod_name: mod_name.clone(),
6612 default_path: default_path_str,
6613 secondary_path: secondary_path_str,
6619 path_exists: default_exists || secondary_exists,
6624 fn submod_path(&mut self,
6626 outer_attrs: &[Attribute],
6628 -> PResult<'a, ModulePathSuccess> {
6629 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6630 return Ok(ModulePathSuccess {
6631 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6632 // All `#[path]` files are treated as though they are a `mod.rs` file.
6633 // This means that `mod foo;` declarations inside `#[path]`-included
6634 // files are siblings,
6636 // Note that this will produce weirdness when a file named `foo.rs` is
6637 // `#[path]` included and contains a `mod foo;` declaration.
6638 // If you encounter this, it's your own darn fault :P
6639 Some(_) => DirectoryOwnership::Owned { relative: None },
6640 _ => DirectoryOwnership::UnownedViaMod(true),
6647 let relative = match self.directory.ownership {
6648 DirectoryOwnership::Owned { relative } => relative,
6649 DirectoryOwnership::UnownedViaBlock |
6650 DirectoryOwnership::UnownedViaMod(_) => None,
6652 let paths = Parser::default_submod_path(
6653 id, relative, &self.directory.path, self.sess.source_map());
6655 match self.directory.ownership {
6656 DirectoryOwnership::Owned { .. } => {
6657 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6659 DirectoryOwnership::UnownedViaBlock => {
6661 "Cannot declare a non-inline module inside a block \
6662 unless it has a path attribute";
6663 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6664 if paths.path_exists {
6665 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6667 err.span_note(id_sp, &msg);
6671 DirectoryOwnership::UnownedViaMod(warn) => {
6673 if let Ok(result) = paths.result {
6674 return Ok(ModulePathSuccess { warn: true, ..result });
6677 let mut err = self.diagnostic().struct_span_err(id_sp,
6678 "cannot declare a new module at this location");
6679 if !id_sp.is_dummy() {
6680 let src_path = self.sess.source_map().span_to_filename(id_sp);
6681 if let FileName::Real(src_path) = src_path {
6682 if let Some(stem) = src_path.file_stem() {
6683 let mut dest_path = src_path.clone();
6684 dest_path.set_file_name(stem);
6685 dest_path.push("mod.rs");
6686 err.span_note(id_sp,
6687 &format!("maybe move this module `{}` to its own \
6688 directory via `{}`", src_path.display(),
6689 dest_path.display()));
6693 if paths.path_exists {
6694 err.span_note(id_sp,
6695 &format!("... or maybe `use` the module `{}` instead \
6696 of possibly redeclaring it",
6704 /// Reads a module from a source file.
6705 fn eval_src_mod(&mut self,
6707 directory_ownership: DirectoryOwnership,
6710 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6711 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6712 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6713 let mut err = String::from("circular modules: ");
6714 let len = included_mod_stack.len();
6715 for p in &included_mod_stack[i.. len] {
6716 err.push_str(&p.to_string_lossy());
6717 err.push_str(" -> ");
6719 err.push_str(&path.to_string_lossy());
6720 return Err(self.span_fatal(id_sp, &err[..]));
6722 included_mod_stack.push(path.clone());
6723 drop(included_mod_stack);
6726 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6727 p0.cfg_mods = self.cfg_mods;
6728 let mod_inner_lo = p0.token.span;
6729 let mod_attrs = p0.parse_inner_attributes()?;
6730 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6732 self.sess.included_mod_stack.borrow_mut().pop();
6736 /// Parses a function declaration from a foreign module.
6737 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6738 -> PResult<'a, ForeignItem> {
6739 self.expect_keyword(kw::Fn)?;
6741 let (ident, mut generics) = self.parse_fn_header()?;
6742 let decl = self.parse_fn_decl(true)?;
6743 generics.where_clause = self.parse_where_clause()?;
6744 let hi = self.token.span;
6745 self.expect(&token::Semi)?;
6746 Ok(ast::ForeignItem {
6749 node: ForeignItemKind::Fn(decl, generics),
6750 id: ast::DUMMY_NODE_ID,
6756 /// Parses a static item from a foreign module.
6757 /// Assumes that the `static` keyword is already parsed.
6758 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6759 -> PResult<'a, ForeignItem> {
6760 let mutbl = self.parse_mutability();
6761 let ident = self.parse_ident()?;
6762 self.expect(&token::Colon)?;
6763 let ty = self.parse_ty()?;
6764 let hi = self.token.span;
6765 self.expect(&token::Semi)?;
6769 node: ForeignItemKind::Static(ty, mutbl),
6770 id: ast::DUMMY_NODE_ID,
6776 /// Parses a type from a foreign module.
6777 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6778 -> PResult<'a, ForeignItem> {
6779 self.expect_keyword(kw::Type)?;
6781 let ident = self.parse_ident()?;
6782 let hi = self.token.span;
6783 self.expect(&token::Semi)?;
6784 Ok(ast::ForeignItem {
6787 node: ForeignItemKind::Ty,
6788 id: ast::DUMMY_NODE_ID,
6794 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6795 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6796 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6798 let mut ident = if self.token.is_keyword(kw::SelfLower) {
6799 self.parse_path_segment_ident()
6803 let mut idents = vec![];
6804 let mut replacement = vec![];
6805 let mut fixed_crate_name = false;
6806 // Accept `extern crate name-like-this` for better diagnostics
6807 let dash = token::BinOp(token::BinOpToken::Minus);
6808 if self.token == dash { // Do not include `-` as part of the expected tokens list
6809 while self.eat(&dash) {
6810 fixed_crate_name = true;
6811 replacement.push((self.prev_span, "_".to_string()));
6812 idents.push(self.parse_ident()?);
6815 if fixed_crate_name {
6816 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6817 let mut fixed_name = format!("{}", ident.name);
6818 for part in idents {
6819 fixed_name.push_str(&format!("_{}", part.name));
6821 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6823 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6824 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6825 err.multipart_suggestion(
6828 Applicability::MachineApplicable,
6835 /// Parses `extern crate` links.
6840 /// extern crate foo;
6841 /// extern crate bar as foo;
6843 fn parse_item_extern_crate(&mut self,
6845 visibility: Visibility,
6846 attrs: Vec<Attribute>)
6847 -> PResult<'a, P<Item>> {
6848 // Accept `extern crate name-like-this` for better diagnostics
6849 let orig_name = self.parse_crate_name_with_dashes()?;
6850 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6851 (rename, Some(orig_name.name))
6855 self.expect(&token::Semi)?;
6857 let span = lo.to(self.prev_span);
6858 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6861 /// Parses `extern` for foreign ABIs modules.
6863 /// `extern` is expected to have been
6864 /// consumed before calling this method.
6868 /// ```ignore (only-for-syntax-highlight)
6872 fn parse_item_foreign_mod(&mut self,
6874 opt_abi: Option<Abi>,
6875 visibility: Visibility,
6876 mut attrs: Vec<Attribute>)
6877 -> PResult<'a, P<Item>> {
6878 self.expect(&token::OpenDelim(token::Brace))?;
6880 let abi = opt_abi.unwrap_or(Abi::C);
6882 attrs.extend(self.parse_inner_attributes()?);
6884 let mut foreign_items = vec![];
6885 while !self.eat(&token::CloseDelim(token::Brace)) {
6886 foreign_items.push(self.parse_foreign_item()?);
6889 let prev_span = self.prev_span;
6890 let m = ast::ForeignMod {
6892 items: foreign_items
6894 let invalid = Ident::invalid();
6895 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6898 /// Parses `type Foo = Bar;`
6900 /// `existential type Foo: Bar;`
6903 /// without modifying the parser state.
6904 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6905 // This parses the grammar:
6906 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6907 if self.check_keyword(kw::Type) ||
6908 self.check_keyword(kw::Existential) &&
6909 self.is_keyword_ahead(1, &[kw::Type]) {
6910 let existential = self.eat_keyword(kw::Existential);
6911 assert!(self.eat_keyword(kw::Type));
6912 Some(self.parse_existential_or_alias(existential))
6918 /// Parses a type alias or existential type.
6919 fn parse_existential_or_alias(
6922 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6923 let ident = self.parse_ident()?;
6924 let mut tps = self.parse_generics()?;
6925 tps.where_clause = self.parse_where_clause()?;
6926 let alias = if existential {
6927 self.expect(&token::Colon)?;
6928 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6929 AliasKind::Existential(bounds)
6931 self.expect(&token::Eq)?;
6932 let ty = self.parse_ty()?;
6935 self.expect(&token::Semi)?;
6936 Ok((ident, alias, tps))
6939 /// Parses the part of an enum declaration following the `{`.
6940 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6941 let mut variants = Vec::new();
6942 let mut any_disr = vec![];
6943 while self.token != token::CloseDelim(token::Brace) {
6944 let variant_attrs = self.parse_outer_attributes()?;
6945 let vlo = self.token.span;
6948 let mut disr_expr = None;
6950 let ident = self.parse_ident()?;
6951 if self.check(&token::OpenDelim(token::Brace)) {
6952 // Parse a struct variant.
6953 let (fields, recovered) = self.parse_record_struct_body()?;
6954 struct_def = VariantData::Struct(fields, recovered);
6955 } else if self.check(&token::OpenDelim(token::Paren)) {
6956 struct_def = VariantData::Tuple(
6957 self.parse_tuple_struct_body()?,
6960 } else if self.eat(&token::Eq) {
6961 disr_expr = Some(AnonConst {
6962 id: ast::DUMMY_NODE_ID,
6963 value: self.parse_expr()?,
6965 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
6968 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6970 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6973 let vr = ast::Variant_ {
6975 id: ast::DUMMY_NODE_ID,
6976 attrs: variant_attrs,
6980 variants.push(respan(vlo.to(self.prev_span), vr));
6982 if !self.eat(&token::Comma) {
6983 if self.token.is_ident() && !self.token.is_reserved_ident() {
6984 let sp = self.sess.source_map().next_point(self.prev_span);
6985 let mut err = self.struct_span_err(sp, "missing comma");
6986 err.span_suggestion_short(
6990 Applicability::MaybeIncorrect,
6998 self.expect(&token::CloseDelim(token::Brace))?;
6999 self.maybe_report_invalid_custom_discriminants(any_disr, &variants);
7001 Ok(ast::EnumDef { variants })
7004 /// Parses an enum declaration.
7005 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7006 let id = self.parse_ident()?;
7007 let mut generics = self.parse_generics()?;
7008 generics.where_clause = self.parse_where_clause()?;
7009 self.expect(&token::OpenDelim(token::Brace))?;
7011 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7012 self.recover_stmt();
7013 self.eat(&token::CloseDelim(token::Brace));
7016 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7019 /// Parses a string as an ABI spec on an extern type or module. Consumes
7020 /// the `extern` keyword, if one is found.
7021 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7022 match self.token.kind {
7023 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
7024 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
7025 let sp = self.token.span;
7026 self.expect_no_suffix(sp, "an ABI spec", suffix);
7028 match abi::lookup(&symbol.as_str()) {
7029 Some(abi) => Ok(Some(abi)),
7031 let prev_span = self.prev_span;
7032 let mut err = struct_span_err!(
7033 self.sess.span_diagnostic,
7036 "invalid ABI: found `{}`",
7038 err.span_label(prev_span, "invalid ABI");
7039 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7050 fn is_static_global(&mut self) -> bool {
7051 if self.check_keyword(kw::Static) {
7052 // Check if this could be a closure
7053 !self.look_ahead(1, |token| {
7054 if token.is_keyword(kw::Move) {
7058 token::BinOp(token::Or) | token::OrOr => true,
7069 attrs: Vec<Attribute>,
7070 macros_allowed: bool,
7071 attributes_allowed: bool,
7072 ) -> PResult<'a, Option<P<Item>>> {
7073 let mut unclosed_delims = vec![];
7074 let (ret, tokens) = self.collect_tokens(|this| {
7075 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7076 unclosed_delims.append(&mut this.unclosed_delims);
7079 self.unclosed_delims.append(&mut unclosed_delims);
7081 // Once we've parsed an item and recorded the tokens we got while
7082 // parsing we may want to store `tokens` into the item we're about to
7083 // return. Note, though, that we specifically didn't capture tokens
7084 // related to outer attributes. The `tokens` field here may later be
7085 // used with procedural macros to convert this item back into a token
7086 // stream, but during expansion we may be removing attributes as we go
7089 // If we've got inner attributes then the `tokens` we've got above holds
7090 // these inner attributes. If an inner attribute is expanded we won't
7091 // actually remove it from the token stream, so we'll just keep yielding
7092 // it (bad!). To work around this case for now we just avoid recording
7093 // `tokens` if we detect any inner attributes. This should help keep
7094 // expansion correct, but we should fix this bug one day!
7097 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7098 i.tokens = Some(tokens);
7105 /// Parses one of the items allowed by the flags.
7106 fn parse_item_implementation(
7108 attrs: Vec<Attribute>,
7109 macros_allowed: bool,
7110 attributes_allowed: bool,
7111 ) -> PResult<'a, Option<P<Item>>> {
7112 maybe_whole!(self, NtItem, |item| {
7113 let mut item = item.into_inner();
7114 let mut attrs = attrs;
7115 mem::swap(&mut item.attrs, &mut attrs);
7116 item.attrs.extend(attrs);
7120 let lo = self.token.span;
7122 let visibility = self.parse_visibility(false)?;
7124 if self.eat_keyword(kw::Use) {
7126 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7127 self.expect(&token::Semi)?;
7129 let span = lo.to(self.prev_span);
7131 self.mk_item(span, Ident::invalid(), item_, visibility, attrs);
7132 return Ok(Some(item));
7135 if self.eat_keyword(kw::Extern) {
7136 if self.eat_keyword(kw::Crate) {
7137 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7140 let opt_abi = self.parse_opt_abi()?;
7142 if self.eat_keyword(kw::Fn) {
7143 // EXTERN FUNCTION ITEM
7144 let fn_span = self.prev_span;
7145 let abi = opt_abi.unwrap_or(Abi::C);
7146 let (ident, item_, extra_attrs) =
7147 self.parse_item_fn(Unsafety::Normal,
7148 respan(fn_span, IsAsync::NotAsync),
7149 respan(fn_span, Constness::NotConst),
7151 let prev_span = self.prev_span;
7152 let item = self.mk_item(lo.to(prev_span),
7156 maybe_append(attrs, extra_attrs));
7157 return Ok(Some(item));
7158 } else if self.check(&token::OpenDelim(token::Brace)) {
7159 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7165 if self.is_static_global() {
7168 let m = if self.eat_keyword(kw::Mut) {
7171 Mutability::Immutable
7173 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7174 let prev_span = self.prev_span;
7175 let item = self.mk_item(lo.to(prev_span),
7179 maybe_append(attrs, extra_attrs));
7180 return Ok(Some(item));
7182 if self.eat_keyword(kw::Const) {
7183 let const_span = self.prev_span;
7184 if self.check_keyword(kw::Fn)
7185 || (self.check_keyword(kw::Unsafe)
7186 && self.is_keyword_ahead(1, &[kw::Fn])) {
7187 // CONST FUNCTION ITEM
7188 let unsafety = self.parse_unsafety();
7190 let (ident, item_, extra_attrs) =
7191 self.parse_item_fn(unsafety,
7192 respan(const_span, IsAsync::NotAsync),
7193 respan(const_span, Constness::Const),
7195 let prev_span = self.prev_span;
7196 let item = self.mk_item(lo.to(prev_span),
7200 maybe_append(attrs, extra_attrs));
7201 return Ok(Some(item));
7205 if self.eat_keyword(kw::Mut) {
7206 let prev_span = self.prev_span;
7207 let mut err = self.diagnostic()
7208 .struct_span_err(prev_span, "const globals cannot be mutable");
7209 err.span_label(prev_span, "cannot be mutable");
7210 err.span_suggestion(
7212 "you might want to declare a static instead",
7213 "static".to_owned(),
7214 Applicability::MaybeIncorrect,
7218 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7219 let prev_span = self.prev_span;
7220 let item = self.mk_item(lo.to(prev_span),
7224 maybe_append(attrs, extra_attrs));
7225 return Ok(Some(item));
7228 // Parse `async unsafe? fn`.
7229 if self.check_keyword(kw::Async) {
7230 let async_span = self.token.span;
7231 if self.is_keyword_ahead(1, &[kw::Fn])
7232 || self.is_keyword_ahead(2, &[kw::Fn])
7234 // ASYNC FUNCTION ITEM
7235 self.bump(); // `async`
7236 let unsafety = self.parse_unsafety(); // `unsafe`?
7237 self.expect_keyword(kw::Fn)?; // `fn`
7238 let fn_span = self.prev_span;
7239 let (ident, item_, extra_attrs) =
7240 self.parse_item_fn(unsafety,
7241 respan(async_span, IsAsync::Async {
7242 closure_id: ast::DUMMY_NODE_ID,
7243 return_impl_trait_id: ast::DUMMY_NODE_ID,
7245 respan(fn_span, Constness::NotConst),
7247 let prev_span = self.prev_span;
7248 let item = self.mk_item(lo.to(prev_span),
7252 maybe_append(attrs, extra_attrs));
7253 if self.token.span.rust_2015() {
7254 self.diagnostic().struct_span_err_with_code(
7256 "`async fn` is not permitted in the 2015 edition",
7257 DiagnosticId::Error("E0670".into())
7260 return Ok(Some(item));
7263 if self.check_keyword(kw::Unsafe) &&
7264 self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
7266 // UNSAFE TRAIT ITEM
7267 self.bump(); // `unsafe`
7268 let is_auto = if self.eat_keyword(kw::Trait) {
7271 self.expect_keyword(kw::Auto)?;
7272 self.expect_keyword(kw::Trait)?;
7275 let (ident, item_, extra_attrs) =
7276 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7277 let prev_span = self.prev_span;
7278 let item = self.mk_item(lo.to(prev_span),
7282 maybe_append(attrs, extra_attrs));
7283 return Ok(Some(item));
7285 if self.check_keyword(kw::Impl) ||
7286 self.check_keyword(kw::Unsafe) &&
7287 self.is_keyword_ahead(1, &[kw::Impl]) ||
7288 self.check_keyword(kw::Default) &&
7289 self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) {
7291 let defaultness = self.parse_defaultness();
7292 let unsafety = self.parse_unsafety();
7293 self.expect_keyword(kw::Impl)?;
7294 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7295 let span = lo.to(self.prev_span);
7296 return Ok(Some(self.mk_item(span, ident, item, visibility,
7297 maybe_append(attrs, extra_attrs))));
7299 if self.check_keyword(kw::Fn) {
7302 let fn_span = self.prev_span;
7303 let (ident, item_, extra_attrs) =
7304 self.parse_item_fn(Unsafety::Normal,
7305 respan(fn_span, IsAsync::NotAsync),
7306 respan(fn_span, Constness::NotConst),
7308 let prev_span = self.prev_span;
7309 let item = self.mk_item(lo.to(prev_span),
7313 maybe_append(attrs, extra_attrs));
7314 return Ok(Some(item));
7316 if self.check_keyword(kw::Unsafe)
7317 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7318 // UNSAFE FUNCTION ITEM
7319 self.bump(); // `unsafe`
7320 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7321 self.check(&token::OpenDelim(token::Brace));
7322 let abi = if self.eat_keyword(kw::Extern) {
7323 self.parse_opt_abi()?.unwrap_or(Abi::C)
7327 self.expect_keyword(kw::Fn)?;
7328 let fn_span = self.prev_span;
7329 let (ident, item_, extra_attrs) =
7330 self.parse_item_fn(Unsafety::Unsafe,
7331 respan(fn_span, IsAsync::NotAsync),
7332 respan(fn_span, Constness::NotConst),
7334 let prev_span = self.prev_span;
7335 let item = self.mk_item(lo.to(prev_span),
7339 maybe_append(attrs, extra_attrs));
7340 return Ok(Some(item));
7342 if self.eat_keyword(kw::Mod) {
7344 let (ident, item_, extra_attrs) =
7345 self.parse_item_mod(&attrs[..])?;
7346 let prev_span = self.prev_span;
7347 let item = self.mk_item(lo.to(prev_span),
7351 maybe_append(attrs, extra_attrs));
7352 return Ok(Some(item));
7354 if let Some(type_) = self.eat_type() {
7355 let (ident, alias, generics) = type_?;
7357 let item_ = match alias {
7358 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7359 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7361 let prev_span = self.prev_span;
7362 let item = self.mk_item(lo.to(prev_span),
7367 return Ok(Some(item));
7369 if self.eat_keyword(kw::Enum) {
7371 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7372 let prev_span = self.prev_span;
7373 let item = self.mk_item(lo.to(prev_span),
7377 maybe_append(attrs, extra_attrs));
7378 return Ok(Some(item));
7380 if self.check_keyword(kw::Trait)
7381 || (self.check_keyword(kw::Auto)
7382 && self.is_keyword_ahead(1, &[kw::Trait]))
7384 let is_auto = if self.eat_keyword(kw::Trait) {
7387 self.expect_keyword(kw::Auto)?;
7388 self.expect_keyword(kw::Trait)?;
7392 let (ident, item_, extra_attrs) =
7393 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7394 let prev_span = self.prev_span;
7395 let item = self.mk_item(lo.to(prev_span),
7399 maybe_append(attrs, extra_attrs));
7400 return Ok(Some(item));
7402 if self.eat_keyword(kw::Struct) {
7404 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7405 let prev_span = self.prev_span;
7406 let item = self.mk_item(lo.to(prev_span),
7410 maybe_append(attrs, extra_attrs));
7411 return Ok(Some(item));
7413 if self.is_union_item() {
7416 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7417 let prev_span = self.prev_span;
7418 let item = self.mk_item(lo.to(prev_span),
7422 maybe_append(attrs, extra_attrs));
7423 return Ok(Some(item));
7425 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7426 return Ok(Some(macro_def));
7429 // Verify whether we have encountered a struct or method definition where the user forgot to
7430 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7431 if visibility.node.is_pub() &&
7432 self.check_ident() &&
7433 self.look_ahead(1, |t| *t != token::Not)
7435 // Space between `pub` keyword and the identifier
7438 // ^^^ `sp` points here
7439 let sp = self.prev_span.between(self.token.span);
7440 let full_sp = self.prev_span.to(self.token.span);
7441 let ident_sp = self.token.span;
7442 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7443 // possible public struct definition where `struct` was forgotten
7444 let ident = self.parse_ident().unwrap();
7445 let msg = format!("add `struct` here to parse `{}` as a public struct",
7447 let mut err = self.diagnostic()
7448 .struct_span_err(sp, "missing `struct` for struct definition");
7449 err.span_suggestion_short(
7450 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7453 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7454 let ident = self.parse_ident().unwrap();
7456 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
7461 self.consume_block(token::Paren);
7462 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7463 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7465 ("fn", kw_name, false)
7466 } else if self.check(&token::OpenDelim(token::Brace)) {
7468 ("fn", kw_name, false)
7469 } else if self.check(&token::Colon) {
7473 ("fn` or `struct", "function or struct", true)
7476 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7477 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7479 self.consume_block(token::Brace);
7480 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7484 err.span_suggestion_short(
7485 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7488 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7489 err.span_suggestion(
7491 "if you meant to call a macro, try",
7492 format!("{}!", snippet),
7493 // this is the `ambiguous` conditional branch
7494 Applicability::MaybeIncorrect
7497 err.help("if you meant to call a macro, remove the `pub` \
7498 and add a trailing `!` after the identifier");
7502 } else if self.look_ahead(1, |t| *t == token::Lt) {
7503 let ident = self.parse_ident().unwrap();
7504 self.eat_to_tokens(&[&token::Gt]);
7506 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7507 if let Ok(Some(_)) = self.parse_self_arg() {
7508 ("fn", "method", false)
7510 ("fn", "function", false)
7512 } else if self.check(&token::OpenDelim(token::Brace)) {
7513 ("struct", "struct", false)
7515 ("fn` or `struct", "function or struct", true)
7517 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7518 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7520 err.span_suggestion_short(
7522 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7523 format!(" {} ", kw),
7524 Applicability::MachineApplicable,
7530 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7533 /// Parses a foreign item.
7534 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7535 maybe_whole!(self, NtForeignItem, |ni| ni);
7537 let attrs = self.parse_outer_attributes()?;
7538 let lo = self.token.span;
7539 let visibility = self.parse_visibility(false)?;
7541 // FOREIGN STATIC ITEM
7542 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7543 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
7544 if self.token.is_keyword(kw::Const) {
7546 .struct_span_err(self.token.span, "extern items cannot be `const`")
7549 "try using a static value",
7550 "static".to_owned(),
7551 Applicability::MachineApplicable
7554 self.bump(); // `static` or `const`
7555 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7557 // FOREIGN FUNCTION ITEM
7558 if self.check_keyword(kw::Fn) {
7559 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7561 // FOREIGN TYPE ITEM
7562 if self.check_keyword(kw::Type) {
7563 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7566 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7570 ident: Ident::invalid(),
7571 span: lo.to(self.prev_span),
7572 id: ast::DUMMY_NODE_ID,
7575 node: ForeignItemKind::Macro(mac),
7580 if !attrs.is_empty() {
7581 self.expected_item_err(&attrs)?;
7589 /// This is the fall-through for parsing items.
7590 fn parse_macro_use_or_failure(
7592 attrs: Vec<Attribute> ,
7593 macros_allowed: bool,
7594 attributes_allowed: bool,
7596 visibility: Visibility
7597 ) -> PResult<'a, Option<P<Item>>> {
7598 if macros_allowed && self.token.is_path_start() &&
7599 !(self.is_async_fn() && self.token.span.rust_2015()) {
7600 // MACRO INVOCATION ITEM
7602 let prev_span = self.prev_span;
7603 self.complain_if_pub_macro(&visibility.node, prev_span);
7605 let mac_lo = self.token.span;
7608 let pth = self.parse_path(PathStyle::Mod)?;
7609 self.expect(&token::Not)?;
7611 // a 'special' identifier (like what `macro_rules!` uses)
7612 // is optional. We should eventually unify invoc syntax
7614 let id = if self.token.is_ident() {
7617 Ident::invalid() // no special identifier
7619 // eat a matched-delimiter token tree:
7620 let (delim, tts) = self.expect_delimited_token_tree()?;
7621 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
7622 self.report_invalid_macro_expansion_item();
7625 let hi = self.prev_span;
7626 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7627 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7628 return Ok(Some(item));
7631 // FAILURE TO PARSE ITEM
7632 match visibility.node {
7633 VisibilityKind::Inherited => {}
7635 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7639 if !attributes_allowed && !attrs.is_empty() {
7640 self.expected_item_err(&attrs)?;
7645 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
7646 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7647 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7649 if self.token.is_path_start() &&
7650 !(self.is_async_fn() && self.token.span.rust_2015()) {
7651 let prev_span = self.prev_span;
7652 let lo = self.token.span;
7653 let pth = self.parse_path(PathStyle::Mod)?;
7655 if pth.segments.len() == 1 {
7656 if !self.eat(&token::Not) {
7657 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7660 self.expect(&token::Not)?;
7663 if let Some(vis) = vis {
7664 self.complain_if_pub_macro(&vis.node, prev_span);
7669 // eat a matched-delimiter token tree:
7670 let (delim, tts) = self.expect_delimited_token_tree()?;
7671 if delim != MacDelimiter::Brace {
7672 self.expect(&token::Semi)?;
7675 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7681 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7682 where F: FnOnce(&mut Self) -> PResult<'a, R>
7684 // Record all tokens we parse when parsing this item.
7685 let mut tokens = Vec::new();
7686 let prev_collecting = match self.token_cursor.frame.last_token {
7687 LastToken::Collecting(ref mut list) => {
7688 Some(mem::replace(list, Vec::new()))
7690 LastToken::Was(ref mut last) => {
7691 tokens.extend(last.take());
7695 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7696 let prev = self.token_cursor.stack.len();
7698 let last_token = if self.token_cursor.stack.len() == prev {
7699 &mut self.token_cursor.frame.last_token
7701 &mut self.token_cursor.stack[prev].last_token
7704 // Pull out the tokens that we've collected from the call to `f` above.
7705 let mut collected_tokens = match *last_token {
7706 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7707 LastToken::Was(_) => panic!("our vector went away?"),
7710 // If we're not at EOF our current token wasn't actually consumed by
7711 // `f`, but it'll still be in our list that we pulled out. In that case
7713 let extra_token = if self.token != token::Eof {
7714 collected_tokens.pop()
7719 // If we were previously collecting tokens, then this was a recursive
7720 // call. In that case we need to record all the tokens we collected in
7721 // our parent list as well. To do that we push a clone of our stream
7722 // onto the previous list.
7723 match prev_collecting {
7725 list.extend(collected_tokens.iter().cloned());
7726 list.extend(extra_token);
7727 *last_token = LastToken::Collecting(list);
7730 *last_token = LastToken::Was(extra_token);
7734 Ok((ret?, TokenStream::new(collected_tokens)))
7737 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7738 let attrs = self.parse_outer_attributes()?;
7739 self.parse_item_(attrs, true, false)
7743 fn is_import_coupler(&mut self) -> bool {
7744 self.check(&token::ModSep) &&
7745 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7746 *t == token::BinOp(token::Star))
7749 /// Parses a `UseTree`.
7752 /// USE_TREE = [`::`] `*` |
7753 /// [`::`] `{` USE_TREE_LIST `}` |
7755 /// PATH `::` `{` USE_TREE_LIST `}` |
7756 /// PATH [`as` IDENT]
7758 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7759 let lo = self.token.span;
7761 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7762 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7763 self.check(&token::BinOp(token::Star)) ||
7764 self.is_import_coupler() {
7765 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7766 let mod_sep_ctxt = self.token.span.ctxt();
7767 if self.eat(&token::ModSep) {
7768 prefix.segments.push(
7769 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7773 if self.eat(&token::BinOp(token::Star)) {
7776 UseTreeKind::Nested(self.parse_use_tree_list()?)
7779 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7780 prefix = self.parse_path(PathStyle::Mod)?;
7782 if self.eat(&token::ModSep) {
7783 if self.eat(&token::BinOp(token::Star)) {
7786 UseTreeKind::Nested(self.parse_use_tree_list()?)
7789 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7793 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7796 /// Parses a `UseTreeKind::Nested(list)`.
7799 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7801 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7802 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7803 &token::CloseDelim(token::Brace),
7804 SeqSep::trailing_allowed(token::Comma), |this| {
7805 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7809 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7810 if self.eat_keyword(kw::As) {
7811 self.parse_ident_or_underscore().map(Some)
7817 /// Parses a source module as a crate. This is the main entry point for the parser.
7818 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7819 let lo = self.token.span;
7820 let krate = Ok(ast::Crate {
7821 attrs: self.parse_inner_attributes()?,
7822 module: self.parse_mod_items(&token::Eof, lo)?,
7823 span: lo.to(self.token.span),
7828 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7829 let ret = match self.token.kind {
7830 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
7831 (symbol, ast::StrStyle::Cooked, suffix),
7832 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
7833 (symbol, ast::StrStyle::Raw(n), suffix),
7840 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7841 match self.parse_optional_str() {
7842 Some((s, style, suf)) => {
7843 let sp = self.prev_span;
7844 self.expect_no_suffix(sp, "a string literal", suf);
7848 let msg = "expected string literal";
7849 let mut err = self.fatal(msg);
7850 err.span_label(self.token.span, msg);
7856 fn report_invalid_macro_expansion_item(&self) {
7857 self.struct_span_err(
7859 "macros that expand to items must be delimited with braces or followed by a semicolon",
7860 ).multipart_suggestion(
7861 "change the delimiters to curly braces",
7863 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
7864 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
7866 Applicability::MaybeIncorrect,
7868 self.sess.source_map.next_point(self.prev_span),
7871 Applicability::MaybeIncorrect,
7876 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
7877 for unmatched in unclosed_delims.iter() {
7878 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
7879 "incorrect close delimiter: `{}`",
7880 pprust::token_to_string(&token::CloseDelim(unmatched.found_delim)),
7882 err.span_label(unmatched.found_span, "incorrect close delimiter");
7883 if let Some(sp) = unmatched.candidate_span {
7884 err.span_label(sp, "close delimiter possibly meant for this");
7886 if let Some(sp) = unmatched.unclosed_span {
7887 err.span_label(sp, "un-closed delimiter");
7891 unclosed_delims.clear();