1 // ignore-tidy-filelength
3 use crate::ast::{AngleBracketedArgs, AsyncArgument, ParenthesizedArgs, AttrStyle, BareFnTy};
4 use crate::ast::{GenericBound, TraitBoundModifier};
5 use crate::ast::Unsafety;
6 use crate::ast::{Mod, AnonConst, Arg, ArgSource, 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, LocalSource};
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, TypeBinding, GenericBounds};
31 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
32 use crate::ast::{UseTree, UseTreeKind};
33 use crate::ast::{BinOpKind, UnOp};
34 use crate::ast::{RangeEnd, RangeSyntax};
35 use crate::{ast, attr};
36 use crate::ext::base::DummyResult;
37 use crate::source_map::{self, SourceMap, Spanned, respan};
38 use crate::parse::{SeqSep, classify, literal, token};
39 use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace};
40 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
41 use crate::parse::token::DelimToken;
42 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
43 use crate::util::parser::{AssocOp, Fixity};
44 use crate::print::pprust;
46 use crate::parse::PResult;
48 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
49 use crate::symbol::{keywords, sym, Symbol};
51 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
52 use rustc_target::spec::abi::{self, Abi};
54 Span, MultiSpan, BytePos, FileName,
55 hygiene::CompilerDesugaringKind,
57 use log::{debug, trace};
62 use std::path::{self, Path, PathBuf};
66 /// Whether the type alias or associated type is a concrete type or an existential type
68 /// Just a new name for the same type
70 /// Only trait impls of the type will be usable, not the actual type itself
71 Existential(GenericBounds),
75 struct Restrictions: u8 {
76 const STMT_EXPR = 1 << 0;
77 const NO_STRUCT_LITERAL = 1 << 1;
81 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
83 /// Specifies how to parse a path.
84 #[derive(Copy, Clone, PartialEq)]
86 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
87 /// with something else. For example, in expressions `segment < ....` can be interpreted
88 /// as a comparison and `segment ( ....` can be interpreted as a function call.
89 /// In all such contexts the non-path interpretation is preferred by default for practical
90 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
91 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
93 /// In other contexts, notably in types, no ambiguity exists and paths can be written
94 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
95 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
97 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
98 /// visibilities or attributes.
99 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
100 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
101 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
102 /// tokens when something goes wrong.
106 #[derive(Clone, Copy, PartialEq, Debug)]
113 #[derive(Clone, Copy, PartialEq, Debug)]
119 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
120 /// dropped into the token stream, which happens while parsing the result of
121 /// macro expansion). Placement of these is not as complex as I feared it would
122 /// be. The important thing is to make sure that lookahead doesn't balk at
123 /// `token::Interpolated` tokens.
124 macro_rules! maybe_whole_expr {
126 if let token::Interpolated(nt) = &$p.token {
128 token::NtExpr(e) | token::NtLiteral(e) => {
133 token::NtPath(path) => {
134 let path = path.clone();
136 return Ok($p.mk_expr($p.span, ExprKind::Path(None, path), ThinVec::new()));
138 token::NtBlock(block) => {
139 let block = block.clone();
141 return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
149 /// As maybe_whole_expr, but for things other than expressions
150 macro_rules! maybe_whole {
151 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
152 if let token::Interpolated(nt) = &$p.token {
153 if let token::$constructor(x) = &**nt {
162 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
163 macro_rules! maybe_recover_from_interpolated_ty_qpath {
164 ($self: expr, $allow_qpath_recovery: expr) => {
165 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
166 if let token::Interpolated(nt) = &$self.token {
167 if let token::NtTy(ty) = &**nt {
170 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
177 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
178 if let Some(ref mut rhs) = rhs {
184 #[derive(Debug, Clone, Copy, PartialEq)]
196 /* ident is handled by common.rs */
199 pub struct Parser<'a> {
200 pub sess: &'a ParseSess,
201 /// the current token:
202 pub token: token::Token,
203 /// the span of the current token:
205 /// the span of the previous token:
206 meta_var_span: Option<Span>,
208 /// the previous token kind
209 prev_token_kind: PrevTokenKind,
210 restrictions: Restrictions,
211 /// Used to determine the path to externally loaded source files
212 crate directory: Directory<'a>,
213 /// Whether to parse sub-modules in other files.
214 pub recurse_into_file_modules: bool,
215 /// Name of the root module this parser originated from. If `None`, then the
216 /// name is not known. This does not change while the parser is descending
217 /// into modules, and sub-parsers have new values for this name.
218 pub root_module_name: Option<String>,
219 crate expected_tokens: Vec<TokenType>,
220 token_cursor: TokenCursor,
221 desugar_doc_comments: bool,
222 /// Whether we should configure out of line modules as we parse.
224 /// This field is used to keep track of how many left angle brackets we have seen. This is
225 /// required in order to detect extra leading left angle brackets (`<` characters) and error
228 /// See the comments in the `parse_path_segment` function for more details.
229 crate unmatched_angle_bracket_count: u32,
230 crate max_angle_bracket_count: u32,
231 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
232 /// it gets removed from here. Every entry left at the end gets emitted as an independent
234 crate unclosed_delims: Vec<UnmatchedBrace>,
235 last_unexpected_token_span: Option<Span>,
238 impl<'a> Drop for Parser<'a> {
240 let diag = self.diagnostic();
241 emit_unclosed_delims(&mut self.unclosed_delims, diag);
247 frame: TokenCursorFrame,
248 stack: Vec<TokenCursorFrame>,
252 struct TokenCursorFrame {
253 delim: token::DelimToken,
256 tree_cursor: tokenstream::Cursor,
258 last_token: LastToken,
261 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
262 /// by the parser, and then that's transitively used to record the tokens that
263 /// each parse AST item is created with.
265 /// Right now this has two states, either collecting tokens or not collecting
266 /// tokens. If we're collecting tokens we just save everything off into a local
267 /// `Vec`. This should eventually though likely save tokens from the original
268 /// token stream and just use slicing of token streams to avoid creation of a
269 /// whole new vector.
271 /// The second state is where we're passively not recording tokens, but the last
272 /// token is still tracked for when we want to start recording tokens. This
273 /// "last token" means that when we start recording tokens we'll want to ensure
274 /// that this, the first token, is included in the output.
276 /// You can find some more example usage of this in the `collect_tokens` method
280 Collecting(Vec<TreeAndJoint>),
281 Was(Option<TreeAndJoint>),
284 impl TokenCursorFrame {
285 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
289 open_delim: delim == token::NoDelim,
290 tree_cursor: tts.clone().into_trees(),
291 close_delim: delim == token::NoDelim,
292 last_token: LastToken::Was(None),
298 fn next(&mut self) -> TokenAndSpan {
300 let tree = if !self.frame.open_delim {
301 self.frame.open_delim = true;
302 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
303 } else if let Some(tree) = self.frame.tree_cursor.next() {
305 } else if !self.frame.close_delim {
306 self.frame.close_delim = true;
307 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
308 } else if let Some(frame) = self.stack.pop() {
312 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
315 match self.frame.last_token {
316 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
317 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
321 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
322 TokenTree::Delimited(sp, delim, tts) => {
323 let frame = TokenCursorFrame::new(sp, delim, &tts);
324 self.stack.push(mem::replace(&mut self.frame, frame));
330 fn next_desugared(&mut self) -> TokenAndSpan {
331 let (sp, name) = match self.next() {
332 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
336 let stripped = strip_doc_comment_decoration(&name.as_str());
338 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
339 // required to wrap the text.
340 let mut num_of_hashes = 0;
342 for ch in stripped.chars() {
345 '#' if count > 0 => count + 1,
348 num_of_hashes = cmp::max(num_of_hashes, count);
351 let delim_span = DelimSpan::from_single(sp);
352 let body = TokenTree::Delimited(
355 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
356 TokenTree::Token(sp, token::Eq),
357 TokenTree::Token(sp, token::Literal(
358 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
360 .iter().cloned().collect::<TokenStream>().into(),
363 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
366 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
367 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
368 .iter().cloned().collect::<TokenStream>().into()
370 [TokenTree::Token(sp, token::Pound), body]
371 .iter().cloned().collect::<TokenStream>().into()
379 #[derive(Clone, PartialEq)]
380 crate enum TokenType {
382 Keyword(keywords::Keyword),
392 fn to_string(&self) -> String {
394 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
395 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
396 TokenType::Operator => "an operator".to_string(),
397 TokenType::Lifetime => "lifetime".to_string(),
398 TokenType::Ident => "identifier".to_string(),
399 TokenType::Path => "path".to_string(),
400 TokenType::Type => "type".to_string(),
401 TokenType::Const => "const".to_string(),
406 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
407 /// `IDENT<<u8 as Trait>::AssocTy>`.
409 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
410 /// that `IDENT` is not the ident of a fn trait.
411 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
412 t == &token::ModSep || t == &token::Lt ||
413 t == &token::BinOp(token::Shl)
416 /// Information about the path to a module.
417 pub struct ModulePath {
420 pub result: Result<ModulePathSuccess, Error>,
423 pub struct ModulePathSuccess {
425 pub directory_ownership: DirectoryOwnership,
430 FileNotFoundForModule {
432 default_path: String,
433 secondary_path: String,
438 default_path: String,
439 secondary_path: String,
442 InclusiveRangeWithNoEnd,
446 fn span_err<S: Into<MultiSpan>>(self,
448 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
450 Error::FileNotFoundForModule { ref mod_name,
454 let mut err = struct_span_err!(handler, sp, E0583,
455 "file not found for module `{}`", mod_name);
456 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
462 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
463 let mut err = struct_span_err!(handler, sp, E0584,
464 "file for module `{}` found at both {} and {}",
468 err.help("delete or rename one of them to remove the ambiguity");
471 Error::UselessDocComment => {
472 let mut err = struct_span_err!(handler, sp, E0585,
473 "found a documentation comment that doesn't document anything");
474 err.help("doc comments must come before what they document, maybe a comment was \
475 intended with `//`?");
478 Error::InclusiveRangeWithNoEnd => {
479 let mut err = struct_span_err!(handler, sp, E0586,
480 "inclusive range with no end");
481 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
491 AttributesParsed(ThinVec<Attribute>),
492 AlreadyParsed(P<Expr>),
495 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
496 fn from(o: Option<ThinVec<Attribute>>) -> Self {
497 if let Some(attrs) = o {
498 LhsExpr::AttributesParsed(attrs)
500 LhsExpr::NotYetParsed
505 impl From<P<Expr>> for LhsExpr {
506 fn from(expr: P<Expr>) -> Self {
507 LhsExpr::AlreadyParsed(expr)
511 /// Creates a placeholder argument.
512 fn dummy_arg(span: Span) -> Arg {
513 let ident = Ident::new(keywords::Invalid.name(), span);
515 id: ast::DUMMY_NODE_ID,
516 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
522 id: ast::DUMMY_NODE_ID
524 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal }
527 #[derive(Copy, Clone, Debug)]
528 enum TokenExpectType {
533 impl<'a> Parser<'a> {
534 pub fn new(sess: &'a ParseSess,
536 directory: Option<Directory<'a>>,
537 recurse_into_file_modules: bool,
538 desugar_doc_comments: bool)
540 let mut parser = Parser {
542 token: token::Whitespace,
543 span: syntax_pos::DUMMY_SP,
544 prev_span: syntax_pos::DUMMY_SP,
546 prev_token_kind: PrevTokenKind::Other,
547 restrictions: Restrictions::empty(),
548 recurse_into_file_modules,
549 directory: Directory {
550 path: Cow::from(PathBuf::new()),
551 ownership: DirectoryOwnership::Owned { relative: None }
553 root_module_name: None,
554 expected_tokens: Vec::new(),
555 token_cursor: TokenCursor {
556 frame: TokenCursorFrame::new(
563 desugar_doc_comments,
565 unmatched_angle_bracket_count: 0,
566 max_angle_bracket_count: 0,
567 unclosed_delims: Vec::new(),
568 last_unexpected_token_span: None,
571 let tok = parser.next_tok();
572 parser.token = tok.tok;
573 parser.span = tok.sp;
575 if let Some(directory) = directory {
576 parser.directory = directory;
577 } else if !parser.span.is_dummy() {
578 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
580 parser.directory.path = Cow::from(path);
584 parser.process_potential_macro_variable();
588 fn next_tok(&mut self) -> TokenAndSpan {
589 let mut next = if self.desugar_doc_comments {
590 self.token_cursor.next_desugared()
592 self.token_cursor.next()
594 if next.sp.is_dummy() {
595 // Tweak the location for better diagnostics, but keep syntactic context intact.
596 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
601 /// Converts the current token to a string using `self`'s reader.
602 pub fn this_token_to_string(&self) -> String {
603 pprust::token_to_string(&self.token)
606 fn token_descr(&self) -> Option<&'static str> {
607 Some(match &self.token {
608 t if t.is_special_ident() => "reserved identifier",
609 t if t.is_used_keyword() => "keyword",
610 t if t.is_unused_keyword() => "reserved keyword",
611 token::DocComment(..) => "doc comment",
616 crate fn this_token_descr(&self) -> String {
617 if let Some(prefix) = self.token_descr() {
618 format!("{} `{}`", prefix, self.this_token_to_string())
620 format!("`{}`", self.this_token_to_string())
624 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
625 match self.expect_one_of(&[], &[]) {
627 Ok(_) => unreachable!(),
631 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
632 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
633 if self.expected_tokens.is_empty() {
634 if self.token == *t {
638 let token_str = pprust::token_to_string(t);
639 let this_token_str = self.this_token_descr();
640 let mut err = self.fatal(&format!("expected `{}`, found {}",
644 let sp = if self.token == token::Token::Eof {
645 // EOF, don't want to point at the following char, but rather the last token
648 self.sess.source_map().next_point(self.prev_span)
650 let label_exp = format!("expected `{}`", token_str);
651 match self.recover_closing_delimiter(&[t.clone()], err) {
654 return Ok(recovered);
657 let cm = self.sess.source_map();
658 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
659 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
660 // When the spans are in the same line, it means that the only content
661 // between them is whitespace, point only at the found token.
662 err.span_label(self.span, label_exp);
665 err.span_label(sp, label_exp);
666 err.span_label(self.span, "unexpected token");
672 self.expect_one_of(slice::from_ref(t), &[])
676 fn recover_closing_delimiter(
678 tokens: &[token::Token],
679 mut err: DiagnosticBuilder<'a>,
680 ) -> PResult<'a, bool> {
682 // we want to use the last closing delim that would apply
683 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
684 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
685 && Some(self.span) > unmatched.unclosed_span
692 // Recover and assume that the detected unclosed delimiter was meant for
693 // this location. Emit the diagnostic and act as if the delimiter was
694 // present for the parser's sake.
696 // Don't attempt to recover from this unclosed delimiter more than once.
697 let unmatched = self.unclosed_delims.remove(pos);
698 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
700 // We want to suggest the inclusion of the closing delimiter where it makes
701 // the most sense, which is immediately after the last token:
706 // | help: `)` may belong here (FIXME: #58270)
708 // unclosed delimiter
709 if let Some(sp) = unmatched.unclosed_span {
710 err.span_label(sp, "unclosed delimiter");
712 err.span_suggestion_short(
713 self.sess.source_map().next_point(self.prev_span),
714 &format!("{} may belong here", delim.to_string()),
716 Applicability::MaybeIncorrect,
719 self.expected_tokens.clear(); // reduce errors
726 /// Expect next token to be edible or inedible token. If edible,
727 /// then consume it; if inedible, then return without consuming
728 /// anything. Signal a fatal error if next token is unexpected.
729 pub fn expect_one_of(
731 edible: &[token::Token],
732 inedible: &[token::Token],
733 ) -> PResult<'a, bool /* recovered */> {
734 fn tokens_to_string(tokens: &[TokenType]) -> String {
735 let mut i = tokens.iter();
736 // This might be a sign we need a connect method on Iterator.
738 .map_or(String::new(), |t| t.to_string());
739 i.enumerate().fold(b, |mut b, (i, a)| {
740 if tokens.len() > 2 && i == tokens.len() - 2 {
742 } else if tokens.len() == 2 && i == tokens.len() - 2 {
747 b.push_str(&a.to_string());
751 if edible.contains(&self.token) {
754 } else if inedible.contains(&self.token) {
755 // leave it in the input
757 } else if self.last_unexpected_token_span == Some(self.span) {
760 let mut expected = edible.iter()
761 .map(|x| TokenType::Token(x.clone()))
762 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
763 .chain(self.expected_tokens.iter().cloned())
764 .collect::<Vec<_>>();
765 expected.sort_by_cached_key(|x| x.to_string());
767 let expect = tokens_to_string(&expected[..]);
768 let actual = self.this_token_to_string();
769 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
770 let short_expect = if expected.len() > 6 {
771 format!("{} possible tokens", expected.len())
775 (format!("expected one of {}, found `{}`", expect, actual),
776 (self.sess.source_map().next_point(self.prev_span),
777 format!("expected one of {} here", short_expect)))
778 } else if expected.is_empty() {
779 (format!("unexpected token: `{}`", actual),
780 (self.prev_span, "unexpected token after this".to_string()))
782 (format!("expected {}, found `{}`", expect, actual),
783 (self.sess.source_map().next_point(self.prev_span),
784 format!("expected {} here", expect)))
786 self.last_unexpected_token_span = Some(self.span);
787 let mut err = self.fatal(&msg_exp);
788 if self.token.is_ident_named("and") {
789 err.span_suggestion_short(
791 "use `&&` instead of `and` for the boolean operator",
793 Applicability::MaybeIncorrect,
796 if self.token.is_ident_named("or") {
797 err.span_suggestion_short(
799 "use `||` instead of `or` for the boolean operator",
801 Applicability::MaybeIncorrect,
804 let sp = if self.token == token::Token::Eof {
805 // This is EOF, don't want to point at the following char, but rather the last token
810 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
811 TokenType::Token(t) => Some(t.clone()),
813 }).collect::<Vec<_>>(), err) {
816 return Ok(recovered);
820 let is_semi_suggestable = expected.iter().any(|t| match t {
821 TokenType::Token(token::Semi) => true, // we expect a `;` here
823 }) && ( // a `;` would be expected before the current keyword
824 self.token.is_keyword(keywords::Break) ||
825 self.token.is_keyword(keywords::Continue) ||
826 self.token.is_keyword(keywords::For) ||
827 self.token.is_keyword(keywords::If) ||
828 self.token.is_keyword(keywords::Let) ||
829 self.token.is_keyword(keywords::Loop) ||
830 self.token.is_keyword(keywords::Match) ||
831 self.token.is_keyword(keywords::Return) ||
832 self.token.is_keyword(keywords::While)
834 let cm = self.sess.source_map();
835 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
836 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
837 // The spans are in different lines, expected `;` and found `let` or `return`.
838 // High likelihood that it is only a missing `;`.
839 err.span_suggestion_short(
841 "a semicolon may be missing here",
843 Applicability::MaybeIncorrect,
848 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
849 // When the spans are in the same line, it means that the only content between
850 // them is whitespace, point at the found token in that case:
852 // X | () => { syntax error };
853 // | ^^^^^ expected one of 8 possible tokens here
855 // instead of having:
857 // X | () => { syntax error };
858 // | -^^^^^ unexpected token
860 // | expected one of 8 possible tokens here
861 err.span_label(self.span, label_exp);
863 _ if self.prev_span == syntax_pos::DUMMY_SP => {
864 // Account for macro context where the previous span might not be
865 // available to avoid incorrect output (#54841).
866 err.span_label(self.span, "unexpected token");
869 err.span_label(sp, label_exp);
870 err.span_label(self.span, "unexpected token");
877 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
878 fn interpolated_or_expr_span(&self,
879 expr: PResult<'a, P<Expr>>)
880 -> PResult<'a, (Span, P<Expr>)> {
882 if self.prev_token_kind == PrevTokenKind::Interpolated {
890 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
891 let mut err = self.struct_span_err(self.span,
892 &format!("expected identifier, found {}",
893 self.this_token_descr()));
894 if let token::Ident(ident, false) = &self.token {
895 if ident.is_raw_guess() {
898 "you can escape reserved keywords to use them as identifiers",
899 format!("r#{}", ident),
900 Applicability::MaybeIncorrect,
904 if let Some(token_descr) = self.token_descr() {
905 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
907 err.span_label(self.span, "expected identifier");
908 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
913 Applicability::MachineApplicable,
920 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
921 self.parse_ident_common(true)
924 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
926 token::Ident(ident, _) => {
927 if self.token.is_reserved_ident() {
928 let mut err = self.expected_ident_found();
935 let span = self.span;
937 Ok(Ident::new(ident.name, span))
940 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
941 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
943 self.expected_ident_found()
949 /// Checks if the next token is `tok`, and returns `true` if so.
951 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
953 crate fn check(&mut self, tok: &token::Token) -> bool {
954 let is_present = self.token == *tok;
955 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
959 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
960 pub fn eat(&mut self, tok: &token::Token) -> bool {
961 let is_present = self.check(tok);
962 if is_present { self.bump() }
966 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
967 self.expected_tokens.push(TokenType::Keyword(kw));
968 self.token.is_keyword(kw)
971 /// If the next token is the given keyword, eats it and returns
972 /// `true`. Otherwise, returns `false`.
973 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
974 if self.check_keyword(kw) {
982 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
983 if self.token.is_keyword(kw) {
991 /// If the given word is not a keyword, signals an error.
992 /// If the next token is not the given word, signals an error.
993 /// Otherwise, eats it.
994 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
995 if !self.eat_keyword(kw) {
1002 fn check_ident(&mut self) -> bool {
1003 if self.token.is_ident() {
1006 self.expected_tokens.push(TokenType::Ident);
1011 fn check_path(&mut self) -> bool {
1012 if self.token.is_path_start() {
1015 self.expected_tokens.push(TokenType::Path);
1020 fn check_type(&mut self) -> bool {
1021 if self.token.can_begin_type() {
1024 self.expected_tokens.push(TokenType::Type);
1029 fn check_const_arg(&mut self) -> bool {
1030 if self.token.can_begin_const_arg() {
1033 self.expected_tokens.push(TokenType::Const);
1038 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
1039 /// and continues. If a `+` is not seen, returns `false`.
1041 /// This is used when token-splitting `+=` into `+`.
1042 /// See issue #47856 for an example of when this may occur.
1043 fn eat_plus(&mut self) -> bool {
1044 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1046 token::BinOp(token::Plus) => {
1050 token::BinOpEq(token::Plus) => {
1051 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1052 self.bump_with(token::Eq, span);
1060 /// Checks to see if the next token is either `+` or `+=`.
1061 /// Otherwise returns `false`.
1062 fn check_plus(&mut self) -> bool {
1063 if self.token.is_like_plus() {
1067 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1072 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1073 /// `&` and continues. If an `&` is not seen, signals an error.
1074 fn expect_and(&mut self) -> PResult<'a, ()> {
1075 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1077 token::BinOp(token::And) => {
1082 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1083 Ok(self.bump_with(token::BinOp(token::And), span))
1085 _ => self.unexpected()
1089 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1090 /// `|` and continues. If an `|` is not seen, signals an error.
1091 fn expect_or(&mut self) -> PResult<'a, ()> {
1092 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1094 token::BinOp(token::Or) => {
1099 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1100 Ok(self.bump_with(token::BinOp(token::Or), span))
1102 _ => self.unexpected()
1106 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1107 literal::expect_no_suffix(sp, &self.sess.span_diagnostic, kind, suffix)
1110 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1111 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1112 /// and continue. If a `<` is not seen, returns false.
1114 /// This is meant to be used when parsing generics on a path to get the
1116 fn eat_lt(&mut self) -> bool {
1117 self.expected_tokens.push(TokenType::Token(token::Lt));
1118 let ate = match self.token {
1123 token::BinOp(token::Shl) => {
1124 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1125 self.bump_with(token::Lt, span);
1129 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1130 self.bump_with(token::BinOp(token::Minus), span);
1137 // See doc comment for `unmatched_angle_bracket_count`.
1138 self.unmatched_angle_bracket_count += 1;
1139 self.max_angle_bracket_count += 1;
1140 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1146 fn expect_lt(&mut self) -> PResult<'a, ()> {
1154 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1155 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1156 fn expect_gt(&mut self) -> PResult<'a, ()> {
1157 self.expected_tokens.push(TokenType::Token(token::Gt));
1158 let ate = match self.token {
1163 token::BinOp(token::Shr) => {
1164 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1165 Some(self.bump_with(token::Gt, span))
1167 token::BinOpEq(token::Shr) => {
1168 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1169 Some(self.bump_with(token::Ge, span))
1172 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1173 Some(self.bump_with(token::Eq, span))
1180 // See doc comment for `unmatched_angle_bracket_count`.
1181 if self.unmatched_angle_bracket_count > 0 {
1182 self.unmatched_angle_bracket_count -= 1;
1183 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1188 None => self.unexpected(),
1192 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1193 /// passes through any errors encountered. Used for error recovery.
1194 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1195 let handler = self.diagnostic();
1197 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1199 TokenExpectType::Expect,
1200 |p| Ok(p.parse_token_tree())) {
1201 handler.cancel(err);
1205 /// Parses a sequence, including the closing delimiter. The function
1206 /// `f` must consume tokens until reaching the next separator or
1207 /// closing bracket.
1208 pub fn parse_seq_to_end<T, F>(&mut self,
1212 -> PResult<'a, Vec<T>> where
1213 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1215 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1222 /// Parses a sequence, not including the closing delimiter. The function
1223 /// `f` must consume tokens until reaching the next separator or
1224 /// closing bracket.
1225 pub fn parse_seq_to_before_end<T, F>(
1230 ) -> PResult<'a, (Vec<T>, bool)>
1231 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1233 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1236 fn parse_seq_to_before_tokens<T, F>(
1238 kets: &[&token::Token],
1240 expect: TokenExpectType,
1242 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1243 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1245 let mut first = true;
1246 let mut recovered = false;
1248 while !kets.iter().any(|k| {
1250 TokenExpectType::Expect => self.check(k),
1251 TokenExpectType::NoExpect => self.token == **k,
1255 token::CloseDelim(..) | token::Eof => break,
1258 if let Some(ref t) = sep.sep {
1262 match self.expect(t) {
1269 // Attempt to keep parsing if it was a similar separator
1270 if let Some(ref tokens) = t.similar_tokens() {
1271 if tokens.contains(&self.token) {
1276 // Attempt to keep parsing if it was an omitted separator
1291 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1293 TokenExpectType::Expect => self.check(k),
1294 TokenExpectType::NoExpect => self.token == **k,
1307 /// Parses a sequence, including the closing delimiter. The function
1308 /// `f` must consume tokens until reaching the next separator or
1309 /// closing bracket.
1310 fn parse_unspanned_seq<T, F>(
1316 ) -> PResult<'a, Vec<T>> where
1317 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1320 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1327 /// Advance the parser by one token
1328 pub fn bump(&mut self) {
1329 if self.prev_token_kind == PrevTokenKind::Eof {
1330 // Bumping after EOF is a bad sign, usually an infinite loop.
1331 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1334 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1336 // Record last token kind for possible error recovery.
1337 self.prev_token_kind = match self.token {
1338 token::DocComment(..) => PrevTokenKind::DocComment,
1339 token::Comma => PrevTokenKind::Comma,
1340 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1341 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1342 token::Interpolated(..) => PrevTokenKind::Interpolated,
1343 token::Eof => PrevTokenKind::Eof,
1344 token::Ident(..) => PrevTokenKind::Ident,
1345 _ => PrevTokenKind::Other,
1348 let next = self.next_tok();
1349 self.span = next.sp;
1350 self.token = next.tok;
1351 self.expected_tokens.clear();
1352 // check after each token
1353 self.process_potential_macro_variable();
1356 /// Advance the parser using provided token as a next one. Use this when
1357 /// consuming a part of a token. For example a single `<` from `<<`.
1358 fn bump_with(&mut self, next: token::Token, span: Span) {
1359 self.prev_span = self.span.with_hi(span.lo());
1360 // It would be incorrect to record the kind of the current token, but
1361 // fortunately for tokens currently using `bump_with`, the
1362 // prev_token_kind will be of no use anyway.
1363 self.prev_token_kind = PrevTokenKind::Other;
1366 self.expected_tokens.clear();
1369 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1370 F: FnOnce(&token::Token) -> R,
1373 return f(&self.token)
1376 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1377 Some(tree) => match tree {
1378 TokenTree::Token(_, tok) => tok,
1379 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1381 None => token::CloseDelim(self.token_cursor.frame.delim),
1385 crate fn look_ahead_span(&self, dist: usize) -> Span {
1390 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1391 Some(TokenTree::Token(span, _)) => span,
1392 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1393 None => self.look_ahead_span(dist - 1),
1396 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1397 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1399 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1400 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1402 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1403 err.span_err(sp, self.diagnostic())
1405 fn bug(&self, m: &str) -> ! {
1406 self.sess.span_diagnostic.span_bug(self.span, m)
1408 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1409 self.sess.span_diagnostic.span_err(sp, m)
1411 crate fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1412 self.sess.span_diagnostic.struct_span_err(sp, m)
1414 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1415 self.sess.span_diagnostic.span_bug(sp, m)
1418 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1419 self.sess.span_diagnostic.cancel(err)
1422 crate fn diagnostic(&self) -> &'a errors::Handler {
1423 &self.sess.span_diagnostic
1426 /// Is the current token one of the keywords that signals a bare function type?
1427 fn token_is_bare_fn_keyword(&mut self) -> bool {
1428 self.check_keyword(keywords::Fn) ||
1429 self.check_keyword(keywords::Unsafe) ||
1430 self.check_keyword(keywords::Extern)
1433 /// Parses a `TyKind::BareFn` type.
1434 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1437 [unsafe] [extern "ABI"] fn (S) -> T
1447 let unsafety = self.parse_unsafety();
1448 let abi = if self.eat_keyword(keywords::Extern) {
1449 self.parse_opt_abi()?.unwrap_or(Abi::C)
1454 self.expect_keyword(keywords::Fn)?;
1455 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1456 let ret_ty = self.parse_ret_ty(false)?;
1457 let decl = P(FnDecl {
1462 Ok(TyKind::BareFn(P(BareFnTy {
1470 /// Parses asyncness: `async` or nothing.
1471 fn parse_asyncness(&mut self) -> IsAsync {
1472 if self.eat_keyword(keywords::Async) {
1474 closure_id: ast::DUMMY_NODE_ID,
1475 return_impl_trait_id: ast::DUMMY_NODE_ID,
1476 arguments: Vec::new(),
1483 /// Parses unsafety: `unsafe` or nothing.
1484 fn parse_unsafety(&mut self) -> Unsafety {
1485 if self.eat_keyword(keywords::Unsafe) {
1492 /// Parses the items in a trait declaration.
1493 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1494 maybe_whole!(self, NtTraitItem, |x| x);
1495 let attrs = self.parse_outer_attributes()?;
1496 let mut unclosed_delims = vec![];
1497 let (mut item, tokens) = self.collect_tokens(|this| {
1498 let item = this.parse_trait_item_(at_end, attrs);
1499 unclosed_delims.append(&mut this.unclosed_delims);
1502 self.unclosed_delims.append(&mut unclosed_delims);
1503 // See `parse_item` for why this clause is here.
1504 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1505 item.tokens = Some(tokens);
1510 fn parse_trait_item_(&mut self,
1512 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1515 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1516 self.parse_trait_item_assoc_ty()?
1517 } else if self.is_const_item() {
1518 self.expect_keyword(keywords::Const)?;
1519 let ident = self.parse_ident()?;
1520 self.expect(&token::Colon)?;
1521 let ty = self.parse_ty()?;
1522 let default = if self.eat(&token::Eq) {
1523 let expr = self.parse_expr()?;
1524 self.expect(&token::Semi)?;
1527 self.expect(&token::Semi)?;
1530 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1531 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1532 // trait item macro.
1533 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1535 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
1537 let ident = self.parse_ident()?;
1538 let mut generics = self.parse_generics()?;
1540 let mut decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1541 // This is somewhat dubious; We don't want to allow
1542 // argument names to be left off if there is a
1545 // We don't allow argument names to be left off in edition 2018.
1546 p.parse_arg_general(p.span.rust_2018(), true, false)
1548 generics.where_clause = self.parse_where_clause()?;
1549 self.construct_async_arguments(&mut asyncness, &mut decl);
1551 let sig = ast::MethodSig {
1561 let body = match self.token {
1565 debug!("parse_trait_methods(): parsing required method");
1568 token::OpenDelim(token::Brace) => {
1569 debug!("parse_trait_methods(): parsing provided method");
1571 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1572 attrs.extend(inner_attrs.iter().cloned());
1575 token::Interpolated(ref nt) => {
1577 token::NtBlock(..) => {
1579 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1580 attrs.extend(inner_attrs.iter().cloned());
1584 let token_str = self.this_token_descr();
1585 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1587 err.span_label(self.span, "expected `;` or `{`");
1593 let token_str = self.this_token_descr();
1594 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1596 err.span_label(self.span, "expected `;` or `{`");
1600 (ident, ast::TraitItemKind::Method(sig, body), generics)
1604 id: ast::DUMMY_NODE_ID,
1609 span: lo.to(self.prev_span),
1614 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1615 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1616 if self.eat(&token::RArrow) {
1617 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1619 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1624 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1625 self.parse_ty_common(true, true, false)
1628 /// Parses a type in restricted contexts where `+` is not permitted.
1630 /// Example 1: `&'a TYPE`
1631 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1632 /// Example 2: `value1 as TYPE + value2`
1633 /// `+` is prohibited to avoid interactions with expression grammar.
1634 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1635 self.parse_ty_common(false, true, false)
1638 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1639 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1640 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1641 maybe_whole!(self, NtTy, |x| x);
1644 let mut impl_dyn_multi = false;
1645 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1646 // `(TYPE)` is a parenthesized type.
1647 // `(TYPE,)` is a tuple with a single field of type TYPE.
1648 let mut ts = vec![];
1649 let mut last_comma = false;
1650 while self.token != token::CloseDelim(token::Paren) {
1651 ts.push(self.parse_ty()?);
1652 if self.eat(&token::Comma) {
1659 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1660 self.expect(&token::CloseDelim(token::Paren))?;
1662 if ts.len() == 1 && !last_comma {
1663 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1664 let maybe_bounds = allow_plus && self.token.is_like_plus();
1666 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1667 TyKind::Path(None, ref path) if maybe_bounds => {
1668 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1670 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1671 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1672 let path = match bounds[0] {
1673 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1674 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1676 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1679 _ => TyKind::Paren(P(ty))
1684 } else if self.eat(&token::Not) {
1687 } else if self.eat(&token::BinOp(token::Star)) {
1689 TyKind::Ptr(self.parse_ptr()?)
1690 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1692 let t = self.parse_ty()?;
1693 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1694 let t = match self.maybe_parse_fixed_length_of_vec()? {
1695 None => TyKind::Slice(t),
1696 Some(length) => TyKind::Array(t, AnonConst {
1697 id: ast::DUMMY_NODE_ID,
1701 self.expect(&token::CloseDelim(token::Bracket))?;
1703 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1706 self.parse_borrowed_pointee()?
1707 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1709 // In order to not be ambiguous, the type must be surrounded by parens.
1710 self.expect(&token::OpenDelim(token::Paren))?;
1712 id: ast::DUMMY_NODE_ID,
1713 value: self.parse_expr()?,
1715 self.expect(&token::CloseDelim(token::Paren))?;
1717 } else if self.eat_keyword(keywords::Underscore) {
1718 // A type to be inferred `_`
1720 } else if self.token_is_bare_fn_keyword() {
1721 // Function pointer type
1722 self.parse_ty_bare_fn(Vec::new())?
1723 } else if self.check_keyword(keywords::For) {
1724 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1725 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1726 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1728 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1729 if self.token_is_bare_fn_keyword() {
1730 self.parse_ty_bare_fn(lifetime_defs)?
1732 let path = self.parse_path(PathStyle::Type)?;
1733 let parse_plus = allow_plus && self.check_plus();
1734 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1736 } else if self.eat_keyword(keywords::Impl) {
1737 // Always parse bounds greedily for better error recovery.
1738 let bounds = self.parse_generic_bounds(None)?;
1739 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1740 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1741 } else if self.check_keyword(keywords::Dyn) &&
1742 (self.span.rust_2018() ||
1743 self.look_ahead(1, |t| t.can_begin_bound() &&
1744 !can_continue_type_after_non_fn_ident(t))) {
1745 self.bump(); // `dyn`
1746 // Always parse bounds greedily for better error recovery.
1747 let bounds = self.parse_generic_bounds(None)?;
1748 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1749 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1750 } else if self.check(&token::Question) ||
1751 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1752 // Bound list (trait object type)
1753 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1754 TraitObjectSyntax::None)
1755 } else if self.eat_lt() {
1757 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1758 TyKind::Path(Some(qself), path)
1759 } else if self.token.is_path_start() {
1761 let path = self.parse_path(PathStyle::Type)?;
1762 if self.eat(&token::Not) {
1763 // Macro invocation in type position
1764 let (delim, tts) = self.expect_delimited_token_tree()?;
1765 let node = Mac_ { path, tts, delim };
1766 TyKind::Mac(respan(lo.to(self.prev_span), node))
1768 // Just a type path or bound list (trait object type) starting with a trait.
1770 // `Trait1 + Trait2 + 'a`
1771 if allow_plus && self.check_plus() {
1772 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1774 TyKind::Path(None, path)
1777 } else if self.check(&token::DotDotDot) {
1778 if allow_c_variadic {
1779 self.eat(&token::DotDotDot);
1782 return Err(self.fatal(
1783 "only foreign functions are allowed to be C-variadic"
1787 let msg = format!("expected type, found {}", self.this_token_descr());
1788 return Err(self.fatal(&msg));
1791 let span = lo.to(self.prev_span);
1792 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1794 // Try to recover from use of `+` with incorrect priority.
1795 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1796 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1797 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1800 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1801 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1802 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1803 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1805 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1806 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1808 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1811 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1812 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1813 let mutbl = self.parse_mutability();
1814 let ty = self.parse_ty_no_plus()?;
1815 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1818 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1819 let mutbl = if self.eat_keyword(keywords::Mut) {
1821 } else if self.eat_keyword(keywords::Const) {
1822 Mutability::Immutable
1824 let span = self.prev_span;
1825 let msg = "expected mut or const in raw pointer type";
1826 self.struct_span_err(span, msg)
1827 .span_label(span, msg)
1828 .help("use `*mut T` or `*const T` as appropriate")
1830 Mutability::Immutable
1832 let t = self.parse_ty_no_plus()?;
1833 Ok(MutTy { ty: t, mutbl: mutbl })
1836 fn is_named_argument(&self) -> bool {
1837 let offset = match self.token {
1838 token::Interpolated(ref nt) => match **nt {
1839 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1842 token::BinOp(token::And) | token::AndAnd => 1,
1843 _ if self.token.is_keyword(keywords::Mut) => 1,
1847 self.look_ahead(offset, |t| t.is_ident()) &&
1848 self.look_ahead(offset + 1, |t| t == &token::Colon)
1851 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1853 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1854 if let token::DocComment(_) = self.token {
1855 let mut err = self.diagnostic().struct_span_err(
1857 &format!("documentation comments cannot be applied to {}", applied_to),
1859 err.span_label(self.span, "doc comments are not allowed here");
1862 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1863 *t == token::OpenDelim(token::Bracket)
1866 // Skip every token until next possible arg.
1867 while self.token != token::CloseDelim(token::Bracket) {
1870 let sp = lo.to(self.span);
1872 let mut err = self.diagnostic().struct_span_err(
1874 &format!("attributes cannot be applied to {}", applied_to),
1876 err.span_label(sp, "attributes are not allowed here");
1881 /// This version of parse arg doesn't necessarily require identifier names.
1882 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
1883 allow_c_variadic: bool) -> PResult<'a, Arg> {
1884 if let Ok(Some(_)) = self.parse_self_arg() {
1885 let mut err = self.struct_span_err(self.prev_span,
1886 "unexpected `self` argument in function");
1887 err.span_label(self.prev_span,
1888 "`self` is only valid as the first argument of an associated function");
1892 let (pat, ty) = if require_name || self.is_named_argument() {
1893 debug!("parse_arg_general parse_pat (require_name:{})",
1895 self.eat_incorrect_doc_comment("method arguments");
1896 let pat = self.parse_pat(Some("argument name"))?;
1898 if let Err(mut err) = self.expect(&token::Colon) {
1899 // If we find a pattern followed by an identifier, it could be an (incorrect)
1900 // C-style parameter declaration.
1901 if self.check_ident() && self.look_ahead(1, |t| {
1902 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1904 let ident = self.parse_ident().unwrap();
1905 let span = pat.span.with_hi(ident.span.hi());
1907 err.span_suggestion(
1909 "declare the type after the parameter binding",
1910 String::from("<identifier>: <type>"),
1911 Applicability::HasPlaceholders,
1913 } else if require_name && is_trait_item {
1914 if let PatKind::Ident(_, ident, _) = pat.node {
1915 err.span_suggestion(
1917 "explicitly ignore parameter",
1918 format!("_: {}", ident),
1919 Applicability::MachineApplicable,
1923 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1929 self.eat_incorrect_doc_comment("a method argument's type");
1930 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1932 debug!("parse_arg_general ident_to_pat");
1933 let parser_snapshot_before_ty = self.clone();
1934 self.eat_incorrect_doc_comment("a method argument's type");
1935 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1936 if ty.is_ok() && self.token != token::Comma &&
1937 self.token != token::CloseDelim(token::Paren) {
1938 // This wasn't actually a type, but a pattern looking like a type,
1939 // so we are going to rollback and re-parse for recovery.
1940 ty = self.unexpected();
1944 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1946 id: ast::DUMMY_NODE_ID,
1947 node: PatKind::Ident(
1948 BindingMode::ByValue(Mutability::Immutable), ident, None),
1954 // If this is a C-variadic argument and we hit an error, return the
1956 if self.token == token::DotDotDot {
1959 // Recover from attempting to parse the argument as a type without pattern.
1961 mem::replace(self, parser_snapshot_before_ty);
1962 let pat = self.parse_pat(Some("argument name"))?;
1963 self.expect(&token::Colon)?;
1964 let ty = self.parse_ty()?;
1966 let mut err = self.diagnostic().struct_span_err_with_code(
1968 "patterns aren't allowed in methods without bodies",
1969 DiagnosticId::Error("E0642".into()),
1971 err.span_suggestion_short(
1973 "give this argument a name or use an underscore to ignore it",
1975 Applicability::MachineApplicable,
1979 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1981 node: PatKind::Wild,
1983 id: ast::DUMMY_NODE_ID
1990 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
1993 /// Parses a single function argument.
1994 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1995 self.parse_arg_general(true, false, false)
1998 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
1999 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2000 let pat = self.parse_pat(Some("argument name"))?;
2001 let t = if self.eat(&token::Colon) {
2005 id: ast::DUMMY_NODE_ID,
2006 node: TyKind::Infer,
2007 span: self.prev_span,
2013 id: ast::DUMMY_NODE_ID,
2014 source: ast::ArgSource::Normal,
2018 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2019 if self.eat(&token::Semi) {
2020 Ok(Some(self.parse_expr()?))
2026 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2027 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2028 maybe_whole_expr!(self);
2030 let minus_lo = self.span;
2031 let minus_present = self.eat(&token::BinOp(token::Minus));
2033 let literal = self.parse_lit()?;
2034 let hi = self.prev_span;
2035 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2038 let minus_hi = self.prev_span;
2039 let unary = self.mk_unary(UnOp::Neg, expr);
2040 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2046 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2048 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2049 let span = self.span;
2051 Ok(Ident::new(ident.name, span))
2053 _ => self.parse_ident(),
2057 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2059 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2060 let span = self.span;
2062 Ok(Ident::new(ident.name, span))
2064 _ => self.parse_ident(),
2068 /// Parses a qualified path.
2069 /// Assumes that the leading `<` has been parsed already.
2071 /// `qualified_path = <type [as trait_ref]>::path`
2076 /// `<T as U>::F::a<S>` (without disambiguator)
2077 /// `<T as U>::F::a::<S>` (with disambiguator)
2078 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2079 let lo = self.prev_span;
2080 let ty = self.parse_ty()?;
2082 // `path` will contain the prefix of the path up to the `>`,
2083 // if any (e.g., `U` in the `<T as U>::*` examples
2084 // above). `path_span` has the span of that path, or an empty
2085 // span in the case of something like `<T>::Bar`.
2086 let (mut path, path_span);
2087 if self.eat_keyword(keywords::As) {
2088 let path_lo = self.span;
2089 path = self.parse_path(PathStyle::Type)?;
2090 path_span = path_lo.to(self.prev_span);
2092 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2093 path_span = self.span.to(self.span);
2096 // See doc comment for `unmatched_angle_bracket_count`.
2097 self.expect(&token::Gt)?;
2098 if self.unmatched_angle_bracket_count > 0 {
2099 self.unmatched_angle_bracket_count -= 1;
2100 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2103 self.expect(&token::ModSep)?;
2105 let qself = QSelf { ty, path_span, position: path.segments.len() };
2106 self.parse_path_segments(&mut path.segments, style)?;
2108 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2111 /// Parses simple paths.
2113 /// `path = [::] segment+`
2114 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2117 /// `a::b::C<D>` (without disambiguator)
2118 /// `a::b::C::<D>` (with disambiguator)
2119 /// `Fn(Args)` (without disambiguator)
2120 /// `Fn::(Args)` (with disambiguator)
2121 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2122 maybe_whole!(self, NtPath, |path| {
2123 if style == PathStyle::Mod &&
2124 path.segments.iter().any(|segment| segment.args.is_some()) {
2125 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2130 let lo = self.meta_var_span.unwrap_or(self.span);
2131 let mut segments = Vec::new();
2132 let mod_sep_ctxt = self.span.ctxt();
2133 if self.eat(&token::ModSep) {
2134 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2136 self.parse_path_segments(&mut segments, style)?;
2138 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2141 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2142 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2144 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2145 let meta_ident = match self.token {
2146 token::Interpolated(ref nt) => match **nt {
2147 token::NtMeta(ref meta) => match meta.node {
2148 ast::MetaItemKind::Word => Some(meta.path.clone()),
2155 if let Some(path) = meta_ident {
2159 self.parse_path(style)
2162 crate fn parse_path_segments(&mut self,
2163 segments: &mut Vec<PathSegment>,
2165 -> PResult<'a, ()> {
2167 let segment = self.parse_path_segment(style)?;
2168 if style == PathStyle::Expr {
2169 // In order to check for trailing angle brackets, we must have finished
2170 // recursing (`parse_path_segment` can indirectly call this function),
2171 // that is, the next token must be the highlighted part of the below example:
2173 // `Foo::<Bar as Baz<T>>::Qux`
2176 // As opposed to the below highlight (if we had only finished the first
2179 // `Foo::<Bar as Baz<T>>::Qux`
2182 // `PathStyle::Expr` is only provided at the root invocation and never in
2183 // `parse_path_segment` to recurse and therefore can be checked to maintain
2185 self.check_trailing_angle_brackets(&segment, token::ModSep);
2187 segments.push(segment);
2189 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2195 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2196 let ident = self.parse_path_segment_ident()?;
2198 let is_args_start = |token: &token::Token| match *token {
2199 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
2200 | token::LArrow => true,
2203 let check_args_start = |this: &mut Self| {
2204 this.expected_tokens.extend_from_slice(
2205 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2207 is_args_start(&this.token)
2210 Ok(if style == PathStyle::Type && check_args_start(self) ||
2211 style != PathStyle::Mod && self.check(&token::ModSep)
2212 && self.look_ahead(1, |t| is_args_start(t)) {
2213 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2214 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2215 // parsing a new path.
2216 if style == PathStyle::Expr {
2217 self.unmatched_angle_bracket_count = 0;
2218 self.max_angle_bracket_count = 0;
2221 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2222 self.eat(&token::ModSep);
2224 let args = if self.eat_lt() {
2226 let (args, bindings) =
2227 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2229 let span = lo.to(self.prev_span);
2230 AngleBracketedArgs { args, bindings, span }.into()
2234 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2235 &[&token::CloseDelim(token::Paren)],
2236 SeqSep::trailing_allowed(token::Comma),
2237 TokenExpectType::Expect,
2242 let span = lo.to(self.prev_span);
2243 let output = if self.eat(&token::RArrow) {
2244 Some(self.parse_ty_common(false, false, false)?)
2248 ParenthesizedArgs { inputs, output, span }.into()
2251 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2253 // Generic arguments are not found.
2254 PathSegment::from_ident(ident)
2258 crate fn check_lifetime(&mut self) -> bool {
2259 self.expected_tokens.push(TokenType::Lifetime);
2260 self.token.is_lifetime()
2263 /// Parses a single lifetime `'a` or panics.
2264 crate fn expect_lifetime(&mut self) -> Lifetime {
2265 if let Some(ident) = self.token.lifetime() {
2266 let span = self.span;
2268 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2270 self.span_bug(self.span, "not a lifetime")
2274 fn eat_label(&mut self) -> Option<Label> {
2275 if let Some(ident) = self.token.lifetime() {
2276 let span = self.span;
2278 Some(Label { ident: Ident::new(ident.name, span) })
2284 /// Parses mutability (`mut` or nothing).
2285 fn parse_mutability(&mut self) -> Mutability {
2286 if self.eat_keyword(keywords::Mut) {
2289 Mutability::Immutable
2293 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2294 if let token::Literal(token::Integer(name), suffix) = self.token {
2295 self.expect_no_suffix(self.span, "a tuple index", suffix);
2297 Ok(Ident::new(name, self.prev_span))
2299 self.parse_ident_common(false)
2303 /// Parse ident (COLON expr)?
2304 fn parse_field(&mut self) -> PResult<'a, Field> {
2305 let attrs = self.parse_outer_attributes()?;
2308 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2309 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2310 t == &token::Colon || t == &token::Eq
2312 let fieldname = self.parse_field_name()?;
2314 // Check for an equals token. This means the source incorrectly attempts to
2315 // initialize a field with an eq rather than a colon.
2316 if self.token == token::Eq {
2318 .struct_span_err(self.span, "expected `:`, found `=`")
2320 fieldname.span.shrink_to_hi().to(self.span),
2321 "replace equals symbol with a colon",
2323 Applicability::MachineApplicable,
2328 (fieldname, self.parse_expr()?, false)
2330 let fieldname = self.parse_ident_common(false)?;
2332 // Mimic `x: x` for the `x` field shorthand.
2333 let path = ast::Path::from_ident(fieldname);
2334 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2335 (fieldname, expr, true)
2339 span: lo.to(expr.span),
2342 attrs: attrs.into(),
2346 fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2347 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2350 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2351 ExprKind::Unary(unop, expr)
2354 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2355 ExprKind::Binary(binop, lhs, rhs)
2358 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2359 ExprKind::Call(f, args)
2362 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2363 ExprKind::Index(expr, idx)
2367 start: Option<P<Expr>>,
2368 end: Option<P<Expr>>,
2369 limits: RangeLimits)
2370 -> PResult<'a, ast::ExprKind> {
2371 if end.is_none() && limits == RangeLimits::Closed {
2372 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2374 Ok(ExprKind::Range(start, end, limits))
2378 fn mk_assign_op(&self, binop: ast::BinOp,
2379 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2380 ExprKind::AssignOp(binop, lhs, rhs)
2383 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2384 let delim = match self.token {
2385 token::OpenDelim(delim) => delim,
2387 let msg = "expected open delimiter";
2388 let mut err = self.fatal(msg);
2389 err.span_label(self.span, msg);
2393 let tts = match self.parse_token_tree() {
2394 TokenTree::Delimited(_, _, tts) => tts,
2395 _ => unreachable!(),
2397 let delim = match delim {
2398 token::Paren => MacDelimiter::Parenthesis,
2399 token::Bracket => MacDelimiter::Bracket,
2400 token::Brace => MacDelimiter::Brace,
2401 token::NoDelim => self.bug("unexpected no delimiter"),
2403 Ok((delim, tts.into()))
2406 /// At the bottom (top?) of the precedence hierarchy,
2407 /// Parses things like parenthesized exprs, macros, `return`, etc.
2409 /// N.B., this does not parse outer attributes, and is private because it only works
2410 /// correctly if called from `parse_dot_or_call_expr()`.
2411 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2412 maybe_recover_from_interpolated_ty_qpath!(self, true);
2413 maybe_whole_expr!(self);
2415 // Outer attributes are already parsed and will be
2416 // added to the return value after the fact.
2418 // Therefore, prevent sub-parser from parsing
2419 // attributes by giving them a empty "already parsed" list.
2420 let mut attrs = ThinVec::new();
2423 let mut hi = self.span;
2427 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2429 token::OpenDelim(token::Paren) => {
2432 attrs.extend(self.parse_inner_attributes()?);
2434 // (e) is parenthesized e
2435 // (e,) is a tuple with only one field, e
2436 let mut es = vec![];
2437 let mut trailing_comma = false;
2438 let mut recovered = false;
2439 while self.token != token::CloseDelim(token::Paren) {
2440 es.push(match self.parse_expr() {
2443 // recover from parse error in tuple list
2444 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2447 recovered = self.expect_one_of(
2449 &[token::Comma, token::CloseDelim(token::Paren)],
2451 if self.eat(&token::Comma) {
2452 trailing_comma = true;
2454 trailing_comma = false;
2462 hi = self.prev_span;
2463 ex = if es.len() == 1 && !trailing_comma {
2464 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2469 token::OpenDelim(token::Brace) => {
2470 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2472 token::BinOp(token::Or) | token::OrOr => {
2473 return self.parse_lambda_expr(attrs);
2475 token::OpenDelim(token::Bracket) => {
2478 attrs.extend(self.parse_inner_attributes()?);
2480 if self.eat(&token::CloseDelim(token::Bracket)) {
2482 ex = ExprKind::Array(Vec::new());
2485 let first_expr = self.parse_expr()?;
2486 if self.eat(&token::Semi) {
2487 // Repeating array syntax: [ 0; 512 ]
2488 let count = AnonConst {
2489 id: ast::DUMMY_NODE_ID,
2490 value: self.parse_expr()?,
2492 self.expect(&token::CloseDelim(token::Bracket))?;
2493 ex = ExprKind::Repeat(first_expr, count);
2494 } else if self.eat(&token::Comma) {
2495 // Vector with two or more elements.
2496 let remaining_exprs = self.parse_seq_to_end(
2497 &token::CloseDelim(token::Bracket),
2498 SeqSep::trailing_allowed(token::Comma),
2499 |p| Ok(p.parse_expr()?)
2501 let mut exprs = vec![first_expr];
2502 exprs.extend(remaining_exprs);
2503 ex = ExprKind::Array(exprs);
2505 // Vector with one element.
2506 self.expect(&token::CloseDelim(token::Bracket))?;
2507 ex = ExprKind::Array(vec![first_expr]);
2510 hi = self.prev_span;
2514 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2516 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2518 if self.span.rust_2018() && self.check_keyword(keywords::Async) {
2519 return if self.is_async_block() { // check for `async {` and `async move {`
2520 self.parse_async_block(attrs)
2522 self.parse_lambda_expr(attrs)
2525 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2526 return self.parse_lambda_expr(attrs);
2528 if self.eat_keyword(keywords::If) {
2529 return self.parse_if_expr(attrs);
2531 if self.eat_keyword(keywords::For) {
2532 let lo = self.prev_span;
2533 return self.parse_for_expr(None, lo, attrs);
2535 if self.eat_keyword(keywords::While) {
2536 let lo = self.prev_span;
2537 return self.parse_while_expr(None, lo, attrs);
2539 if let Some(label) = self.eat_label() {
2540 let lo = label.ident.span;
2541 self.expect(&token::Colon)?;
2542 if self.eat_keyword(keywords::While) {
2543 return self.parse_while_expr(Some(label), lo, attrs)
2545 if self.eat_keyword(keywords::For) {
2546 return self.parse_for_expr(Some(label), lo, attrs)
2548 if self.eat_keyword(keywords::Loop) {
2549 return self.parse_loop_expr(Some(label), lo, attrs)
2551 if self.token == token::OpenDelim(token::Brace) {
2552 return self.parse_block_expr(Some(label),
2554 BlockCheckMode::Default,
2557 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2558 let mut err = self.fatal(msg);
2559 err.span_label(self.span, msg);
2562 if self.eat_keyword(keywords::Loop) {
2563 let lo = self.prev_span;
2564 return self.parse_loop_expr(None, lo, attrs);
2566 if self.eat_keyword(keywords::Continue) {
2567 let label = self.eat_label();
2568 let ex = ExprKind::Continue(label);
2569 let hi = self.prev_span;
2570 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2572 if self.eat_keyword(keywords::Match) {
2573 let match_sp = self.prev_span;
2574 return self.parse_match_expr(attrs).map_err(|mut err| {
2575 err.span_label(match_sp, "while parsing this match expression");
2579 if self.eat_keyword(keywords::Unsafe) {
2580 return self.parse_block_expr(
2583 BlockCheckMode::Unsafe(ast::UserProvided),
2586 if self.is_do_catch_block() {
2587 let mut db = self.fatal("found removed `do catch` syntax");
2588 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2591 if self.is_try_block() {
2593 assert!(self.eat_keyword(keywords::Try));
2594 return self.parse_try_block(lo, attrs);
2596 if self.eat_keyword(keywords::Return) {
2597 if self.token.can_begin_expr() {
2598 let e = self.parse_expr()?;
2600 ex = ExprKind::Ret(Some(e));
2602 ex = ExprKind::Ret(None);
2604 } else if self.eat_keyword(keywords::Break) {
2605 let label = self.eat_label();
2606 let e = if self.token.can_begin_expr()
2607 && !(self.token == token::OpenDelim(token::Brace)
2608 && self.restrictions.contains(
2609 Restrictions::NO_STRUCT_LITERAL)) {
2610 Some(self.parse_expr()?)
2614 ex = ExprKind::Break(label, e);
2615 hi = self.prev_span;
2616 } else if self.eat_keyword(keywords::Yield) {
2617 if self.token.can_begin_expr() {
2618 let e = self.parse_expr()?;
2620 ex = ExprKind::Yield(Some(e));
2622 ex = ExprKind::Yield(None);
2624 } else if self.token.is_keyword(keywords::Let) {
2625 // Catch this syntax error here, instead of in `parse_ident`, so
2626 // that we can explicitly mention that let is not to be used as an expression
2627 let mut db = self.fatal("expected expression, found statement (`let`)");
2628 db.span_label(self.span, "expected expression");
2629 db.note("variable declaration using `let` is a statement");
2631 } else if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
2632 // FIXME: remove this branch when `await!` is no longer supported
2633 // https://github.com/rust-lang/rust/issues/60610
2634 self.expect(&token::Not)?;
2635 self.expect(&token::OpenDelim(token::Paren))?;
2636 let expr = self.parse_expr()?;
2637 self.expect(&token::CloseDelim(token::Paren))?;
2638 hi = self.prev_span;
2639 ex = ExprKind::Await(ast::AwaitOrigin::MacroLike, expr);
2640 } else if self.token.is_path_start() {
2641 let path = self.parse_path(PathStyle::Expr)?;
2643 // `!`, as an operator, is prefix, so we know this isn't that
2644 if self.eat(&token::Not) {
2645 // MACRO INVOCATION expression
2646 let (delim, tts) = self.expect_delimited_token_tree()?;
2647 hi = self.prev_span;
2648 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2649 } else if self.check(&token::OpenDelim(token::Brace)) {
2650 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2654 ex = ExprKind::Path(None, path);
2658 ex = ExprKind::Path(None, path);
2661 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2662 // Don't complain about bare semicolons after unclosed braces
2663 // recovery in order to keep the error count down. Fixing the
2664 // delimiters will possibly also fix the bare semicolon found in
2665 // expression context. For example, silence the following error:
2667 // error: expected expression, found `;`
2671 // | ^ expected expression
2674 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2676 match self.parse_literal_maybe_minus() {
2679 ex = expr.node.clone();
2682 self.cancel(&mut err);
2683 let msg = format!("expected expression, found {}",
2684 self.this_token_descr());
2685 let mut err = self.fatal(&msg);
2686 let sp = self.sess.source_map().start_point(self.span);
2687 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow()
2690 self.sess.expr_parentheses_needed(&mut err, *sp, None);
2692 err.span_label(self.span, "expected expression");
2700 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2701 self.maybe_recover_from_bad_qpath(expr, true)
2704 fn maybe_parse_struct_expr(
2708 attrs: &ThinVec<Attribute>,
2709 ) -> Option<PResult<'a, P<Expr>>> {
2710 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2711 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2712 // `{ ident, ` cannot start a block
2713 self.look_ahead(2, |t| t == &token::Comma) ||
2714 self.look_ahead(2, |t| t == &token::Colon) && (
2715 // `{ ident: token, ` cannot start a block
2716 self.look_ahead(4, |t| t == &token::Comma) ||
2717 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2718 self.look_ahead(3, |t| !t.can_begin_type())
2722 if struct_allowed || certainly_not_a_block() {
2723 // This is a struct literal, but we don't can't accept them here
2724 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2725 if let (Ok(expr), false) = (&expr, struct_allowed) {
2726 let mut err = self.diagnostic().struct_span_err(
2728 "struct literals are not allowed here",
2730 err.multipart_suggestion(
2731 "surround the struct literal with parentheses",
2733 (lo.shrink_to_lo(), "(".to_string()),
2734 (expr.span.shrink_to_hi(), ")".to_string()),
2736 Applicability::MachineApplicable,
2745 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2746 -> PResult<'a, P<Expr>> {
2747 let struct_sp = lo.to(self.prev_span);
2749 let mut fields = Vec::new();
2750 let mut base = None;
2752 attrs.extend(self.parse_inner_attributes()?);
2754 while self.token != token::CloseDelim(token::Brace) {
2755 if self.eat(&token::DotDot) {
2756 let exp_span = self.prev_span;
2757 match self.parse_expr() {
2763 self.recover_stmt();
2766 if self.token == token::Comma {
2767 let mut err = self.sess.span_diagnostic.mut_span_err(
2768 exp_span.to(self.prev_span),
2769 "cannot use a comma after the base struct",
2771 err.span_suggestion_short(
2773 "remove this comma",
2775 Applicability::MachineApplicable
2777 err.note("the base struct must always be the last field");
2779 self.recover_stmt();
2784 let mut recovery_field = None;
2785 if let token::Ident(ident, _) = self.token {
2786 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2787 // Use in case of error after field-looking code: `S { foo: () with a }`
2788 let mut ident = ident.clone();
2789 ident.span = self.span;
2790 recovery_field = Some(ast::Field {
2793 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2794 is_shorthand: false,
2795 attrs: ThinVec::new(),
2799 let mut parsed_field = None;
2800 match self.parse_field() {
2801 Ok(f) => parsed_field = Some(f),
2803 e.span_label(struct_sp, "while parsing this struct");
2806 // If the next token is a comma, then try to parse
2807 // what comes next as additional fields, rather than
2808 // bailing out until next `}`.
2809 if self.token != token::Comma {
2810 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2811 if self.token != token::Comma {
2818 match self.expect_one_of(&[token::Comma],
2819 &[token::CloseDelim(token::Brace)]) {
2820 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2821 // only include the field if there's no parse error for the field name
2825 if let Some(f) = recovery_field {
2828 e.span_label(struct_sp, "while parsing this struct");
2830 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2831 self.eat(&token::Comma);
2836 let span = lo.to(self.span);
2837 self.expect(&token::CloseDelim(token::Brace))?;
2838 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2841 fn parse_or_use_outer_attributes(&mut self,
2842 already_parsed_attrs: Option<ThinVec<Attribute>>)
2843 -> PResult<'a, ThinVec<Attribute>> {
2844 if let Some(attrs) = already_parsed_attrs {
2847 self.parse_outer_attributes().map(|a| a.into())
2851 /// Parses a block or unsafe block.
2852 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2853 lo: Span, blk_mode: BlockCheckMode,
2854 outer_attrs: ThinVec<Attribute>)
2855 -> PResult<'a, P<Expr>> {
2856 self.expect(&token::OpenDelim(token::Brace))?;
2858 let mut attrs = outer_attrs;
2859 attrs.extend(self.parse_inner_attributes()?);
2861 let blk = self.parse_block_tail(lo, blk_mode)?;
2862 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2865 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2866 fn parse_dot_or_call_expr(&mut self,
2867 already_parsed_attrs: Option<ThinVec<Attribute>>)
2868 -> PResult<'a, P<Expr>> {
2869 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2871 let b = self.parse_bottom_expr();
2872 let (span, b) = self.interpolated_or_expr_span(b)?;
2873 self.parse_dot_or_call_expr_with(b, span, attrs)
2876 fn parse_dot_or_call_expr_with(&mut self,
2879 mut attrs: ThinVec<Attribute>)
2880 -> PResult<'a, P<Expr>> {
2881 // Stitch the list of outer attributes onto the return value.
2882 // A little bit ugly, but the best way given the current code
2884 self.parse_dot_or_call_expr_with_(e0, lo)
2886 expr.map(|mut expr| {
2887 attrs.extend::<Vec<_>>(expr.attrs.into());
2890 ExprKind::If(..) | ExprKind::IfLet(..) => {
2891 if !expr.attrs.is_empty() {
2892 // Just point to the first attribute in there...
2893 let span = expr.attrs[0].span;
2896 "attributes are not yet allowed on `if` \
2907 // Assuming we have just parsed `.`, continue parsing into an expression.
2908 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2909 if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
2910 let span = lo.to(self.prev_span);
2911 let await_expr = self.mk_expr(
2913 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
2916 return Ok(await_expr);
2918 let segment = self.parse_path_segment(PathStyle::Expr)?;
2919 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2921 Ok(match self.token {
2922 token::OpenDelim(token::Paren) => {
2923 // Method call `expr.f()`
2924 let mut args = self.parse_unspanned_seq(
2925 &token::OpenDelim(token::Paren),
2926 &token::CloseDelim(token::Paren),
2927 SeqSep::trailing_allowed(token::Comma),
2928 |p| Ok(p.parse_expr()?)
2930 args.insert(0, self_arg);
2932 let span = lo.to(self.prev_span);
2933 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2936 // Field access `expr.f`
2937 if let Some(args) = segment.args {
2938 self.span_err(args.span(),
2939 "field expressions may not have generic arguments");
2942 let span = lo.to(self.prev_span);
2943 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2948 /// This function checks if there are trailing angle brackets and produces
2949 /// a diagnostic to suggest removing them.
2951 /// ```ignore (diagnostic)
2952 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
2953 /// ^^ help: remove extra angle brackets
2955 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
2956 // This function is intended to be invoked after parsing a path segment where there are two
2959 // 1. A specific token is expected after the path segment.
2960 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
2961 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
2962 // 2. No specific token is expected after the path segment.
2963 // eg. `x.foo` (field access)
2965 // This function is called after parsing `.foo` and before parsing the token `end` (if
2966 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
2969 // We only care about trailing angle brackets if we previously parsed angle bracket
2970 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
2971 // removed in this case:
2973 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
2975 // This case is particularly tricky as we won't notice it just looking at the tokens -
2976 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
2977 // have already been parsed):
2979 // `x.foo::<u32>>>(3)`
2980 let parsed_angle_bracket_args = segment.args
2982 .map(|args| args.is_angle_bracketed())
2986 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
2987 parsed_angle_bracket_args,
2989 if !parsed_angle_bracket_args {
2993 // Keep the span at the start so we can highlight the sequence of `>` characters to be
2997 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
2998 // (since we might have the field access case and the characters we're eating are
2999 // actual operators and not trailing characters - ie `x.foo >> 3`).
3000 let mut position = 0;
3002 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3003 // many of each (so we can correctly pluralize our error messages) and continue to
3005 let mut number_of_shr = 0;
3006 let mut number_of_gt = 0;
3007 while self.look_ahead(position, |t| {
3008 trace!("check_trailing_angle_brackets: t={:?}", t);
3009 if *t == token::BinOp(token::BinOpToken::Shr) {
3012 } else if *t == token::Gt {
3022 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3024 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3025 number_of_gt, number_of_shr,
3027 if number_of_gt < 1 && number_of_shr < 1 {
3031 // Finally, double check that we have our end token as otherwise this is the
3033 if self.look_ahead(position, |t| {
3034 trace!("check_trailing_angle_brackets: t={:?}", t);
3037 // Eat from where we started until the end token so that parsing can continue
3038 // as if we didn't have those extra angle brackets.
3039 self.eat_to_tokens(&[&end]);
3040 let span = lo.until(self.span);
3042 let plural = number_of_gt > 1 || number_of_shr >= 1;
3046 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3050 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3052 Applicability::MachineApplicable,
3058 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3063 while self.eat(&token::Question) {
3064 let hi = self.prev_span;
3065 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3069 if self.eat(&token::Dot) {
3071 token::Ident(..) => {
3072 e = self.parse_dot_suffix(e, lo)?;
3074 token::Literal(token::Integer(name), suffix) => {
3075 let span = self.span;
3077 let field = ExprKind::Field(e, Ident::new(name, span));
3078 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3080 self.expect_no_suffix(span, "a tuple index", suffix);
3082 token::Literal(token::Float(n), _suf) => {
3084 let fstr = n.as_str();
3085 let mut err = self.diagnostic()
3086 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3087 err.span_label(self.prev_span, "unexpected token");
3088 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3089 let float = match fstr.parse::<f64>().ok() {
3093 let sugg = pprust::to_string(|s| {
3094 use crate::print::pprust::PrintState;
3098 s.print_usize(float.trunc() as usize)?;
3101 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3103 err.span_suggestion(
3104 lo.to(self.prev_span),
3105 "try parenthesizing the first index",
3107 Applicability::MachineApplicable
3114 // FIXME Could factor this out into non_fatal_unexpected or something.
3115 let actual = self.this_token_to_string();
3116 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3121 if self.expr_is_complete(&e) { break; }
3124 token::OpenDelim(token::Paren) => {
3125 let seq = self.parse_unspanned_seq(
3126 &token::OpenDelim(token::Paren),
3127 &token::CloseDelim(token::Paren),
3128 SeqSep::trailing_allowed(token::Comma),
3129 |p| Ok(p.parse_expr()?)
3131 let nd = self.mk_call(e, es);
3132 let hi = self.prev_span;
3133 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3135 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3139 // Could be either an index expression or a slicing expression.
3140 token::OpenDelim(token::Bracket) => {
3142 let ix = self.parse_expr()?;
3144 self.expect(&token::CloseDelim(token::Bracket))?;
3145 let index = self.mk_index(e, ix);
3146 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3154 fn recover_seq_parse_error(
3156 delim: token::DelimToken,
3158 result: PResult<'a, P<Expr>>,
3164 // recover from parse error
3165 self.consume_block(delim);
3166 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
3171 crate fn process_potential_macro_variable(&mut self) {
3172 let (token, span) = match self.token {
3173 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3174 self.look_ahead(1, |t| t.is_ident()) => {
3176 let name = match self.token {
3177 token::Ident(ident, _) => ident,
3180 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3181 err.span_label(self.span, "unknown macro variable");
3186 token::Interpolated(ref nt) => {
3187 self.meta_var_span = Some(self.span);
3188 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3189 // and lifetime tokens, so the former are never encountered during normal parsing.
3191 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3192 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3202 /// Parses a single token tree from the input.
3203 crate fn parse_token_tree(&mut self) -> TokenTree {
3205 token::OpenDelim(..) => {
3206 let frame = mem::replace(&mut self.token_cursor.frame,
3207 self.token_cursor.stack.pop().unwrap());
3208 self.span = frame.span.entire();
3210 TokenTree::Delimited(
3213 frame.tree_cursor.stream.into(),
3216 token::CloseDelim(_) | token::Eof => unreachable!(),
3218 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3220 TokenTree::Token(span, token)
3225 // parse a stream of tokens into a list of TokenTree's,
3227 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3228 let mut tts = Vec::new();
3229 while self.token != token::Eof {
3230 tts.push(self.parse_token_tree());
3235 pub fn parse_tokens(&mut self) -> TokenStream {
3236 let mut result = Vec::new();
3239 token::Eof | token::CloseDelim(..) => break,
3240 _ => result.push(self.parse_token_tree().into()),
3243 TokenStream::new(result)
3246 /// Parse a prefix-unary-operator expr
3247 fn parse_prefix_expr(&mut self,
3248 already_parsed_attrs: Option<ThinVec<Attribute>>)
3249 -> PResult<'a, P<Expr>> {
3250 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3252 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3253 let (hi, ex) = match self.token {
3256 let e = self.parse_prefix_expr(None);
3257 let (span, e) = self.interpolated_or_expr_span(e)?;
3258 (lo.to(span), self.mk_unary(UnOp::Not, e))
3260 // Suggest `!` for bitwise negation when encountering a `~`
3263 let e = self.parse_prefix_expr(None);
3264 let (span, e) = self.interpolated_or_expr_span(e)?;
3265 let span_of_tilde = lo;
3266 let mut err = self.diagnostic()
3267 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3268 err.span_suggestion_short(
3270 "use `!` to perform bitwise negation",
3272 Applicability::MachineApplicable
3275 (lo.to(span), self.mk_unary(UnOp::Not, e))
3277 token::BinOp(token::Minus) => {
3279 let e = self.parse_prefix_expr(None);
3280 let (span, e) = self.interpolated_or_expr_span(e)?;
3281 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3283 token::BinOp(token::Star) => {
3285 let e = self.parse_prefix_expr(None);
3286 let (span, e) = self.interpolated_or_expr_span(e)?;
3287 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3289 token::BinOp(token::And) | token::AndAnd => {
3291 let m = self.parse_mutability();
3292 let e = self.parse_prefix_expr(None);
3293 let (span, e) = self.interpolated_or_expr_span(e)?;
3294 (lo.to(span), ExprKind::AddrOf(m, e))
3296 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3298 let place = self.parse_expr_res(
3299 Restrictions::NO_STRUCT_LITERAL,
3302 let blk = self.parse_block()?;
3303 let span = blk.span;
3304 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3305 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3307 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3309 let e = self.parse_prefix_expr(None);
3310 let (span, e) = self.interpolated_or_expr_span(e)?;
3311 (lo.to(span), ExprKind::Box(e))
3313 token::Ident(..) if self.token.is_ident_named("not") => {
3314 // `not` is just an ordinary identifier in Rust-the-language,
3315 // but as `rustc`-the-compiler, we can issue clever diagnostics
3316 // for confused users who really want to say `!`
3317 let token_cannot_continue_expr = |t: &token::Token| match *t {
3318 // These tokens can start an expression after `!`, but
3319 // can't continue an expression after an ident
3320 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3321 token::Literal(..) | token::Pound => true,
3322 token::Interpolated(ref nt) => match **nt {
3323 token::NtIdent(..) | token::NtExpr(..) |
3324 token::NtBlock(..) | token::NtPath(..) => true,
3329 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3330 if cannot_continue_expr {
3332 // Emit the error ...
3333 let mut err = self.diagnostic()
3334 .struct_span_err(self.span,
3335 &format!("unexpected {} after identifier",
3336 self.this_token_descr()));
3337 // span the `not` plus trailing whitespace to avoid
3338 // trailing whitespace after the `!` in our suggestion
3339 let to_replace = self.sess.source_map()
3340 .span_until_non_whitespace(lo.to(self.span));
3341 err.span_suggestion_short(
3343 "use `!` to perform logical negation",
3345 Applicability::MachineApplicable
3348 // —and recover! (just as if we were in the block
3349 // for the `token::Not` arm)
3350 let e = self.parse_prefix_expr(None);
3351 let (span, e) = self.interpolated_or_expr_span(e)?;
3352 (lo.to(span), self.mk_unary(UnOp::Not, e))
3354 return self.parse_dot_or_call_expr(Some(attrs));
3357 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3359 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3362 /// Parses an associative expression.
3364 /// This parses an expression accounting for associativity and precedence of the operators in
3367 fn parse_assoc_expr(&mut self,
3368 already_parsed_attrs: Option<ThinVec<Attribute>>)
3369 -> PResult<'a, P<Expr>> {
3370 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3373 /// Parses an associative expression with operators of at least `min_prec` precedence.
3374 fn parse_assoc_expr_with(&mut self,
3377 -> PResult<'a, P<Expr>> {
3378 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3381 let attrs = match lhs {
3382 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3385 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3386 return self.parse_prefix_range_expr(attrs);
3388 self.parse_prefix_expr(attrs)?
3392 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
3394 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3397 (false, _) => {} // continue parsing the expression
3398 // An exhaustive check is done in the following block, but these are checked first
3399 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
3400 // want to keep their span info to improve diagnostics in these cases in a later stage.
3401 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
3402 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
3403 (true, Some(AssocOp::Add)) => { // `{ 42 } + 42
3404 // These cases are ambiguous and can't be identified in the parser alone
3405 let sp = self.sess.source_map().start_point(self.span);
3406 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
3409 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
3412 (true, Some(_)) => {
3413 // We've found an expression that would be parsed as a statement, but the next
3414 // token implies this should be parsed as an expression.
3415 // For example: `if let Some(x) = x { x } else { 0 } / 2`
3416 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
3417 "expected expression, found `{}`",
3418 pprust::token_to_string(&self.token),
3420 err.span_label(self.span, "expected expression");
3421 self.sess.expr_parentheses_needed(
3424 Some(pprust::expr_to_string(&lhs),
3429 self.expected_tokens.push(TokenType::Operator);
3430 while let Some(op) = AssocOp::from_token(&self.token) {
3432 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3433 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3434 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3435 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3436 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3437 (PrevTokenKind::Interpolated, _) => self.prev_span,
3438 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3439 if path.segments.len() == 1 => self.prev_span,
3443 let cur_op_span = self.span;
3444 let restrictions = if op.is_assign_like() {
3445 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3449 let prec = op.precedence();
3450 if prec < min_prec {
3453 // Check for deprecated `...` syntax
3454 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3455 self.err_dotdotdot_syntax(self.span);
3459 if op.is_comparison() {
3460 self.check_no_chained_comparison(&lhs, &op);
3463 if op == AssocOp::As {
3464 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3466 } else if op == AssocOp::Colon {
3467 let maybe_path = self.could_ascription_be_path(&lhs.node);
3468 let next_sp = self.span;
3470 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3473 self.bad_type_ascription(
3484 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3485 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3486 // generalise it to the Fixity::None code.
3488 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3489 // two variants are handled with `parse_prefix_range_expr` call above.
3490 let rhs = if self.is_at_start_of_range_notation_rhs() {
3491 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
3495 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3500 let limits = if op == AssocOp::DotDot {
3501 RangeLimits::HalfOpen
3506 let r = self.mk_range(Some(lhs), rhs, limits)?;
3507 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3511 let fixity = op.fixity();
3512 let prec_adjustment = match fixity {
3515 // We currently have no non-associative operators that are not handled above by
3516 // the special cases. The code is here only for future convenience.
3519 let rhs = self.with_res(
3520 restrictions - Restrictions::STMT_EXPR,
3521 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
3524 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3525 // including the attributes.
3529 .filter(|a| a.style == AttrStyle::Outer)
3531 .map_or(lhs_span, |a| a.span);
3532 let span = lhs_span.to(rhs.span);
3534 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3535 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3536 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3537 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3538 AssocOp::Greater | AssocOp::GreaterEqual => {
3539 let ast_op = op.to_ast_binop().unwrap();
3540 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3541 self.mk_expr(span, binary, ThinVec::new())
3544 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3545 AssocOp::ObsoleteInPlace =>
3546 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3547 AssocOp::AssignOp(k) => {
3549 token::Plus => BinOpKind::Add,
3550 token::Minus => BinOpKind::Sub,
3551 token::Star => BinOpKind::Mul,
3552 token::Slash => BinOpKind::Div,
3553 token::Percent => BinOpKind::Rem,
3554 token::Caret => BinOpKind::BitXor,
3555 token::And => BinOpKind::BitAnd,
3556 token::Or => BinOpKind::BitOr,
3557 token::Shl => BinOpKind::Shl,
3558 token::Shr => BinOpKind::Shr,
3560 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3561 self.mk_expr(span, aopexpr, ThinVec::new())
3563 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3564 self.bug("AssocOp should have been handled by special case")
3568 if let Fixity::None = fixity { break }
3573 fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
3574 self.token.is_ident() &&
3575 if let ast::ExprKind::Path(..) = node { true } else { false } &&
3576 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
3577 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
3578 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
3579 self.look_ahead(2, |t| t.is_ident()) ||
3580 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
3581 self.look_ahead(2, |t| t.is_ident()) ||
3582 self.look_ahead(1, |t| t == &token::ModSep) && // `foo:bar::baz`
3583 self.look_ahead(2, |t| t.is_ident())
3586 fn bad_type_ascription(
3588 err: &mut DiagnosticBuilder<'a>,
3594 err.span_label(self.span, "expecting a type here because of type ascription");
3595 let cm = self.sess.source_map();
3596 let next_pos = cm.lookup_char_pos(next_sp.lo());
3597 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3598 if op_pos.line != next_pos.line {
3599 err.span_suggestion(
3601 "try using a semicolon",
3603 Applicability::MaybeIncorrect,
3607 err.span_suggestion(
3609 "maybe you meant to write a path separator here",
3611 Applicability::MaybeIncorrect,
3614 err.note("type ascription is a nightly-only feature that lets \
3615 you annotate an expression with a type: `<expr>: <type>`");
3618 "this expression expects an ascribed type after the colon",
3620 err.help("this might be indicative of a syntax error elsewhere");
3625 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3626 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3627 -> PResult<'a, P<Expr>> {
3628 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3629 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3632 // Save the state of the parser before parsing type normally, in case there is a
3633 // LessThan comparison after this cast.
3634 let parser_snapshot_before_type = self.clone();
3635 match self.parse_ty_no_plus() {
3637 Ok(mk_expr(self, rhs))
3639 Err(mut type_err) => {
3640 // Rewind to before attempting to parse the type with generics, to recover
3641 // from situations like `x as usize < y` in which we first tried to parse
3642 // `usize < y` as a type with generic arguments.
3643 let parser_snapshot_after_type = self.clone();
3644 mem::replace(self, parser_snapshot_before_type);
3646 match self.parse_path(PathStyle::Expr) {
3648 let (op_noun, op_verb) = match self.token {
3649 token::Lt => ("comparison", "comparing"),
3650 token::BinOp(token::Shl) => ("shift", "shifting"),
3652 // We can end up here even without `<` being the next token, for
3653 // example because `parse_ty_no_plus` returns `Err` on keywords,
3654 // but `parse_path` returns `Ok` on them due to error recovery.
3655 // Return original error and parser state.
3656 mem::replace(self, parser_snapshot_after_type);
3657 return Err(type_err);
3661 // Successfully parsed the type path leaving a `<` yet to parse.
3664 // Report non-fatal diagnostics, keep `x as usize` as an expression
3665 // in AST and continue parsing.
3666 let msg = format!("`<` is interpreted as a start of generic \
3667 arguments for `{}`, not a {}", path, op_noun);
3668 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3669 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3670 "interpreted as generic arguments");
3671 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3673 let expr = mk_expr(self, P(Ty {
3675 node: TyKind::Path(None, path),
3676 id: ast::DUMMY_NODE_ID
3679 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3680 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3681 err.span_suggestion(
3683 &format!("try {} the cast value", op_verb),
3684 format!("({})", expr_str),
3685 Applicability::MachineApplicable
3691 Err(mut path_err) => {
3692 // Couldn't parse as a path, return original error and parser state.
3694 mem::replace(self, parser_snapshot_after_type);
3702 /// Produce an error if comparison operators are chained (RFC #558).
3703 /// We only need to check lhs, not rhs, because all comparison ops
3704 /// have same precedence and are left-associative
3705 fn check_no_chained_comparison(&self, lhs: &Expr, outer_op: &AssocOp) {
3706 debug_assert!(outer_op.is_comparison(),
3707 "check_no_chained_comparison: {:?} is not comparison",
3710 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3711 // respan to include both operators
3712 let op_span = op.span.to(self.span);
3713 let mut err = self.diagnostic().struct_span_err(op_span,
3714 "chained comparison operators require parentheses");
3715 if op.node == BinOpKind::Lt &&
3716 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3717 *outer_op == AssocOp::Greater // even in a case like the following:
3718 { // Foo<Bar<Baz<Qux, ()>>>
3720 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3721 err.help("or use `(...)` if you meant to specify fn arguments");
3729 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3730 fn parse_prefix_range_expr(&mut self,
3731 already_parsed_attrs: Option<ThinVec<Attribute>>)
3732 -> PResult<'a, P<Expr>> {
3733 // Check for deprecated `...` syntax
3734 if self.token == token::DotDotDot {
3735 self.err_dotdotdot_syntax(self.span);
3738 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3739 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3741 let tok = self.token.clone();
3742 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3744 let mut hi = self.span;
3746 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3747 // RHS must be parsed with more associativity than the dots.
3748 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3749 Some(self.parse_assoc_expr_with(next_prec,
3750 LhsExpr::NotYetParsed)
3758 let limits = if tok == token::DotDot {
3759 RangeLimits::HalfOpen
3764 let r = self.mk_range(None, opt_end, limits)?;
3765 Ok(self.mk_expr(lo.to(hi), r, attrs))
3768 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3769 if self.token.can_begin_expr() {
3770 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3771 if self.token == token::OpenDelim(token::Brace) {
3772 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3780 /// Parses an `if` or `if let` expression (`if` token already eaten).
3781 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3782 if self.check_keyword(keywords::Let) {
3783 return self.parse_if_let_expr(attrs);
3785 let lo = self.prev_span;
3786 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3788 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3789 // verify that the last statement is either an implicit return (no `;`) or an explicit
3790 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3791 // the dead code lint.
3792 if self.eat_keyword(keywords::Else) || !cond.returns() {
3793 let sp = self.sess.source_map().next_point(lo);
3794 let mut err = self.diagnostic()
3795 .struct_span_err(sp, "missing condition for `if` statemement");
3796 err.span_label(sp, "expected if condition here");
3799 let not_block = self.token != token::OpenDelim(token::Brace);
3800 let thn = self.parse_block().map_err(|mut err| {
3802 err.span_label(lo, "this `if` statement has a condition, but no block");
3806 let mut els: Option<P<Expr>> = None;
3807 let mut hi = thn.span;
3808 if self.eat_keyword(keywords::Else) {
3809 let elexpr = self.parse_else_expr()?;
3813 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3816 /// Parses an `if let` expression (`if` token already eaten).
3817 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3818 -> PResult<'a, P<Expr>> {
3819 let lo = self.prev_span;
3820 self.expect_keyword(keywords::Let)?;
3821 let pats = self.parse_pats()?;
3822 self.expect(&token::Eq)?;
3823 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3824 let thn = self.parse_block()?;
3825 let (hi, els) = if self.eat_keyword(keywords::Else) {
3826 let expr = self.parse_else_expr()?;
3827 (expr.span, Some(expr))
3831 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3834 /// Parses `move |args| expr`.
3835 fn parse_lambda_expr(&mut self,
3836 attrs: ThinVec<Attribute>)
3837 -> PResult<'a, P<Expr>>
3840 let movability = if self.eat_keyword(keywords::Static) {
3845 let asyncness = if self.span.rust_2018() {
3846 self.parse_asyncness()
3850 let capture_clause = if self.eat_keyword(keywords::Move) {
3855 let decl = self.parse_fn_block_decl()?;
3856 let decl_hi = self.prev_span;
3857 let body = match decl.output {
3858 FunctionRetTy::Default(_) => {
3859 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3860 self.parse_expr_res(restrictions, None)?
3863 // If an explicit return type is given, require a
3864 // block to appear (RFC 968).
3865 let body_lo = self.span;
3866 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3872 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3876 // `else` token already eaten
3877 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3878 if self.eat_keyword(keywords::If) {
3879 return self.parse_if_expr(ThinVec::new());
3881 let blk = self.parse_block()?;
3882 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3886 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3887 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3889 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3890 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3892 let pat = self.parse_top_level_pat()?;
3893 if !self.eat_keyword(keywords::In) {
3894 let in_span = self.prev_span.between(self.span);
3895 let mut err = self.sess.span_diagnostic
3896 .struct_span_err(in_span, "missing `in` in `for` loop");
3897 err.span_suggestion_short(
3898 in_span, "try adding `in` here", " in ".into(),
3899 // has been misleading, at least in the past (closed Issue #48492)
3900 Applicability::MaybeIncorrect
3904 let in_span = self.prev_span;
3905 if self.eat_keyword(keywords::In) {
3906 // a common typo: `for _ in in bar {}`
3907 let mut err = self.sess.span_diagnostic.struct_span_err(
3909 "expected iterable, found keyword `in`",
3911 err.span_suggestion_short(
3912 in_span.until(self.prev_span),
3913 "remove the duplicated `in`",
3915 Applicability::MachineApplicable,
3917 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3918 err.note("for more information on the status of emplacement syntax, see <\
3919 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3922 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3923 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3924 attrs.extend(iattrs);
3926 let hi = self.prev_span;
3927 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3930 /// Parses a `while` or `while let` expression (`while` token already eaten).
3931 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3933 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3934 if self.token.is_keyword(keywords::Let) {
3935 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3937 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3938 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3939 attrs.extend(iattrs);
3940 let span = span_lo.to(body.span);
3941 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3944 /// Parses a `while let` expression (`while` token already eaten).
3945 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3947 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3948 self.expect_keyword(keywords::Let)?;
3949 let pats = self.parse_pats()?;
3950 self.expect(&token::Eq)?;
3951 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3952 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3953 attrs.extend(iattrs);
3954 let span = span_lo.to(body.span);
3955 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3958 // parse `loop {...}`, `loop` token already eaten
3959 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3961 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3962 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3963 attrs.extend(iattrs);
3964 let span = span_lo.to(body.span);
3965 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3968 /// Parses an `async move {...}` expression.
3969 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3970 -> PResult<'a, P<Expr>>
3972 let span_lo = self.span;
3973 self.expect_keyword(keywords::Async)?;
3974 let capture_clause = if self.eat_keyword(keywords::Move) {
3979 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3980 attrs.extend(iattrs);
3982 span_lo.to(body.span),
3983 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3986 /// Parses a `try {...}` expression (`try` token already eaten).
3987 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3988 -> PResult<'a, P<Expr>>
3990 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3991 attrs.extend(iattrs);
3992 if self.eat_keyword(keywords::Catch) {
3993 let mut error = self.struct_span_err(self.prev_span,
3994 "keyword `catch` cannot follow a `try` block");
3995 error.help("try using `match` on the result of the `try` block instead");
3999 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4003 // `match` token already eaten
4004 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4005 let match_span = self.prev_span;
4006 let lo = self.prev_span;
4007 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4009 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4010 if self.token == token::Token::Semi {
4011 e.span_suggestion_short(
4013 "try removing this `match`",
4015 Applicability::MaybeIncorrect // speculative
4020 attrs.extend(self.parse_inner_attributes()?);
4022 let mut arms: Vec<Arm> = Vec::new();
4023 while self.token != token::CloseDelim(token::Brace) {
4024 match self.parse_arm() {
4025 Ok(arm) => arms.push(arm),
4027 // Recover by skipping to the end of the block.
4029 self.recover_stmt();
4030 let span = lo.to(self.span);
4031 if self.token == token::CloseDelim(token::Brace) {
4034 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4040 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4043 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4044 let attrs = self.parse_outer_attributes()?;
4045 let pats = self.parse_pats()?;
4046 let guard = if self.eat_keyword(keywords::If) {
4047 Some(Guard::If(self.parse_expr()?))
4051 let arrow_span = self.span;
4052 self.expect(&token::FatArrow)?;
4053 let arm_start_span = self.span;
4055 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4056 .map_err(|mut err| {
4057 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4061 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4062 && self.token != token::CloseDelim(token::Brace);
4065 let cm = self.sess.source_map();
4066 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4067 .map_err(|mut err| {
4068 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4069 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4070 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4071 && expr_lines.lines.len() == 2
4072 && self.token == token::FatArrow => {
4073 // We check whether there's any trailing code in the parse span,
4074 // if there isn't, we very likely have the following:
4077 // | -- - missing comma
4083 // | parsed until here as `"y" & X`
4084 err.span_suggestion_short(
4085 cm.next_point(arm_start_span),
4086 "missing a comma here to end this `match` arm",
4088 Applicability::MachineApplicable
4092 err.span_label(arrow_span,
4093 "while parsing the `match` arm starting here");
4099 self.eat(&token::Comma);
4110 /// Parses an expression.
4112 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4113 self.parse_expr_res(Restrictions::empty(), None)
4116 /// Evaluates the closure with restrictions in place.
4118 /// Afters the closure is evaluated, restrictions are reset.
4119 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4120 where F: FnOnce(&mut Self) -> T
4122 let old = self.restrictions;
4123 self.restrictions = r;
4125 self.restrictions = old;
4130 /// Parses an expression, subject to the given restrictions.
4132 fn parse_expr_res(&mut self, r: Restrictions,
4133 already_parsed_attrs: Option<ThinVec<Attribute>>)
4134 -> PResult<'a, P<Expr>> {
4135 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4138 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4139 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4140 if self.eat(&token::Eq) {
4141 Ok(Some(self.parse_expr()?))
4143 Ok(Some(self.parse_expr()?))
4149 /// Parses patterns, separated by '|' s.
4150 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4151 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4152 self.eat(&token::BinOp(token::Or));
4154 let mut pats = Vec::new();
4156 pats.push(self.parse_top_level_pat()?);
4158 if self.token == token::OrOr {
4159 let mut err = self.struct_span_err(self.span,
4160 "unexpected token `||` after pattern");
4161 err.span_suggestion(
4163 "use a single `|` to specify multiple patterns",
4165 Applicability::MachineApplicable
4169 } else if self.eat(&token::BinOp(token::Or)) {
4170 // This is a No-op. Continue the loop to parse the next
4178 // Parses a parenthesized list of patterns like
4179 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4180 // - a vector of the patterns that were parsed
4181 // - an option indicating the index of the `..` element
4182 // - a boolean indicating whether a trailing comma was present.
4183 // Trailing commas are significant because (p) and (p,) are different patterns.
4184 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4185 self.expect(&token::OpenDelim(token::Paren))?;
4186 let result = match self.parse_pat_list() {
4187 Ok(result) => result,
4188 Err(mut err) => { // recover from parse error in tuple pattern list
4190 self.consume_block(token::Paren);
4191 return Ok((vec![], Some(0), false));
4194 self.expect(&token::CloseDelim(token::Paren))?;
4198 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4199 let mut fields = Vec::new();
4200 let mut ddpos = None;
4201 let mut prev_dd_sp = None;
4202 let mut trailing_comma = false;
4204 if self.eat(&token::DotDot) {
4205 if ddpos.is_none() {
4206 ddpos = Some(fields.len());
4207 prev_dd_sp = Some(self.prev_span);
4209 // Emit a friendly error, ignore `..` and continue parsing
4210 let mut err = self.struct_span_err(
4212 "`..` can only be used once per tuple or tuple struct pattern",
4214 err.span_label(self.prev_span, "can only be used once per pattern");
4215 if let Some(sp) = prev_dd_sp {
4216 err.span_label(sp, "previously present here");
4220 } else if !self.check(&token::CloseDelim(token::Paren)) {
4221 fields.push(self.parse_pat(None)?);
4226 trailing_comma = self.eat(&token::Comma);
4227 if !trailing_comma {
4232 if ddpos == Some(fields.len()) && trailing_comma {
4233 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4234 let msg = "trailing comma is not permitted after `..`";
4235 self.struct_span_err(self.prev_span, msg)
4236 .span_label(self.prev_span, msg)
4240 Ok((fields, ddpos, trailing_comma))
4243 fn parse_pat_vec_elements(
4245 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4246 let mut before = Vec::new();
4247 let mut slice = None;
4248 let mut after = Vec::new();
4249 let mut first = true;
4250 let mut before_slice = true;
4252 while self.token != token::CloseDelim(token::Bracket) {
4256 self.expect(&token::Comma)?;
4258 if self.token == token::CloseDelim(token::Bracket)
4259 && (before_slice || !after.is_empty()) {
4265 if self.eat(&token::DotDot) {
4267 if self.check(&token::Comma) ||
4268 self.check(&token::CloseDelim(token::Bracket)) {
4269 slice = Some(P(Pat {
4270 id: ast::DUMMY_NODE_ID,
4271 node: PatKind::Wild,
4272 span: self.prev_span,
4274 before_slice = false;
4280 let subpat = self.parse_pat(None)?;
4281 if before_slice && self.eat(&token::DotDot) {
4282 slice = Some(subpat);
4283 before_slice = false;
4284 } else if before_slice {
4285 before.push(subpat);
4291 Ok((before, slice, after))
4297 attrs: Vec<Attribute>
4298 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4299 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4301 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4302 // Parsing a pattern of the form "fieldname: pat"
4303 let fieldname = self.parse_field_name()?;
4305 let pat = self.parse_pat(None)?;
4307 (pat, fieldname, false)
4309 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4310 let is_box = self.eat_keyword(keywords::Box);
4311 let boxed_span = self.span;
4312 let is_ref = self.eat_keyword(keywords::Ref);
4313 let is_mut = self.eat_keyword(keywords::Mut);
4314 let fieldname = self.parse_ident()?;
4315 hi = self.prev_span;
4317 let bind_type = match (is_ref, is_mut) {
4318 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4319 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4320 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4321 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4323 let fieldpat = P(Pat {
4324 id: ast::DUMMY_NODE_ID,
4325 node: PatKind::Ident(bind_type, fieldname, None),
4326 span: boxed_span.to(hi),
4329 let subpat = if is_box {
4331 id: ast::DUMMY_NODE_ID,
4332 node: PatKind::Box(fieldpat),
4338 (subpat, fieldname, true)
4341 Ok(source_map::Spanned {
4343 node: ast::FieldPat {
4347 attrs: attrs.into(),
4352 /// Parses the fields of a struct-like pattern.
4353 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4354 let mut fields = Vec::new();
4355 let mut etc = false;
4356 let mut ate_comma = true;
4357 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4358 let mut etc_span = None;
4360 while self.token != token::CloseDelim(token::Brace) {
4361 let attrs = self.parse_outer_attributes()?;
4364 // check that a comma comes after every field
4366 let err = self.struct_span_err(self.prev_span, "expected `,`");
4367 if let Some(mut delayed) = delayed_err {
4374 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4376 let mut etc_sp = self.span;
4378 if self.token == token::DotDotDot { // Issue #46718
4379 // Accept `...` as if it were `..` to avoid further errors
4380 let mut err = self.struct_span_err(self.span,
4381 "expected field pattern, found `...`");
4382 err.span_suggestion(
4384 "to omit remaining fields, use one fewer `.`",
4386 Applicability::MachineApplicable
4390 self.bump(); // `..` || `...`
4392 if self.token == token::CloseDelim(token::Brace) {
4393 etc_span = Some(etc_sp);
4396 let token_str = self.this_token_descr();
4397 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4399 err.span_label(self.span, "expected `}`");
4400 let mut comma_sp = None;
4401 if self.token == token::Comma { // Issue #49257
4402 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4403 err.span_label(etc_sp,
4404 "`..` must be at the end and cannot have a trailing comma");
4405 comma_sp = Some(self.span);
4410 etc_span = Some(etc_sp.until(self.span));
4411 if self.token == token::CloseDelim(token::Brace) {
4412 // If the struct looks otherwise well formed, recover and continue.
4413 if let Some(sp) = comma_sp {
4414 err.span_suggestion_short(
4416 "remove this comma",
4418 Applicability::MachineApplicable,
4423 } else if self.token.is_ident() && ate_comma {
4424 // Accept fields coming after `..,`.
4425 // This way we avoid "pattern missing fields" errors afterwards.
4426 // We delay this error until the end in order to have a span for a
4428 if let Some(mut delayed_err) = delayed_err {
4432 delayed_err = Some(err);
4435 if let Some(mut err) = delayed_err {
4442 fields.push(match self.parse_pat_field(lo, attrs) {
4445 if let Some(mut delayed_err) = delayed_err {
4451 ate_comma = self.eat(&token::Comma);
4454 if let Some(mut err) = delayed_err {
4455 if let Some(etc_span) = etc_span {
4456 err.multipart_suggestion(
4457 "move the `..` to the end of the field list",
4459 (etc_span, String::new()),
4460 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4462 Applicability::MachineApplicable,
4467 return Ok((fields, etc));
4470 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4471 if self.token.is_path_start() {
4473 let (qself, path) = if self.eat_lt() {
4474 // Parse a qualified path
4475 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4478 // Parse an unqualified path
4479 (None, self.parse_path(PathStyle::Expr)?)
4481 let hi = self.prev_span;
4482 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4484 self.parse_literal_maybe_minus()
4488 // helper function to decide whether to parse as ident binding or to try to do
4489 // something more complex like range patterns
4490 fn parse_as_ident(&mut self) -> bool {
4491 self.look_ahead(1, |t| match *t {
4492 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4493 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4494 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4495 // range pattern branch
4496 token::DotDot => None,
4498 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4499 token::Comma | token::CloseDelim(token::Bracket) => true,
4504 /// A wrapper around `parse_pat` with some special error handling for the
4505 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4506 /// to subpatterns within such).
4507 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4508 let pat = self.parse_pat(None)?;
4509 if self.token == token::Comma {
4510 // An unexpected comma after a top-level pattern is a clue that the
4511 // user (perhaps more accustomed to some other language) forgot the
4512 // parentheses in what should have been a tuple pattern; return a
4513 // suggestion-enhanced error here rather than choking on the comma
4515 let comma_span = self.span;
4517 if let Err(mut err) = self.parse_pat_list() {
4518 // We didn't expect this to work anyway; we just wanted
4519 // to advance to the end of the comma-sequence so we know
4520 // the span to suggest parenthesizing
4523 let seq_span = pat.span.to(self.prev_span);
4524 let mut err = self.struct_span_err(comma_span,
4525 "unexpected `,` in pattern");
4526 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4527 err.span_suggestion(
4529 "try adding parentheses to match on a tuple..",
4530 format!("({})", seq_snippet),
4531 Applicability::MachineApplicable
4534 "..or a vertical bar to match on multiple alternatives",
4535 format!("{}", seq_snippet.replace(",", " |")),
4536 Applicability::MachineApplicable
4544 /// Parses a pattern.
4545 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4546 self.parse_pat_with_range_pat(true, expected)
4549 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4551 fn parse_pat_with_range_pat(
4553 allow_range_pat: bool,
4554 expected: Option<&'static str>,
4555 ) -> PResult<'a, P<Pat>> {
4556 maybe_recover_from_interpolated_ty_qpath!(self, true);
4557 maybe_whole!(self, NtPat, |x| x);
4562 token::BinOp(token::And) | token::AndAnd => {
4563 // Parse &pat / &mut pat
4565 let mutbl = self.parse_mutability();
4566 if let token::Lifetime(ident) = self.token {
4567 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4569 err.span_label(self.span, "unexpected lifetime");
4572 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4573 pat = PatKind::Ref(subpat, mutbl);
4575 token::OpenDelim(token::Paren) => {
4576 // Parse (pat,pat,pat,...) as tuple pattern
4577 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4578 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4579 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4581 PatKind::Tuple(fields, ddpos)
4584 token::OpenDelim(token::Bracket) => {
4585 // Parse [pat,pat,...] as slice pattern
4587 let (before, slice, after) = self.parse_pat_vec_elements()?;
4588 self.expect(&token::CloseDelim(token::Bracket))?;
4589 pat = PatKind::Slice(before, slice, after);
4591 // At this point, token != &, &&, (, [
4592 _ => if self.eat_keyword(keywords::Underscore) {
4594 pat = PatKind::Wild;
4595 } else if self.eat_keyword(keywords::Mut) {
4596 // Parse mut ident @ pat / mut ref ident @ pat
4597 let mutref_span = self.prev_span.to(self.span);
4598 let binding_mode = if self.eat_keyword(keywords::Ref) {
4600 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4603 "try switching the order",
4605 Applicability::MachineApplicable
4607 BindingMode::ByRef(Mutability::Mutable)
4609 BindingMode::ByValue(Mutability::Mutable)
4611 pat = self.parse_pat_ident(binding_mode)?;
4612 } else if self.eat_keyword(keywords::Ref) {
4613 // Parse ref ident @ pat / ref mut ident @ pat
4614 let mutbl = self.parse_mutability();
4615 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4616 } else if self.eat_keyword(keywords::Box) {
4618 let subpat = self.parse_pat_with_range_pat(false, None)?;
4619 pat = PatKind::Box(subpat);
4620 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4621 self.parse_as_ident() {
4622 // Parse ident @ pat
4623 // This can give false positives and parse nullary enums,
4624 // they are dealt with later in resolve
4625 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4626 pat = self.parse_pat_ident(binding_mode)?;
4627 } else if self.token.is_path_start() {
4628 // Parse pattern starting with a path
4629 let (qself, path) = if self.eat_lt() {
4630 // Parse a qualified path
4631 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4634 // Parse an unqualified path
4635 (None, self.parse_path(PathStyle::Expr)?)
4638 token::Not if qself.is_none() => {
4639 // Parse macro invocation
4641 let (delim, tts) = self.expect_delimited_token_tree()?;
4642 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4643 pat = PatKind::Mac(mac);
4645 token::DotDotDot | token::DotDotEq | token::DotDot => {
4646 let end_kind = match self.token {
4647 token::DotDot => RangeEnd::Excluded,
4648 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4649 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4650 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4653 let op_span = self.span;
4655 let span = lo.to(self.prev_span);
4656 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4658 let end = self.parse_pat_range_end()?;
4659 let op = Spanned { span: op_span, node: end_kind };
4660 pat = PatKind::Range(begin, end, op);
4662 token::OpenDelim(token::Brace) => {
4663 if qself.is_some() {
4664 let msg = "unexpected `{` after qualified path";
4665 let mut err = self.fatal(msg);
4666 err.span_label(self.span, msg);
4669 // Parse struct pattern
4671 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4673 self.recover_stmt();
4677 pat = PatKind::Struct(path, fields, etc);
4679 token::OpenDelim(token::Paren) => {
4680 if qself.is_some() {
4681 let msg = "unexpected `(` after qualified path";
4682 let mut err = self.fatal(msg);
4683 err.span_label(self.span, msg);
4686 // Parse tuple struct or enum pattern
4687 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4688 pat = PatKind::TupleStruct(path, fields, ddpos)
4690 _ => pat = PatKind::Path(qself, path),
4693 // Try to parse everything else as literal with optional minus
4694 match self.parse_literal_maybe_minus() {
4696 let op_span = self.span;
4697 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4698 self.check(&token::DotDotDot) {
4699 let end_kind = if self.eat(&token::DotDotDot) {
4700 RangeEnd::Included(RangeSyntax::DotDotDot)
4701 } else if self.eat(&token::DotDotEq) {
4702 RangeEnd::Included(RangeSyntax::DotDotEq)
4703 } else if self.eat(&token::DotDot) {
4706 panic!("impossible case: we already matched \
4707 on a range-operator token")
4709 let end = self.parse_pat_range_end()?;
4710 let op = Spanned { span: op_span, node: end_kind };
4711 pat = PatKind::Range(begin, end, op);
4713 pat = PatKind::Lit(begin);
4717 self.cancel(&mut err);
4718 let expected = expected.unwrap_or("pattern");
4720 "expected {}, found {}",
4722 self.this_token_descr(),
4724 let mut err = self.fatal(&msg);
4725 err.span_label(self.span, format!("expected {}", expected));
4726 let sp = self.sess.source_map().start_point(self.span);
4727 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4728 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4736 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4737 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4739 if !allow_range_pat {
4742 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4744 PatKind::Range(..) => {
4745 let mut err = self.struct_span_err(
4747 "the range pattern here has ambiguous interpretation",
4749 err.span_suggestion(
4751 "add parentheses to clarify the precedence",
4752 format!("({})", pprust::pat_to_string(&pat)),
4753 // "ambiguous interpretation" implies that we have to be guessing
4754 Applicability::MaybeIncorrect
4765 /// Parses `ident` or `ident @ pat`.
4766 /// used by the copy foo and ref foo patterns to give a good
4767 /// error message when parsing mistakes like `ref foo(a, b)`.
4768 fn parse_pat_ident(&mut self,
4769 binding_mode: ast::BindingMode)
4770 -> PResult<'a, PatKind> {
4771 let ident = self.parse_ident()?;
4772 let sub = if self.eat(&token::At) {
4773 Some(self.parse_pat(Some("binding pattern"))?)
4778 // just to be friendly, if they write something like
4780 // we end up here with ( as the current token. This shortly
4781 // leads to a parse error. Note that if there is no explicit
4782 // binding mode then we do not end up here, because the lookahead
4783 // will direct us over to parse_enum_variant()
4784 if self.token == token::OpenDelim(token::Paren) {
4785 return Err(self.span_fatal(
4787 "expected identifier, found enum pattern"))
4790 Ok(PatKind::Ident(binding_mode, ident, sub))
4793 /// Parses a local variable declaration.
4794 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4795 let lo = self.prev_span;
4796 let pat = self.parse_top_level_pat()?;
4798 let (err, ty) = if self.eat(&token::Colon) {
4799 // Save the state of the parser before parsing type normally, in case there is a `:`
4800 // instead of an `=` typo.
4801 let parser_snapshot_before_type = self.clone();
4802 let colon_sp = self.prev_span;
4803 match self.parse_ty() {
4804 Ok(ty) => (None, Some(ty)),
4806 // Rewind to before attempting to parse the type and continue parsing
4807 let parser_snapshot_after_type = self.clone();
4808 mem::replace(self, parser_snapshot_before_type);
4810 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4811 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4812 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4818 let init = match (self.parse_initializer(err.is_some()), err) {
4819 (Ok(init), None) => { // init parsed, ty parsed
4822 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4823 // Could parse the type as if it were the initializer, it is likely there was a
4824 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4825 err.span_suggestion_short(
4827 "use `=` if you meant to assign",
4829 Applicability::MachineApplicable
4832 // As this was parsed successfully, continue as if the code has been fixed for the
4833 // rest of the file. It will still fail due to the emitted error, but we avoid
4837 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4839 // Couldn't parse the type nor the initializer, only raise the type error and
4840 // return to the parser state before parsing the type as the initializer.
4841 // let x: <parse_error>;
4842 mem::replace(self, snapshot);
4845 (Err(err), None) => { // init error, ty parsed
4846 // Couldn't parse the initializer and we're not attempting to recover a failed
4847 // parse of the type, return the error.
4851 let hi = if self.token == token::Semi {
4860 id: ast::DUMMY_NODE_ID,
4863 source: LocalSource::Normal,
4867 /// Parses a structure field.
4868 fn parse_name_and_ty(&mut self,
4871 attrs: Vec<Attribute>)
4872 -> PResult<'a, StructField> {
4873 let name = self.parse_ident()?;
4874 self.expect(&token::Colon)?;
4875 let ty = self.parse_ty()?;
4877 span: lo.to(self.prev_span),
4880 id: ast::DUMMY_NODE_ID,
4886 /// Emits an expected-item-after-attributes error.
4887 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4888 let message = match attrs.last() {
4889 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4890 _ => "expected item after attributes",
4893 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4894 if attrs.last().unwrap().is_sugared_doc {
4895 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4900 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4901 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4902 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4903 Ok(self.parse_stmt_(true))
4906 // Eat tokens until we can be relatively sure we reached the end of the
4907 // statement. This is something of a best-effort heuristic.
4909 // We terminate when we find an unmatched `}` (without consuming it).
4910 fn recover_stmt(&mut self) {
4911 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4914 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4915 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4916 // approximate - it can mean we break too early due to macros, but that
4917 // should only lead to sub-optimal recovery, not inaccurate parsing).
4919 // If `break_on_block` is `Break`, then we will stop consuming tokens
4920 // after finding (and consuming) a brace-delimited block.
4921 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4922 let mut brace_depth = 0;
4923 let mut bracket_depth = 0;
4924 let mut in_block = false;
4925 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4926 break_on_semi, break_on_block);
4928 debug!("recover_stmt_ loop {:?}", self.token);
4930 token::OpenDelim(token::DelimToken::Brace) => {
4933 if break_on_block == BlockMode::Break &&
4935 bracket_depth == 0 {
4939 token::OpenDelim(token::DelimToken::Bracket) => {
4943 token::CloseDelim(token::DelimToken::Brace) => {
4944 if brace_depth == 0 {
4945 debug!("recover_stmt_ return - close delim {:?}", self.token);
4950 if in_block && bracket_depth == 0 && brace_depth == 0 {
4951 debug!("recover_stmt_ return - block end {:?}", self.token);
4955 token::CloseDelim(token::DelimToken::Bracket) => {
4957 if bracket_depth < 0 {
4963 debug!("recover_stmt_ return - Eof");
4968 if break_on_semi == SemiColonMode::Break &&
4970 bracket_depth == 0 {
4971 debug!("recover_stmt_ return - Semi");
4976 if break_on_semi == SemiColonMode::Comma &&
4978 bracket_depth == 0 {
4979 debug!("recover_stmt_ return - Semi");
4992 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4993 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4995 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5000 fn is_async_block(&self) -> bool {
5001 self.token.is_keyword(keywords::Async) &&
5004 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5005 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5007 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5012 fn is_async_fn(&self) -> bool {
5013 self.token.is_keyword(keywords::Async) &&
5014 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5017 fn is_do_catch_block(&self) -> bool {
5018 self.token.is_keyword(keywords::Do) &&
5019 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5020 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5021 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5024 fn is_try_block(&self) -> bool {
5025 self.token.is_keyword(keywords::Try) &&
5026 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5027 self.span.rust_2018() &&
5028 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5029 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5032 fn is_union_item(&self) -> bool {
5033 self.token.is_keyword(keywords::Union) &&
5034 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5037 fn is_crate_vis(&self) -> bool {
5038 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5041 fn is_existential_type_decl(&self) -> bool {
5042 self.token.is_keyword(keywords::Existential) &&
5043 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5046 fn is_auto_trait_item(&self) -> bool {
5048 (self.token.is_keyword(keywords::Auto)
5049 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5050 || // unsafe auto trait
5051 (self.token.is_keyword(keywords::Unsafe) &&
5052 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5053 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5056 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5057 -> PResult<'a, Option<P<Item>>> {
5058 let token_lo = self.span;
5059 let (ident, def) = match self.token {
5060 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5062 let ident = self.parse_ident()?;
5063 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5064 match self.parse_token_tree() {
5065 TokenTree::Delimited(_, _, tts) => tts,
5066 _ => unreachable!(),
5068 } else if self.check(&token::OpenDelim(token::Paren)) {
5069 let args = self.parse_token_tree();
5070 let body = if self.check(&token::OpenDelim(token::Brace)) {
5071 self.parse_token_tree()
5076 TokenStream::new(vec![
5078 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5086 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5088 token::Ident(ident, _) if ident.name == sym::macro_rules &&
5089 self.look_ahead(1, |t| *t == token::Not) => {
5090 let prev_span = self.prev_span;
5091 self.complain_if_pub_macro(&vis.node, prev_span);
5095 let ident = self.parse_ident()?;
5096 let (delim, tokens) = self.expect_delimited_token_tree()?;
5097 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5098 self.report_invalid_macro_expansion_item();
5101 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5103 _ => return Ok(None),
5106 let span = lo.to(self.prev_span);
5107 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5110 fn parse_stmt_without_recovery(&mut self,
5111 macro_legacy_warnings: bool)
5112 -> PResult<'a, Option<Stmt>> {
5113 maybe_whole!(self, NtStmt, |x| Some(x));
5115 let attrs = self.parse_outer_attributes()?;
5118 Ok(Some(if self.eat_keyword(keywords::Let) {
5120 id: ast::DUMMY_NODE_ID,
5121 node: StmtKind::Local(self.parse_local(attrs.into())?),
5122 span: lo.to(self.prev_span),
5124 } else if let Some(macro_def) = self.eat_macro_def(
5126 &source_map::respan(lo, VisibilityKind::Inherited),
5130 id: ast::DUMMY_NODE_ID,
5131 node: StmtKind::Item(macro_def),
5132 span: lo.to(self.prev_span),
5134 // Starts like a simple path, being careful to avoid contextual keywords
5135 // such as a union items, item with `crate` visibility or auto trait items.
5136 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5137 // like a path (1 token), but it fact not a path.
5138 // `union::b::c` - path, `union U { ... }` - not a path.
5139 // `crate::b::c` - path, `crate struct S;` - not a path.
5140 } else if self.token.is_path_start() &&
5141 !self.token.is_qpath_start() &&
5142 !self.is_union_item() &&
5143 !self.is_crate_vis() &&
5144 !self.is_existential_type_decl() &&
5145 !self.is_auto_trait_item() &&
5146 !self.is_async_fn() {
5147 let pth = self.parse_path(PathStyle::Expr)?;
5149 if !self.eat(&token::Not) {
5150 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5151 self.parse_struct_expr(lo, pth, ThinVec::new())?
5153 let hi = self.prev_span;
5154 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5157 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5158 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5159 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5162 return Ok(Some(Stmt {
5163 id: ast::DUMMY_NODE_ID,
5164 node: StmtKind::Expr(expr),
5165 span: lo.to(self.prev_span),
5169 // it's a macro invocation
5170 let id = match self.token {
5171 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5172 _ => self.parse_ident()?,
5175 // check that we're pointing at delimiters (need to check
5176 // again after the `if`, because of `parse_ident`
5177 // consuming more tokens).
5179 token::OpenDelim(_) => {}
5181 // we only expect an ident if we didn't parse one
5183 let ident_str = if id.name == keywords::Invalid.name() {
5188 let tok_str = self.this_token_descr();
5189 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5192 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5197 let (delim, tts) = self.expect_delimited_token_tree()?;
5198 let hi = self.prev_span;
5200 let style = if delim == MacDelimiter::Brace {
5201 MacStmtStyle::Braces
5203 MacStmtStyle::NoBraces
5206 if id.name == keywords::Invalid.name() {
5207 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5208 let node = if delim == MacDelimiter::Brace ||
5209 self.token == token::Semi || self.token == token::Eof {
5210 StmtKind::Mac(P((mac, style, attrs.into())))
5212 // We used to incorrectly stop parsing macro-expanded statements here.
5213 // If the next token will be an error anyway but could have parsed with the
5214 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5215 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5216 // These can continue an expression, so we can't stop parsing and warn.
5217 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5218 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5219 token::BinOp(token::And) | token::BinOp(token::Or) |
5220 token::AndAnd | token::OrOr |
5221 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5224 self.warn_missing_semicolon();
5225 StmtKind::Mac(P((mac, style, attrs.into())))
5227 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5228 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5229 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5230 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5234 id: ast::DUMMY_NODE_ID,
5239 // if it has a special ident, it's definitely an item
5241 // Require a semicolon or braces.
5242 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5243 self.report_invalid_macro_expansion_item();
5245 let span = lo.to(hi);
5247 id: ast::DUMMY_NODE_ID,
5249 node: StmtKind::Item({
5251 span, id /*id is good here*/,
5252 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5253 respan(lo, VisibilityKind::Inherited),
5259 // FIXME: Bad copy of attrs
5260 let old_directory_ownership =
5261 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5262 let item = self.parse_item_(attrs.clone(), false, true)?;
5263 self.directory.ownership = old_directory_ownership;
5267 id: ast::DUMMY_NODE_ID,
5268 span: lo.to(i.span),
5269 node: StmtKind::Item(i),
5272 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5273 if !attrs.is_empty() {
5274 if s.prev_token_kind == PrevTokenKind::DocComment {
5275 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5276 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5277 s.span_err(s.span, "expected statement after outer attribute");
5282 // Do not attempt to parse an expression if we're done here.
5283 if self.token == token::Semi {
5284 unused_attrs(&attrs, self);
5289 if self.token == token::CloseDelim(token::Brace) {
5290 unused_attrs(&attrs, self);
5294 // Remainder are line-expr stmts.
5295 let e = self.parse_expr_res(
5296 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5298 id: ast::DUMMY_NODE_ID,
5299 span: lo.to(e.span),
5300 node: StmtKind::Expr(e),
5307 /// Checks if this expression is a successfully parsed statement.
5308 fn expr_is_complete(&self, e: &Expr) -> bool {
5309 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5310 !classify::expr_requires_semi_to_be_stmt(e)
5313 /// Parses a block. No inner attributes are allowed.
5314 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5315 maybe_whole!(self, NtBlock, |x| x);
5319 if !self.eat(&token::OpenDelim(token::Brace)) {
5321 let tok = self.this_token_descr();
5322 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5323 let do_not_suggest_help =
5324 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5326 if self.token.is_ident_named("and") {
5327 e.span_suggestion_short(
5329 "use `&&` instead of `and` for the boolean operator",
5331 Applicability::MaybeIncorrect,
5334 if self.token.is_ident_named("or") {
5335 e.span_suggestion_short(
5337 "use `||` instead of `or` for the boolean operator",
5339 Applicability::MaybeIncorrect,
5343 // Check to see if the user has written something like
5348 // Which is valid in other languages, but not Rust.
5349 match self.parse_stmt_without_recovery(false) {
5351 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5352 || do_not_suggest_help {
5353 // if the next token is an open brace (e.g., `if a b {`), the place-
5354 // inside-a-block suggestion would be more likely wrong than right
5355 e.span_label(sp, "expected `{`");
5358 let mut stmt_span = stmt.span;
5359 // expand the span to include the semicolon, if it exists
5360 if self.eat(&token::Semi) {
5361 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5363 let sugg = pprust::to_string(|s| {
5364 use crate::print::pprust::{PrintState, INDENT_UNIT};
5365 s.ibox(INDENT_UNIT)?;
5367 s.print_stmt(&stmt)?;
5368 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5372 "try placing this code inside a block",
5374 // speculative, has been misleading in the past (closed Issue #46836)
5375 Applicability::MaybeIncorrect
5379 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5380 self.cancel(&mut e);
5384 e.span_label(sp, "expected `{`");
5388 self.parse_block_tail(lo, BlockCheckMode::Default)
5391 /// Parses a block. Inner attributes are allowed.
5392 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5393 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5396 self.expect(&token::OpenDelim(token::Brace))?;
5397 Ok((self.parse_inner_attributes()?,
5398 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5401 /// Parses the rest of a block expression or function body.
5402 /// Precondition: already parsed the '{'.
5403 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5404 let mut stmts = vec![];
5405 while !self.eat(&token::CloseDelim(token::Brace)) {
5406 let stmt = match self.parse_full_stmt(false) {
5409 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5411 id: ast::DUMMY_NODE_ID,
5412 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5418 if let Some(stmt) = stmt {
5420 } else if self.token == token::Eof {
5423 // Found only `;` or `}`.
5429 id: ast::DUMMY_NODE_ID,
5431 span: lo.to(self.prev_span),
5435 /// Parses a statement, including the trailing semicolon.
5436 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5437 // skip looking for a trailing semicolon when we have an interpolated statement
5438 maybe_whole!(self, NtStmt, |x| Some(x));
5440 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5442 None => return Ok(None),
5446 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5447 // expression without semicolon
5448 if classify::expr_requires_semi_to_be_stmt(expr) {
5449 // Just check for errors and recover; do not eat semicolon yet.
5451 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5454 self.recover_stmt();
5458 StmtKind::Local(..) => {
5459 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5460 if macro_legacy_warnings && self.token != token::Semi {
5461 self.warn_missing_semicolon();
5463 self.expect_one_of(&[], &[token::Semi])?;
5469 if self.eat(&token::Semi) {
5470 stmt = stmt.add_trailing_semicolon();
5473 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5477 fn warn_missing_semicolon(&self) {
5478 self.diagnostic().struct_span_warn(self.span, {
5479 &format!("expected `;`, found {}", self.this_token_descr())
5481 "This was erroneously allowed and will become a hard error in a future release"
5485 fn err_dotdotdot_syntax(&self, span: Span) {
5486 self.diagnostic().struct_span_err(span, {
5487 "unexpected token: `...`"
5489 span, "use `..` for an exclusive range", "..".to_owned(),
5490 Applicability::MaybeIncorrect
5492 span, "or `..=` for an inclusive range", "..=".to_owned(),
5493 Applicability::MaybeIncorrect
5497 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5500 /// BOUND = TY_BOUND | LT_BOUND
5501 /// LT_BOUND = LIFETIME (e.g., `'a`)
5502 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5503 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5505 fn parse_generic_bounds_common(&mut self,
5507 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5508 let mut bounds = Vec::new();
5509 let mut negative_bounds = Vec::new();
5510 let mut last_plus_span = None;
5511 let mut was_negative = false;
5513 // This needs to be synchronized with `Token::can_begin_bound`.
5514 let is_bound_start = self.check_path() || self.check_lifetime() ||
5515 self.check(&token::Not) || // used for error reporting only
5516 self.check(&token::Question) ||
5517 self.check_keyword(keywords::For) ||
5518 self.check(&token::OpenDelim(token::Paren));
5521 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5522 let inner_lo = self.span;
5523 let is_negative = self.eat(&token::Not);
5524 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5525 if self.token.is_lifetime() {
5526 if let Some(question_span) = question {
5527 self.span_err(question_span,
5528 "`?` may only modify trait bounds, not lifetime bounds");
5530 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5532 let inner_span = inner_lo.to(self.prev_span);
5533 self.expect(&token::CloseDelim(token::Paren))?;
5534 let mut err = self.struct_span_err(
5535 lo.to(self.prev_span),
5536 "parenthesized lifetime bounds are not supported"
5538 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5539 err.span_suggestion_short(
5540 lo.to(self.prev_span),
5541 "remove the parentheses",
5543 Applicability::MachineApplicable
5549 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5550 let path = self.parse_path(PathStyle::Type)?;
5552 self.expect(&token::CloseDelim(token::Paren))?;
5554 let poly_span = lo.to(self.prev_span);
5556 was_negative = true;
5557 if let Some(sp) = last_plus_span.or(colon_span) {
5558 negative_bounds.push(sp.to(poly_span));
5561 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5562 let modifier = if question.is_some() {
5563 TraitBoundModifier::Maybe
5565 TraitBoundModifier::None
5567 bounds.push(GenericBound::Trait(poly_trait, modifier));
5574 if !allow_plus || !self.eat_plus() {
5577 last_plus_span = Some(self.prev_span);
5581 if !negative_bounds.is_empty() || was_negative {
5582 let plural = negative_bounds.len() > 1;
5583 let last_span = negative_bounds.last().map(|sp| *sp);
5584 let mut err = self.struct_span_err(
5586 "negative trait bounds are not supported",
5588 if let Some(sp) = last_span {
5589 err.span_label(sp, "negative trait bounds are not supported");
5591 if let Some(bound_list) = colon_span {
5592 let bound_list = bound_list.to(self.prev_span);
5593 let mut new_bound_list = String::new();
5594 if !bounds.is_empty() {
5595 let mut snippets = bounds.iter().map(|bound| bound.span())
5596 .map(|span| self.sess.source_map().span_to_snippet(span));
5597 while let Some(Ok(snippet)) = snippets.next() {
5598 new_bound_list.push_str(" + ");
5599 new_bound_list.push_str(&snippet);
5601 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5603 err.span_suggestion_hidden(
5605 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5607 Applicability::MachineApplicable,
5616 crate fn parse_generic_bounds(&mut self,
5617 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5618 self.parse_generic_bounds_common(true, colon_span)
5621 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5624 /// BOUND = LT_BOUND (e.g., `'a`)
5626 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5627 let mut lifetimes = Vec::new();
5628 while self.check_lifetime() {
5629 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5631 if !self.eat_plus() {
5638 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5639 fn parse_ty_param(&mut self,
5640 preceding_attrs: Vec<Attribute>)
5641 -> PResult<'a, GenericParam> {
5642 let ident = self.parse_ident()?;
5644 // Parse optional colon and param bounds.
5645 let bounds = if self.eat(&token::Colon) {
5646 self.parse_generic_bounds(Some(self.prev_span))?
5651 let default = if self.eat(&token::Eq) {
5652 Some(self.parse_ty()?)
5659 id: ast::DUMMY_NODE_ID,
5660 attrs: preceding_attrs.into(),
5662 kind: GenericParamKind::Type {
5668 /// Parses the following grammar:
5670 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5671 fn parse_trait_item_assoc_ty(&mut self)
5672 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5673 let ident = self.parse_ident()?;
5674 let mut generics = self.parse_generics()?;
5676 // Parse optional colon and param bounds.
5677 let bounds = if self.eat(&token::Colon) {
5678 self.parse_generic_bounds(None)?
5682 generics.where_clause = self.parse_where_clause()?;
5684 let default = if self.eat(&token::Eq) {
5685 Some(self.parse_ty()?)
5689 self.expect(&token::Semi)?;
5691 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5694 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5695 self.expect_keyword(keywords::Const)?;
5696 let ident = self.parse_ident()?;
5697 self.expect(&token::Colon)?;
5698 let ty = self.parse_ty()?;
5702 id: ast::DUMMY_NODE_ID,
5703 attrs: preceding_attrs.into(),
5705 kind: GenericParamKind::Const {
5711 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5712 /// a trailing comma and erroneous trailing attributes.
5713 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5714 let mut params = Vec::new();
5716 let attrs = self.parse_outer_attributes()?;
5717 if self.check_lifetime() {
5718 let lifetime = self.expect_lifetime();
5719 // Parse lifetime parameter.
5720 let bounds = if self.eat(&token::Colon) {
5721 self.parse_lt_param_bounds()
5725 params.push(ast::GenericParam {
5726 ident: lifetime.ident,
5728 attrs: attrs.into(),
5730 kind: ast::GenericParamKind::Lifetime,
5732 } else if self.check_keyword(keywords::Const) {
5733 // Parse const parameter.
5734 params.push(self.parse_const_param(attrs)?);
5735 } else if self.check_ident() {
5736 // Parse type parameter.
5737 params.push(self.parse_ty_param(attrs)?);
5739 // Check for trailing attributes and stop parsing.
5740 if !attrs.is_empty() {
5741 if !params.is_empty() {
5742 self.struct_span_err(
5744 &format!("trailing attribute after generic parameter"),
5746 .span_label(attrs[0].span, "attributes must go before parameters")
5749 self.struct_span_err(
5751 &format!("attribute without generic parameters"),
5755 "attributes are only permitted when preceding parameters",
5763 if !self.eat(&token::Comma) {
5770 /// Parses a set of optional generic type parameter declarations. Where
5771 /// clauses are not parsed here, and must be added later via
5772 /// `parse_where_clause()`.
5774 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5775 /// | ( < lifetimes , typaramseq ( , )? > )
5776 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5777 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5778 let span_lo = self.span;
5780 let params = self.parse_generic_params()?;
5784 where_clause: WhereClause {
5785 id: ast::DUMMY_NODE_ID,
5786 predicates: Vec::new(),
5787 span: syntax_pos::DUMMY_SP,
5789 span: span_lo.to(self.prev_span),
5792 Ok(ast::Generics::default())
5796 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5797 /// For the purposes of understanding the parsing logic of generic arguments, this function
5798 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5799 /// had the correct amount of leading angle brackets.
5801 /// ```ignore (diagnostics)
5802 /// bar::<<<<T as Foo>::Output>();
5803 /// ^^ help: remove extra angle brackets
5805 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5809 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5810 // We need to detect whether there are extra leading left angle brackets and produce an
5811 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5812 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5813 // then there won't be matching `>` tokens to find.
5815 // To explain how this detection works, consider the following example:
5817 // ```ignore (diagnostics)
5818 // bar::<<<<T as Foo>::Output>();
5819 // ^^ help: remove extra angle brackets
5822 // Parsing of the left angle brackets starts in this function. We start by parsing the
5823 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5826 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5827 // *Unmatched count:* 1
5828 // *`parse_path_segment` calls deep:* 0
5830 // This has the effect of recursing as this function is called if a `<` character
5831 // is found within the expected generic arguments:
5833 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5834 // *Unmatched count:* 2
5835 // *`parse_path_segment` calls deep:* 1
5837 // Eventually we will have recursed until having consumed all of the `<` tokens and
5838 // this will be reflected in the count:
5840 // *Upcoming tokens:* `T as Foo>::Output>;`
5841 // *Unmatched count:* 4
5842 // `parse_path_segment` calls deep:* 3
5844 // The parser will continue until reaching the first `>` - this will decrement the
5845 // unmatched angle bracket count and return to the parent invocation of this function
5846 // having succeeded in parsing:
5848 // *Upcoming tokens:* `::Output>;`
5849 // *Unmatched count:* 3
5850 // *`parse_path_segment` calls deep:* 2
5852 // This will continue until the next `>` character which will also return successfully
5853 // to the parent invocation of this function and decrement the count:
5855 // *Upcoming tokens:* `;`
5856 // *Unmatched count:* 2
5857 // *`parse_path_segment` calls deep:* 1
5859 // At this point, this function will expect to find another matching `>` character but
5860 // won't be able to and will return an error. This will continue all the way up the
5861 // call stack until the first invocation:
5863 // *Upcoming tokens:* `;`
5864 // *Unmatched count:* 2
5865 // *`parse_path_segment` calls deep:* 0
5867 // In doing this, we have managed to work out how many unmatched leading left angle
5868 // brackets there are, but we cannot recover as the unmatched angle brackets have
5869 // already been consumed. To remedy this, we keep a snapshot of the parser state
5870 // before we do the above. We can then inspect whether we ended up with a parsing error
5871 // and unmatched left angle brackets and if so, restore the parser state before we
5872 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5873 // recover by attempting to parse again.
5875 // In practice, the recursion of this function is indirect and there will be other
5876 // locations that consume some `<` characters - as long as we update the count when
5877 // this happens, it isn't an issue.
5879 let is_first_invocation = style == PathStyle::Expr;
5880 // Take a snapshot before attempting to parse - we can restore this later.
5881 let snapshot = if is_first_invocation {
5887 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5888 match self.parse_generic_args() {
5889 Ok(value) => Ok(value),
5890 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5891 // Cancel error from being unable to find `>`. We know the error
5892 // must have been this due to a non-zero unmatched angle bracket
5896 // Swap `self` with our backup of the parser state before attempting to parse
5897 // generic arguments.
5898 let snapshot = mem::replace(self, snapshot.unwrap());
5901 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5902 snapshot.count={:?}",
5903 snapshot.unmatched_angle_bracket_count,
5906 // Eat the unmatched angle brackets.
5907 for _ in 0..snapshot.unmatched_angle_bracket_count {
5911 // Make a span over ${unmatched angle bracket count} characters.
5912 let span = lo.with_hi(
5913 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5915 let plural = snapshot.unmatched_angle_bracket_count > 1;
5920 "unmatched angle bracket{}",
5921 if plural { "s" } else { "" }
5927 "remove extra angle bracket{}",
5928 if plural { "s" } else { "" }
5931 Applicability::MachineApplicable,
5935 // Try again without unmatched angle bracket characters.
5936 self.parse_generic_args()
5942 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5943 /// possibly including trailing comma.
5944 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5945 let mut args = Vec::new();
5946 let mut bindings = Vec::new();
5947 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
5948 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
5950 let args_lo = self.span;
5953 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5954 // Parse lifetime argument.
5955 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5956 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5957 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5958 // Parse associated type binding.
5960 let ident = self.parse_ident()?;
5962 let ty = self.parse_ty()?;
5963 let span = lo.to(self.prev_span);
5964 bindings.push(TypeBinding {
5965 id: ast::DUMMY_NODE_ID,
5970 assoc_ty_bindings.push(span);
5971 } else if self.check_const_arg() {
5972 // Parse const argument.
5973 let expr = if let token::OpenDelim(token::Brace) = self.token {
5974 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
5975 } else if self.token.is_ident() {
5976 // FIXME(const_generics): to distinguish between idents for types and consts,
5977 // we should introduce a GenericArg::Ident in the AST and distinguish when
5978 // lowering to the HIR. For now, idents for const args are not permitted.
5980 self.fatal("identifiers may currently not be used for const generics")
5983 self.parse_literal_maybe_minus()?
5985 let value = AnonConst {
5986 id: ast::DUMMY_NODE_ID,
5989 args.push(GenericArg::Const(value));
5990 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5991 } else if self.check_type() {
5992 // Parse type argument.
5993 args.push(GenericArg::Type(self.parse_ty()?));
5994 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5999 if !self.eat(&token::Comma) {
6004 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6005 // preserve ordering of generic parameters with respect to associated type binding, so we
6006 // lose that information after parsing.
6007 if misplaced_assoc_ty_bindings.len() > 0 {
6008 let mut err = self.struct_span_err(
6009 args_lo.to(self.prev_span),
6010 "associated type bindings must be declared after generic parameters",
6012 for span in misplaced_assoc_ty_bindings {
6015 "this associated type binding should be moved after the generic parameters",
6021 Ok((args, bindings))
6024 /// Parses an optional where-clause and places it in `generics`.
6026 /// ```ignore (only-for-syntax-highlight)
6027 /// where T : Trait<U, V> + 'b, 'a : 'b
6029 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6030 let mut where_clause = WhereClause {
6031 id: ast::DUMMY_NODE_ID,
6032 predicates: Vec::new(),
6033 span: syntax_pos::DUMMY_SP,
6036 if !self.eat_keyword(keywords::Where) {
6037 return Ok(where_clause);
6039 let lo = self.prev_span;
6041 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6042 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6043 // change we parse those generics now, but report an error.
6044 if self.choose_generics_over_qpath() {
6045 let generics = self.parse_generics()?;
6046 self.struct_span_err(
6048 "generic parameters on `where` clauses are reserved for future use",
6050 .span_label(generics.span, "currently unsupported")
6056 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6057 let lifetime = self.expect_lifetime();
6058 // Bounds starting with a colon are mandatory, but possibly empty.
6059 self.expect(&token::Colon)?;
6060 let bounds = self.parse_lt_param_bounds();
6061 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6062 ast::WhereRegionPredicate {
6063 span: lo.to(self.prev_span),
6068 } else if self.check_type() {
6069 // Parse optional `for<'a, 'b>`.
6070 // This `for` is parsed greedily and applies to the whole predicate,
6071 // the bounded type can have its own `for` applying only to it.
6072 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6073 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6074 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6075 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6077 // Parse type with mandatory colon and (possibly empty) bounds,
6078 // or with mandatory equality sign and the second type.
6079 let ty = self.parse_ty()?;
6080 if self.eat(&token::Colon) {
6081 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6082 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6083 ast::WhereBoundPredicate {
6084 span: lo.to(self.prev_span),
6085 bound_generic_params: lifetime_defs,
6090 // FIXME: Decide what should be used here, `=` or `==`.
6091 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6092 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6093 let rhs_ty = self.parse_ty()?;
6094 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6095 ast::WhereEqPredicate {
6096 span: lo.to(self.prev_span),
6099 id: ast::DUMMY_NODE_ID,
6103 return self.unexpected();
6109 if !self.eat(&token::Comma) {
6114 where_clause.span = lo.to(self.prev_span);
6118 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6119 -> PResult<'a, (Vec<Arg> , bool)> {
6120 self.expect(&token::OpenDelim(token::Paren))?;
6123 let mut c_variadic = false;
6124 let (args, recovered): (Vec<Option<Arg>>, bool) =
6125 self.parse_seq_to_before_end(
6126 &token::CloseDelim(token::Paren),
6127 SeqSep::trailing_allowed(token::Comma),
6129 // If the argument is a C-variadic argument we should not
6130 // enforce named arguments.
6131 let enforce_named_args = if p.token == token::DotDotDot {
6136 match p.parse_arg_general(enforce_named_args, false,
6139 if let TyKind::CVarArgs = arg.ty.node {
6141 if p.token != token::CloseDelim(token::Paren) {
6144 "`...` must be the last argument of a C-variadic function");
6155 let lo = p.prev_span;
6156 // Skip every token until next possible arg or end.
6157 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6158 // Create a placeholder argument for proper arg count (issue #34264).
6159 let span = lo.to(p.prev_span);
6160 Ok(Some(dummy_arg(span)))
6167 self.eat(&token::CloseDelim(token::Paren));
6170 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6172 if c_variadic && args.is_empty() {
6174 "C-variadic function must be declared with at least one named argument");
6177 Ok((args, c_variadic))
6180 /// Parses the argument list and result type of a function declaration.
6181 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6183 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6184 let ret_ty = self.parse_ret_ty(true)?;
6193 /// Returns the parsed optional self argument and whether a self shortcut was used.
6194 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6195 let expect_ident = |this: &mut Self| match this.token {
6196 // Preserve hygienic context.
6197 token::Ident(ident, _) =>
6198 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6201 let isolated_self = |this: &mut Self, n| {
6202 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6203 this.look_ahead(n + 1, |t| t != &token::ModSep)
6206 // Parse optional self parameter of a method.
6207 // Only a limited set of initial token sequences is considered self parameters, anything
6208 // else is parsed as a normal function parameter list, so some lookahead is required.
6209 let eself_lo = self.span;
6210 let (eself, eself_ident, eself_hi) = match self.token {
6211 token::BinOp(token::And) => {
6217 (if isolated_self(self, 1) {
6219 SelfKind::Region(None, Mutability::Immutable)
6220 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6221 isolated_self(self, 2) {
6224 SelfKind::Region(None, Mutability::Mutable)
6225 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6226 isolated_self(self, 2) {
6228 let lt = self.expect_lifetime();
6229 SelfKind::Region(Some(lt), Mutability::Immutable)
6230 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6231 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6232 isolated_self(self, 3) {
6234 let lt = self.expect_lifetime();
6236 SelfKind::Region(Some(lt), Mutability::Mutable)
6239 }, expect_ident(self), self.prev_span)
6241 token::BinOp(token::Star) => {
6246 // Emit special error for `self` cases.
6247 let msg = "cannot pass `self` by raw pointer";
6248 (if isolated_self(self, 1) {
6250 self.struct_span_err(self.span, msg)
6251 .span_label(self.span, msg)
6253 SelfKind::Value(Mutability::Immutable)
6254 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6255 isolated_self(self, 2) {
6258 self.struct_span_err(self.span, msg)
6259 .span_label(self.span, msg)
6261 SelfKind::Value(Mutability::Immutable)
6264 }, expect_ident(self), self.prev_span)
6266 token::Ident(..) => {
6267 if isolated_self(self, 0) {
6270 let eself_ident = expect_ident(self);
6271 let eself_hi = self.prev_span;
6272 (if self.eat(&token::Colon) {
6273 let ty = self.parse_ty()?;
6274 SelfKind::Explicit(ty, Mutability::Immutable)
6276 SelfKind::Value(Mutability::Immutable)
6277 }, eself_ident, eself_hi)
6278 } else if self.token.is_keyword(keywords::Mut) &&
6279 isolated_self(self, 1) {
6283 let eself_ident = expect_ident(self);
6284 let eself_hi = self.prev_span;
6285 (if self.eat(&token::Colon) {
6286 let ty = self.parse_ty()?;
6287 SelfKind::Explicit(ty, Mutability::Mutable)
6289 SelfKind::Value(Mutability::Mutable)
6290 }, eself_ident, eself_hi)
6295 _ => return Ok(None),
6298 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6299 Ok(Some(Arg::from_self(eself, eself_ident)))
6302 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6303 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6304 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6306 self.expect(&token::OpenDelim(token::Paren))?;
6308 // Parse optional self argument
6309 let self_arg = self.parse_self_arg()?;
6311 // Parse the rest of the function parameter list.
6312 let sep = SeqSep::trailing_allowed(token::Comma);
6313 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6314 if self.check(&token::CloseDelim(token::Paren)) {
6315 (vec![self_arg], false)
6316 } else if self.eat(&token::Comma) {
6317 let mut fn_inputs = vec![self_arg];
6318 let (mut input, recovered) = self.parse_seq_to_before_end(
6319 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6320 fn_inputs.append(&mut input);
6321 (fn_inputs, recovered)
6323 match self.expect_one_of(&[], &[]) {
6324 Err(err) => return Err(err),
6325 Ok(recovered) => (vec![self_arg], recovered),
6329 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6333 // Parse closing paren and return type.
6334 self.expect(&token::CloseDelim(token::Paren))?;
6338 output: self.parse_ret_ty(true)?,
6343 /// Parses the `|arg, arg|` header of a closure.
6344 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6345 let inputs_captures = {
6346 if self.eat(&token::OrOr) {
6349 self.expect(&token::BinOp(token::Or))?;
6350 let args = self.parse_seq_to_before_tokens(
6351 &[&token::BinOp(token::Or), &token::OrOr],
6352 SeqSep::trailing_allowed(token::Comma),
6353 TokenExpectType::NoExpect,
6354 |p| p.parse_fn_block_arg()
6360 let output = self.parse_ret_ty(true)?;
6363 inputs: inputs_captures,
6369 /// Parses the name and optional generic types of a function header.
6370 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6371 let id = self.parse_ident()?;
6372 let generics = self.parse_generics()?;
6376 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6377 attrs: Vec<Attribute>) -> P<Item> {
6381 id: ast::DUMMY_NODE_ID,
6389 /// Parses an item-position function declaration.
6390 fn parse_item_fn(&mut self,
6392 mut asyncness: Spanned<IsAsync>,
6393 constness: Spanned<Constness>,
6395 -> PResult<'a, ItemInfo> {
6396 let (ident, mut generics) = self.parse_fn_header()?;
6397 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6398 let mut decl = self.parse_fn_decl(allow_c_variadic)?;
6399 generics.where_clause = self.parse_where_clause()?;
6400 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6401 self.construct_async_arguments(&mut asyncness, &mut decl);
6402 let header = FnHeader { unsafety, asyncness, constness, abi };
6403 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6406 /// Returns `true` if we are looking at `const ID`
6407 /// (returns `false` for things like `const fn`, etc.).
6408 fn is_const_item(&self) -> bool {
6409 self.token.is_keyword(keywords::Const) &&
6410 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6411 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6414 /// Parses all the "front matter" for a `fn` declaration, up to
6415 /// and including the `fn` keyword:
6419 /// - `const unsafe fn`
6422 fn parse_fn_front_matter(&mut self)
6430 let is_const_fn = self.eat_keyword(keywords::Const);
6431 let const_span = self.prev_span;
6432 let unsafety = self.parse_unsafety();
6433 let asyncness = self.parse_asyncness();
6434 let asyncness = respan(self.prev_span, asyncness);
6435 let (constness, unsafety, abi) = if is_const_fn {
6436 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6438 let abi = if self.eat_keyword(keywords::Extern) {
6439 self.parse_opt_abi()?.unwrap_or(Abi::C)
6443 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6445 if !self.eat_keyword(keywords::Fn) {
6446 // It is possible for `expect_one_of` to recover given the contents of
6447 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6448 // account for this.
6449 if !self.expect_one_of(&[], &[])? { unreachable!() }
6451 Ok((constness, unsafety, asyncness, abi))
6454 /// Parses an impl item.
6455 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6456 maybe_whole!(self, NtImplItem, |x| x);
6457 let attrs = self.parse_outer_attributes()?;
6458 let mut unclosed_delims = vec![];
6459 let (mut item, tokens) = self.collect_tokens(|this| {
6460 let item = this.parse_impl_item_(at_end, attrs);
6461 unclosed_delims.append(&mut this.unclosed_delims);
6464 self.unclosed_delims.append(&mut unclosed_delims);
6466 // See `parse_item` for why this clause is here.
6467 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6468 item.tokens = Some(tokens);
6473 fn parse_impl_item_(&mut self,
6475 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6477 let vis = self.parse_visibility(false)?;
6478 let defaultness = self.parse_defaultness();
6479 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6480 let (name, alias, generics) = type_?;
6481 let kind = match alias {
6482 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6483 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6485 (name, kind, generics)
6486 } else if self.is_const_item() {
6487 // This parses the grammar:
6488 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6489 self.expect_keyword(keywords::Const)?;
6490 let name = self.parse_ident()?;
6491 self.expect(&token::Colon)?;
6492 let typ = self.parse_ty()?;
6493 self.expect(&token::Eq)?;
6494 let expr = self.parse_expr()?;
6495 self.expect(&token::Semi)?;
6496 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6498 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6499 attrs.extend(inner_attrs);
6500 (name, node, generics)
6504 id: ast::DUMMY_NODE_ID,
6505 span: lo.to(self.prev_span),
6516 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
6518 VisibilityKind::Inherited => {}
6520 let is_macro_rules: bool = match self.token {
6521 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6524 let mut err = if is_macro_rules {
6525 let mut err = self.diagnostic()
6526 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6527 err.span_suggestion(
6529 "try exporting the macro",
6530 "#[macro_export]".to_owned(),
6531 Applicability::MaybeIncorrect // speculative
6535 let mut err = self.diagnostic()
6536 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6537 err.help("try adjusting the macro to put `pub` inside the invocation");
6545 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
6546 -> DiagnosticBuilder<'a>
6548 let expected_kinds = if item_type == "extern" {
6549 "missing `fn`, `type`, or `static`"
6551 "missing `fn`, `type`, or `const`"
6554 // Given this code `path(`, it seems like this is not
6555 // setting the visibility of a macro invocation, but rather
6556 // a mistyped method declaration.
6557 // Create a diagnostic pointing out that `fn` is missing.
6559 // x | pub path(&self) {
6560 // | ^ missing `fn`, `type`, or `const`
6562 // ^^ `sp` below will point to this
6563 let sp = prev_span.between(self.prev_span);
6564 let mut err = self.diagnostic().struct_span_err(
6566 &format!("{} for {}-item declaration",
6567 expected_kinds, item_type));
6568 err.span_label(sp, expected_kinds);
6572 /// Parse a method or a macro invocation in a trait impl.
6573 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6574 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6575 ast::ImplItemKind)> {
6576 // code copied from parse_macro_use_or_failure... abstraction!
6577 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6579 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6580 ast::ImplItemKind::Macro(mac)))
6582 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6583 let ident = self.parse_ident()?;
6584 let mut generics = self.parse_generics()?;
6585 let mut decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6586 generics.where_clause = self.parse_where_clause()?;
6587 self.construct_async_arguments(&mut asyncness, &mut decl);
6589 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6590 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6591 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6592 ast::MethodSig { header, decl },
6598 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6599 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6600 let ident = self.parse_ident()?;
6601 let mut tps = self.parse_generics()?;
6603 // Parse optional colon and supertrait bounds.
6604 let bounds = if self.eat(&token::Colon) {
6605 self.parse_generic_bounds(Some(self.prev_span))?
6610 if self.eat(&token::Eq) {
6611 // it's a trait alias
6612 let bounds = self.parse_generic_bounds(None)?;
6613 tps.where_clause = self.parse_where_clause()?;
6614 self.expect(&token::Semi)?;
6615 if is_auto == IsAuto::Yes {
6616 let msg = "trait aliases cannot be `auto`";
6617 self.struct_span_err(self.prev_span, msg)
6618 .span_label(self.prev_span, msg)
6621 if unsafety != Unsafety::Normal {
6622 let msg = "trait aliases cannot be `unsafe`";
6623 self.struct_span_err(self.prev_span, msg)
6624 .span_label(self.prev_span, msg)
6627 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6629 // it's a normal trait
6630 tps.where_clause = self.parse_where_clause()?;
6631 self.expect(&token::OpenDelim(token::Brace))?;
6632 let mut trait_items = vec![];
6633 while !self.eat(&token::CloseDelim(token::Brace)) {
6634 if let token::DocComment(_) = self.token {
6635 if self.look_ahead(1,
6636 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6637 let mut err = self.diagnostic().struct_span_err_with_code(
6639 "found a documentation comment that doesn't document anything",
6640 DiagnosticId::Error("E0584".into()),
6642 err.help("doc comments must come before what they document, maybe a \
6643 comment was intended with `//`?",
6650 let mut at_end = false;
6651 match self.parse_trait_item(&mut at_end) {
6652 Ok(item) => trait_items.push(item),
6656 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6661 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6665 fn choose_generics_over_qpath(&self) -> bool {
6666 // There's an ambiguity between generic parameters and qualified paths in impls.
6667 // If we see `<` it may start both, so we have to inspect some following tokens.
6668 // The following combinations can only start generics,
6669 // but not qualified paths (with one exception):
6670 // `<` `>` - empty generic parameters
6671 // `<` `#` - generic parameters with attributes
6672 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6673 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6674 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6675 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6676 // `<` const - generic const parameter
6677 // The only truly ambiguous case is
6678 // `<` IDENT `>` `::` IDENT ...
6679 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6680 // because this is what almost always expected in practice, qualified paths in impls
6681 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6682 self.token == token::Lt &&
6683 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6684 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6685 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6686 t == &token::Colon || t == &token::Eq) ||
6687 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6690 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6691 self.expect(&token::OpenDelim(token::Brace))?;
6692 let attrs = self.parse_inner_attributes()?;
6694 let mut impl_items = Vec::new();
6695 while !self.eat(&token::CloseDelim(token::Brace)) {
6696 let mut at_end = false;
6697 match self.parse_impl_item(&mut at_end) {
6698 Ok(impl_item) => impl_items.push(impl_item),
6702 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6707 Ok((impl_items, attrs))
6710 /// Parses an implementation item, `impl` keyword is already parsed.
6712 /// impl<'a, T> TYPE { /* impl items */ }
6713 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6714 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6716 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6717 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6718 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6719 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6720 -> PResult<'a, ItemInfo> {
6721 // First, parse generic parameters if necessary.
6722 let mut generics = if self.choose_generics_over_qpath() {
6723 self.parse_generics()?
6725 ast::Generics::default()
6728 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6729 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6731 ast::ImplPolarity::Negative
6733 ast::ImplPolarity::Positive
6736 // Parse both types and traits as a type, then reinterpret if necessary.
6737 let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6738 let ty_first = if self.token.is_keyword(keywords::For) &&
6739 self.look_ahead(1, |t| t != &token::Lt) {
6740 let span = self.prev_span.between(self.span);
6741 self.struct_span_err(span, "missing trait in a trait impl").emit();
6742 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6747 // If `for` is missing we try to recover.
6748 let has_for = self.eat_keyword(keywords::For);
6749 let missing_for_span = self.prev_span.between(self.span);
6751 let ty_second = if self.token == token::DotDot {
6752 // We need to report this error after `cfg` expansion for compatibility reasons
6753 self.bump(); // `..`, do not add it to expected tokens
6754 Some(DummyResult::raw_ty(self.prev_span, true))
6755 } else if has_for || self.token.can_begin_type() {
6756 Some(self.parse_ty()?)
6761 generics.where_clause = self.parse_where_clause()?;
6763 let (impl_items, attrs) = self.parse_impl_body()?;
6765 let item_kind = match ty_second {
6766 Some(ty_second) => {
6767 // impl Trait for Type
6769 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6770 .span_suggestion_short(
6773 " for ".to_string(),
6774 Applicability::MachineApplicable,
6778 let ty_first = ty_first.into_inner();
6779 let path = match ty_first.node {
6780 // This notably includes paths passed through `ty` macro fragments (#46438).
6781 TyKind::Path(None, path) => path,
6783 self.span_err(ty_first.span, "expected a trait, found type");
6784 err_path(ty_first.span)
6787 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6789 ItemKind::Impl(unsafety, polarity, defaultness,
6790 generics, Some(trait_ref), ty_second, impl_items)
6794 ItemKind::Impl(unsafety, polarity, defaultness,
6795 generics, None, ty_first, impl_items)
6799 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6802 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6803 if self.eat_keyword(keywords::For) {
6805 let params = self.parse_generic_params()?;
6807 // We rely on AST validation to rule out invalid cases: There must not be type
6808 // parameters, and the lifetime parameters must not have bounds.
6815 /// Parses `struct Foo { ... }`.
6816 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6817 let class_name = self.parse_ident()?;
6819 let mut generics = self.parse_generics()?;
6821 // There is a special case worth noting here, as reported in issue #17904.
6822 // If we are parsing a tuple struct it is the case that the where clause
6823 // should follow the field list. Like so:
6825 // struct Foo<T>(T) where T: Copy;
6827 // If we are parsing a normal record-style struct it is the case
6828 // that the where clause comes before the body, and after the generics.
6829 // So if we look ahead and see a brace or a where-clause we begin
6830 // parsing a record style struct.
6832 // Otherwise if we look ahead and see a paren we parse a tuple-style
6835 let vdata = if self.token.is_keyword(keywords::Where) {
6836 generics.where_clause = self.parse_where_clause()?;
6837 if self.eat(&token::Semi) {
6838 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6839 VariantData::Unit(ast::DUMMY_NODE_ID)
6841 // If we see: `struct Foo<T> where T: Copy { ... }`
6842 let (fields, recovered) = self.parse_record_struct_body()?;
6843 VariantData::Struct(fields, recovered)
6845 // No `where` so: `struct Foo<T>;`
6846 } else if self.eat(&token::Semi) {
6847 VariantData::Unit(ast::DUMMY_NODE_ID)
6848 // Record-style struct definition
6849 } else if self.token == token::OpenDelim(token::Brace) {
6850 let (fields, recovered) = self.parse_record_struct_body()?;
6851 VariantData::Struct(fields, recovered)
6852 // Tuple-style struct definition with optional where-clause.
6853 } else if self.token == token::OpenDelim(token::Paren) {
6854 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6855 generics.where_clause = self.parse_where_clause()?;
6856 self.expect(&token::Semi)?;
6859 let token_str = self.this_token_descr();
6860 let mut err = self.fatal(&format!(
6861 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6864 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6868 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6871 /// Parses `union Foo { ... }`.
6872 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6873 let class_name = self.parse_ident()?;
6875 let mut generics = self.parse_generics()?;
6877 let vdata = if self.token.is_keyword(keywords::Where) {
6878 generics.where_clause = self.parse_where_clause()?;
6879 let (fields, recovered) = self.parse_record_struct_body()?;
6880 VariantData::Struct(fields, recovered)
6881 } else if self.token == token::OpenDelim(token::Brace) {
6882 let (fields, recovered) = self.parse_record_struct_body()?;
6883 VariantData::Struct(fields, recovered)
6885 let token_str = self.this_token_descr();
6886 let mut err = self.fatal(&format!(
6887 "expected `where` or `{{` after union name, found {}", token_str));
6888 err.span_label(self.span, "expected `where` or `{` after union name");
6892 Ok((class_name, ItemKind::Union(vdata, generics), None))
6895 fn consume_block(&mut self, delim: token::DelimToken) {
6896 let mut brace_depth = 0;
6898 if self.eat(&token::OpenDelim(delim)) {
6900 } else if self.eat(&token::CloseDelim(delim)) {
6901 if brace_depth == 0 {
6907 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6915 fn parse_record_struct_body(
6917 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6918 let mut fields = Vec::new();
6919 let mut recovered = false;
6920 if self.eat(&token::OpenDelim(token::Brace)) {
6921 while self.token != token::CloseDelim(token::Brace) {
6922 let field = self.parse_struct_decl_field().map_err(|e| {
6923 self.recover_stmt();
6928 Ok(field) => fields.push(field),
6934 self.eat(&token::CloseDelim(token::Brace));
6936 let token_str = self.this_token_descr();
6937 let mut err = self.fatal(&format!(
6938 "expected `where`, or `{{` after struct name, found {}", token_str));
6939 err.span_label(self.span, "expected `where`, or `{` after struct name");
6943 Ok((fields, recovered))
6946 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6947 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6948 // Unit like structs are handled in parse_item_struct function
6949 let fields = self.parse_unspanned_seq(
6950 &token::OpenDelim(token::Paren),
6951 &token::CloseDelim(token::Paren),
6952 SeqSep::trailing_allowed(token::Comma),
6954 let attrs = p.parse_outer_attributes()?;
6956 let vis = p.parse_visibility(true)?;
6957 let ty = p.parse_ty()?;
6959 span: lo.to(ty.span),
6962 id: ast::DUMMY_NODE_ID,
6971 /// Parses a structure field declaration.
6972 fn parse_single_struct_field(&mut self,
6975 attrs: Vec<Attribute> )
6976 -> PResult<'a, StructField> {
6977 let mut seen_comma: bool = false;
6978 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6979 if self.token == token::Comma {
6986 token::CloseDelim(token::Brace) => {}
6987 token::DocComment(_) => {
6988 let previous_span = self.prev_span;
6989 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6990 self.bump(); // consume the doc comment
6991 let comma_after_doc_seen = self.eat(&token::Comma);
6992 // `seen_comma` is always false, because we are inside doc block
6993 // condition is here to make code more readable
6994 if seen_comma == false && comma_after_doc_seen == true {
6997 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7000 if seen_comma == false {
7001 let sp = self.sess.source_map().next_point(previous_span);
7002 err.span_suggestion(
7004 "missing comma here",
7006 Applicability::MachineApplicable
7013 let sp = self.sess.source_map().next_point(self.prev_span);
7014 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7015 self.this_token_descr()));
7016 if self.token.is_ident() {
7017 // This is likely another field; emit the diagnostic and keep going
7018 err.span_suggestion(
7020 "try adding a comma",
7022 Applicability::MachineApplicable,
7033 /// Parses an element of a struct declaration.
7034 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7035 let attrs = self.parse_outer_attributes()?;
7037 let vis = self.parse_visibility(false)?;
7038 self.parse_single_struct_field(lo, vis, attrs)
7041 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7042 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7043 /// If the following element can't be a tuple (i.e., it's a function definition), then
7044 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7045 /// so emit a proper diagnostic.
7046 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7047 maybe_whole!(self, NtVis, |x| x);
7049 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7050 if self.is_crate_vis() {
7051 self.bump(); // `crate`
7052 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7055 if !self.eat_keyword(keywords::Pub) {
7056 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7057 // keyword to grab a span from for inherited visibility; an empty span at the
7058 // beginning of the current token would seem to be the "Schelling span".
7059 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7061 let lo = self.prev_span;
7063 if self.check(&token::OpenDelim(token::Paren)) {
7064 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7065 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7066 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7067 // by the following tokens.
7068 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) &&
7069 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
7073 self.bump(); // `crate`
7074 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7076 lo.to(self.prev_span),
7077 VisibilityKind::Crate(CrateSugar::PubCrate),
7080 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7083 self.bump(); // `in`
7084 let path = self.parse_path(PathStyle::Mod)?; // `path`
7085 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7086 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7088 id: ast::DUMMY_NODE_ID,
7091 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7092 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7093 t.is_keyword(keywords::SelfLower))
7095 // `pub(self)` or `pub(super)`
7097 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7098 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7099 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7101 id: ast::DUMMY_NODE_ID,
7104 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7105 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7107 let msg = "incorrect visibility restriction";
7108 let suggestion = r##"some possible visibility restrictions are:
7109 `pub(crate)`: visible only on the current crate
7110 `pub(super)`: visible only in the current module's parent
7111 `pub(in path::to::module)`: visible only on the specified path"##;
7112 let path = self.parse_path(PathStyle::Mod)?;
7114 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7115 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7116 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7117 err.help(suggestion);
7118 err.span_suggestion(
7119 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7121 err.emit(); // emit diagnostic, but continue with public visibility
7125 Ok(respan(lo, VisibilityKind::Public))
7128 /// Parses defaultness (i.e., `default` or nothing).
7129 fn parse_defaultness(&mut self) -> Defaultness {
7130 // `pub` is included for better error messages
7131 if self.check_keyword(keywords::Default) &&
7132 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7133 t.is_keyword(keywords::Const) ||
7134 t.is_keyword(keywords::Fn) ||
7135 t.is_keyword(keywords::Unsafe) ||
7136 t.is_keyword(keywords::Extern) ||
7137 t.is_keyword(keywords::Type) ||
7138 t.is_keyword(keywords::Pub)) {
7139 self.bump(); // `default`
7140 Defaultness::Default
7146 /// Given a termination token, parses all of the items in a module.
7147 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7148 let mut items = vec![];
7149 while let Some(item) = self.parse_item()? {
7151 self.maybe_consume_incorrect_semicolon(&items);
7154 if !self.eat(term) {
7155 let token_str = self.this_token_descr();
7156 if !self.maybe_consume_incorrect_semicolon(&items) {
7157 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7158 err.span_label(self.span, "expected item");
7163 let hi = if self.span.is_dummy() {
7170 inner: inner_lo.to(hi),
7176 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7177 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7178 self.expect(&token::Colon)?;
7179 let ty = self.parse_ty()?;
7180 self.expect(&token::Eq)?;
7181 let e = self.parse_expr()?;
7182 self.expect(&token::Semi)?;
7183 let item = match m {
7184 Some(m) => ItemKind::Static(ty, m, e),
7185 None => ItemKind::Const(ty, e),
7187 Ok((id, item, None))
7190 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7191 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7192 let (in_cfg, outer_attrs) = {
7193 let mut strip_unconfigured = crate::config::StripUnconfigured {
7195 features: None, // don't perform gated feature checking
7197 let mut outer_attrs = outer_attrs.to_owned();
7198 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7199 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7202 let id_span = self.span;
7203 let id = self.parse_ident()?;
7204 if self.eat(&token::Semi) {
7205 if in_cfg && self.recurse_into_file_modules {
7206 // This mod is in an external file. Let's go get it!
7207 let ModulePathSuccess { path, directory_ownership, warn } =
7208 self.submod_path(id, &outer_attrs, id_span)?;
7209 let (module, mut attrs) =
7210 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7211 // Record that we fetched the mod from an external file
7213 let attr = Attribute {
7214 id: attr::mk_attr_id(),
7215 style: ast::AttrStyle::Outer,
7216 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7217 tokens: TokenStream::empty(),
7218 is_sugared_doc: false,
7219 span: syntax_pos::DUMMY_SP,
7221 attr::mark_known(&attr);
7224 Ok((id, ItemKind::Mod(module), Some(attrs)))
7226 let placeholder = ast::Mod {
7227 inner: syntax_pos::DUMMY_SP,
7231 Ok((id, ItemKind::Mod(placeholder), None))
7234 let old_directory = self.directory.clone();
7235 self.push_directory(id, &outer_attrs);
7237 self.expect(&token::OpenDelim(token::Brace))?;
7238 let mod_inner_lo = self.span;
7239 let attrs = self.parse_inner_attributes()?;
7240 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7242 self.directory = old_directory;
7243 Ok((id, ItemKind::Mod(module), Some(attrs)))
7247 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7248 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
7249 self.directory.path.to_mut().push(&path.as_str());
7250 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7252 // We have to push on the current module name in the case of relative
7253 // paths in order to ensure that any additional module paths from inline
7254 // `mod x { ... }` come after the relative extension.
7256 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7257 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7258 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7259 if let Some(ident) = relative.take() { // remove the relative offset
7260 self.directory.path.to_mut().push(ident.as_str());
7263 self.directory.path.to_mut().push(&id.as_str());
7267 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7268 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
7271 // On windows, the base path might have the form
7272 // `\\?\foo\bar` in which case it does not tolerate
7273 // mixed `/` and `\` separators, so canonicalize
7276 let s = s.replace("/", "\\");
7277 Some(dir_path.join(s))
7283 /// Returns a path to a module.
7284 pub fn default_submod_path(
7286 relative: Option<ast::Ident>,
7288 source_map: &SourceMap) -> ModulePath
7290 // If we're in a foo.rs file instead of a mod.rs file,
7291 // we need to look for submodules in
7292 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7293 // `./<id>.rs` and `./<id>/mod.rs`.
7294 let relative_prefix_string;
7295 let relative_prefix = if let Some(ident) = relative {
7296 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7297 &relative_prefix_string
7302 let mod_name = id.to_string();
7303 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7304 let secondary_path_str = format!("{}{}{}mod.rs",
7305 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7306 let default_path = dir_path.join(&default_path_str);
7307 let secondary_path = dir_path.join(&secondary_path_str);
7308 let default_exists = source_map.file_exists(&default_path);
7309 let secondary_exists = source_map.file_exists(&secondary_path);
7311 let result = match (default_exists, secondary_exists) {
7312 (true, false) => Ok(ModulePathSuccess {
7314 directory_ownership: DirectoryOwnership::Owned {
7319 (false, true) => Ok(ModulePathSuccess {
7320 path: secondary_path,
7321 directory_ownership: DirectoryOwnership::Owned {
7326 (false, false) => Err(Error::FileNotFoundForModule {
7327 mod_name: mod_name.clone(),
7328 default_path: default_path_str,
7329 secondary_path: secondary_path_str,
7330 dir_path: dir_path.display().to_string(),
7332 (true, true) => Err(Error::DuplicatePaths {
7333 mod_name: mod_name.clone(),
7334 default_path: default_path_str,
7335 secondary_path: secondary_path_str,
7341 path_exists: default_exists || secondary_exists,
7346 fn submod_path(&mut self,
7348 outer_attrs: &[Attribute],
7350 -> PResult<'a, ModulePathSuccess> {
7351 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7352 return Ok(ModulePathSuccess {
7353 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7354 // All `#[path]` files are treated as though they are a `mod.rs` file.
7355 // This means that `mod foo;` declarations inside `#[path]`-included
7356 // files are siblings,
7358 // Note that this will produce weirdness when a file named `foo.rs` is
7359 // `#[path]` included and contains a `mod foo;` declaration.
7360 // If you encounter this, it's your own darn fault :P
7361 Some(_) => DirectoryOwnership::Owned { relative: None },
7362 _ => DirectoryOwnership::UnownedViaMod(true),
7369 let relative = match self.directory.ownership {
7370 DirectoryOwnership::Owned { relative } => relative,
7371 DirectoryOwnership::UnownedViaBlock |
7372 DirectoryOwnership::UnownedViaMod(_) => None,
7374 let paths = Parser::default_submod_path(
7375 id, relative, &self.directory.path, self.sess.source_map());
7377 match self.directory.ownership {
7378 DirectoryOwnership::Owned { .. } => {
7379 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7381 DirectoryOwnership::UnownedViaBlock => {
7383 "Cannot declare a non-inline module inside a block \
7384 unless it has a path attribute";
7385 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7386 if paths.path_exists {
7387 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7389 err.span_note(id_sp, &msg);
7393 DirectoryOwnership::UnownedViaMod(warn) => {
7395 if let Ok(result) = paths.result {
7396 return Ok(ModulePathSuccess { warn: true, ..result });
7399 let mut err = self.diagnostic().struct_span_err(id_sp,
7400 "cannot declare a new module at this location");
7401 if !id_sp.is_dummy() {
7402 let src_path = self.sess.source_map().span_to_filename(id_sp);
7403 if let FileName::Real(src_path) = src_path {
7404 if let Some(stem) = src_path.file_stem() {
7405 let mut dest_path = src_path.clone();
7406 dest_path.set_file_name(stem);
7407 dest_path.push("mod.rs");
7408 err.span_note(id_sp,
7409 &format!("maybe move this module `{}` to its own \
7410 directory via `{}`", src_path.display(),
7411 dest_path.display()));
7415 if paths.path_exists {
7416 err.span_note(id_sp,
7417 &format!("... or maybe `use` the module `{}` instead \
7418 of possibly redeclaring it",
7426 /// Reads a module from a source file.
7427 fn eval_src_mod(&mut self,
7429 directory_ownership: DirectoryOwnership,
7432 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7433 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7434 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7435 let mut err = String::from("circular modules: ");
7436 let len = included_mod_stack.len();
7437 for p in &included_mod_stack[i.. len] {
7438 err.push_str(&p.to_string_lossy());
7439 err.push_str(" -> ");
7441 err.push_str(&path.to_string_lossy());
7442 return Err(self.span_fatal(id_sp, &err[..]));
7444 included_mod_stack.push(path.clone());
7445 drop(included_mod_stack);
7448 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7449 p0.cfg_mods = self.cfg_mods;
7450 let mod_inner_lo = p0.span;
7451 let mod_attrs = p0.parse_inner_attributes()?;
7452 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7454 self.sess.included_mod_stack.borrow_mut().pop();
7458 /// Parses a function declaration from a foreign module.
7459 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7460 -> PResult<'a, ForeignItem> {
7461 self.expect_keyword(keywords::Fn)?;
7463 let (ident, mut generics) = self.parse_fn_header()?;
7464 let decl = self.parse_fn_decl(true)?;
7465 generics.where_clause = self.parse_where_clause()?;
7467 self.expect(&token::Semi)?;
7468 Ok(ast::ForeignItem {
7471 node: ForeignItemKind::Fn(decl, generics),
7472 id: ast::DUMMY_NODE_ID,
7478 /// Parses a static item from a foreign module.
7479 /// Assumes that the `static` keyword is already parsed.
7480 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7481 -> PResult<'a, ForeignItem> {
7482 let mutbl = self.parse_mutability();
7483 let ident = self.parse_ident()?;
7484 self.expect(&token::Colon)?;
7485 let ty = self.parse_ty()?;
7487 self.expect(&token::Semi)?;
7491 node: ForeignItemKind::Static(ty, mutbl),
7492 id: ast::DUMMY_NODE_ID,
7498 /// Parses a type from a foreign module.
7499 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7500 -> PResult<'a, ForeignItem> {
7501 self.expect_keyword(keywords::Type)?;
7503 let ident = self.parse_ident()?;
7505 self.expect(&token::Semi)?;
7506 Ok(ast::ForeignItem {
7509 node: ForeignItemKind::Ty,
7510 id: ast::DUMMY_NODE_ID,
7516 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7517 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7518 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7520 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7521 self.parse_path_segment_ident()
7525 let mut idents = vec![];
7526 let mut replacement = vec![];
7527 let mut fixed_crate_name = false;
7528 // Accept `extern crate name-like-this` for better diagnostics
7529 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7530 if self.token == dash { // Do not include `-` as part of the expected tokens list
7531 while self.eat(&dash) {
7532 fixed_crate_name = true;
7533 replacement.push((self.prev_span, "_".to_string()));
7534 idents.push(self.parse_ident()?);
7537 if fixed_crate_name {
7538 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7539 let mut fixed_name = format!("{}", ident.name);
7540 for part in idents {
7541 fixed_name.push_str(&format!("_{}", part.name));
7543 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7545 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7546 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7547 err.multipart_suggestion(
7550 Applicability::MachineApplicable,
7557 /// Parses `extern crate` links.
7562 /// extern crate foo;
7563 /// extern crate bar as foo;
7565 fn parse_item_extern_crate(&mut self,
7567 visibility: Visibility,
7568 attrs: Vec<Attribute>)
7569 -> PResult<'a, P<Item>> {
7570 // Accept `extern crate name-like-this` for better diagnostics
7571 let orig_name = self.parse_crate_name_with_dashes()?;
7572 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7573 (rename, Some(orig_name.name))
7577 self.expect(&token::Semi)?;
7579 let span = lo.to(self.prev_span);
7580 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7583 /// Parses `extern` for foreign ABIs modules.
7585 /// `extern` is expected to have been
7586 /// consumed before calling this method.
7590 /// ```ignore (only-for-syntax-highlight)
7594 fn parse_item_foreign_mod(&mut self,
7596 opt_abi: Option<Abi>,
7597 visibility: Visibility,
7598 mut attrs: Vec<Attribute>)
7599 -> PResult<'a, P<Item>> {
7600 self.expect(&token::OpenDelim(token::Brace))?;
7602 let abi = opt_abi.unwrap_or(Abi::C);
7604 attrs.extend(self.parse_inner_attributes()?);
7606 let mut foreign_items = vec![];
7607 while !self.eat(&token::CloseDelim(token::Brace)) {
7608 foreign_items.push(self.parse_foreign_item()?);
7611 let prev_span = self.prev_span;
7612 let m = ast::ForeignMod {
7614 items: foreign_items
7616 let invalid = keywords::Invalid.ident();
7617 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7620 /// Parses `type Foo = Bar;`
7622 /// `existential type Foo: Bar;`
7625 /// without modifying the parser state.
7626 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7627 // This parses the grammar:
7628 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7629 if self.check_keyword(keywords::Type) ||
7630 self.check_keyword(keywords::Existential) &&
7631 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7632 let existential = self.eat_keyword(keywords::Existential);
7633 assert!(self.eat_keyword(keywords::Type));
7634 Some(self.parse_existential_or_alias(existential))
7640 /// Parses a type alias or existential type.
7641 fn parse_existential_or_alias(
7644 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7645 let ident = self.parse_ident()?;
7646 let mut tps = self.parse_generics()?;
7647 tps.where_clause = self.parse_where_clause()?;
7648 let alias = if existential {
7649 self.expect(&token::Colon)?;
7650 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7651 AliasKind::Existential(bounds)
7653 self.expect(&token::Eq)?;
7654 let ty = self.parse_ty()?;
7657 self.expect(&token::Semi)?;
7658 Ok((ident, alias, tps))
7661 /// Parses the part of an enum declaration following the `{`.
7662 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7663 let mut variants = Vec::new();
7664 let mut all_nullary = true;
7665 let mut any_disr = vec![];
7666 while self.token != token::CloseDelim(token::Brace) {
7667 let variant_attrs = self.parse_outer_attributes()?;
7668 let vlo = self.span;
7671 let mut disr_expr = None;
7673 let ident = self.parse_ident()?;
7674 if self.check(&token::OpenDelim(token::Brace)) {
7675 // Parse a struct variant.
7676 all_nullary = false;
7677 let (fields, recovered) = self.parse_record_struct_body()?;
7678 struct_def = VariantData::Struct(fields, recovered);
7679 } else if self.check(&token::OpenDelim(token::Paren)) {
7680 all_nullary = false;
7681 struct_def = VariantData::Tuple(
7682 self.parse_tuple_struct_body()?,
7685 } else if self.eat(&token::Eq) {
7686 disr_expr = Some(AnonConst {
7687 id: ast::DUMMY_NODE_ID,
7688 value: self.parse_expr()?,
7690 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7693 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7695 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7698 let vr = ast::Variant_ {
7700 id: ast::DUMMY_NODE_ID,
7701 attrs: variant_attrs,
7705 variants.push(respan(vlo.to(self.prev_span), vr));
7707 if !self.eat(&token::Comma) {
7708 if self.token.is_ident() && !self.token.is_reserved_ident() {
7709 let sp = self.sess.source_map().next_point(self.prev_span);
7710 let mut err = self.struct_span_err(sp, "missing comma");
7711 err.span_suggestion_short(
7715 Applicability::MaybeIncorrect,
7723 self.expect(&token::CloseDelim(token::Brace))?;
7724 if !any_disr.is_empty() && !all_nullary {
7725 let mut err = self.struct_span_err(
7727 "discriminator values can only be used with a field-less enum",
7729 for sp in any_disr {
7730 err.span_label(sp, "only valid in field-less enums");
7735 Ok(ast::EnumDef { variants })
7738 /// Parses an enum declaration.
7739 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7740 let id = self.parse_ident()?;
7741 let mut generics = self.parse_generics()?;
7742 generics.where_clause = self.parse_where_clause()?;
7743 self.expect(&token::OpenDelim(token::Brace))?;
7745 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7746 self.recover_stmt();
7747 self.eat(&token::CloseDelim(token::Brace));
7750 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7753 /// Parses a string as an ABI spec on an extern type or module. Consumes
7754 /// the `extern` keyword, if one is found.
7755 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7757 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7759 self.expect_no_suffix(sp, "an ABI spec", suf);
7761 match abi::lookup(&s.as_str()) {
7762 Some(abi) => Ok(Some(abi)),
7764 let prev_span = self.prev_span;
7765 let mut err = struct_span_err!(
7766 self.sess.span_diagnostic,
7769 "invalid ABI: found `{}`",
7771 err.span_label(prev_span, "invalid ABI");
7772 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7783 fn is_static_global(&mut self) -> bool {
7784 if self.check_keyword(keywords::Static) {
7785 // Check if this could be a closure
7786 !self.look_ahead(1, |token| {
7787 if token.is_keyword(keywords::Move) {
7791 token::BinOp(token::Or) | token::OrOr => true,
7802 attrs: Vec<Attribute>,
7803 macros_allowed: bool,
7804 attributes_allowed: bool,
7805 ) -> PResult<'a, Option<P<Item>>> {
7806 let mut unclosed_delims = vec![];
7807 let (ret, tokens) = self.collect_tokens(|this| {
7808 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7809 unclosed_delims.append(&mut this.unclosed_delims);
7812 self.unclosed_delims.append(&mut unclosed_delims);
7814 // Once we've parsed an item and recorded the tokens we got while
7815 // parsing we may want to store `tokens` into the item we're about to
7816 // return. Note, though, that we specifically didn't capture tokens
7817 // related to outer attributes. The `tokens` field here may later be
7818 // used with procedural macros to convert this item back into a token
7819 // stream, but during expansion we may be removing attributes as we go
7822 // If we've got inner attributes then the `tokens` we've got above holds
7823 // these inner attributes. If an inner attribute is expanded we won't
7824 // actually remove it from the token stream, so we'll just keep yielding
7825 // it (bad!). To work around this case for now we just avoid recording
7826 // `tokens` if we detect any inner attributes. This should help keep
7827 // expansion correct, but we should fix this bug one day!
7830 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7831 i.tokens = Some(tokens);
7838 /// Parses one of the items allowed by the flags.
7839 fn parse_item_implementation(
7841 attrs: Vec<Attribute>,
7842 macros_allowed: bool,
7843 attributes_allowed: bool,
7844 ) -> PResult<'a, Option<P<Item>>> {
7845 maybe_whole!(self, NtItem, |item| {
7846 let mut item = item.into_inner();
7847 let mut attrs = attrs;
7848 mem::swap(&mut item.attrs, &mut attrs);
7849 item.attrs.extend(attrs);
7855 let visibility = self.parse_visibility(false)?;
7857 if self.eat_keyword(keywords::Use) {
7859 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7860 self.expect(&token::Semi)?;
7862 let span = lo.to(self.prev_span);
7863 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7864 return Ok(Some(item));
7867 if self.eat_keyword(keywords::Extern) {
7868 if self.eat_keyword(keywords::Crate) {
7869 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7872 let opt_abi = self.parse_opt_abi()?;
7874 if self.eat_keyword(keywords::Fn) {
7875 // EXTERN FUNCTION ITEM
7876 let fn_span = self.prev_span;
7877 let abi = opt_abi.unwrap_or(Abi::C);
7878 let (ident, item_, extra_attrs) =
7879 self.parse_item_fn(Unsafety::Normal,
7880 respan(fn_span, IsAsync::NotAsync),
7881 respan(fn_span, Constness::NotConst),
7883 let prev_span = self.prev_span;
7884 let item = self.mk_item(lo.to(prev_span),
7888 maybe_append(attrs, extra_attrs));
7889 return Ok(Some(item));
7890 } else if self.check(&token::OpenDelim(token::Brace)) {
7891 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7897 if self.is_static_global() {
7900 let m = if self.eat_keyword(keywords::Mut) {
7903 Mutability::Immutable
7905 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7906 let prev_span = self.prev_span;
7907 let item = self.mk_item(lo.to(prev_span),
7911 maybe_append(attrs, extra_attrs));
7912 return Ok(Some(item));
7914 if self.eat_keyword(keywords::Const) {
7915 let const_span = self.prev_span;
7916 if self.check_keyword(keywords::Fn)
7917 || (self.check_keyword(keywords::Unsafe)
7918 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7919 // CONST FUNCTION ITEM
7920 let unsafety = self.parse_unsafety();
7922 let (ident, item_, extra_attrs) =
7923 self.parse_item_fn(unsafety,
7924 respan(const_span, IsAsync::NotAsync),
7925 respan(const_span, Constness::Const),
7927 let prev_span = self.prev_span;
7928 let item = self.mk_item(lo.to(prev_span),
7932 maybe_append(attrs, extra_attrs));
7933 return Ok(Some(item));
7937 if self.eat_keyword(keywords::Mut) {
7938 let prev_span = self.prev_span;
7939 let mut err = self.diagnostic()
7940 .struct_span_err(prev_span, "const globals cannot be mutable");
7941 err.span_label(prev_span, "cannot be mutable");
7942 err.span_suggestion(
7944 "you might want to declare a static instead",
7945 "static".to_owned(),
7946 Applicability::MaybeIncorrect,
7950 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7951 let prev_span = self.prev_span;
7952 let item = self.mk_item(lo.to(prev_span),
7956 maybe_append(attrs, extra_attrs));
7957 return Ok(Some(item));
7960 // `unsafe async fn` or `async fn`
7962 self.check_keyword(keywords::Unsafe) &&
7963 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7965 self.check_keyword(keywords::Async) &&
7966 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7969 // ASYNC FUNCTION ITEM
7970 let unsafety = self.parse_unsafety();
7971 self.expect_keyword(keywords::Async)?;
7972 let async_span = self.prev_span;
7973 self.expect_keyword(keywords::Fn)?;
7974 let fn_span = self.prev_span;
7975 let (ident, item_, extra_attrs) =
7976 self.parse_item_fn(unsafety,
7977 respan(async_span, IsAsync::Async {
7978 closure_id: ast::DUMMY_NODE_ID,
7979 return_impl_trait_id: ast::DUMMY_NODE_ID,
7980 arguments: Vec::new(),
7982 respan(fn_span, Constness::NotConst),
7984 let prev_span = self.prev_span;
7985 let item = self.mk_item(lo.to(prev_span),
7989 maybe_append(attrs, extra_attrs));
7990 if self.span.rust_2015() {
7991 self.diagnostic().struct_span_err_with_code(
7993 "`async fn` is not permitted in the 2015 edition",
7994 DiagnosticId::Error("E0670".into())
7997 return Ok(Some(item));
7999 if self.check_keyword(keywords::Unsafe) &&
8000 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8001 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8003 // UNSAFE TRAIT ITEM
8004 self.bump(); // `unsafe`
8005 let is_auto = if self.eat_keyword(keywords::Trait) {
8008 self.expect_keyword(keywords::Auto)?;
8009 self.expect_keyword(keywords::Trait)?;
8012 let (ident, item_, extra_attrs) =
8013 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8014 let prev_span = self.prev_span;
8015 let item = self.mk_item(lo.to(prev_span),
8019 maybe_append(attrs, extra_attrs));
8020 return Ok(Some(item));
8022 if self.check_keyword(keywords::Impl) ||
8023 self.check_keyword(keywords::Unsafe) &&
8024 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8025 self.check_keyword(keywords::Default) &&
8026 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8027 self.check_keyword(keywords::Default) &&
8028 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8030 let defaultness = self.parse_defaultness();
8031 let unsafety = self.parse_unsafety();
8032 self.expect_keyword(keywords::Impl)?;
8033 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8034 let span = lo.to(self.prev_span);
8035 return Ok(Some(self.mk_item(span, ident, item, visibility,
8036 maybe_append(attrs, extra_attrs))));
8038 if self.check_keyword(keywords::Fn) {
8041 let fn_span = self.prev_span;
8042 let (ident, item_, extra_attrs) =
8043 self.parse_item_fn(Unsafety::Normal,
8044 respan(fn_span, IsAsync::NotAsync),
8045 respan(fn_span, Constness::NotConst),
8047 let prev_span = self.prev_span;
8048 let item = self.mk_item(lo.to(prev_span),
8052 maybe_append(attrs, extra_attrs));
8053 return Ok(Some(item));
8055 if self.check_keyword(keywords::Unsafe)
8056 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8057 // UNSAFE FUNCTION ITEM
8058 self.bump(); // `unsafe`
8059 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8060 self.check(&token::OpenDelim(token::Brace));
8061 let abi = if self.eat_keyword(keywords::Extern) {
8062 self.parse_opt_abi()?.unwrap_or(Abi::C)
8066 self.expect_keyword(keywords::Fn)?;
8067 let fn_span = self.prev_span;
8068 let (ident, item_, extra_attrs) =
8069 self.parse_item_fn(Unsafety::Unsafe,
8070 respan(fn_span, IsAsync::NotAsync),
8071 respan(fn_span, Constness::NotConst),
8073 let prev_span = self.prev_span;
8074 let item = self.mk_item(lo.to(prev_span),
8078 maybe_append(attrs, extra_attrs));
8079 return Ok(Some(item));
8081 if self.eat_keyword(keywords::Mod) {
8083 let (ident, item_, extra_attrs) =
8084 self.parse_item_mod(&attrs[..])?;
8085 let prev_span = self.prev_span;
8086 let item = self.mk_item(lo.to(prev_span),
8090 maybe_append(attrs, extra_attrs));
8091 return Ok(Some(item));
8093 if let Some(type_) = self.eat_type() {
8094 let (ident, alias, generics) = type_?;
8096 let item_ = match alias {
8097 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8098 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8100 let prev_span = self.prev_span;
8101 let item = self.mk_item(lo.to(prev_span),
8106 return Ok(Some(item));
8108 if self.eat_keyword(keywords::Enum) {
8110 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8111 let prev_span = self.prev_span;
8112 let item = self.mk_item(lo.to(prev_span),
8116 maybe_append(attrs, extra_attrs));
8117 return Ok(Some(item));
8119 if self.check_keyword(keywords::Trait)
8120 || (self.check_keyword(keywords::Auto)
8121 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8123 let is_auto = if self.eat_keyword(keywords::Trait) {
8126 self.expect_keyword(keywords::Auto)?;
8127 self.expect_keyword(keywords::Trait)?;
8131 let (ident, item_, extra_attrs) =
8132 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8133 let prev_span = self.prev_span;
8134 let item = self.mk_item(lo.to(prev_span),
8138 maybe_append(attrs, extra_attrs));
8139 return Ok(Some(item));
8141 if self.eat_keyword(keywords::Struct) {
8143 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8144 let prev_span = self.prev_span;
8145 let item = self.mk_item(lo.to(prev_span),
8149 maybe_append(attrs, extra_attrs));
8150 return Ok(Some(item));
8152 if self.is_union_item() {
8155 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8156 let prev_span = self.prev_span;
8157 let item = self.mk_item(lo.to(prev_span),
8161 maybe_append(attrs, extra_attrs));
8162 return Ok(Some(item));
8164 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8165 return Ok(Some(macro_def));
8168 // Verify whether we have encountered a struct or method definition where the user forgot to
8169 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8170 if visibility.node.is_pub() &&
8171 self.check_ident() &&
8172 self.look_ahead(1, |t| *t != token::Not)
8174 // Space between `pub` keyword and the identifier
8177 // ^^^ `sp` points here
8178 let sp = self.prev_span.between(self.span);
8179 let full_sp = self.prev_span.to(self.span);
8180 let ident_sp = self.span;
8181 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8182 // possible public struct definition where `struct` was forgotten
8183 let ident = self.parse_ident().unwrap();
8184 let msg = format!("add `struct` here to parse `{}` as a public struct",
8186 let mut err = self.diagnostic()
8187 .struct_span_err(sp, "missing `struct` for struct definition");
8188 err.span_suggestion_short(
8189 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8192 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8193 let ident = self.parse_ident().unwrap();
8195 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8200 self.consume_block(token::Paren);
8201 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8202 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8204 ("fn", kw_name, false)
8205 } else if self.check(&token::OpenDelim(token::Brace)) {
8207 ("fn", kw_name, false)
8208 } else if self.check(&token::Colon) {
8212 ("fn` or `struct", "function or struct", true)
8215 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8216 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8218 self.consume_block(token::Brace);
8219 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8223 err.span_suggestion_short(
8224 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8227 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8228 err.span_suggestion(
8230 "if you meant to call a macro, try",
8231 format!("{}!", snippet),
8232 // this is the `ambiguous` conditional branch
8233 Applicability::MaybeIncorrect
8236 err.help("if you meant to call a macro, remove the `pub` \
8237 and add a trailing `!` after the identifier");
8241 } else if self.look_ahead(1, |t| *t == token::Lt) {
8242 let ident = self.parse_ident().unwrap();
8243 self.eat_to_tokens(&[&token::Gt]);
8245 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8246 if let Ok(Some(_)) = self.parse_self_arg() {
8247 ("fn", "method", false)
8249 ("fn", "function", false)
8251 } else if self.check(&token::OpenDelim(token::Brace)) {
8252 ("struct", "struct", false)
8254 ("fn` or `struct", "function or struct", true)
8256 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8257 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8259 err.span_suggestion_short(
8261 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8262 format!(" {} ", kw),
8263 Applicability::MachineApplicable,
8269 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8272 /// Parses a foreign item.
8273 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8274 maybe_whole!(self, NtForeignItem, |ni| ni);
8276 let attrs = self.parse_outer_attributes()?;
8278 let visibility = self.parse_visibility(false)?;
8280 // FOREIGN STATIC ITEM
8281 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8282 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8283 if self.token.is_keyword(keywords::Const) {
8285 .struct_span_err(self.span, "extern items cannot be `const`")
8288 "try using a static value",
8289 "static".to_owned(),
8290 Applicability::MachineApplicable
8293 self.bump(); // `static` or `const`
8294 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8296 // FOREIGN FUNCTION ITEM
8297 if self.check_keyword(keywords::Fn) {
8298 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8300 // FOREIGN TYPE ITEM
8301 if self.check_keyword(keywords::Type) {
8302 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8305 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8309 ident: keywords::Invalid.ident(),
8310 span: lo.to(self.prev_span),
8311 id: ast::DUMMY_NODE_ID,
8314 node: ForeignItemKind::Macro(mac),
8319 if !attrs.is_empty() {
8320 self.expected_item_err(&attrs)?;
8328 /// This is the fall-through for parsing items.
8329 fn parse_macro_use_or_failure(
8331 attrs: Vec<Attribute> ,
8332 macros_allowed: bool,
8333 attributes_allowed: bool,
8335 visibility: Visibility
8336 ) -> PResult<'a, Option<P<Item>>> {
8337 if macros_allowed && self.token.is_path_start() &&
8338 !(self.is_async_fn() && self.span.rust_2015()) {
8339 // MACRO INVOCATION ITEM
8341 let prev_span = self.prev_span;
8342 self.complain_if_pub_macro(&visibility.node, prev_span);
8344 let mac_lo = self.span;
8347 let pth = self.parse_path(PathStyle::Mod)?;
8348 self.expect(&token::Not)?;
8350 // a 'special' identifier (like what `macro_rules!` uses)
8351 // is optional. We should eventually unify invoc syntax
8353 let id = if self.token.is_ident() {
8356 keywords::Invalid.ident() // no special identifier
8358 // eat a matched-delimiter token tree:
8359 let (delim, tts) = self.expect_delimited_token_tree()?;
8360 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8361 self.report_invalid_macro_expansion_item();
8364 let hi = self.prev_span;
8365 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8366 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8367 return Ok(Some(item));
8370 // FAILURE TO PARSE ITEM
8371 match visibility.node {
8372 VisibilityKind::Inherited => {}
8374 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8378 if !attributes_allowed && !attrs.is_empty() {
8379 self.expected_item_err(&attrs)?;
8384 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8385 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8386 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8388 if self.token.is_path_start() &&
8389 !(self.is_async_fn() && self.span.rust_2015()) {
8390 let prev_span = self.prev_span;
8392 let pth = self.parse_path(PathStyle::Mod)?;
8394 if pth.segments.len() == 1 {
8395 if !self.eat(&token::Not) {
8396 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8399 self.expect(&token::Not)?;
8402 if let Some(vis) = vis {
8403 self.complain_if_pub_macro(&vis.node, prev_span);
8408 // eat a matched-delimiter token tree:
8409 let (delim, tts) = self.expect_delimited_token_tree()?;
8410 if delim != MacDelimiter::Brace {
8411 self.expect(&token::Semi)?;
8414 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8420 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8421 where F: FnOnce(&mut Self) -> PResult<'a, R>
8423 // Record all tokens we parse when parsing this item.
8424 let mut tokens = Vec::new();
8425 let prev_collecting = match self.token_cursor.frame.last_token {
8426 LastToken::Collecting(ref mut list) => {
8427 Some(mem::replace(list, Vec::new()))
8429 LastToken::Was(ref mut last) => {
8430 tokens.extend(last.take());
8434 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8435 let prev = self.token_cursor.stack.len();
8437 let last_token = if self.token_cursor.stack.len() == prev {
8438 &mut self.token_cursor.frame.last_token
8440 &mut self.token_cursor.stack[prev].last_token
8443 // Pull out the tokens that we've collected from the call to `f` above.
8444 let mut collected_tokens = match *last_token {
8445 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8446 LastToken::Was(_) => panic!("our vector went away?"),
8449 // If we're not at EOF our current token wasn't actually consumed by
8450 // `f`, but it'll still be in our list that we pulled out. In that case
8452 let extra_token = if self.token != token::Eof {
8453 collected_tokens.pop()
8458 // If we were previously collecting tokens, then this was a recursive
8459 // call. In that case we need to record all the tokens we collected in
8460 // our parent list as well. To do that we push a clone of our stream
8461 // onto the previous list.
8462 match prev_collecting {
8464 list.extend(collected_tokens.iter().cloned());
8465 list.extend(extra_token);
8466 *last_token = LastToken::Collecting(list);
8469 *last_token = LastToken::Was(extra_token);
8473 Ok((ret?, TokenStream::new(collected_tokens)))
8476 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8477 let attrs = self.parse_outer_attributes()?;
8478 self.parse_item_(attrs, true, false)
8482 fn is_import_coupler(&mut self) -> bool {
8483 self.check(&token::ModSep) &&
8484 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8485 *t == token::BinOp(token::Star))
8488 /// Parses a `UseTree`.
8491 /// USE_TREE = [`::`] `*` |
8492 /// [`::`] `{` USE_TREE_LIST `}` |
8494 /// PATH `::` `{` USE_TREE_LIST `}` |
8495 /// PATH [`as` IDENT]
8497 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8500 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8501 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8502 self.check(&token::BinOp(token::Star)) ||
8503 self.is_import_coupler() {
8504 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8505 let mod_sep_ctxt = self.span.ctxt();
8506 if self.eat(&token::ModSep) {
8507 prefix.segments.push(
8508 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8512 if self.eat(&token::BinOp(token::Star)) {
8515 UseTreeKind::Nested(self.parse_use_tree_list()?)
8518 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8519 prefix = self.parse_path(PathStyle::Mod)?;
8521 if self.eat(&token::ModSep) {
8522 if self.eat(&token::BinOp(token::Star)) {
8525 UseTreeKind::Nested(self.parse_use_tree_list()?)
8528 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8532 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8535 /// Parses a `UseTreeKind::Nested(list)`.
8538 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8540 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8541 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8542 &token::CloseDelim(token::Brace),
8543 SeqSep::trailing_allowed(token::Comma), |this| {
8544 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8548 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8549 if self.eat_keyword(keywords::As) {
8550 self.parse_ident_or_underscore().map(Some)
8556 /// Parses a source module as a crate. This is the main entry point for the parser.
8557 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8559 let krate = Ok(ast::Crate {
8560 attrs: self.parse_inner_attributes()?,
8561 module: self.parse_mod_items(&token::Eof, lo)?,
8562 span: lo.to(self.span),
8567 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8568 let ret = match self.token {
8569 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8570 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8577 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8578 match self.parse_optional_str() {
8579 Some((s, style, suf)) => {
8580 let sp = self.prev_span;
8581 self.expect_no_suffix(sp, "a string literal", suf);
8585 let msg = "expected string literal";
8586 let mut err = self.fatal(msg);
8587 err.span_label(self.span, msg);
8593 fn report_invalid_macro_expansion_item(&self) {
8594 self.struct_span_err(
8596 "macros that expand to items must be delimited with braces or followed by a semicolon",
8597 ).multipart_suggestion(
8598 "change the delimiters to curly braces",
8600 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8601 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8603 Applicability::MaybeIncorrect,
8605 self.sess.source_map.next_point(self.prev_span),
8608 Applicability::MaybeIncorrect,
8612 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8613 fn eat_bad_pub(&mut self) {
8614 if self.token.is_keyword(keywords::Pub) {
8615 match self.parse_visibility(false) {
8617 let mut err = self.diagnostic()
8618 .struct_span_err(vis.span, "unnecessary visibility qualifier");
8619 err.span_label(vis.span, "`pub` not permitted here");
8622 Err(mut err) => err.emit(),
8627 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8628 /// into the generated closure so that they are dropped when the future is polled and not when
8631 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8632 /// this function and the statements created here are inserted at the top of the closure body.
8633 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &mut FnDecl) {
8634 // FIXME(davidtwco): This function should really live in the HIR lowering but because
8635 // the types constructed here need to be used in parts of resolve so that the correct
8636 // locals are considered upvars, it is currently easier for it to live here in the parser,
8637 // where it can be constructed once.
8638 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8639 for (index, input) in decl.inputs.iter_mut().enumerate() {
8640 let id = ast::DUMMY_NODE_ID;
8641 let span = input.pat.span;
8643 // Construct a name for our temporary argument.
8644 let name = format!("__arg{}", index);
8645 let ident = Ident::from_str(&name).gensym();
8647 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
8648 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
8650 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
8651 PatKind::Ident(binding_mode @ BindingMode::ByValue(_), ident, _) => {
8652 // Simple patterns like this don't have a generated argument, but they are
8653 // moved into the closure with a statement, so any `mut` bindings on the
8654 // argument will be unused. This binding mode can't be removed, because
8655 // this would affect the input to procedural macros, but they can have
8656 // their span marked as being the result of a compiler desugaring so
8657 // that they aren't linted against.
8658 input.pat.span = self.sess.source_map().mark_span_with_reason(
8659 CompilerDesugaringKind::Async, span, None);
8661 (binding_mode, ident, true)
8663 _ => (BindingMode::ByValue(Mutability::Mutable), ident, false),
8666 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8667 // async function if it isn't a simple pattern.
8668 let arg = if is_simple_pattern {
8672 ty: input.ty.clone(),
8676 node: PatKind::Ident(
8677 BindingMode::ByValue(Mutability::Immutable), ident, None,
8681 source: ArgSource::AsyncFn(input.pat.clone()),
8685 // Construct a `let __argN = __argN;` statement to insert at the top of the
8686 // async closure. This makes sure that the argument is captured by the closure and
8687 // that the drop order is correct.
8688 let move_local = Local {
8691 node: PatKind::Ident(binding_mode, ident, None),
8694 // We explicitly do not specify the type for this statement. When the user's
8695 // argument type is `impl Trait` then this would require the
8696 // `impl_trait_in_bindings` feature to also be present for that same type to
8697 // be valid in this binding. At the time of writing (13 Mar 19),
8698 // `impl_trait_in_bindings` is not stable.
8702 node: ExprKind::Path(None, ast::Path {
8704 segments: vec![PathSegment { ident, id, args: None }],
8707 attrs: ThinVec::new(),
8711 attrs: ThinVec::new(),
8712 source: LocalSource::AsyncFn,
8715 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8716 // async closure if this isn't a simple pattern.
8717 let pat_stmt = if is_simple_pattern {
8722 node: StmtKind::Local(P(Local {
8723 pat: input.pat.clone(),
8724 ..move_local.clone()
8730 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
8731 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
8737 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8738 for unmatched in unclosed_delims.iter() {
8739 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8740 "incorrect close delimiter: `{}`",
8741 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8743 err.span_label(unmatched.found_span, "incorrect close delimiter");
8744 if let Some(sp) = unmatched.candidate_span {
8745 err.span_label(sp, "close delimiter possibly meant for this");
8747 if let Some(sp) = unmatched.unclosed_span {
8748 err.span_label(sp, "un-closed delimiter");
8752 unclosed_delims.clear();