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::{kw, 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)]
107 crate enum SemiColonMode {
113 #[derive(Clone, Copy, PartialEq, Debug)]
114 crate enum BlockMode {
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(
356 TokenTree::Token(sp, token::Ident(ast::Ident::with_empty_ctxt(sym::doc), false)),
357 TokenTree::Token(sp, token::Eq),
358 TokenTree::Token(sp, token::Token::lit(
359 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
362 .iter().cloned().collect::<TokenStream>().into(),
365 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
368 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
369 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
370 .iter().cloned().collect::<TokenStream>().into()
372 [TokenTree::Token(sp, token::Pound), body]
373 .iter().cloned().collect::<TokenStream>().into()
381 #[derive(Clone, PartialEq)]
382 crate enum TokenType {
394 crate fn to_string(&self) -> String {
396 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
397 TokenType::Keyword(kw) => format!("`{}`", kw),
398 TokenType::Operator => "an operator".to_string(),
399 TokenType::Lifetime => "lifetime".to_string(),
400 TokenType::Ident => "identifier".to_string(),
401 TokenType::Path => "path".to_string(),
402 TokenType::Type => "type".to_string(),
403 TokenType::Const => "const".to_string(),
408 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
409 /// `IDENT<<u8 as Trait>::AssocTy>`.
411 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
412 /// that `IDENT` is not the ident of a fn trait.
413 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
414 t == &token::ModSep || t == &token::Lt ||
415 t == &token::BinOp(token::Shl)
418 /// Information about the path to a module.
419 pub struct ModulePath {
422 pub result: Result<ModulePathSuccess, Error>,
425 pub struct ModulePathSuccess {
427 pub directory_ownership: DirectoryOwnership,
432 FileNotFoundForModule {
434 default_path: String,
435 secondary_path: String,
440 default_path: String,
441 secondary_path: String,
444 InclusiveRangeWithNoEnd,
448 fn span_err<S: Into<MultiSpan>>(self,
450 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
452 Error::FileNotFoundForModule { ref mod_name,
456 let mut err = struct_span_err!(handler, sp, E0583,
457 "file not found for module `{}`", mod_name);
458 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
464 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
465 let mut err = struct_span_err!(handler, sp, E0584,
466 "file for module `{}` found at both {} and {}",
470 err.help("delete or rename one of them to remove the ambiguity");
473 Error::UselessDocComment => {
474 let mut err = struct_span_err!(handler, sp, E0585,
475 "found a documentation comment that doesn't document anything");
476 err.help("doc comments must come before what they document, maybe a comment was \
477 intended with `//`?");
480 Error::InclusiveRangeWithNoEnd => {
481 let mut err = struct_span_err!(handler, sp, E0586,
482 "inclusive range with no end");
483 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
493 AttributesParsed(ThinVec<Attribute>),
494 AlreadyParsed(P<Expr>),
497 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
498 fn from(o: Option<ThinVec<Attribute>>) -> Self {
499 if let Some(attrs) = o {
500 LhsExpr::AttributesParsed(attrs)
502 LhsExpr::NotYetParsed
507 impl From<P<Expr>> for LhsExpr {
508 fn from(expr: P<Expr>) -> Self {
509 LhsExpr::AlreadyParsed(expr)
513 /// Creates a placeholder argument.
514 fn dummy_arg(span: Span) -> Arg {
515 let ident = Ident::new(kw::Invalid, span);
517 id: ast::DUMMY_NODE_ID,
518 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
524 id: ast::DUMMY_NODE_ID
526 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal }
529 #[derive(Copy, Clone, Debug)]
530 enum TokenExpectType {
535 impl<'a> Parser<'a> {
536 pub fn new(sess: &'a ParseSess,
538 directory: Option<Directory<'a>>,
539 recurse_into_file_modules: bool,
540 desugar_doc_comments: bool)
542 let mut parser = Parser {
544 token: token::Whitespace,
545 span: syntax_pos::DUMMY_SP,
546 prev_span: syntax_pos::DUMMY_SP,
548 prev_token_kind: PrevTokenKind::Other,
549 restrictions: Restrictions::empty(),
550 recurse_into_file_modules,
551 directory: Directory {
552 path: Cow::from(PathBuf::new()),
553 ownership: DirectoryOwnership::Owned { relative: None }
555 root_module_name: None,
556 expected_tokens: Vec::new(),
557 token_cursor: TokenCursor {
558 frame: TokenCursorFrame::new(
565 desugar_doc_comments,
567 unmatched_angle_bracket_count: 0,
568 max_angle_bracket_count: 0,
569 unclosed_delims: Vec::new(),
570 last_unexpected_token_span: None,
573 let tok = parser.next_tok();
574 parser.token = tok.tok;
575 parser.span = tok.sp;
577 if let Some(directory) = directory {
578 parser.directory = directory;
579 } else if !parser.span.is_dummy() {
580 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
582 parser.directory.path = Cow::from(path);
586 parser.process_potential_macro_variable();
590 fn next_tok(&mut self) -> TokenAndSpan {
591 let mut next = if self.desugar_doc_comments {
592 self.token_cursor.next_desugared()
594 self.token_cursor.next()
596 if next.sp.is_dummy() {
597 // Tweak the location for better diagnostics, but keep syntactic context intact.
598 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
603 /// Converts the current token to a string using `self`'s reader.
604 pub fn this_token_to_string(&self) -> String {
605 pprust::token_to_string(&self.token)
608 fn token_descr(&self) -> Option<&'static str> {
609 Some(match &self.token {
610 t if t.is_special_ident() => "reserved identifier",
611 t if t.is_used_keyword() => "keyword",
612 t if t.is_unused_keyword() => "reserved keyword",
613 token::DocComment(..) => "doc comment",
618 crate fn this_token_descr(&self) -> String {
619 if let Some(prefix) = self.token_descr() {
620 format!("{} `{}`", prefix, self.this_token_to_string())
622 format!("`{}`", self.this_token_to_string())
626 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
627 match self.expect_one_of(&[], &[]) {
629 Ok(_) => unreachable!(),
633 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
634 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
635 if self.expected_tokens.is_empty() {
636 if self.token == *t {
640 let token_str = pprust::token_to_string(t);
641 let this_token_str = self.this_token_descr();
642 let mut err = self.fatal(&format!("expected `{}`, found {}",
646 let sp = if self.token == token::Token::Eof {
647 // EOF, don't want to point at the following char, but rather the last token
650 self.sess.source_map().next_point(self.prev_span)
652 let label_exp = format!("expected `{}`", token_str);
653 match self.recover_closing_delimiter(&[t.clone()], err) {
656 return Ok(recovered);
659 let cm = self.sess.source_map();
660 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
661 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
662 // When the spans are in the same line, it means that the only content
663 // between them is whitespace, point only at the found token.
664 err.span_label(self.span, label_exp);
667 err.span_label(sp, label_exp);
668 err.span_label(self.span, "unexpected token");
674 self.expect_one_of(slice::from_ref(t), &[])
678 /// Expect next token to be edible or inedible token. If edible,
679 /// then consume it; if inedible, then return without consuming
680 /// anything. Signal a fatal error if next token is unexpected.
681 pub fn expect_one_of(
683 edible: &[token::Token],
684 inedible: &[token::Token],
685 ) -> PResult<'a, bool /* recovered */> {
686 fn tokens_to_string(tokens: &[TokenType]) -> String {
687 let mut i = tokens.iter();
688 // This might be a sign we need a connect method on Iterator.
690 .map_or(String::new(), |t| t.to_string());
691 i.enumerate().fold(b, |mut b, (i, a)| {
692 if tokens.len() > 2 && i == tokens.len() - 2 {
694 } else if tokens.len() == 2 && i == tokens.len() - 2 {
699 b.push_str(&a.to_string());
703 if edible.contains(&self.token) {
706 } else if inedible.contains(&self.token) {
707 // leave it in the input
709 } else if self.last_unexpected_token_span == Some(self.span) {
712 let mut expected = edible.iter()
713 .map(|x| TokenType::Token(x.clone()))
714 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
715 .chain(self.expected_tokens.iter().cloned())
716 .collect::<Vec<_>>();
717 expected.sort_by_cached_key(|x| x.to_string());
719 let expect = tokens_to_string(&expected[..]);
720 let actual = self.this_token_to_string();
721 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
722 let short_expect = if expected.len() > 6 {
723 format!("{} possible tokens", expected.len())
727 (format!("expected one of {}, found `{}`", expect, actual),
728 (self.sess.source_map().next_point(self.prev_span),
729 format!("expected one of {} here", short_expect)))
730 } else if expected.is_empty() {
731 (format!("unexpected token: `{}`", actual),
732 (self.prev_span, "unexpected token after this".to_string()))
734 (format!("expected {}, found `{}`", expect, actual),
735 (self.sess.source_map().next_point(self.prev_span),
736 format!("expected {} here", expect)))
738 self.last_unexpected_token_span = Some(self.span);
739 let mut err = self.fatal(&msg_exp);
740 if self.token.is_ident_named("and") {
741 err.span_suggestion_short(
743 "use `&&` instead of `and` for the boolean operator",
745 Applicability::MaybeIncorrect,
748 if self.token.is_ident_named("or") {
749 err.span_suggestion_short(
751 "use `||` instead of `or` for the boolean operator",
753 Applicability::MaybeIncorrect,
756 let sp = if self.token == token::Token::Eof {
757 // This is EOF, don't want to point at the following char, but rather the last token
762 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
763 TokenType::Token(t) => Some(t.clone()),
765 }).collect::<Vec<_>>(), err) {
768 return Ok(recovered);
772 let is_semi_suggestable = expected.iter().any(|t| match t {
773 TokenType::Token(token::Semi) => true, // we expect a `;` here
775 }) && ( // a `;` would be expected before the current keyword
776 self.token.is_keyword(kw::Break) ||
777 self.token.is_keyword(kw::Continue) ||
778 self.token.is_keyword(kw::For) ||
779 self.token.is_keyword(kw::If) ||
780 self.token.is_keyword(kw::Let) ||
781 self.token.is_keyword(kw::Loop) ||
782 self.token.is_keyword(kw::Match) ||
783 self.token.is_keyword(kw::Return) ||
784 self.token.is_keyword(kw::While)
786 let cm = self.sess.source_map();
787 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
788 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
789 // The spans are in different lines, expected `;` and found `let` or `return`.
790 // High likelihood that it is only a missing `;`.
791 err.span_suggestion_short(
793 "a semicolon may be missing here",
795 Applicability::MaybeIncorrect,
800 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
801 // When the spans are in the same line, it means that the only content between
802 // them is whitespace, point at the found token in that case:
804 // X | () => { syntax error };
805 // | ^^^^^ expected one of 8 possible tokens here
807 // instead of having:
809 // X | () => { syntax error };
810 // | -^^^^^ unexpected token
812 // | expected one of 8 possible tokens here
813 err.span_label(self.span, label_exp);
815 _ if self.prev_span == syntax_pos::DUMMY_SP => {
816 // Account for macro context where the previous span might not be
817 // available to avoid incorrect output (#54841).
818 err.span_label(self.span, "unexpected token");
821 err.span_label(sp, label_exp);
822 err.span_label(self.span, "unexpected token");
829 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
830 fn interpolated_or_expr_span(&self,
831 expr: PResult<'a, P<Expr>>)
832 -> PResult<'a, (Span, P<Expr>)> {
834 if self.prev_token_kind == PrevTokenKind::Interpolated {
842 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
843 let mut err = self.struct_span_err(self.span,
844 &format!("expected identifier, found {}",
845 self.this_token_descr()));
846 if let token::Ident(ident, false) = &self.token {
847 if ident.is_raw_guess() {
850 "you can escape reserved keywords to use them as identifiers",
851 format!("r#{}", ident),
852 Applicability::MaybeIncorrect,
856 if let Some(token_descr) = self.token_descr() {
857 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
859 err.span_label(self.span, "expected identifier");
860 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
865 Applicability::MachineApplicable,
872 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
873 self.parse_ident_common(true)
876 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
878 token::Ident(ident, _) => {
879 if self.token.is_reserved_ident() {
880 let mut err = self.expected_ident_found();
887 let span = self.span;
889 Ok(Ident::new(ident.name, span))
892 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
893 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
895 self.expected_ident_found()
901 /// Checks if the next token is `tok`, and returns `true` if so.
903 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
905 crate fn check(&mut self, tok: &token::Token) -> bool {
906 let is_present = self.token == *tok;
907 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
911 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
912 pub fn eat(&mut self, tok: &token::Token) -> bool {
913 let is_present = self.check(tok);
914 if is_present { self.bump() }
918 fn check_keyword(&mut self, kw: Symbol) -> bool {
919 self.expected_tokens.push(TokenType::Keyword(kw));
920 self.token.is_keyword(kw)
923 /// If the next token is the given keyword, eats it and returns
924 /// `true`. Otherwise, returns `false`.
925 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
926 if self.check_keyword(kw) {
934 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
935 if self.token.is_keyword(kw) {
943 /// If the given word is not a keyword, signals an error.
944 /// If the next token is not the given word, signals an error.
945 /// Otherwise, eats it.
946 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
947 if !self.eat_keyword(kw) {
954 fn check_ident(&mut self) -> bool {
955 if self.token.is_ident() {
958 self.expected_tokens.push(TokenType::Ident);
963 fn check_path(&mut self) -> bool {
964 if self.token.is_path_start() {
967 self.expected_tokens.push(TokenType::Path);
972 fn check_type(&mut self) -> bool {
973 if self.token.can_begin_type() {
976 self.expected_tokens.push(TokenType::Type);
981 fn check_const_arg(&mut self) -> bool {
982 if self.token.can_begin_const_arg() {
985 self.expected_tokens.push(TokenType::Const);
990 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
991 /// and continues. If a `+` is not seen, returns `false`.
993 /// This is used when token-splitting `+=` into `+`.
994 /// See issue #47856 for an example of when this may occur.
995 fn eat_plus(&mut self) -> bool {
996 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
998 token::BinOp(token::Plus) => {
1002 token::BinOpEq(token::Plus) => {
1003 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1004 self.bump_with(token::Eq, span);
1012 /// Checks to see if the next token is either `+` or `+=`.
1013 /// Otherwise returns `false`.
1014 fn check_plus(&mut self) -> bool {
1015 if self.token.is_like_plus() {
1019 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1024 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1025 /// `&` and continues. If an `&` is not seen, signals an error.
1026 fn expect_and(&mut self) -> PResult<'a, ()> {
1027 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1029 token::BinOp(token::And) => {
1034 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1035 Ok(self.bump_with(token::BinOp(token::And), span))
1037 _ => self.unexpected()
1041 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1042 /// `|` and continues. If an `|` is not seen, signals an error.
1043 fn expect_or(&mut self) -> PResult<'a, ()> {
1044 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1046 token::BinOp(token::Or) => {
1051 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1052 Ok(self.bump_with(token::BinOp(token::Or), span))
1054 _ => self.unexpected()
1058 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1059 literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
1062 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1063 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1064 /// and continue. If a `<` is not seen, returns false.
1066 /// This is meant to be used when parsing generics on a path to get the
1068 fn eat_lt(&mut self) -> bool {
1069 self.expected_tokens.push(TokenType::Token(token::Lt));
1070 let ate = match self.token {
1075 token::BinOp(token::Shl) => {
1076 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1077 self.bump_with(token::Lt, span);
1081 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1082 self.bump_with(token::BinOp(token::Minus), span);
1089 // See doc comment for `unmatched_angle_bracket_count`.
1090 self.unmatched_angle_bracket_count += 1;
1091 self.max_angle_bracket_count += 1;
1092 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1098 fn expect_lt(&mut self) -> PResult<'a, ()> {
1106 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1107 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1108 fn expect_gt(&mut self) -> PResult<'a, ()> {
1109 self.expected_tokens.push(TokenType::Token(token::Gt));
1110 let ate = match self.token {
1115 token::BinOp(token::Shr) => {
1116 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1117 Some(self.bump_with(token::Gt, span))
1119 token::BinOpEq(token::Shr) => {
1120 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1121 Some(self.bump_with(token::Ge, span))
1124 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1125 Some(self.bump_with(token::Eq, span))
1132 // See doc comment for `unmatched_angle_bracket_count`.
1133 if self.unmatched_angle_bracket_count > 0 {
1134 self.unmatched_angle_bracket_count -= 1;
1135 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1140 None => self.unexpected(),
1144 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1145 /// passes through any errors encountered. Used for error recovery.
1146 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1147 let handler = self.diagnostic();
1149 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1151 TokenExpectType::Expect,
1152 |p| Ok(p.parse_token_tree())) {
1153 handler.cancel(err);
1157 /// Parses a sequence, including the closing delimiter. The function
1158 /// `f` must consume tokens until reaching the next separator or
1159 /// closing bracket.
1160 pub fn parse_seq_to_end<T, F>(&mut self,
1164 -> PResult<'a, Vec<T>> where
1165 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1167 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1174 /// Parses a sequence, not including the closing delimiter. The function
1175 /// `f` must consume tokens until reaching the next separator or
1176 /// closing bracket.
1177 pub fn parse_seq_to_before_end<T, F>(
1182 ) -> PResult<'a, (Vec<T>, bool)>
1183 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1185 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1188 fn parse_seq_to_before_tokens<T, F>(
1190 kets: &[&token::Token],
1192 expect: TokenExpectType,
1194 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1195 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1197 let mut first = true;
1198 let mut recovered = false;
1200 while !kets.iter().any(|k| {
1202 TokenExpectType::Expect => self.check(k),
1203 TokenExpectType::NoExpect => self.token == **k,
1207 token::CloseDelim(..) | token::Eof => break,
1210 if let Some(ref t) = sep.sep {
1214 match self.expect(t) {
1221 // Attempt to keep parsing if it was a similar separator
1222 if let Some(ref tokens) = t.similar_tokens() {
1223 if tokens.contains(&self.token) {
1228 // Attempt to keep parsing if it was an omitted separator
1243 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1245 TokenExpectType::Expect => self.check(k),
1246 TokenExpectType::NoExpect => self.token == **k,
1259 /// Parses a sequence, including the closing delimiter. The function
1260 /// `f` must consume tokens until reaching the next separator or
1261 /// closing bracket.
1262 fn parse_unspanned_seq<T, F>(
1268 ) -> PResult<'a, Vec<T>> where
1269 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1272 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1279 /// Advance the parser by one token
1280 pub fn bump(&mut self) {
1281 if self.prev_token_kind == PrevTokenKind::Eof {
1282 // Bumping after EOF is a bad sign, usually an infinite loop.
1283 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1286 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1288 // Record last token kind for possible error recovery.
1289 self.prev_token_kind = match self.token {
1290 token::DocComment(..) => PrevTokenKind::DocComment,
1291 token::Comma => PrevTokenKind::Comma,
1292 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1293 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1294 token::Interpolated(..) => PrevTokenKind::Interpolated,
1295 token::Eof => PrevTokenKind::Eof,
1296 token::Ident(..) => PrevTokenKind::Ident,
1297 _ => PrevTokenKind::Other,
1300 let next = self.next_tok();
1301 self.span = next.sp;
1302 self.token = next.tok;
1303 self.expected_tokens.clear();
1304 // check after each token
1305 self.process_potential_macro_variable();
1308 /// Advance the parser using provided token as a next one. Use this when
1309 /// consuming a part of a token. For example a single `<` from `<<`.
1310 fn bump_with(&mut self, next: token::Token, span: Span) {
1311 self.prev_span = self.span.with_hi(span.lo());
1312 // It would be incorrect to record the kind of the current token, but
1313 // fortunately for tokens currently using `bump_with`, the
1314 // prev_token_kind will be of no use anyway.
1315 self.prev_token_kind = PrevTokenKind::Other;
1318 self.expected_tokens.clear();
1321 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1322 F: FnOnce(&token::Token) -> R,
1325 return f(&self.token)
1328 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1329 Some(tree) => match tree {
1330 TokenTree::Token(_, tok) => tok,
1331 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1333 None => token::CloseDelim(self.token_cursor.frame.delim),
1337 crate fn look_ahead_span(&self, dist: usize) -> Span {
1342 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1343 Some(TokenTree::Token(span, _)) => span,
1344 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1345 None => self.look_ahead_span(dist - 1),
1348 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1349 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1351 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1352 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1354 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1355 err.span_err(sp, self.diagnostic())
1357 fn bug(&self, m: &str) -> ! {
1358 self.sess.span_diagnostic.span_bug(self.span, m)
1360 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1361 self.sess.span_diagnostic.span_err(sp, m)
1363 crate fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1364 self.sess.span_diagnostic.struct_span_err(sp, m)
1366 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1367 self.sess.span_diagnostic.span_bug(sp, m)
1370 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1371 self.sess.span_diagnostic.cancel(err)
1374 crate fn diagnostic(&self) -> &'a errors::Handler {
1375 &self.sess.span_diagnostic
1378 /// Is the current token one of the keywords that signals a bare function type?
1379 fn token_is_bare_fn_keyword(&mut self) -> bool {
1380 self.check_keyword(kw::Fn) ||
1381 self.check_keyword(kw::Unsafe) ||
1382 self.check_keyword(kw::Extern)
1385 /// Parses a `TyKind::BareFn` type.
1386 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1389 [unsafe] [extern "ABI"] fn (S) -> T
1399 let unsafety = self.parse_unsafety();
1400 let abi = if self.eat_keyword(kw::Extern) {
1401 self.parse_opt_abi()?.unwrap_or(Abi::C)
1406 self.expect_keyword(kw::Fn)?;
1407 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1408 let ret_ty = self.parse_ret_ty(false)?;
1409 let decl = P(FnDecl {
1414 Ok(TyKind::BareFn(P(BareFnTy {
1422 /// Parses asyncness: `async` or nothing.
1423 fn parse_asyncness(&mut self) -> IsAsync {
1424 if self.eat_keyword(kw::Async) {
1426 closure_id: ast::DUMMY_NODE_ID,
1427 return_impl_trait_id: ast::DUMMY_NODE_ID,
1428 arguments: Vec::new(),
1435 /// Parses unsafety: `unsafe` or nothing.
1436 fn parse_unsafety(&mut self) -> Unsafety {
1437 if self.eat_keyword(kw::Unsafe) {
1444 /// Parses the items in a trait declaration.
1445 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1446 maybe_whole!(self, NtTraitItem, |x| x);
1447 let attrs = self.parse_outer_attributes()?;
1448 let mut unclosed_delims = vec![];
1449 let (mut item, tokens) = self.collect_tokens(|this| {
1450 let item = this.parse_trait_item_(at_end, attrs);
1451 unclosed_delims.append(&mut this.unclosed_delims);
1454 self.unclosed_delims.append(&mut unclosed_delims);
1455 // See `parse_item` for why this clause is here.
1456 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1457 item.tokens = Some(tokens);
1462 fn parse_trait_item_(&mut self,
1464 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1467 let (name, node, generics) = if self.eat_keyword(kw::Type) {
1468 self.parse_trait_item_assoc_ty()?
1469 } else if self.is_const_item() {
1470 self.expect_keyword(kw::Const)?;
1471 let ident = self.parse_ident()?;
1472 self.expect(&token::Colon)?;
1473 let ty = self.parse_ty()?;
1474 let default = if self.eat(&token::Eq) {
1475 let expr = self.parse_expr()?;
1476 self.expect(&token::Semi)?;
1479 self.expect(&token::Semi)?;
1482 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1483 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1484 // trait item macro.
1485 (Ident::invalid(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1487 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
1489 let ident = self.parse_ident()?;
1490 let mut generics = self.parse_generics()?;
1492 let mut decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1493 // This is somewhat dubious; We don't want to allow
1494 // argument names to be left off if there is a
1497 // We don't allow argument names to be left off in edition 2018.
1498 p.parse_arg_general(p.span.rust_2018(), true, false)
1500 generics.where_clause = self.parse_where_clause()?;
1501 self.construct_async_arguments(&mut asyncness, &mut decl);
1503 let sig = ast::MethodSig {
1513 let body = match self.token {
1517 debug!("parse_trait_methods(): parsing required method");
1520 token::OpenDelim(token::Brace) => {
1521 debug!("parse_trait_methods(): parsing provided method");
1523 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1524 attrs.extend(inner_attrs.iter().cloned());
1527 token::Interpolated(ref nt) => {
1529 token::NtBlock(..) => {
1531 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1532 attrs.extend(inner_attrs.iter().cloned());
1536 let token_str = self.this_token_descr();
1537 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1539 err.span_label(self.span, "expected `;` or `{`");
1545 let token_str = self.this_token_descr();
1546 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1548 err.span_label(self.span, "expected `;` or `{`");
1552 (ident, ast::TraitItemKind::Method(sig, body), generics)
1556 id: ast::DUMMY_NODE_ID,
1561 span: lo.to(self.prev_span),
1566 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1567 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1568 if self.eat(&token::RArrow) {
1569 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1571 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1576 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1577 self.parse_ty_common(true, true, false)
1580 /// Parses a type in restricted contexts where `+` is not permitted.
1582 /// Example 1: `&'a TYPE`
1583 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1584 /// Example 2: `value1 as TYPE + value2`
1585 /// `+` is prohibited to avoid interactions with expression grammar.
1586 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1587 self.parse_ty_common(false, true, false)
1590 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1591 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1592 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1593 maybe_whole!(self, NtTy, |x| x);
1596 let mut impl_dyn_multi = false;
1597 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1598 // `(TYPE)` is a parenthesized type.
1599 // `(TYPE,)` is a tuple with a single field of type TYPE.
1600 let mut ts = vec![];
1601 let mut last_comma = false;
1602 while self.token != token::CloseDelim(token::Paren) {
1603 ts.push(self.parse_ty()?);
1604 if self.eat(&token::Comma) {
1611 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1612 self.expect(&token::CloseDelim(token::Paren))?;
1614 if ts.len() == 1 && !last_comma {
1615 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1616 let maybe_bounds = allow_plus && self.token.is_like_plus();
1618 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1619 TyKind::Path(None, ref path) if maybe_bounds => {
1620 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1622 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1623 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1624 let path = match bounds[0] {
1625 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1626 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1628 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1631 _ => TyKind::Paren(P(ty))
1636 } else if self.eat(&token::Not) {
1639 } else if self.eat(&token::BinOp(token::Star)) {
1641 TyKind::Ptr(self.parse_ptr()?)
1642 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1644 let t = self.parse_ty()?;
1645 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1646 let t = match self.maybe_parse_fixed_length_of_vec()? {
1647 None => TyKind::Slice(t),
1648 Some(length) => TyKind::Array(t, AnonConst {
1649 id: ast::DUMMY_NODE_ID,
1653 self.expect(&token::CloseDelim(token::Bracket))?;
1655 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1658 self.parse_borrowed_pointee()?
1659 } else if self.eat_keyword_noexpect(kw::Typeof) {
1661 // In order to not be ambiguous, the type must be surrounded by parens.
1662 self.expect(&token::OpenDelim(token::Paren))?;
1664 id: ast::DUMMY_NODE_ID,
1665 value: self.parse_expr()?,
1667 self.expect(&token::CloseDelim(token::Paren))?;
1669 } else if self.eat_keyword(kw::Underscore) {
1670 // A type to be inferred `_`
1672 } else if self.token_is_bare_fn_keyword() {
1673 // Function pointer type
1674 self.parse_ty_bare_fn(Vec::new())?
1675 } else if self.check_keyword(kw::For) {
1676 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1677 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1678 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1680 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1681 if self.token_is_bare_fn_keyword() {
1682 self.parse_ty_bare_fn(lifetime_defs)?
1684 let path = self.parse_path(PathStyle::Type)?;
1685 let parse_plus = allow_plus && self.check_plus();
1686 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1688 } else if self.eat_keyword(kw::Impl) {
1689 // Always parse bounds greedily for better error recovery.
1690 let bounds = self.parse_generic_bounds(None)?;
1691 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1692 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1693 } else if self.check_keyword(kw::Dyn) &&
1694 (self.span.rust_2018() ||
1695 self.look_ahead(1, |t| t.can_begin_bound() &&
1696 !can_continue_type_after_non_fn_ident(t))) {
1697 self.bump(); // `dyn`
1698 // Always parse bounds greedily for better error recovery.
1699 let bounds = self.parse_generic_bounds(None)?;
1700 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1701 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1702 } else if self.check(&token::Question) ||
1703 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1704 // Bound list (trait object type)
1705 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1706 TraitObjectSyntax::None)
1707 } else if self.eat_lt() {
1709 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1710 TyKind::Path(Some(qself), path)
1711 } else if self.token.is_path_start() {
1713 let path = self.parse_path(PathStyle::Type)?;
1714 if self.eat(&token::Not) {
1715 // Macro invocation in type position
1716 let (delim, tts) = self.expect_delimited_token_tree()?;
1717 let node = Mac_ { path, tts, delim };
1718 TyKind::Mac(respan(lo.to(self.prev_span), node))
1720 // Just a type path or bound list (trait object type) starting with a trait.
1722 // `Trait1 + Trait2 + 'a`
1723 if allow_plus && self.check_plus() {
1724 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1726 TyKind::Path(None, path)
1729 } else if self.check(&token::DotDotDot) {
1730 if allow_c_variadic {
1731 self.eat(&token::DotDotDot);
1734 return Err(self.fatal(
1735 "only foreign functions are allowed to be C-variadic"
1739 let msg = format!("expected type, found {}", self.this_token_descr());
1740 return Err(self.fatal(&msg));
1743 let span = lo.to(self.prev_span);
1744 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1746 // Try to recover from use of `+` with incorrect priority.
1747 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1748 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1749 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1752 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1753 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1754 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1755 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1757 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1758 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1760 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1763 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1764 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1765 let mutbl = self.parse_mutability();
1766 let ty = self.parse_ty_no_plus()?;
1767 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1770 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1771 let mutbl = if self.eat_keyword(kw::Mut) {
1773 } else if self.eat_keyword(kw::Const) {
1774 Mutability::Immutable
1776 let span = self.prev_span;
1777 let msg = "expected mut or const in raw pointer type";
1778 self.struct_span_err(span, msg)
1779 .span_label(span, msg)
1780 .help("use `*mut T` or `*const T` as appropriate")
1782 Mutability::Immutable
1784 let t = self.parse_ty_no_plus()?;
1785 Ok(MutTy { ty: t, mutbl: mutbl })
1788 fn is_named_argument(&self) -> bool {
1789 let offset = match self.token {
1790 token::Interpolated(ref nt) => match **nt {
1791 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1794 token::BinOp(token::And) | token::AndAnd => 1,
1795 _ if self.token.is_keyword(kw::Mut) => 1,
1799 self.look_ahead(offset, |t| t.is_ident()) &&
1800 self.look_ahead(offset + 1, |t| t == &token::Colon)
1803 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1805 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1806 if let token::DocComment(_) = self.token {
1807 let mut err = self.diagnostic().struct_span_err(
1809 &format!("documentation comments cannot be applied to {}", applied_to),
1811 err.span_label(self.span, "doc comments are not allowed here");
1814 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1815 *t == token::OpenDelim(token::Bracket)
1818 // Skip every token until next possible arg.
1819 while self.token != token::CloseDelim(token::Bracket) {
1822 let sp = lo.to(self.span);
1824 let mut err = self.diagnostic().struct_span_err(
1826 &format!("attributes cannot be applied to {}", applied_to),
1828 err.span_label(sp, "attributes are not allowed here");
1833 /// This version of parse arg doesn't necessarily require identifier names.
1834 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
1835 allow_c_variadic: bool) -> PResult<'a, Arg> {
1836 if let Ok(Some(_)) = self.parse_self_arg() {
1837 let mut err = self.struct_span_err(self.prev_span,
1838 "unexpected `self` argument in function");
1839 err.span_label(self.prev_span,
1840 "`self` is only valid as the first argument of an associated function");
1844 let (pat, ty) = if require_name || self.is_named_argument() {
1845 debug!("parse_arg_general parse_pat (require_name:{})",
1847 self.eat_incorrect_doc_comment("method arguments");
1848 let pat = self.parse_pat(Some("argument name"))?;
1850 if let Err(mut err) = self.expect(&token::Colon) {
1851 // If we find a pattern followed by an identifier, it could be an (incorrect)
1852 // C-style parameter declaration.
1853 if self.check_ident() && self.look_ahead(1, |t| {
1854 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1856 let ident = self.parse_ident().unwrap();
1857 let span = pat.span.with_hi(ident.span.hi());
1859 err.span_suggestion(
1861 "declare the type after the parameter binding",
1862 String::from("<identifier>: <type>"),
1863 Applicability::HasPlaceholders,
1865 } else if require_name && is_trait_item {
1866 if let PatKind::Ident(_, ident, _) = pat.node {
1867 err.span_suggestion(
1869 "explicitly ignore parameter",
1870 format!("_: {}", ident),
1871 Applicability::MachineApplicable,
1875 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1881 self.eat_incorrect_doc_comment("a method argument's type");
1882 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1884 debug!("parse_arg_general ident_to_pat");
1885 let parser_snapshot_before_ty = self.clone();
1886 self.eat_incorrect_doc_comment("a method argument's type");
1887 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1888 if ty.is_ok() && self.token != token::Comma &&
1889 self.token != token::CloseDelim(token::Paren) {
1890 // This wasn't actually a type, but a pattern looking like a type,
1891 // so we are going to rollback and re-parse for recovery.
1892 ty = self.unexpected();
1896 let ident = Ident::new(kw::Invalid, self.prev_span);
1898 id: ast::DUMMY_NODE_ID,
1899 node: PatKind::Ident(
1900 BindingMode::ByValue(Mutability::Immutable), ident, None),
1906 // If this is a C-variadic argument and we hit an error, return the
1908 if self.token == token::DotDotDot {
1911 // Recover from attempting to parse the argument as a type without pattern.
1913 mem::replace(self, parser_snapshot_before_ty);
1914 let pat = self.parse_pat(Some("argument name"))?;
1915 self.expect(&token::Colon)?;
1916 let ty = self.parse_ty()?;
1918 let mut err = self.diagnostic().struct_span_err_with_code(
1920 "patterns aren't allowed in methods without bodies",
1921 DiagnosticId::Error("E0642".into()),
1923 err.span_suggestion_short(
1925 "give this argument a name or use an underscore to ignore it",
1927 Applicability::MachineApplicable,
1931 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1933 node: PatKind::Wild,
1935 id: ast::DUMMY_NODE_ID
1942 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
1945 /// Parses a single function argument.
1946 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1947 self.parse_arg_general(true, false, false)
1950 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
1951 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1952 let pat = self.parse_pat(Some("argument name"))?;
1953 let t = if self.eat(&token::Colon) {
1957 id: ast::DUMMY_NODE_ID,
1958 node: TyKind::Infer,
1959 span: self.prev_span,
1965 id: ast::DUMMY_NODE_ID,
1966 source: ast::ArgSource::Normal,
1970 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1971 if self.eat(&token::Semi) {
1972 Ok(Some(self.parse_expr()?))
1978 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1979 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1980 maybe_whole_expr!(self);
1982 let minus_lo = self.span;
1983 let minus_present = self.eat(&token::BinOp(token::Minus));
1985 let literal = self.parse_lit()?;
1986 let hi = self.prev_span;
1987 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1990 let minus_hi = self.prev_span;
1991 let unary = self.mk_unary(UnOp::Neg, expr);
1992 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1998 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2000 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2001 let span = self.span;
2003 Ok(Ident::new(ident.name, span))
2005 _ => self.parse_ident(),
2009 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2011 token::Ident(ident, false) if ident.name == kw::Underscore => {
2012 let span = self.span;
2014 Ok(Ident::new(ident.name, span))
2016 _ => self.parse_ident(),
2020 /// Parses a qualified path.
2021 /// Assumes that the leading `<` has been parsed already.
2023 /// `qualified_path = <type [as trait_ref]>::path`
2028 /// `<T as U>::F::a<S>` (without disambiguator)
2029 /// `<T as U>::F::a::<S>` (with disambiguator)
2030 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2031 let lo = self.prev_span;
2032 let ty = self.parse_ty()?;
2034 // `path` will contain the prefix of the path up to the `>`,
2035 // if any (e.g., `U` in the `<T as U>::*` examples
2036 // above). `path_span` has the span of that path, or an empty
2037 // span in the case of something like `<T>::Bar`.
2038 let (mut path, path_span);
2039 if self.eat_keyword(kw::As) {
2040 let path_lo = self.span;
2041 path = self.parse_path(PathStyle::Type)?;
2042 path_span = path_lo.to(self.prev_span);
2044 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2045 path_span = self.span.to(self.span);
2048 // See doc comment for `unmatched_angle_bracket_count`.
2049 self.expect(&token::Gt)?;
2050 if self.unmatched_angle_bracket_count > 0 {
2051 self.unmatched_angle_bracket_count -= 1;
2052 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2055 self.expect(&token::ModSep)?;
2057 let qself = QSelf { ty, path_span, position: path.segments.len() };
2058 self.parse_path_segments(&mut path.segments, style)?;
2060 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2063 /// Parses simple paths.
2065 /// `path = [::] segment+`
2066 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2069 /// `a::b::C<D>` (without disambiguator)
2070 /// `a::b::C::<D>` (with disambiguator)
2071 /// `Fn(Args)` (without disambiguator)
2072 /// `Fn::(Args)` (with disambiguator)
2073 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2074 maybe_whole!(self, NtPath, |path| {
2075 if style == PathStyle::Mod &&
2076 path.segments.iter().any(|segment| segment.args.is_some()) {
2077 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2082 let lo = self.meta_var_span.unwrap_or(self.span);
2083 let mut segments = Vec::new();
2084 let mod_sep_ctxt = self.span.ctxt();
2085 if self.eat(&token::ModSep) {
2086 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2088 self.parse_path_segments(&mut segments, style)?;
2090 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2093 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2094 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2096 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2097 let meta_ident = match self.token {
2098 token::Interpolated(ref nt) => match **nt {
2099 token::NtMeta(ref meta) => match meta.node {
2100 ast::MetaItemKind::Word => Some(meta.path.clone()),
2107 if let Some(path) = meta_ident {
2111 self.parse_path(style)
2114 crate fn parse_path_segments(&mut self,
2115 segments: &mut Vec<PathSegment>,
2117 -> PResult<'a, ()> {
2119 let segment = self.parse_path_segment(style)?;
2120 if style == PathStyle::Expr {
2121 // In order to check for trailing angle brackets, we must have finished
2122 // recursing (`parse_path_segment` can indirectly call this function),
2123 // that is, the next token must be the highlighted part of the below example:
2125 // `Foo::<Bar as Baz<T>>::Qux`
2128 // As opposed to the below highlight (if we had only finished the first
2131 // `Foo::<Bar as Baz<T>>::Qux`
2134 // `PathStyle::Expr` is only provided at the root invocation and never in
2135 // `parse_path_segment` to recurse and therefore can be checked to maintain
2137 self.check_trailing_angle_brackets(&segment, token::ModSep);
2139 segments.push(segment);
2141 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2147 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2148 let ident = self.parse_path_segment_ident()?;
2150 let is_args_start = |token: &token::Token| match *token {
2151 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
2152 | token::LArrow => true,
2155 let check_args_start = |this: &mut Self| {
2156 this.expected_tokens.extend_from_slice(
2157 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2159 is_args_start(&this.token)
2162 Ok(if style == PathStyle::Type && check_args_start(self) ||
2163 style != PathStyle::Mod && self.check(&token::ModSep)
2164 && self.look_ahead(1, |t| is_args_start(t)) {
2165 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2166 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2167 // parsing a new path.
2168 if style == PathStyle::Expr {
2169 self.unmatched_angle_bracket_count = 0;
2170 self.max_angle_bracket_count = 0;
2173 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2174 self.eat(&token::ModSep);
2176 let args = if self.eat_lt() {
2178 let (args, bindings) =
2179 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2181 let span = lo.to(self.prev_span);
2182 AngleBracketedArgs { args, bindings, span }.into()
2186 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2187 &[&token::CloseDelim(token::Paren)],
2188 SeqSep::trailing_allowed(token::Comma),
2189 TokenExpectType::Expect,
2194 let span = lo.to(self.prev_span);
2195 let output = if self.eat(&token::RArrow) {
2196 Some(self.parse_ty_common(false, false, false)?)
2200 ParenthesizedArgs { inputs, output, span }.into()
2203 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2205 // Generic arguments are not found.
2206 PathSegment::from_ident(ident)
2210 crate fn check_lifetime(&mut self) -> bool {
2211 self.expected_tokens.push(TokenType::Lifetime);
2212 self.token.is_lifetime()
2215 /// Parses a single lifetime `'a` or panics.
2216 crate fn expect_lifetime(&mut self) -> Lifetime {
2217 if let Some(ident) = self.token.lifetime() {
2218 let span = self.span;
2220 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2222 self.span_bug(self.span, "not a lifetime")
2226 fn eat_label(&mut self) -> Option<Label> {
2227 if let Some(ident) = self.token.lifetime() {
2228 let span = self.span;
2230 Some(Label { ident: Ident::new(ident.name, span) })
2236 /// Parses mutability (`mut` or nothing).
2237 fn parse_mutability(&mut self) -> Mutability {
2238 if self.eat_keyword(kw::Mut) {
2241 Mutability::Immutable
2245 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2246 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token {
2247 self.expect_no_suffix(self.span, "a tuple index", suffix);
2249 Ok(Ident::new(symbol, self.prev_span))
2251 self.parse_ident_common(false)
2255 /// Parse ident (COLON expr)?
2256 fn parse_field(&mut self) -> PResult<'a, Field> {
2257 let attrs = self.parse_outer_attributes()?;
2260 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2261 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2262 t == &token::Colon || t == &token::Eq
2264 let fieldname = self.parse_field_name()?;
2266 // Check for an equals token. This means the source incorrectly attempts to
2267 // initialize a field with an eq rather than a colon.
2268 if self.token == token::Eq {
2270 .struct_span_err(self.span, "expected `:`, found `=`")
2272 fieldname.span.shrink_to_hi().to(self.span),
2273 "replace equals symbol with a colon",
2275 Applicability::MachineApplicable,
2280 (fieldname, self.parse_expr()?, false)
2282 let fieldname = self.parse_ident_common(false)?;
2284 // Mimic `x: x` for the `x` field shorthand.
2285 let path = ast::Path::from_ident(fieldname);
2286 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2287 (fieldname, expr, true)
2291 span: lo.to(expr.span),
2294 attrs: attrs.into(),
2298 crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2299 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2302 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2303 ExprKind::Unary(unop, expr)
2306 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2307 ExprKind::Binary(binop, lhs, rhs)
2310 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2311 ExprKind::Call(f, args)
2314 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2315 ExprKind::Index(expr, idx)
2319 start: Option<P<Expr>>,
2320 end: Option<P<Expr>>,
2321 limits: RangeLimits)
2322 -> PResult<'a, ast::ExprKind> {
2323 if end.is_none() && limits == RangeLimits::Closed {
2324 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2326 Ok(ExprKind::Range(start, end, limits))
2330 fn mk_assign_op(&self, binop: ast::BinOp,
2331 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2332 ExprKind::AssignOp(binop, lhs, rhs)
2335 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2336 let delim = match self.token {
2337 token::OpenDelim(delim) => delim,
2339 let msg = "expected open delimiter";
2340 let mut err = self.fatal(msg);
2341 err.span_label(self.span, msg);
2345 let tts = match self.parse_token_tree() {
2346 TokenTree::Delimited(_, _, tts) => tts,
2347 _ => unreachable!(),
2349 let delim = match delim {
2350 token::Paren => MacDelimiter::Parenthesis,
2351 token::Bracket => MacDelimiter::Bracket,
2352 token::Brace => MacDelimiter::Brace,
2353 token::NoDelim => self.bug("unexpected no delimiter"),
2355 Ok((delim, tts.into()))
2358 /// At the bottom (top?) of the precedence hierarchy,
2359 /// Parses things like parenthesized exprs, macros, `return`, etc.
2361 /// N.B., this does not parse outer attributes, and is private because it only works
2362 /// correctly if called from `parse_dot_or_call_expr()`.
2363 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2364 maybe_recover_from_interpolated_ty_qpath!(self, true);
2365 maybe_whole_expr!(self);
2367 // Outer attributes are already parsed and will be
2368 // added to the return value after the fact.
2370 // Therefore, prevent sub-parser from parsing
2371 // attributes by giving them a empty "already parsed" list.
2372 let mut attrs = ThinVec::new();
2375 let mut hi = self.span;
2379 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2381 token::OpenDelim(token::Paren) => {
2384 attrs.extend(self.parse_inner_attributes()?);
2386 // (e) is parenthesized e
2387 // (e,) is a tuple with only one field, e
2388 let mut es = vec![];
2389 let mut trailing_comma = false;
2390 let mut recovered = false;
2391 while self.token != token::CloseDelim(token::Paren) {
2392 es.push(match self.parse_expr() {
2395 // recover from parse error in tuple list
2396 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2399 recovered = self.expect_one_of(
2401 &[token::Comma, token::CloseDelim(token::Paren)],
2403 if self.eat(&token::Comma) {
2404 trailing_comma = true;
2406 trailing_comma = false;
2414 hi = self.prev_span;
2415 ex = if es.len() == 1 && !trailing_comma {
2416 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2421 token::OpenDelim(token::Brace) => {
2422 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2424 token::BinOp(token::Or) | token::OrOr => {
2425 return self.parse_lambda_expr(attrs);
2427 token::OpenDelim(token::Bracket) => {
2430 attrs.extend(self.parse_inner_attributes()?);
2432 if self.eat(&token::CloseDelim(token::Bracket)) {
2434 ex = ExprKind::Array(Vec::new());
2437 let first_expr = self.parse_expr()?;
2438 if self.eat(&token::Semi) {
2439 // Repeating array syntax: [ 0; 512 ]
2440 let count = AnonConst {
2441 id: ast::DUMMY_NODE_ID,
2442 value: self.parse_expr()?,
2444 self.expect(&token::CloseDelim(token::Bracket))?;
2445 ex = ExprKind::Repeat(first_expr, count);
2446 } else if self.eat(&token::Comma) {
2447 // Vector with two or more elements.
2448 let remaining_exprs = self.parse_seq_to_end(
2449 &token::CloseDelim(token::Bracket),
2450 SeqSep::trailing_allowed(token::Comma),
2451 |p| Ok(p.parse_expr()?)
2453 let mut exprs = vec![first_expr];
2454 exprs.extend(remaining_exprs);
2455 ex = ExprKind::Array(exprs);
2457 // Vector with one element.
2458 self.expect(&token::CloseDelim(token::Bracket))?;
2459 ex = ExprKind::Array(vec![first_expr]);
2462 hi = self.prev_span;
2466 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2468 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2470 if self.span.rust_2018() && self.check_keyword(kw::Async) {
2471 return if self.is_async_block() { // check for `async {` and `async move {`
2472 self.parse_async_block(attrs)
2474 self.parse_lambda_expr(attrs)
2477 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
2478 return self.parse_lambda_expr(attrs);
2480 if self.eat_keyword(kw::If) {
2481 return self.parse_if_expr(attrs);
2483 if self.eat_keyword(kw::For) {
2484 let lo = self.prev_span;
2485 return self.parse_for_expr(None, lo, attrs);
2487 if self.eat_keyword(kw::While) {
2488 let lo = self.prev_span;
2489 return self.parse_while_expr(None, lo, attrs);
2491 if let Some(label) = self.eat_label() {
2492 let lo = label.ident.span;
2493 self.expect(&token::Colon)?;
2494 if self.eat_keyword(kw::While) {
2495 return self.parse_while_expr(Some(label), lo, attrs)
2497 if self.eat_keyword(kw::For) {
2498 return self.parse_for_expr(Some(label), lo, attrs)
2500 if self.eat_keyword(kw::Loop) {
2501 return self.parse_loop_expr(Some(label), lo, attrs)
2503 if self.token == token::OpenDelim(token::Brace) {
2504 return self.parse_block_expr(Some(label),
2506 BlockCheckMode::Default,
2509 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2510 let mut err = self.fatal(msg);
2511 err.span_label(self.span, msg);
2514 if self.eat_keyword(kw::Loop) {
2515 let lo = self.prev_span;
2516 return self.parse_loop_expr(None, lo, attrs);
2518 if self.eat_keyword(kw::Continue) {
2519 let label = self.eat_label();
2520 let ex = ExprKind::Continue(label);
2521 let hi = self.prev_span;
2522 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2524 if self.eat_keyword(kw::Match) {
2525 let match_sp = self.prev_span;
2526 return self.parse_match_expr(attrs).map_err(|mut err| {
2527 err.span_label(match_sp, "while parsing this match expression");
2531 if self.eat_keyword(kw::Unsafe) {
2532 return self.parse_block_expr(
2535 BlockCheckMode::Unsafe(ast::UserProvided),
2538 if self.is_do_catch_block() {
2539 let mut db = self.fatal("found removed `do catch` syntax");
2540 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2543 if self.is_try_block() {
2545 assert!(self.eat_keyword(kw::Try));
2546 return self.parse_try_block(lo, attrs);
2548 if self.eat_keyword(kw::Return) {
2549 if self.token.can_begin_expr() {
2550 let e = self.parse_expr()?;
2552 ex = ExprKind::Ret(Some(e));
2554 ex = ExprKind::Ret(None);
2556 } else if self.eat_keyword(kw::Break) {
2557 let label = self.eat_label();
2558 let e = if self.token.can_begin_expr()
2559 && !(self.token == token::OpenDelim(token::Brace)
2560 && self.restrictions.contains(
2561 Restrictions::NO_STRUCT_LITERAL)) {
2562 Some(self.parse_expr()?)
2566 ex = ExprKind::Break(label, e);
2567 hi = self.prev_span;
2568 } else if self.eat_keyword(kw::Yield) {
2569 if self.token.can_begin_expr() {
2570 let e = self.parse_expr()?;
2572 ex = ExprKind::Yield(Some(e));
2574 ex = ExprKind::Yield(None);
2576 } else if self.token.is_keyword(kw::Let) {
2577 // Catch this syntax error here, instead of in `parse_ident`, so
2578 // that we can explicitly mention that let is not to be used as an expression
2579 let mut db = self.fatal("expected expression, found statement (`let`)");
2580 db.span_label(self.span, "expected expression");
2581 db.note("variable declaration using `let` is a statement");
2583 } else if self.span.rust_2018() && self.eat_keyword(kw::Await) {
2584 let (await_hi, e_kind) = self.parse_await_macro_or_alt(lo, self.prev_span)?;
2587 } else if self.token.is_path_start() {
2588 let path = self.parse_path(PathStyle::Expr)?;
2590 // `!`, as an operator, is prefix, so we know this isn't that
2591 if self.eat(&token::Not) {
2592 // MACRO INVOCATION expression
2593 let (delim, tts) = self.expect_delimited_token_tree()?;
2594 hi = self.prev_span;
2595 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2596 } else if self.check(&token::OpenDelim(token::Brace)) {
2597 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2601 ex = ExprKind::Path(None, path);
2605 ex = ExprKind::Path(None, path);
2608 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2609 // Don't complain about bare semicolons after unclosed braces
2610 // recovery in order to keep the error count down. Fixing the
2611 // delimiters will possibly also fix the bare semicolon found in
2612 // expression context. For example, silence the following error:
2614 // error: expected expression, found `;`
2618 // | ^ expected expression
2621 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2623 match self.parse_literal_maybe_minus() {
2626 ex = expr.node.clone();
2629 self.cancel(&mut err);
2630 let msg = format!("expected expression, found {}",
2631 self.this_token_descr());
2632 let mut err = self.fatal(&msg);
2633 let sp = self.sess.source_map().start_point(self.span);
2634 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow()
2637 self.sess.expr_parentheses_needed(&mut err, *sp, None);
2639 err.span_label(self.span, "expected expression");
2647 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2648 self.maybe_recover_from_bad_qpath(expr, true)
2651 /// Parse `await!(<expr>)` calls, or alternatively recover from incorrect but reasonable
2652 /// alternative syntaxes `await <expr>`, `await? <expr>`, `await(<expr>)` and
2653 /// `await { <expr> }`.
2654 fn parse_await_macro_or_alt(
2658 ) -> PResult<'a, (Span, ExprKind)> {
2659 if self.token == token::Not {
2660 // Handle correct `await!(<expr>)`.
2661 // FIXME: make this an error when `await!` is no longer supported
2662 // https://github.com/rust-lang/rust/issues/60610
2663 self.expect(&token::Not)?;
2664 self.expect(&token::OpenDelim(token::Paren))?;
2665 let expr = self.parse_expr().map_err(|mut err| {
2666 err.span_label(await_sp, "while parsing this await macro call");
2669 self.expect(&token::CloseDelim(token::Paren))?;
2670 Ok((self.prev_span, ExprKind::Await(ast::AwaitOrigin::MacroLike, expr)))
2671 } else { // Handle `await <expr>`.
2672 self.parse_incorrect_await_syntax(lo, await_sp)
2676 fn maybe_parse_struct_expr(
2680 attrs: &ThinVec<Attribute>,
2681 ) -> Option<PResult<'a, P<Expr>>> {
2682 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2683 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2684 // `{ ident, ` cannot start a block
2685 self.look_ahead(2, |t| t == &token::Comma) ||
2686 self.look_ahead(2, |t| t == &token::Colon) && (
2687 // `{ ident: token, ` cannot start a block
2688 self.look_ahead(4, |t| t == &token::Comma) ||
2689 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2690 self.look_ahead(3, |t| !t.can_begin_type())
2694 if struct_allowed || certainly_not_a_block() {
2695 // This is a struct literal, but we don't can't accept them here
2696 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2697 if let (Ok(expr), false) = (&expr, struct_allowed) {
2698 let mut err = self.diagnostic().struct_span_err(
2700 "struct literals are not allowed here",
2702 err.multipart_suggestion(
2703 "surround the struct literal with parentheses",
2705 (lo.shrink_to_lo(), "(".to_string()),
2706 (expr.span.shrink_to_hi(), ")".to_string()),
2708 Applicability::MachineApplicable,
2717 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2718 -> PResult<'a, P<Expr>> {
2719 let struct_sp = lo.to(self.prev_span);
2721 let mut fields = Vec::new();
2722 let mut base = None;
2724 attrs.extend(self.parse_inner_attributes()?);
2726 while self.token != token::CloseDelim(token::Brace) {
2727 if self.eat(&token::DotDot) {
2728 let exp_span = self.prev_span;
2729 match self.parse_expr() {
2735 self.recover_stmt();
2738 if self.token == token::Comma {
2739 let mut err = self.sess.span_diagnostic.mut_span_err(
2740 exp_span.to(self.prev_span),
2741 "cannot use a comma after the base struct",
2743 err.span_suggestion_short(
2745 "remove this comma",
2747 Applicability::MachineApplicable
2749 err.note("the base struct must always be the last field");
2751 self.recover_stmt();
2756 let mut recovery_field = None;
2757 if let token::Ident(ident, _) = self.token {
2758 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2759 // Use in case of error after field-looking code: `S { foo: () with a }`
2760 let mut ident = ident.clone();
2761 ident.span = self.span;
2762 recovery_field = Some(ast::Field {
2765 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2766 is_shorthand: false,
2767 attrs: ThinVec::new(),
2771 let mut parsed_field = None;
2772 match self.parse_field() {
2773 Ok(f) => parsed_field = Some(f),
2775 e.span_label(struct_sp, "while parsing this struct");
2778 // If the next token is a comma, then try to parse
2779 // what comes next as additional fields, rather than
2780 // bailing out until next `}`.
2781 if self.token != token::Comma {
2782 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2783 if self.token != token::Comma {
2790 match self.expect_one_of(&[token::Comma],
2791 &[token::CloseDelim(token::Brace)]) {
2792 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2793 // only include the field if there's no parse error for the field name
2797 if let Some(f) = recovery_field {
2800 e.span_label(struct_sp, "while parsing this struct");
2802 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2803 self.eat(&token::Comma);
2808 let span = lo.to(self.span);
2809 self.expect(&token::CloseDelim(token::Brace))?;
2810 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2813 fn parse_or_use_outer_attributes(&mut self,
2814 already_parsed_attrs: Option<ThinVec<Attribute>>)
2815 -> PResult<'a, ThinVec<Attribute>> {
2816 if let Some(attrs) = already_parsed_attrs {
2819 self.parse_outer_attributes().map(|a| a.into())
2823 /// Parses a block or unsafe block.
2824 crate fn parse_block_expr(
2826 opt_label: Option<Label>,
2828 blk_mode: BlockCheckMode,
2829 outer_attrs: ThinVec<Attribute>,
2830 ) -> PResult<'a, P<Expr>> {
2831 self.expect(&token::OpenDelim(token::Brace))?;
2833 let mut attrs = outer_attrs;
2834 attrs.extend(self.parse_inner_attributes()?);
2836 let blk = self.parse_block_tail(lo, blk_mode)?;
2837 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2840 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2841 fn parse_dot_or_call_expr(&mut self,
2842 already_parsed_attrs: Option<ThinVec<Attribute>>)
2843 -> PResult<'a, P<Expr>> {
2844 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2846 let b = self.parse_bottom_expr();
2847 let (span, b) = self.interpolated_or_expr_span(b)?;
2848 self.parse_dot_or_call_expr_with(b, span, attrs)
2851 fn parse_dot_or_call_expr_with(&mut self,
2854 mut attrs: ThinVec<Attribute>)
2855 -> PResult<'a, P<Expr>> {
2856 // Stitch the list of outer attributes onto the return value.
2857 // A little bit ugly, but the best way given the current code
2859 self.parse_dot_or_call_expr_with_(e0, lo)
2861 expr.map(|mut expr| {
2862 attrs.extend::<Vec<_>>(expr.attrs.into());
2865 ExprKind::If(..) | ExprKind::IfLet(..) => {
2866 if !expr.attrs.is_empty() {
2867 // Just point to the first attribute in there...
2868 let span = expr.attrs[0].span;
2871 "attributes are not yet allowed on `if` \
2882 // Assuming we have just parsed `.`, continue parsing into an expression.
2883 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2884 if self.span.rust_2018() && self.eat_keyword(kw::Await) {
2885 let span = lo.to(self.prev_span);
2886 let await_expr = self.mk_expr(
2888 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
2891 self.recover_from_await_method_call();
2892 return Ok(await_expr);
2894 let segment = self.parse_path_segment(PathStyle::Expr)?;
2895 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2897 Ok(match self.token {
2898 token::OpenDelim(token::Paren) => {
2899 // Method call `expr.f()`
2900 let mut args = self.parse_unspanned_seq(
2901 &token::OpenDelim(token::Paren),
2902 &token::CloseDelim(token::Paren),
2903 SeqSep::trailing_allowed(token::Comma),
2904 |p| Ok(p.parse_expr()?)
2906 args.insert(0, self_arg);
2908 let span = lo.to(self.prev_span);
2909 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2912 // Field access `expr.f`
2913 if let Some(args) = segment.args {
2914 self.span_err(args.span(),
2915 "field expressions may not have generic arguments");
2918 let span = lo.to(self.prev_span);
2919 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2924 /// This function checks if there are trailing angle brackets and produces
2925 /// a diagnostic to suggest removing them.
2927 /// ```ignore (diagnostic)
2928 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
2929 /// ^^ help: remove extra angle brackets
2931 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
2932 // This function is intended to be invoked after parsing a path segment where there are two
2935 // 1. A specific token is expected after the path segment.
2936 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
2937 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
2938 // 2. No specific token is expected after the path segment.
2939 // eg. `x.foo` (field access)
2941 // This function is called after parsing `.foo` and before parsing the token `end` (if
2942 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
2945 // We only care about trailing angle brackets if we previously parsed angle bracket
2946 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
2947 // removed in this case:
2949 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
2951 // This case is particularly tricky as we won't notice it just looking at the tokens -
2952 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
2953 // have already been parsed):
2955 // `x.foo::<u32>>>(3)`
2956 let parsed_angle_bracket_args = segment.args
2958 .map(|args| args.is_angle_bracketed())
2962 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
2963 parsed_angle_bracket_args,
2965 if !parsed_angle_bracket_args {
2969 // Keep the span at the start so we can highlight the sequence of `>` characters to be
2973 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
2974 // (since we might have the field access case and the characters we're eating are
2975 // actual operators and not trailing characters - ie `x.foo >> 3`).
2976 let mut position = 0;
2978 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
2979 // many of each (so we can correctly pluralize our error messages) and continue to
2981 let mut number_of_shr = 0;
2982 let mut number_of_gt = 0;
2983 while self.look_ahead(position, |t| {
2984 trace!("check_trailing_angle_brackets: t={:?}", t);
2985 if *t == token::BinOp(token::BinOpToken::Shr) {
2988 } else if *t == token::Gt {
2998 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3000 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3001 number_of_gt, number_of_shr,
3003 if number_of_gt < 1 && number_of_shr < 1 {
3007 // Finally, double check that we have our end token as otherwise this is the
3009 if self.look_ahead(position, |t| {
3010 trace!("check_trailing_angle_brackets: t={:?}", t);
3013 // Eat from where we started until the end token so that parsing can continue
3014 // as if we didn't have those extra angle brackets.
3015 self.eat_to_tokens(&[&end]);
3016 let span = lo.until(self.span);
3018 let plural = number_of_gt > 1 || number_of_shr >= 1;
3022 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3026 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3028 Applicability::MachineApplicable,
3034 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3039 while self.eat(&token::Question) {
3040 let hi = self.prev_span;
3041 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3045 if self.eat(&token::Dot) {
3047 token::Ident(..) => {
3048 e = self.parse_dot_suffix(e, lo)?;
3050 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
3051 let span = self.span;
3053 let field = ExprKind::Field(e, Ident::new(symbol, span));
3054 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3056 self.expect_no_suffix(span, "a tuple index", suffix);
3058 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
3060 let fstr = symbol.as_str();
3061 let msg = format!("unexpected token: `{}`", symbol);
3062 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
3063 err.span_label(self.prev_span, "unexpected token");
3064 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3065 let float = match fstr.parse::<f64>().ok() {
3069 let sugg = pprust::to_string(|s| {
3070 use crate::print::pprust::PrintState;
3074 s.print_usize(float.trunc() as usize)?;
3077 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3079 err.span_suggestion(
3080 lo.to(self.prev_span),
3081 "try parenthesizing the first index",
3083 Applicability::MachineApplicable
3090 // FIXME Could factor this out into non_fatal_unexpected or something.
3091 let actual = self.this_token_to_string();
3092 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3097 if self.expr_is_complete(&e) { break; }
3100 token::OpenDelim(token::Paren) => {
3101 let seq = self.parse_unspanned_seq(
3102 &token::OpenDelim(token::Paren),
3103 &token::CloseDelim(token::Paren),
3104 SeqSep::trailing_allowed(token::Comma),
3105 |p| Ok(p.parse_expr()?)
3107 let nd = self.mk_call(e, es);
3108 let hi = self.prev_span;
3109 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3111 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3115 // Could be either an index expression or a slicing expression.
3116 token::OpenDelim(token::Bracket) => {
3118 let ix = self.parse_expr()?;
3120 self.expect(&token::CloseDelim(token::Bracket))?;
3121 let index = self.mk_index(e, ix);
3122 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3130 crate fn process_potential_macro_variable(&mut self) {
3131 let (token, span) = match self.token {
3132 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3133 self.look_ahead(1, |t| t.is_ident()) => {
3135 let name = match self.token {
3136 token::Ident(ident, _) => ident,
3139 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3140 err.span_label(self.span, "unknown macro variable");
3145 token::Interpolated(ref nt) => {
3146 self.meta_var_span = Some(self.span);
3147 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3148 // and lifetime tokens, so the former are never encountered during normal parsing.
3150 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3151 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3161 /// Parses a single token tree from the input.
3162 crate fn parse_token_tree(&mut self) -> TokenTree {
3164 token::OpenDelim(..) => {
3165 let frame = mem::replace(&mut self.token_cursor.frame,
3166 self.token_cursor.stack.pop().unwrap());
3167 self.span = frame.span.entire();
3169 TokenTree::Delimited(
3172 frame.tree_cursor.stream.into(),
3175 token::CloseDelim(_) | token::Eof => unreachable!(),
3177 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3179 TokenTree::Token(span, token)
3184 // parse a stream of tokens into a list of TokenTree's,
3186 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3187 let mut tts = Vec::new();
3188 while self.token != token::Eof {
3189 tts.push(self.parse_token_tree());
3194 pub fn parse_tokens(&mut self) -> TokenStream {
3195 let mut result = Vec::new();
3198 token::Eof | token::CloseDelim(..) => break,
3199 _ => result.push(self.parse_token_tree().into()),
3202 TokenStream::new(result)
3205 /// Parse a prefix-unary-operator expr
3206 fn parse_prefix_expr(&mut self,
3207 already_parsed_attrs: Option<ThinVec<Attribute>>)
3208 -> PResult<'a, P<Expr>> {
3209 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3211 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3212 let (hi, ex) = match self.token {
3215 let e = self.parse_prefix_expr(None);
3216 let (span, e) = self.interpolated_or_expr_span(e)?;
3217 (lo.to(span), self.mk_unary(UnOp::Not, e))
3219 // Suggest `!` for bitwise negation when encountering a `~`
3222 let e = self.parse_prefix_expr(None);
3223 let (span, e) = self.interpolated_or_expr_span(e)?;
3224 let span_of_tilde = lo;
3225 let mut err = self.diagnostic()
3226 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3227 err.span_suggestion_short(
3229 "use `!` to perform bitwise negation",
3231 Applicability::MachineApplicable
3234 (lo.to(span), self.mk_unary(UnOp::Not, e))
3236 token::BinOp(token::Minus) => {
3238 let e = self.parse_prefix_expr(None);
3239 let (span, e) = self.interpolated_or_expr_span(e)?;
3240 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3242 token::BinOp(token::Star) => {
3244 let e = self.parse_prefix_expr(None);
3245 let (span, e) = self.interpolated_or_expr_span(e)?;
3246 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3248 token::BinOp(token::And) | token::AndAnd => {
3250 let m = self.parse_mutability();
3251 let e = self.parse_prefix_expr(None);
3252 let (span, e) = self.interpolated_or_expr_span(e)?;
3253 (lo.to(span), ExprKind::AddrOf(m, e))
3255 token::Ident(..) if self.token.is_keyword(kw::In) => {
3257 let place = self.parse_expr_res(
3258 Restrictions::NO_STRUCT_LITERAL,
3261 let blk = self.parse_block()?;
3262 let span = blk.span;
3263 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3264 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3266 token::Ident(..) if self.token.is_keyword(kw::Box) => {
3268 let e = self.parse_prefix_expr(None);
3269 let (span, e) = self.interpolated_or_expr_span(e)?;
3270 (lo.to(span), ExprKind::Box(e))
3272 token::Ident(..) if self.token.is_ident_named("not") => {
3273 // `not` is just an ordinary identifier in Rust-the-language,
3274 // but as `rustc`-the-compiler, we can issue clever diagnostics
3275 // for confused users who really want to say `!`
3276 let token_cannot_continue_expr = |t: &token::Token| match *t {
3277 // These tokens can start an expression after `!`, but
3278 // can't continue an expression after an ident
3279 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3280 token::Literal(..) | token::Pound => true,
3281 token::Interpolated(ref nt) => match **nt {
3282 token::NtIdent(..) | token::NtExpr(..) |
3283 token::NtBlock(..) | token::NtPath(..) => true,
3288 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3289 if cannot_continue_expr {
3291 // Emit the error ...
3292 let mut err = self.diagnostic()
3293 .struct_span_err(self.span,
3294 &format!("unexpected {} after identifier",
3295 self.this_token_descr()));
3296 // span the `not` plus trailing whitespace to avoid
3297 // trailing whitespace after the `!` in our suggestion
3298 let to_replace = self.sess.source_map()
3299 .span_until_non_whitespace(lo.to(self.span));
3300 err.span_suggestion_short(
3302 "use `!` to perform logical negation",
3304 Applicability::MachineApplicable
3307 // —and recover! (just as if we were in the block
3308 // for the `token::Not` arm)
3309 let e = self.parse_prefix_expr(None);
3310 let (span, e) = self.interpolated_or_expr_span(e)?;
3311 (lo.to(span), self.mk_unary(UnOp::Not, e))
3313 return self.parse_dot_or_call_expr(Some(attrs));
3316 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3318 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3321 /// Parses an associative expression.
3323 /// This parses an expression accounting for associativity and precedence of the operators in
3326 fn parse_assoc_expr(&mut self,
3327 already_parsed_attrs: Option<ThinVec<Attribute>>)
3328 -> PResult<'a, P<Expr>> {
3329 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3332 /// Parses an associative expression with operators of at least `min_prec` precedence.
3333 fn parse_assoc_expr_with(&mut self,
3336 -> PResult<'a, P<Expr>> {
3337 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3340 let attrs = match lhs {
3341 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3344 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3345 return self.parse_prefix_range_expr(attrs);
3347 self.parse_prefix_expr(attrs)?
3351 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
3353 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3356 (false, _) => {} // continue parsing the expression
3357 // An exhaustive check is done in the following block, but these are checked first
3358 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
3359 // want to keep their span info to improve diagnostics in these cases in a later stage.
3360 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
3361 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
3362 (true, Some(AssocOp::Add)) => { // `{ 42 } + 42
3363 // These cases are ambiguous and can't be identified in the parser alone
3364 let sp = self.sess.source_map().start_point(self.span);
3365 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
3368 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
3371 (true, Some(_)) => {
3372 // We've found an expression that would be parsed as a statement, but the next
3373 // token implies this should be parsed as an expression.
3374 // For example: `if let Some(x) = x { x } else { 0 } / 2`
3375 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
3376 "expected expression, found `{}`",
3377 pprust::token_to_string(&self.token),
3379 err.span_label(self.span, "expected expression");
3380 self.sess.expr_parentheses_needed(
3383 Some(pprust::expr_to_string(&lhs),
3388 self.expected_tokens.push(TokenType::Operator);
3389 while let Some(op) = AssocOp::from_token(&self.token) {
3391 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3392 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3393 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3394 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3395 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3396 (PrevTokenKind::Interpolated, _) => self.prev_span,
3397 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3398 if path.segments.len() == 1 => self.prev_span,
3402 let cur_op_span = self.span;
3403 let restrictions = if op.is_assign_like() {
3404 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3408 let prec = op.precedence();
3409 if prec < min_prec {
3412 // Check for deprecated `...` syntax
3413 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3414 self.err_dotdotdot_syntax(self.span);
3418 if op.is_comparison() {
3419 self.check_no_chained_comparison(&lhs, &op);
3422 if op == AssocOp::As {
3423 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3425 } else if op == AssocOp::Colon {
3426 let maybe_path = self.could_ascription_be_path(&lhs.node);
3427 let next_sp = self.span;
3429 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3432 self.bad_type_ascription(
3443 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3444 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3445 // generalise it to the Fixity::None code.
3447 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3448 // two variants are handled with `parse_prefix_range_expr` call above.
3449 let rhs = if self.is_at_start_of_range_notation_rhs() {
3450 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
3454 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3459 let limits = if op == AssocOp::DotDot {
3460 RangeLimits::HalfOpen
3465 let r = self.mk_range(Some(lhs), rhs, limits)?;
3466 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3470 let fixity = op.fixity();
3471 let prec_adjustment = match fixity {
3474 // We currently have no non-associative operators that are not handled above by
3475 // the special cases. The code is here only for future convenience.
3478 let rhs = self.with_res(
3479 restrictions - Restrictions::STMT_EXPR,
3480 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
3483 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3484 // including the attributes.
3488 .filter(|a| a.style == AttrStyle::Outer)
3490 .map_or(lhs_span, |a| a.span);
3491 let span = lhs_span.to(rhs.span);
3493 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3494 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3495 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3496 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3497 AssocOp::Greater | AssocOp::GreaterEqual => {
3498 let ast_op = op.to_ast_binop().unwrap();
3499 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3500 self.mk_expr(span, binary, ThinVec::new())
3502 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3503 AssocOp::ObsoleteInPlace =>
3504 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3505 AssocOp::AssignOp(k) => {
3507 token::Plus => BinOpKind::Add,
3508 token::Minus => BinOpKind::Sub,
3509 token::Star => BinOpKind::Mul,
3510 token::Slash => BinOpKind::Div,
3511 token::Percent => BinOpKind::Rem,
3512 token::Caret => BinOpKind::BitXor,
3513 token::And => BinOpKind::BitAnd,
3514 token::Or => BinOpKind::BitOr,
3515 token::Shl => BinOpKind::Shl,
3516 token::Shr => BinOpKind::Shr,
3518 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3519 self.mk_expr(span, aopexpr, ThinVec::new())
3521 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3522 self.bug("AssocOp should have been handled by special case")
3526 if let Fixity::None = fixity { break }
3531 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3532 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3533 -> PResult<'a, P<Expr>> {
3534 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3535 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3538 // Save the state of the parser before parsing type normally, in case there is a
3539 // LessThan comparison after this cast.
3540 let parser_snapshot_before_type = self.clone();
3541 match self.parse_ty_no_plus() {
3543 Ok(mk_expr(self, rhs))
3545 Err(mut type_err) => {
3546 // Rewind to before attempting to parse the type with generics, to recover
3547 // from situations like `x as usize < y` in which we first tried to parse
3548 // `usize < y` as a type with generic arguments.
3549 let parser_snapshot_after_type = self.clone();
3550 mem::replace(self, parser_snapshot_before_type);
3552 match self.parse_path(PathStyle::Expr) {
3554 let (op_noun, op_verb) = match self.token {
3555 token::Lt => ("comparison", "comparing"),
3556 token::BinOp(token::Shl) => ("shift", "shifting"),
3558 // We can end up here even without `<` being the next token, for
3559 // example because `parse_ty_no_plus` returns `Err` on keywords,
3560 // but `parse_path` returns `Ok` on them due to error recovery.
3561 // Return original error and parser state.
3562 mem::replace(self, parser_snapshot_after_type);
3563 return Err(type_err);
3567 // Successfully parsed the type path leaving a `<` yet to parse.
3570 // Report non-fatal diagnostics, keep `x as usize` as an expression
3571 // in AST and continue parsing.
3572 let msg = format!("`<` is interpreted as a start of generic \
3573 arguments for `{}`, not a {}", path, op_noun);
3574 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3575 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3576 "interpreted as generic arguments");
3577 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3579 let expr = mk_expr(self, P(Ty {
3581 node: TyKind::Path(None, path),
3582 id: ast::DUMMY_NODE_ID
3585 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3586 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3587 err.span_suggestion(
3589 &format!("try {} the cast value", op_verb),
3590 format!("({})", expr_str),
3591 Applicability::MachineApplicable
3597 Err(mut path_err) => {
3598 // Couldn't parse as a path, return original error and parser state.
3600 mem::replace(self, parser_snapshot_after_type);
3608 /// Produce an error if comparison operators are chained (RFC #558).
3609 /// We only need to check lhs, not rhs, because all comparison ops
3610 /// have same precedence and are left-associative
3611 fn check_no_chained_comparison(&self, lhs: &Expr, outer_op: &AssocOp) {
3612 debug_assert!(outer_op.is_comparison(),
3613 "check_no_chained_comparison: {:?} is not comparison",
3616 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3617 // respan to include both operators
3618 let op_span = op.span.to(self.span);
3619 let mut err = self.diagnostic().struct_span_err(op_span,
3620 "chained comparison operators require parentheses");
3621 if op.node == BinOpKind::Lt &&
3622 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3623 *outer_op == AssocOp::Greater // even in a case like the following:
3624 { // Foo<Bar<Baz<Qux, ()>>>
3626 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3627 err.help("or use `(...)` if you meant to specify fn arguments");
3635 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3636 fn parse_prefix_range_expr(&mut self,
3637 already_parsed_attrs: Option<ThinVec<Attribute>>)
3638 -> PResult<'a, P<Expr>> {
3639 // Check for deprecated `...` syntax
3640 if self.token == token::DotDotDot {
3641 self.err_dotdotdot_syntax(self.span);
3644 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3645 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3647 let tok = self.token.clone();
3648 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3650 let mut hi = self.span;
3652 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3653 // RHS must be parsed with more associativity than the dots.
3654 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3655 Some(self.parse_assoc_expr_with(next_prec,
3656 LhsExpr::NotYetParsed)
3664 let limits = if tok == token::DotDot {
3665 RangeLimits::HalfOpen
3670 let r = self.mk_range(None, opt_end, limits)?;
3671 Ok(self.mk_expr(lo.to(hi), r, attrs))
3674 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3675 if self.token.can_begin_expr() {
3676 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3677 if self.token == token::OpenDelim(token::Brace) {
3678 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3686 /// Parses an `if` or `if let` expression (`if` token already eaten).
3687 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3688 if self.check_keyword(kw::Let) {
3689 return self.parse_if_let_expr(attrs);
3691 let lo = self.prev_span;
3692 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3694 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3695 // verify that the last statement is either an implicit return (no `;`) or an explicit
3696 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3697 // the dead code lint.
3698 if self.eat_keyword(kw::Else) || !cond.returns() {
3699 let sp = self.sess.source_map().next_point(lo);
3700 let mut err = self.diagnostic()
3701 .struct_span_err(sp, "missing condition for `if` statemement");
3702 err.span_label(sp, "expected if condition here");
3705 let not_block = self.token != token::OpenDelim(token::Brace);
3706 let thn = self.parse_block().map_err(|mut err| {
3708 err.span_label(lo, "this `if` statement has a condition, but no block");
3712 let mut els: Option<P<Expr>> = None;
3713 let mut hi = thn.span;
3714 if self.eat_keyword(kw::Else) {
3715 let elexpr = self.parse_else_expr()?;
3719 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3722 /// Parses an `if let` expression (`if` token already eaten).
3723 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3724 -> PResult<'a, P<Expr>> {
3725 let lo = self.prev_span;
3726 self.expect_keyword(kw::Let)?;
3727 let pats = self.parse_pats()?;
3728 self.expect(&token::Eq)?;
3729 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3730 let thn = self.parse_block()?;
3731 let (hi, els) = if self.eat_keyword(kw::Else) {
3732 let expr = self.parse_else_expr()?;
3733 (expr.span, Some(expr))
3737 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3740 /// Parses `move |args| expr`.
3741 fn parse_lambda_expr(&mut self,
3742 attrs: ThinVec<Attribute>)
3743 -> PResult<'a, P<Expr>>
3746 let movability = if self.eat_keyword(kw::Static) {
3751 let asyncness = if self.span.rust_2018() {
3752 self.parse_asyncness()
3756 let capture_clause = if self.eat_keyword(kw::Move) {
3761 let decl = self.parse_fn_block_decl()?;
3762 let decl_hi = self.prev_span;
3763 let body = match decl.output {
3764 FunctionRetTy::Default(_) => {
3765 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3766 self.parse_expr_res(restrictions, None)?
3769 // If an explicit return type is given, require a
3770 // block to appear (RFC 968).
3771 let body_lo = self.span;
3772 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3778 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3782 // `else` token already eaten
3783 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3784 if self.eat_keyword(kw::If) {
3785 return self.parse_if_expr(ThinVec::new());
3787 let blk = self.parse_block()?;
3788 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3792 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3793 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3795 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3796 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3798 let pat = self.parse_top_level_pat()?;
3799 if !self.eat_keyword(kw::In) {
3800 let in_span = self.prev_span.between(self.span);
3801 let mut err = self.sess.span_diagnostic
3802 .struct_span_err(in_span, "missing `in` in `for` loop");
3803 err.span_suggestion_short(
3804 in_span, "try adding `in` here", " in ".into(),
3805 // has been misleading, at least in the past (closed Issue #48492)
3806 Applicability::MaybeIncorrect
3810 let in_span = self.prev_span;
3811 if self.eat_keyword(kw::In) {
3812 // a common typo: `for _ in in bar {}`
3813 let mut err = self.sess.span_diagnostic.struct_span_err(
3815 "expected iterable, found keyword `in`",
3817 err.span_suggestion_short(
3818 in_span.until(self.prev_span),
3819 "remove the duplicated `in`",
3821 Applicability::MachineApplicable,
3823 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3824 err.note("for more information on the status of emplacement syntax, see <\
3825 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3828 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3829 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3830 attrs.extend(iattrs);
3832 let hi = self.prev_span;
3833 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3836 /// Parses a `while` or `while let` expression (`while` token already eaten).
3837 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3839 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3840 if self.token.is_keyword(kw::Let) {
3841 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3843 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3844 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3845 attrs.extend(iattrs);
3846 let span = span_lo.to(body.span);
3847 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3850 /// Parses a `while let` expression (`while` token already eaten).
3851 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3853 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3854 self.expect_keyword(kw::Let)?;
3855 let pats = self.parse_pats()?;
3856 self.expect(&token::Eq)?;
3857 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3858 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3859 attrs.extend(iattrs);
3860 let span = span_lo.to(body.span);
3861 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3864 // parse `loop {...}`, `loop` token already eaten
3865 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3867 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3868 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3869 attrs.extend(iattrs);
3870 let span = span_lo.to(body.span);
3871 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3874 /// Parses an `async move {...}` expression.
3875 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3876 -> PResult<'a, P<Expr>>
3878 let span_lo = self.span;
3879 self.expect_keyword(kw::Async)?;
3880 let capture_clause = if self.eat_keyword(kw::Move) {
3885 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3886 attrs.extend(iattrs);
3888 span_lo.to(body.span),
3889 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3892 /// Parses a `try {...}` expression (`try` token already eaten).
3893 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3894 -> PResult<'a, P<Expr>>
3896 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3897 attrs.extend(iattrs);
3898 if self.eat_keyword(kw::Catch) {
3899 let mut error = self.struct_span_err(self.prev_span,
3900 "keyword `catch` cannot follow a `try` block");
3901 error.help("try using `match` on the result of the `try` block instead");
3905 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3909 // `match` token already eaten
3910 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3911 let match_span = self.prev_span;
3912 let lo = self.prev_span;
3913 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3915 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3916 if self.token == token::Token::Semi {
3917 e.span_suggestion_short(
3919 "try removing this `match`",
3921 Applicability::MaybeIncorrect // speculative
3926 attrs.extend(self.parse_inner_attributes()?);
3928 let mut arms: Vec<Arm> = Vec::new();
3929 while self.token != token::CloseDelim(token::Brace) {
3930 match self.parse_arm() {
3931 Ok(arm) => arms.push(arm),
3933 // Recover by skipping to the end of the block.
3935 self.recover_stmt();
3936 let span = lo.to(self.span);
3937 if self.token == token::CloseDelim(token::Brace) {
3940 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3946 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3949 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3950 let attrs = self.parse_outer_attributes()?;
3952 let pats = self.parse_pats()?;
3953 let guard = if self.eat_keyword(kw::If) {
3954 Some(Guard::If(self.parse_expr()?))
3958 let arrow_span = self.span;
3959 self.expect(&token::FatArrow)?;
3960 let arm_start_span = self.span;
3962 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3963 .map_err(|mut err| {
3964 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3968 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3969 && self.token != token::CloseDelim(token::Brace);
3974 let cm = self.sess.source_map();
3975 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3976 .map_err(|mut err| {
3977 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3978 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3979 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3980 && expr_lines.lines.len() == 2
3981 && self.token == token::FatArrow => {
3982 // We check whether there's any trailing code in the parse span,
3983 // if there isn't, we very likely have the following:
3986 // | -- - missing comma
3992 // | parsed until here as `"y" & X`
3993 err.span_suggestion_short(
3994 cm.next_point(arm_start_span),
3995 "missing a comma here to end this `match` arm",
3997 Applicability::MachineApplicable
4001 err.span_label(arrow_span,
4002 "while parsing the `match` arm starting here");
4008 self.eat(&token::Comma);
4020 /// Parses an expression.
4022 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4023 self.parse_expr_res(Restrictions::empty(), None)
4026 /// Evaluates the closure with restrictions in place.
4028 /// Afters the closure is evaluated, restrictions are reset.
4029 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4030 where F: FnOnce(&mut Self) -> T
4032 let old = self.restrictions;
4033 self.restrictions = r;
4035 self.restrictions = old;
4040 /// Parses an expression, subject to the given restrictions.
4042 fn parse_expr_res(&mut self, r: Restrictions,
4043 already_parsed_attrs: Option<ThinVec<Attribute>>)
4044 -> PResult<'a, P<Expr>> {
4045 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4048 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4049 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4050 if self.eat(&token::Eq) {
4051 Ok(Some(self.parse_expr()?))
4053 Ok(Some(self.parse_expr()?))
4059 /// Parses patterns, separated by '|' s.
4060 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4061 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4062 self.eat(&token::BinOp(token::Or));
4064 let mut pats = Vec::new();
4066 pats.push(self.parse_top_level_pat()?);
4068 if self.token == token::OrOr {
4069 let mut err = self.struct_span_err(self.span,
4070 "unexpected token `||` after pattern");
4071 err.span_suggestion(
4073 "use a single `|` to specify multiple patterns",
4075 Applicability::MachineApplicable
4079 } else if self.eat(&token::BinOp(token::Or)) {
4080 // This is a No-op. Continue the loop to parse the next
4088 // Parses a parenthesized list of patterns like
4089 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4090 // - a vector of the patterns that were parsed
4091 // - an option indicating the index of the `..` element
4092 // - a boolean indicating whether a trailing comma was present.
4093 // Trailing commas are significant because (p) and (p,) are different patterns.
4094 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4095 self.expect(&token::OpenDelim(token::Paren))?;
4096 let result = match self.parse_pat_list() {
4097 Ok(result) => result,
4098 Err(mut err) => { // recover from parse error in tuple pattern list
4100 self.consume_block(token::Paren);
4101 return Ok((vec![], Some(0), false));
4104 self.expect(&token::CloseDelim(token::Paren))?;
4108 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4109 let mut fields = Vec::new();
4110 let mut ddpos = None;
4111 let mut prev_dd_sp = None;
4112 let mut trailing_comma = false;
4114 if self.eat(&token::DotDot) {
4115 if ddpos.is_none() {
4116 ddpos = Some(fields.len());
4117 prev_dd_sp = Some(self.prev_span);
4119 // Emit a friendly error, ignore `..` and continue parsing
4120 let mut err = self.struct_span_err(
4122 "`..` can only be used once per tuple or tuple struct pattern",
4124 err.span_label(self.prev_span, "can only be used once per pattern");
4125 if let Some(sp) = prev_dd_sp {
4126 err.span_label(sp, "previously present here");
4130 } else if !self.check(&token::CloseDelim(token::Paren)) {
4131 fields.push(self.parse_pat(None)?);
4136 trailing_comma = self.eat(&token::Comma);
4137 if !trailing_comma {
4142 if ddpos == Some(fields.len()) && trailing_comma {
4143 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4144 let msg = "trailing comma is not permitted after `..`";
4145 self.struct_span_err(self.prev_span, msg)
4146 .span_label(self.prev_span, msg)
4150 Ok((fields, ddpos, trailing_comma))
4153 fn parse_pat_vec_elements(
4155 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4156 let mut before = Vec::new();
4157 let mut slice = None;
4158 let mut after = Vec::new();
4159 let mut first = true;
4160 let mut before_slice = true;
4162 while self.token != token::CloseDelim(token::Bracket) {
4166 self.expect(&token::Comma)?;
4168 if self.token == token::CloseDelim(token::Bracket)
4169 && (before_slice || !after.is_empty()) {
4175 if self.eat(&token::DotDot) {
4177 if self.check(&token::Comma) ||
4178 self.check(&token::CloseDelim(token::Bracket)) {
4179 slice = Some(P(Pat {
4180 id: ast::DUMMY_NODE_ID,
4181 node: PatKind::Wild,
4182 span: self.prev_span,
4184 before_slice = false;
4190 let subpat = self.parse_pat(None)?;
4191 if before_slice && self.eat(&token::DotDot) {
4192 slice = Some(subpat);
4193 before_slice = false;
4194 } else if before_slice {
4195 before.push(subpat);
4201 Ok((before, slice, after))
4207 attrs: Vec<Attribute>
4208 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4209 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4211 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4212 // Parsing a pattern of the form "fieldname: pat"
4213 let fieldname = self.parse_field_name()?;
4215 let pat = self.parse_pat(None)?;
4217 (pat, fieldname, false)
4219 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4220 let is_box = self.eat_keyword(kw::Box);
4221 let boxed_span = self.span;
4222 let is_ref = self.eat_keyword(kw::Ref);
4223 let is_mut = self.eat_keyword(kw::Mut);
4224 let fieldname = self.parse_ident()?;
4225 hi = self.prev_span;
4227 let bind_type = match (is_ref, is_mut) {
4228 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4229 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4230 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4231 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4233 let fieldpat = P(Pat {
4234 id: ast::DUMMY_NODE_ID,
4235 node: PatKind::Ident(bind_type, fieldname, None),
4236 span: boxed_span.to(hi),
4239 let subpat = if is_box {
4241 id: ast::DUMMY_NODE_ID,
4242 node: PatKind::Box(fieldpat),
4248 (subpat, fieldname, true)
4251 Ok(source_map::Spanned {
4253 node: ast::FieldPat {
4257 attrs: attrs.into(),
4262 /// Parses the fields of a struct-like pattern.
4263 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4264 let mut fields = Vec::new();
4265 let mut etc = false;
4266 let mut ate_comma = true;
4267 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4268 let mut etc_span = None;
4270 while self.token != token::CloseDelim(token::Brace) {
4271 let attrs = self.parse_outer_attributes()?;
4274 // check that a comma comes after every field
4276 let err = self.struct_span_err(self.prev_span, "expected `,`");
4277 if let Some(mut delayed) = delayed_err {
4284 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4286 let mut etc_sp = self.span;
4288 if self.token == token::DotDotDot { // Issue #46718
4289 // Accept `...` as if it were `..` to avoid further errors
4290 let mut err = self.struct_span_err(self.span,
4291 "expected field pattern, found `...`");
4292 err.span_suggestion(
4294 "to omit remaining fields, use one fewer `.`",
4296 Applicability::MachineApplicable
4300 self.bump(); // `..` || `...`
4302 if self.token == token::CloseDelim(token::Brace) {
4303 etc_span = Some(etc_sp);
4306 let token_str = self.this_token_descr();
4307 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4309 err.span_label(self.span, "expected `}`");
4310 let mut comma_sp = None;
4311 if self.token == token::Comma { // Issue #49257
4312 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4313 err.span_label(etc_sp,
4314 "`..` must be at the end and cannot have a trailing comma");
4315 comma_sp = Some(self.span);
4320 etc_span = Some(etc_sp.until(self.span));
4321 if self.token == token::CloseDelim(token::Brace) {
4322 // If the struct looks otherwise well formed, recover and continue.
4323 if let Some(sp) = comma_sp {
4324 err.span_suggestion_short(
4326 "remove this comma",
4328 Applicability::MachineApplicable,
4333 } else if self.token.is_ident() && ate_comma {
4334 // Accept fields coming after `..,`.
4335 // This way we avoid "pattern missing fields" errors afterwards.
4336 // We delay this error until the end in order to have a span for a
4338 if let Some(mut delayed_err) = delayed_err {
4342 delayed_err = Some(err);
4345 if let Some(mut err) = delayed_err {
4352 fields.push(match self.parse_pat_field(lo, attrs) {
4355 if let Some(mut delayed_err) = delayed_err {
4361 ate_comma = self.eat(&token::Comma);
4364 if let Some(mut err) = delayed_err {
4365 if let Some(etc_span) = etc_span {
4366 err.multipart_suggestion(
4367 "move the `..` to the end of the field list",
4369 (etc_span, String::new()),
4370 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4372 Applicability::MachineApplicable,
4377 return Ok((fields, etc));
4380 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4381 if self.token.is_path_start() {
4383 let (qself, path) = if self.eat_lt() {
4384 // Parse a qualified path
4385 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4388 // Parse an unqualified path
4389 (None, self.parse_path(PathStyle::Expr)?)
4391 let hi = self.prev_span;
4392 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4394 self.parse_literal_maybe_minus()
4398 // helper function to decide whether to parse as ident binding or to try to do
4399 // something more complex like range patterns
4400 fn parse_as_ident(&mut self) -> bool {
4401 self.look_ahead(1, |t| match *t {
4402 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4403 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4404 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4405 // range pattern branch
4406 token::DotDot => None,
4408 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4409 token::Comma | token::CloseDelim(token::Bracket) => true,
4414 /// A wrapper around `parse_pat` with some special error handling for the
4415 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4416 /// to subpatterns within such).
4417 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4418 let pat = self.parse_pat(None)?;
4419 if self.token == token::Comma {
4420 // An unexpected comma after a top-level pattern is a clue that the
4421 // user (perhaps more accustomed to some other language) forgot the
4422 // parentheses in what should have been a tuple pattern; return a
4423 // suggestion-enhanced error here rather than choking on the comma
4425 let comma_span = self.span;
4427 if let Err(mut err) = self.parse_pat_list() {
4428 // We didn't expect this to work anyway; we just wanted
4429 // to advance to the end of the comma-sequence so we know
4430 // the span to suggest parenthesizing
4433 let seq_span = pat.span.to(self.prev_span);
4434 let mut err = self.struct_span_err(comma_span,
4435 "unexpected `,` in pattern");
4436 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4437 err.span_suggestion(
4439 "try adding parentheses to match on a tuple..",
4440 format!("({})", seq_snippet),
4441 Applicability::MachineApplicable
4444 "..or a vertical bar to match on multiple alternatives",
4445 format!("{}", seq_snippet.replace(",", " |")),
4446 Applicability::MachineApplicable
4454 /// Parses a pattern.
4455 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4456 self.parse_pat_with_range_pat(true, expected)
4459 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4461 fn parse_pat_with_range_pat(
4463 allow_range_pat: bool,
4464 expected: Option<&'static str>,
4465 ) -> PResult<'a, P<Pat>> {
4466 maybe_recover_from_interpolated_ty_qpath!(self, true);
4467 maybe_whole!(self, NtPat, |x| x);
4472 token::BinOp(token::And) | token::AndAnd => {
4473 // Parse &pat / &mut pat
4475 let mutbl = self.parse_mutability();
4476 if let token::Lifetime(ident) = self.token {
4477 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4479 err.span_label(self.span, "unexpected lifetime");
4482 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4483 pat = PatKind::Ref(subpat, mutbl);
4485 token::OpenDelim(token::Paren) => {
4486 // Parse (pat,pat,pat,...) as tuple pattern
4487 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4488 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4489 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4491 PatKind::Tuple(fields, ddpos)
4494 token::OpenDelim(token::Bracket) => {
4495 // Parse [pat,pat,...] as slice pattern
4497 let (before, slice, after) = self.parse_pat_vec_elements()?;
4498 self.expect(&token::CloseDelim(token::Bracket))?;
4499 pat = PatKind::Slice(before, slice, after);
4501 // At this point, token != &, &&, (, [
4502 _ => if self.eat_keyword(kw::Underscore) {
4504 pat = PatKind::Wild;
4505 } else if self.eat_keyword(kw::Mut) {
4506 // Parse mut ident @ pat / mut ref ident @ pat
4507 let mutref_span = self.prev_span.to(self.span);
4508 let binding_mode = if self.eat_keyword(kw::Ref) {
4510 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4513 "try switching the order",
4515 Applicability::MachineApplicable
4517 BindingMode::ByRef(Mutability::Mutable)
4519 BindingMode::ByValue(Mutability::Mutable)
4521 pat = self.parse_pat_ident(binding_mode)?;
4522 } else if self.eat_keyword(kw::Ref) {
4523 // Parse ref ident @ pat / ref mut ident @ pat
4524 let mutbl = self.parse_mutability();
4525 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4526 } else if self.eat_keyword(kw::Box) {
4528 let subpat = self.parse_pat_with_range_pat(false, None)?;
4529 pat = PatKind::Box(subpat);
4530 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4531 self.parse_as_ident() {
4532 // Parse ident @ pat
4533 // This can give false positives and parse nullary enums,
4534 // they are dealt with later in resolve
4535 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4536 pat = self.parse_pat_ident(binding_mode)?;
4537 } else if self.token.is_path_start() {
4538 // Parse pattern starting with a path
4539 let (qself, path) = if self.eat_lt() {
4540 // Parse a qualified path
4541 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4544 // Parse an unqualified path
4545 (None, self.parse_path(PathStyle::Expr)?)
4548 token::Not if qself.is_none() => {
4549 // Parse macro invocation
4551 let (delim, tts) = self.expect_delimited_token_tree()?;
4552 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4553 pat = PatKind::Mac(mac);
4555 token::DotDotDot | token::DotDotEq | token::DotDot => {
4556 let end_kind = match self.token {
4557 token::DotDot => RangeEnd::Excluded,
4558 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4559 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4560 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4563 let op_span = self.span;
4565 let span = lo.to(self.prev_span);
4566 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4568 let end = self.parse_pat_range_end()?;
4569 let op = Spanned { span: op_span, node: end_kind };
4570 pat = PatKind::Range(begin, end, op);
4572 token::OpenDelim(token::Brace) => {
4573 if qself.is_some() {
4574 let msg = "unexpected `{` after qualified path";
4575 let mut err = self.fatal(msg);
4576 err.span_label(self.span, msg);
4579 // Parse struct pattern
4581 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4583 self.recover_stmt();
4587 pat = PatKind::Struct(path, fields, etc);
4589 token::OpenDelim(token::Paren) => {
4590 if qself.is_some() {
4591 let msg = "unexpected `(` after qualified path";
4592 let mut err = self.fatal(msg);
4593 err.span_label(self.span, msg);
4596 // Parse tuple struct or enum pattern
4597 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4598 pat = PatKind::TupleStruct(path, fields, ddpos)
4600 _ => pat = PatKind::Path(qself, path),
4603 // Try to parse everything else as literal with optional minus
4604 match self.parse_literal_maybe_minus() {
4606 let op_span = self.span;
4607 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4608 self.check(&token::DotDotDot) {
4609 let end_kind = if self.eat(&token::DotDotDot) {
4610 RangeEnd::Included(RangeSyntax::DotDotDot)
4611 } else if self.eat(&token::DotDotEq) {
4612 RangeEnd::Included(RangeSyntax::DotDotEq)
4613 } else if self.eat(&token::DotDot) {
4616 panic!("impossible case: we already matched \
4617 on a range-operator token")
4619 let end = self.parse_pat_range_end()?;
4620 let op = Spanned { span: op_span, node: end_kind };
4621 pat = PatKind::Range(begin, end, op);
4623 pat = PatKind::Lit(begin);
4627 self.cancel(&mut err);
4628 let expected = expected.unwrap_or("pattern");
4630 "expected {}, found {}",
4632 self.this_token_descr(),
4634 let mut err = self.fatal(&msg);
4635 err.span_label(self.span, format!("expected {}", expected));
4636 let sp = self.sess.source_map().start_point(self.span);
4637 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4638 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4646 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4647 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4649 if !allow_range_pat {
4652 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4654 PatKind::Range(..) => {
4655 let mut err = self.struct_span_err(
4657 "the range pattern here has ambiguous interpretation",
4659 err.span_suggestion(
4661 "add parentheses to clarify the precedence",
4662 format!("({})", pprust::pat_to_string(&pat)),
4663 // "ambiguous interpretation" implies that we have to be guessing
4664 Applicability::MaybeIncorrect
4675 /// Parses `ident` or `ident @ pat`.
4676 /// used by the copy foo and ref foo patterns to give a good
4677 /// error message when parsing mistakes like `ref foo(a, b)`.
4678 fn parse_pat_ident(&mut self,
4679 binding_mode: ast::BindingMode)
4680 -> PResult<'a, PatKind> {
4681 let ident = self.parse_ident()?;
4682 let sub = if self.eat(&token::At) {
4683 Some(self.parse_pat(Some("binding pattern"))?)
4688 // just to be friendly, if they write something like
4690 // we end up here with ( as the current token. This shortly
4691 // leads to a parse error. Note that if there is no explicit
4692 // binding mode then we do not end up here, because the lookahead
4693 // will direct us over to parse_enum_variant()
4694 if self.token == token::OpenDelim(token::Paren) {
4695 return Err(self.span_fatal(
4697 "expected identifier, found enum pattern"))
4700 Ok(PatKind::Ident(binding_mode, ident, sub))
4703 /// Parses a local variable declaration.
4704 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4705 let lo = self.prev_span;
4706 let pat = self.parse_top_level_pat()?;
4708 let (err, ty) = if self.eat(&token::Colon) {
4709 // Save the state of the parser before parsing type normally, in case there is a `:`
4710 // instead of an `=` typo.
4711 let parser_snapshot_before_type = self.clone();
4712 let colon_sp = self.prev_span;
4713 match self.parse_ty() {
4714 Ok(ty) => (None, Some(ty)),
4716 // Rewind to before attempting to parse the type and continue parsing
4717 let parser_snapshot_after_type = self.clone();
4718 mem::replace(self, parser_snapshot_before_type);
4720 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4721 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4722 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4728 let init = match (self.parse_initializer(err.is_some()), err) {
4729 (Ok(init), None) => { // init parsed, ty parsed
4732 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4733 // Could parse the type as if it were the initializer, it is likely there was a
4734 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4735 err.span_suggestion_short(
4737 "use `=` if you meant to assign",
4739 Applicability::MachineApplicable
4742 // As this was parsed successfully, continue as if the code has been fixed for the
4743 // rest of the file. It will still fail due to the emitted error, but we avoid
4747 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4749 // Couldn't parse the type nor the initializer, only raise the type error and
4750 // return to the parser state before parsing the type as the initializer.
4751 // let x: <parse_error>;
4752 mem::replace(self, snapshot);
4755 (Err(err), None) => { // init error, ty parsed
4756 // Couldn't parse the initializer and we're not attempting to recover a failed
4757 // parse of the type, return the error.
4761 let hi = if self.token == token::Semi {
4770 id: ast::DUMMY_NODE_ID,
4773 source: LocalSource::Normal,
4777 /// Parses a structure field.
4778 fn parse_name_and_ty(&mut self,
4781 attrs: Vec<Attribute>)
4782 -> PResult<'a, StructField> {
4783 let name = self.parse_ident()?;
4784 self.expect(&token::Colon)?;
4785 let ty = self.parse_ty()?;
4787 span: lo.to(self.prev_span),
4790 id: ast::DUMMY_NODE_ID,
4796 /// Emits an expected-item-after-attributes error.
4797 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4798 let message = match attrs.last() {
4799 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4800 _ => "expected item after attributes",
4803 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4804 if attrs.last().unwrap().is_sugared_doc {
4805 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4810 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4811 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4812 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4813 Ok(self.parse_stmt_(true))
4816 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4817 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4819 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4824 fn is_async_block(&self) -> bool {
4825 self.token.is_keyword(kw::Async) &&
4828 self.look_ahead(1, |t| t.is_keyword(kw::Move)) &&
4829 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4831 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4836 fn is_async_fn(&self) -> bool {
4837 self.token.is_keyword(kw::Async) &&
4838 self.look_ahead(1, |t| t.is_keyword(kw::Fn))
4841 fn is_do_catch_block(&self) -> bool {
4842 self.token.is_keyword(kw::Do) &&
4843 self.look_ahead(1, |t| t.is_keyword(kw::Catch)) &&
4844 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4845 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4848 fn is_try_block(&self) -> bool {
4849 self.token.is_keyword(kw::Try) &&
4850 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4851 self.span.rust_2018() &&
4852 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4853 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4856 fn is_union_item(&self) -> bool {
4857 self.token.is_keyword(kw::Union) &&
4858 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4861 fn is_crate_vis(&self) -> bool {
4862 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4865 fn is_existential_type_decl(&self) -> bool {
4866 self.token.is_keyword(kw::Existential) &&
4867 self.look_ahead(1, |t| t.is_keyword(kw::Type))
4870 fn is_auto_trait_item(&self) -> bool {
4872 (self.token.is_keyword(kw::Auto)
4873 && self.look_ahead(1, |t| t.is_keyword(kw::Trait)))
4874 || // unsafe auto trait
4875 (self.token.is_keyword(kw::Unsafe) &&
4876 self.look_ahead(1, |t| t.is_keyword(kw::Auto)) &&
4877 self.look_ahead(2, |t| t.is_keyword(kw::Trait)))
4880 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4881 -> PResult<'a, Option<P<Item>>> {
4882 let token_lo = self.span;
4883 let (ident, def) = match self.token {
4884 token::Ident(ident, false) if ident.name == kw::Macro => {
4886 let ident = self.parse_ident()?;
4887 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4888 match self.parse_token_tree() {
4889 TokenTree::Delimited(_, _, tts) => tts,
4890 _ => unreachable!(),
4892 } else if self.check(&token::OpenDelim(token::Paren)) {
4893 let args = self.parse_token_tree();
4894 let body = if self.check(&token::OpenDelim(token::Brace)) {
4895 self.parse_token_tree()
4900 TokenStream::new(vec![
4902 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4910 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4912 token::Ident(ident, _) if ident.name == sym::macro_rules &&
4913 self.look_ahead(1, |t| *t == token::Not) => {
4914 let prev_span = self.prev_span;
4915 self.complain_if_pub_macro(&vis.node, prev_span);
4919 let ident = self.parse_ident()?;
4920 let (delim, tokens) = self.expect_delimited_token_tree()?;
4921 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
4922 self.report_invalid_macro_expansion_item();
4925 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4927 _ => return Ok(None),
4930 let span = lo.to(self.prev_span);
4931 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4934 fn parse_stmt_without_recovery(&mut self,
4935 macro_legacy_warnings: bool)
4936 -> PResult<'a, Option<Stmt>> {
4937 maybe_whole!(self, NtStmt, |x| Some(x));
4939 let attrs = self.parse_outer_attributes()?;
4942 Ok(Some(if self.eat_keyword(kw::Let) {
4944 id: ast::DUMMY_NODE_ID,
4945 node: StmtKind::Local(self.parse_local(attrs.into())?),
4946 span: lo.to(self.prev_span),
4948 } else if let Some(macro_def) = self.eat_macro_def(
4950 &source_map::respan(lo, VisibilityKind::Inherited),
4954 id: ast::DUMMY_NODE_ID,
4955 node: StmtKind::Item(macro_def),
4956 span: lo.to(self.prev_span),
4958 // Starts like a simple path, being careful to avoid contextual keywords
4959 // such as a union items, item with `crate` visibility or auto trait items.
4960 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4961 // like a path (1 token), but it fact not a path.
4962 // `union::b::c` - path, `union U { ... }` - not a path.
4963 // `crate::b::c` - path, `crate struct S;` - not a path.
4964 } else if self.token.is_path_start() &&
4965 !self.token.is_qpath_start() &&
4966 !self.is_union_item() &&
4967 !self.is_crate_vis() &&
4968 !self.is_existential_type_decl() &&
4969 !self.is_auto_trait_item() &&
4970 !self.is_async_fn() {
4971 let pth = self.parse_path(PathStyle::Expr)?;
4973 if !self.eat(&token::Not) {
4974 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4975 self.parse_struct_expr(lo, pth, ThinVec::new())?
4977 let hi = self.prev_span;
4978 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4981 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4982 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4983 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4986 return Ok(Some(Stmt {
4987 id: ast::DUMMY_NODE_ID,
4988 node: StmtKind::Expr(expr),
4989 span: lo.to(self.prev_span),
4993 // it's a macro invocation
4994 let id = match self.token {
4995 token::OpenDelim(_) => Ident::invalid(), // no special identifier
4996 _ => self.parse_ident()?,
4999 // check that we're pointing at delimiters (need to check
5000 // again after the `if`, because of `parse_ident`
5001 // consuming more tokens).
5003 token::OpenDelim(_) => {}
5005 // we only expect an ident if we didn't parse one
5007 let ident_str = if id.name == kw::Invalid {
5012 let tok_str = self.this_token_descr();
5013 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5016 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5021 let (delim, tts) = self.expect_delimited_token_tree()?;
5022 let hi = self.prev_span;
5024 let style = if delim == MacDelimiter::Brace {
5025 MacStmtStyle::Braces
5027 MacStmtStyle::NoBraces
5030 if id.name == kw::Invalid {
5031 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5032 let node = if delim == MacDelimiter::Brace ||
5033 self.token == token::Semi || self.token == token::Eof {
5034 StmtKind::Mac(P((mac, style, attrs.into())))
5036 // We used to incorrectly stop parsing macro-expanded statements here.
5037 // If the next token will be an error anyway but could have parsed with the
5038 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5039 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5040 // These can continue an expression, so we can't stop parsing and warn.
5041 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5042 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5043 token::BinOp(token::And) | token::BinOp(token::Or) |
5044 token::AndAnd | token::OrOr |
5045 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5048 self.warn_missing_semicolon();
5049 StmtKind::Mac(P((mac, style, attrs.into())))
5051 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5052 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5053 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5054 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5058 id: ast::DUMMY_NODE_ID,
5063 // if it has a special ident, it's definitely an item
5065 // Require a semicolon or braces.
5066 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5067 self.report_invalid_macro_expansion_item();
5069 let span = lo.to(hi);
5071 id: ast::DUMMY_NODE_ID,
5073 node: StmtKind::Item({
5075 span, id /*id is good here*/,
5076 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5077 respan(lo, VisibilityKind::Inherited),
5083 // FIXME: Bad copy of attrs
5084 let old_directory_ownership =
5085 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5086 let item = self.parse_item_(attrs.clone(), false, true)?;
5087 self.directory.ownership = old_directory_ownership;
5091 id: ast::DUMMY_NODE_ID,
5092 span: lo.to(i.span),
5093 node: StmtKind::Item(i),
5096 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5097 if !attrs.is_empty() {
5098 if s.prev_token_kind == PrevTokenKind::DocComment {
5099 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5100 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5101 s.span_err(s.span, "expected statement after outer attribute");
5106 // Do not attempt to parse an expression if we're done here.
5107 if self.token == token::Semi {
5108 unused_attrs(&attrs, self);
5113 if self.token == token::CloseDelim(token::Brace) {
5114 unused_attrs(&attrs, self);
5118 // Remainder are line-expr stmts.
5119 let e = self.parse_expr_res(
5120 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5122 id: ast::DUMMY_NODE_ID,
5123 span: lo.to(e.span),
5124 node: StmtKind::Expr(e),
5131 /// Checks if this expression is a successfully parsed statement.
5132 fn expr_is_complete(&self, e: &Expr) -> bool {
5133 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5134 !classify::expr_requires_semi_to_be_stmt(e)
5137 /// Parses a block. No inner attributes are allowed.
5138 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5139 maybe_whole!(self, NtBlock, |x| x);
5143 if !self.eat(&token::OpenDelim(token::Brace)) {
5145 let tok = self.this_token_descr();
5146 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5147 let do_not_suggest_help =
5148 self.token.is_keyword(kw::In) || self.token == token::Colon;
5150 if self.token.is_ident_named("and") {
5151 e.span_suggestion_short(
5153 "use `&&` instead of `and` for the boolean operator",
5155 Applicability::MaybeIncorrect,
5158 if self.token.is_ident_named("or") {
5159 e.span_suggestion_short(
5161 "use `||` instead of `or` for the boolean operator",
5163 Applicability::MaybeIncorrect,
5167 // Check to see if the user has written something like
5172 // Which is valid in other languages, but not Rust.
5173 match self.parse_stmt_without_recovery(false) {
5175 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5176 || do_not_suggest_help {
5177 // if the next token is an open brace (e.g., `if a b {`), the place-
5178 // inside-a-block suggestion would be more likely wrong than right
5179 e.span_label(sp, "expected `{`");
5182 let mut stmt_span = stmt.span;
5183 // expand the span to include the semicolon, if it exists
5184 if self.eat(&token::Semi) {
5185 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5187 let sugg = pprust::to_string(|s| {
5188 use crate::print::pprust::{PrintState, INDENT_UNIT};
5189 s.ibox(INDENT_UNIT)?;
5191 s.print_stmt(&stmt)?;
5192 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5196 "try placing this code inside a block",
5198 // speculative, has been misleading in the past (closed Issue #46836)
5199 Applicability::MaybeIncorrect
5203 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5204 self.cancel(&mut e);
5208 e.span_label(sp, "expected `{`");
5212 self.parse_block_tail(lo, BlockCheckMode::Default)
5215 /// Parses a block. Inner attributes are allowed.
5216 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5217 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5220 self.expect(&token::OpenDelim(token::Brace))?;
5221 Ok((self.parse_inner_attributes()?,
5222 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5225 /// Parses the rest of a block expression or function body.
5226 /// Precondition: already parsed the '{'.
5227 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5228 let mut stmts = vec![];
5229 while !self.eat(&token::CloseDelim(token::Brace)) {
5230 let stmt = match self.parse_full_stmt(false) {
5233 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5235 id: ast::DUMMY_NODE_ID,
5236 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5242 if let Some(stmt) = stmt {
5244 } else if self.token == token::Eof {
5247 // Found only `;` or `}`.
5253 id: ast::DUMMY_NODE_ID,
5255 span: lo.to(self.prev_span),
5259 /// Parses a statement, including the trailing semicolon.
5260 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5261 // skip looking for a trailing semicolon when we have an interpolated statement
5262 maybe_whole!(self, NtStmt, |x| Some(x));
5264 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5266 None => return Ok(None),
5270 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5271 // expression without semicolon
5272 if classify::expr_requires_semi_to_be_stmt(expr) {
5273 // Just check for errors and recover; do not eat semicolon yet.
5275 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5278 self.recover_stmt();
5282 StmtKind::Local(..) => {
5283 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5284 if macro_legacy_warnings && self.token != token::Semi {
5285 self.warn_missing_semicolon();
5287 self.expect_one_of(&[], &[token::Semi])?;
5293 if self.eat(&token::Semi) {
5294 stmt = stmt.add_trailing_semicolon();
5297 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5301 fn warn_missing_semicolon(&self) {
5302 self.diagnostic().struct_span_warn(self.span, {
5303 &format!("expected `;`, found {}", self.this_token_descr())
5305 "This was erroneously allowed and will become a hard error in a future release"
5309 fn err_dotdotdot_syntax(&self, span: Span) {
5310 self.diagnostic().struct_span_err(span, {
5311 "unexpected token: `...`"
5313 span, "use `..` for an exclusive range", "..".to_owned(),
5314 Applicability::MaybeIncorrect
5316 span, "or `..=` for an inclusive range", "..=".to_owned(),
5317 Applicability::MaybeIncorrect
5321 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5324 /// BOUND = TY_BOUND | LT_BOUND
5325 /// LT_BOUND = LIFETIME (e.g., `'a`)
5326 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5327 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5329 fn parse_generic_bounds_common(&mut self,
5331 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5332 let mut bounds = Vec::new();
5333 let mut negative_bounds = Vec::new();
5334 let mut last_plus_span = None;
5335 let mut was_negative = false;
5337 // This needs to be synchronized with `Token::can_begin_bound`.
5338 let is_bound_start = self.check_path() || self.check_lifetime() ||
5339 self.check(&token::Not) || // used for error reporting only
5340 self.check(&token::Question) ||
5341 self.check_keyword(kw::For) ||
5342 self.check(&token::OpenDelim(token::Paren));
5345 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5346 let inner_lo = self.span;
5347 let is_negative = self.eat(&token::Not);
5348 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5349 if self.token.is_lifetime() {
5350 if let Some(question_span) = question {
5351 self.span_err(question_span,
5352 "`?` may only modify trait bounds, not lifetime bounds");
5354 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5356 let inner_span = inner_lo.to(self.prev_span);
5357 self.expect(&token::CloseDelim(token::Paren))?;
5358 let mut err = self.struct_span_err(
5359 lo.to(self.prev_span),
5360 "parenthesized lifetime bounds are not supported"
5362 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5363 err.span_suggestion_short(
5364 lo.to(self.prev_span),
5365 "remove the parentheses",
5367 Applicability::MachineApplicable
5373 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5374 let path = self.parse_path(PathStyle::Type)?;
5376 self.expect(&token::CloseDelim(token::Paren))?;
5378 let poly_span = lo.to(self.prev_span);
5380 was_negative = true;
5381 if let Some(sp) = last_plus_span.or(colon_span) {
5382 negative_bounds.push(sp.to(poly_span));
5385 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5386 let modifier = if question.is_some() {
5387 TraitBoundModifier::Maybe
5389 TraitBoundModifier::None
5391 bounds.push(GenericBound::Trait(poly_trait, modifier));
5398 if !allow_plus || !self.eat_plus() {
5401 last_plus_span = Some(self.prev_span);
5405 if !negative_bounds.is_empty() || was_negative {
5406 let plural = negative_bounds.len() > 1;
5407 let last_span = negative_bounds.last().map(|sp| *sp);
5408 let mut err = self.struct_span_err(
5410 "negative trait bounds are not supported",
5412 if let Some(sp) = last_span {
5413 err.span_label(sp, "negative trait bounds are not supported");
5415 if let Some(bound_list) = colon_span {
5416 let bound_list = bound_list.to(self.prev_span);
5417 let mut new_bound_list = String::new();
5418 if !bounds.is_empty() {
5419 let mut snippets = bounds.iter().map(|bound| bound.span())
5420 .map(|span| self.sess.source_map().span_to_snippet(span));
5421 while let Some(Ok(snippet)) = snippets.next() {
5422 new_bound_list.push_str(" + ");
5423 new_bound_list.push_str(&snippet);
5425 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5427 err.span_suggestion_hidden(
5429 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5431 Applicability::MachineApplicable,
5440 crate fn parse_generic_bounds(&mut self,
5441 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5442 self.parse_generic_bounds_common(true, colon_span)
5445 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5448 /// BOUND = LT_BOUND (e.g., `'a`)
5450 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5451 let mut lifetimes = Vec::new();
5452 while self.check_lifetime() {
5453 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5455 if !self.eat_plus() {
5462 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5463 fn parse_ty_param(&mut self,
5464 preceding_attrs: Vec<Attribute>)
5465 -> PResult<'a, GenericParam> {
5466 let ident = self.parse_ident()?;
5468 // Parse optional colon and param bounds.
5469 let bounds = if self.eat(&token::Colon) {
5470 self.parse_generic_bounds(Some(self.prev_span))?
5475 let default = if self.eat(&token::Eq) {
5476 Some(self.parse_ty()?)
5483 id: ast::DUMMY_NODE_ID,
5484 attrs: preceding_attrs.into(),
5486 kind: GenericParamKind::Type {
5492 /// Parses the following grammar:
5494 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5495 fn parse_trait_item_assoc_ty(&mut self)
5496 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5497 let ident = self.parse_ident()?;
5498 let mut generics = self.parse_generics()?;
5500 // Parse optional colon and param bounds.
5501 let bounds = if self.eat(&token::Colon) {
5502 self.parse_generic_bounds(None)?
5506 generics.where_clause = self.parse_where_clause()?;
5508 let default = if self.eat(&token::Eq) {
5509 Some(self.parse_ty()?)
5513 self.expect(&token::Semi)?;
5515 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5518 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5519 self.expect_keyword(kw::Const)?;
5520 let ident = self.parse_ident()?;
5521 self.expect(&token::Colon)?;
5522 let ty = self.parse_ty()?;
5526 id: ast::DUMMY_NODE_ID,
5527 attrs: preceding_attrs.into(),
5529 kind: GenericParamKind::Const {
5535 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5536 /// a trailing comma and erroneous trailing attributes.
5537 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5538 let mut params = Vec::new();
5540 let attrs = self.parse_outer_attributes()?;
5541 if self.check_lifetime() {
5542 let lifetime = self.expect_lifetime();
5543 // Parse lifetime parameter.
5544 let bounds = if self.eat(&token::Colon) {
5545 self.parse_lt_param_bounds()
5549 params.push(ast::GenericParam {
5550 ident: lifetime.ident,
5552 attrs: attrs.into(),
5554 kind: ast::GenericParamKind::Lifetime,
5556 } else if self.check_keyword(kw::Const) {
5557 // Parse const parameter.
5558 params.push(self.parse_const_param(attrs)?);
5559 } else if self.check_ident() {
5560 // Parse type parameter.
5561 params.push(self.parse_ty_param(attrs)?);
5563 // Check for trailing attributes and stop parsing.
5564 if !attrs.is_empty() {
5565 if !params.is_empty() {
5566 self.struct_span_err(
5568 &format!("trailing attribute after generic parameter"),
5570 .span_label(attrs[0].span, "attributes must go before parameters")
5573 self.struct_span_err(
5575 &format!("attribute without generic parameters"),
5579 "attributes are only permitted when preceding parameters",
5587 if !self.eat(&token::Comma) {
5594 /// Parses a set of optional generic type parameter declarations. Where
5595 /// clauses are not parsed here, and must be added later via
5596 /// `parse_where_clause()`.
5598 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5599 /// | ( < lifetimes , typaramseq ( , )? > )
5600 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5601 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5602 let span_lo = self.span;
5604 let params = self.parse_generic_params()?;
5608 where_clause: WhereClause {
5609 id: ast::DUMMY_NODE_ID,
5610 predicates: Vec::new(),
5611 span: syntax_pos::DUMMY_SP,
5613 span: span_lo.to(self.prev_span),
5616 Ok(ast::Generics::default())
5620 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5621 /// For the purposes of understanding the parsing logic of generic arguments, this function
5622 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5623 /// had the correct amount of leading angle brackets.
5625 /// ```ignore (diagnostics)
5626 /// bar::<<<<T as Foo>::Output>();
5627 /// ^^ help: remove extra angle brackets
5629 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5633 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5634 // We need to detect whether there are extra leading left angle brackets and produce an
5635 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5636 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5637 // then there won't be matching `>` tokens to find.
5639 // To explain how this detection works, consider the following example:
5641 // ```ignore (diagnostics)
5642 // bar::<<<<T as Foo>::Output>();
5643 // ^^ help: remove extra angle brackets
5646 // Parsing of the left angle brackets starts in this function. We start by parsing the
5647 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5650 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5651 // *Unmatched count:* 1
5652 // *`parse_path_segment` calls deep:* 0
5654 // This has the effect of recursing as this function is called if a `<` character
5655 // is found within the expected generic arguments:
5657 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5658 // *Unmatched count:* 2
5659 // *`parse_path_segment` calls deep:* 1
5661 // Eventually we will have recursed until having consumed all of the `<` tokens and
5662 // this will be reflected in the count:
5664 // *Upcoming tokens:* `T as Foo>::Output>;`
5665 // *Unmatched count:* 4
5666 // `parse_path_segment` calls deep:* 3
5668 // The parser will continue until reaching the first `>` - this will decrement the
5669 // unmatched angle bracket count and return to the parent invocation of this function
5670 // having succeeded in parsing:
5672 // *Upcoming tokens:* `::Output>;`
5673 // *Unmatched count:* 3
5674 // *`parse_path_segment` calls deep:* 2
5676 // This will continue until the next `>` character which will also return successfully
5677 // to the parent invocation of this function and decrement the count:
5679 // *Upcoming tokens:* `;`
5680 // *Unmatched count:* 2
5681 // *`parse_path_segment` calls deep:* 1
5683 // At this point, this function will expect to find another matching `>` character but
5684 // won't be able to and will return an error. This will continue all the way up the
5685 // call stack until the first invocation:
5687 // *Upcoming tokens:* `;`
5688 // *Unmatched count:* 2
5689 // *`parse_path_segment` calls deep:* 0
5691 // In doing this, we have managed to work out how many unmatched leading left angle
5692 // brackets there are, but we cannot recover as the unmatched angle brackets have
5693 // already been consumed. To remedy this, we keep a snapshot of the parser state
5694 // before we do the above. We can then inspect whether we ended up with a parsing error
5695 // and unmatched left angle brackets and if so, restore the parser state before we
5696 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5697 // recover by attempting to parse again.
5699 // In practice, the recursion of this function is indirect and there will be other
5700 // locations that consume some `<` characters - as long as we update the count when
5701 // this happens, it isn't an issue.
5703 let is_first_invocation = style == PathStyle::Expr;
5704 // Take a snapshot before attempting to parse - we can restore this later.
5705 let snapshot = if is_first_invocation {
5711 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5712 match self.parse_generic_args() {
5713 Ok(value) => Ok(value),
5714 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5715 // Cancel error from being unable to find `>`. We know the error
5716 // must have been this due to a non-zero unmatched angle bracket
5720 // Swap `self` with our backup of the parser state before attempting to parse
5721 // generic arguments.
5722 let snapshot = mem::replace(self, snapshot.unwrap());
5725 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5726 snapshot.count={:?}",
5727 snapshot.unmatched_angle_bracket_count,
5730 // Eat the unmatched angle brackets.
5731 for _ in 0..snapshot.unmatched_angle_bracket_count {
5735 // Make a span over ${unmatched angle bracket count} characters.
5736 let span = lo.with_hi(
5737 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5739 let plural = snapshot.unmatched_angle_bracket_count > 1;
5744 "unmatched angle bracket{}",
5745 if plural { "s" } else { "" }
5751 "remove extra angle bracket{}",
5752 if plural { "s" } else { "" }
5755 Applicability::MachineApplicable,
5759 // Try again without unmatched angle bracket characters.
5760 self.parse_generic_args()
5766 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5767 /// possibly including trailing comma.
5768 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5769 let mut args = Vec::new();
5770 let mut bindings = Vec::new();
5771 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
5772 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
5774 let args_lo = self.span;
5777 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5778 // Parse lifetime argument.
5779 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5780 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5781 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5782 // Parse associated type binding.
5784 let ident = self.parse_ident()?;
5786 let ty = self.parse_ty()?;
5787 let span = lo.to(self.prev_span);
5788 bindings.push(TypeBinding {
5789 id: ast::DUMMY_NODE_ID,
5794 assoc_ty_bindings.push(span);
5795 } else if self.check_const_arg() {
5796 // Parse const argument.
5797 let expr = if let token::OpenDelim(token::Brace) = self.token {
5798 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
5799 } else if self.token.is_ident() {
5800 // FIXME(const_generics): to distinguish between idents for types and consts,
5801 // we should introduce a GenericArg::Ident in the AST and distinguish when
5802 // lowering to the HIR. For now, idents for const args are not permitted.
5804 self.fatal("identifiers may currently not be used for const generics")
5807 self.parse_literal_maybe_minus()?
5809 let value = AnonConst {
5810 id: ast::DUMMY_NODE_ID,
5813 args.push(GenericArg::Const(value));
5814 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5815 } else if self.check_type() {
5816 // Parse type argument.
5817 args.push(GenericArg::Type(self.parse_ty()?));
5818 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5823 if !self.eat(&token::Comma) {
5828 // FIXME: we would like to report this in ast_validation instead, but we currently do not
5829 // preserve ordering of generic parameters with respect to associated type binding, so we
5830 // lose that information after parsing.
5831 if misplaced_assoc_ty_bindings.len() > 0 {
5832 let mut err = self.struct_span_err(
5833 args_lo.to(self.prev_span),
5834 "associated type bindings must be declared after generic parameters",
5836 for span in misplaced_assoc_ty_bindings {
5839 "this associated type binding should be moved after the generic parameters",
5845 Ok((args, bindings))
5848 /// Parses an optional where-clause and places it in `generics`.
5850 /// ```ignore (only-for-syntax-highlight)
5851 /// where T : Trait<U, V> + 'b, 'a : 'b
5853 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5854 let mut where_clause = WhereClause {
5855 id: ast::DUMMY_NODE_ID,
5856 predicates: Vec::new(),
5857 span: syntax_pos::DUMMY_SP,
5860 if !self.eat_keyword(kw::Where) {
5861 return Ok(where_clause);
5863 let lo = self.prev_span;
5865 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5866 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5867 // change we parse those generics now, but report an error.
5868 if self.choose_generics_over_qpath() {
5869 let generics = self.parse_generics()?;
5870 self.struct_span_err(
5872 "generic parameters on `where` clauses are reserved for future use",
5874 .span_label(generics.span, "currently unsupported")
5880 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5881 let lifetime = self.expect_lifetime();
5882 // Bounds starting with a colon are mandatory, but possibly empty.
5883 self.expect(&token::Colon)?;
5884 let bounds = self.parse_lt_param_bounds();
5885 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5886 ast::WhereRegionPredicate {
5887 span: lo.to(self.prev_span),
5892 } else if self.check_type() {
5893 // Parse optional `for<'a, 'b>`.
5894 // This `for` is parsed greedily and applies to the whole predicate,
5895 // the bounded type can have its own `for` applying only to it.
5896 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5897 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5898 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5899 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5901 // Parse type with mandatory colon and (possibly empty) bounds,
5902 // or with mandatory equality sign and the second type.
5903 let ty = self.parse_ty()?;
5904 if self.eat(&token::Colon) {
5905 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
5906 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5907 ast::WhereBoundPredicate {
5908 span: lo.to(self.prev_span),
5909 bound_generic_params: lifetime_defs,
5914 // FIXME: Decide what should be used here, `=` or `==`.
5915 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5916 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5917 let rhs_ty = self.parse_ty()?;
5918 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5919 ast::WhereEqPredicate {
5920 span: lo.to(self.prev_span),
5923 id: ast::DUMMY_NODE_ID,
5927 return self.unexpected();
5933 if !self.eat(&token::Comma) {
5938 where_clause.span = lo.to(self.prev_span);
5942 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
5943 -> PResult<'a, (Vec<Arg> , bool)> {
5944 self.expect(&token::OpenDelim(token::Paren))?;
5947 let mut c_variadic = false;
5948 let (args, recovered): (Vec<Option<Arg>>, bool) =
5949 self.parse_seq_to_before_end(
5950 &token::CloseDelim(token::Paren),
5951 SeqSep::trailing_allowed(token::Comma),
5953 // If the argument is a C-variadic argument we should not
5954 // enforce named arguments.
5955 let enforce_named_args = if p.token == token::DotDotDot {
5960 match p.parse_arg_general(enforce_named_args, false,
5963 if let TyKind::CVarArgs = arg.ty.node {
5965 if p.token != token::CloseDelim(token::Paren) {
5968 "`...` must be the last argument of a C-variadic function");
5979 let lo = p.prev_span;
5980 // Skip every token until next possible arg or end.
5981 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5982 // Create a placeholder argument for proper arg count (issue #34264).
5983 let span = lo.to(p.prev_span);
5984 Ok(Some(dummy_arg(span)))
5991 self.eat(&token::CloseDelim(token::Paren));
5994 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5996 if c_variadic && args.is_empty() {
5998 "C-variadic function must be declared with at least one named argument");
6001 Ok((args, c_variadic))
6004 /// Parses the argument list and result type of a function declaration.
6005 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6007 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6008 let ret_ty = self.parse_ret_ty(true)?;
6017 /// Returns the parsed optional self argument and whether a self shortcut was used.
6018 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6019 let expect_ident = |this: &mut Self| match this.token {
6020 // Preserve hygienic context.
6021 token::Ident(ident, _) =>
6022 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6025 let isolated_self = |this: &mut Self, n| {
6026 this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
6027 this.look_ahead(n + 1, |t| t != &token::ModSep)
6030 // Parse optional self parameter of a method.
6031 // Only a limited set of initial token sequences is considered self parameters, anything
6032 // else is parsed as a normal function parameter list, so some lookahead is required.
6033 let eself_lo = self.span;
6034 let (eself, eself_ident, eself_hi) = match self.token {
6035 token::BinOp(token::And) => {
6041 (if isolated_self(self, 1) {
6043 SelfKind::Region(None, Mutability::Immutable)
6044 } else if self.look_ahead(1, |t| t.is_keyword(kw::Mut)) &&
6045 isolated_self(self, 2) {
6048 SelfKind::Region(None, Mutability::Mutable)
6049 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6050 isolated_self(self, 2) {
6052 let lt = self.expect_lifetime();
6053 SelfKind::Region(Some(lt), Mutability::Immutable)
6054 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6055 self.look_ahead(2, |t| t.is_keyword(kw::Mut)) &&
6056 isolated_self(self, 3) {
6058 let lt = self.expect_lifetime();
6060 SelfKind::Region(Some(lt), Mutability::Mutable)
6063 }, expect_ident(self), self.prev_span)
6065 token::BinOp(token::Star) => {
6070 // Emit special error for `self` cases.
6071 let msg = "cannot pass `self` by raw pointer";
6072 (if isolated_self(self, 1) {
6074 self.struct_span_err(self.span, msg)
6075 .span_label(self.span, msg)
6077 SelfKind::Value(Mutability::Immutable)
6078 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6079 isolated_self(self, 2) {
6082 self.struct_span_err(self.span, msg)
6083 .span_label(self.span, msg)
6085 SelfKind::Value(Mutability::Immutable)
6088 }, expect_ident(self), self.prev_span)
6090 token::Ident(..) => {
6091 if isolated_self(self, 0) {
6094 let eself_ident = expect_ident(self);
6095 let eself_hi = self.prev_span;
6096 (if self.eat(&token::Colon) {
6097 let ty = self.parse_ty()?;
6098 SelfKind::Explicit(ty, Mutability::Immutable)
6100 SelfKind::Value(Mutability::Immutable)
6101 }, eself_ident, eself_hi)
6102 } else if self.token.is_keyword(kw::Mut) &&
6103 isolated_self(self, 1) {
6107 let eself_ident = expect_ident(self);
6108 let eself_hi = self.prev_span;
6109 (if self.eat(&token::Colon) {
6110 let ty = self.parse_ty()?;
6111 SelfKind::Explicit(ty, Mutability::Mutable)
6113 SelfKind::Value(Mutability::Mutable)
6114 }, eself_ident, eself_hi)
6119 _ => return Ok(None),
6122 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6123 Ok(Some(Arg::from_self(eself, eself_ident)))
6126 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6127 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6128 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6130 self.expect(&token::OpenDelim(token::Paren))?;
6132 // Parse optional self argument
6133 let self_arg = self.parse_self_arg()?;
6135 // Parse the rest of the function parameter list.
6136 let sep = SeqSep::trailing_allowed(token::Comma);
6137 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6138 if self.check(&token::CloseDelim(token::Paren)) {
6139 (vec![self_arg], false)
6140 } else if self.eat(&token::Comma) {
6141 let mut fn_inputs = vec![self_arg];
6142 let (mut input, recovered) = self.parse_seq_to_before_end(
6143 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6144 fn_inputs.append(&mut input);
6145 (fn_inputs, recovered)
6147 match self.expect_one_of(&[], &[]) {
6148 Err(err) => return Err(err),
6149 Ok(recovered) => (vec![self_arg], recovered),
6153 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6157 // Parse closing paren and return type.
6158 self.expect(&token::CloseDelim(token::Paren))?;
6162 output: self.parse_ret_ty(true)?,
6167 /// Parses the `|arg, arg|` header of a closure.
6168 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6169 let inputs_captures = {
6170 if self.eat(&token::OrOr) {
6173 self.expect(&token::BinOp(token::Or))?;
6174 let args = self.parse_seq_to_before_tokens(
6175 &[&token::BinOp(token::Or), &token::OrOr],
6176 SeqSep::trailing_allowed(token::Comma),
6177 TokenExpectType::NoExpect,
6178 |p| p.parse_fn_block_arg()
6184 let output = self.parse_ret_ty(true)?;
6187 inputs: inputs_captures,
6193 /// Parses the name and optional generic types of a function header.
6194 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6195 let id = self.parse_ident()?;
6196 let generics = self.parse_generics()?;
6200 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6201 attrs: Vec<Attribute>) -> P<Item> {
6205 id: ast::DUMMY_NODE_ID,
6213 /// Parses an item-position function declaration.
6214 fn parse_item_fn(&mut self,
6216 mut asyncness: Spanned<IsAsync>,
6217 constness: Spanned<Constness>,
6219 -> PResult<'a, ItemInfo> {
6220 let (ident, mut generics) = self.parse_fn_header()?;
6221 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6222 let mut decl = self.parse_fn_decl(allow_c_variadic)?;
6223 generics.where_clause = self.parse_where_clause()?;
6224 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6225 self.construct_async_arguments(&mut asyncness, &mut decl);
6226 let header = FnHeader { unsafety, asyncness, constness, abi };
6227 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6230 /// Returns `true` if we are looking at `const ID`
6231 /// (returns `false` for things like `const fn`, etc.).
6232 fn is_const_item(&self) -> bool {
6233 self.token.is_keyword(kw::Const) &&
6234 !self.look_ahead(1, |t| t.is_keyword(kw::Fn)) &&
6235 !self.look_ahead(1, |t| t.is_keyword(kw::Unsafe))
6238 /// Parses all the "front matter" for a `fn` declaration, up to
6239 /// and including the `fn` keyword:
6243 /// - `const unsafe fn`
6246 fn parse_fn_front_matter(&mut self)
6254 let is_const_fn = self.eat_keyword(kw::Const);
6255 let const_span = self.prev_span;
6256 let unsafety = self.parse_unsafety();
6257 let asyncness = self.parse_asyncness();
6258 let asyncness = respan(self.prev_span, asyncness);
6259 let (constness, unsafety, abi) = if is_const_fn {
6260 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6262 let abi = if self.eat_keyword(kw::Extern) {
6263 self.parse_opt_abi()?.unwrap_or(Abi::C)
6267 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6269 if !self.eat_keyword(kw::Fn) {
6270 // It is possible for `expect_one_of` to recover given the contents of
6271 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6272 // account for this.
6273 if !self.expect_one_of(&[], &[])? { unreachable!() }
6275 Ok((constness, unsafety, asyncness, abi))
6278 /// Parses an impl item.
6279 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6280 maybe_whole!(self, NtImplItem, |x| x);
6281 let attrs = self.parse_outer_attributes()?;
6282 let mut unclosed_delims = vec![];
6283 let (mut item, tokens) = self.collect_tokens(|this| {
6284 let item = this.parse_impl_item_(at_end, attrs);
6285 unclosed_delims.append(&mut this.unclosed_delims);
6288 self.unclosed_delims.append(&mut unclosed_delims);
6290 // See `parse_item` for why this clause is here.
6291 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6292 item.tokens = Some(tokens);
6297 fn parse_impl_item_(&mut self,
6299 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6301 let vis = self.parse_visibility(false)?;
6302 let defaultness = self.parse_defaultness();
6303 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6304 let (name, alias, generics) = type_?;
6305 let kind = match alias {
6306 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6307 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6309 (name, kind, generics)
6310 } else if self.is_const_item() {
6311 // This parses the grammar:
6312 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6313 self.expect_keyword(kw::Const)?;
6314 let name = self.parse_ident()?;
6315 self.expect(&token::Colon)?;
6316 let typ = self.parse_ty()?;
6317 self.expect(&token::Eq)?;
6318 let expr = self.parse_expr()?;
6319 self.expect(&token::Semi)?;
6320 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6322 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6323 attrs.extend(inner_attrs);
6324 (name, node, generics)
6328 id: ast::DUMMY_NODE_ID,
6329 span: lo.to(self.prev_span),
6340 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
6342 VisibilityKind::Inherited => {}
6344 let is_macro_rules: bool = match self.token {
6345 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6348 let mut err = if is_macro_rules {
6349 let mut err = self.diagnostic()
6350 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6351 err.span_suggestion(
6353 "try exporting the macro",
6354 "#[macro_export]".to_owned(),
6355 Applicability::MaybeIncorrect // speculative
6359 let mut err = self.diagnostic()
6360 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6361 err.help("try adjusting the macro to put `pub` inside the invocation");
6369 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
6370 -> DiagnosticBuilder<'a>
6372 let expected_kinds = if item_type == "extern" {
6373 "missing `fn`, `type`, or `static`"
6375 "missing `fn`, `type`, or `const`"
6378 // Given this code `path(`, it seems like this is not
6379 // setting the visibility of a macro invocation, but rather
6380 // a mistyped method declaration.
6381 // Create a diagnostic pointing out that `fn` is missing.
6383 // x | pub path(&self) {
6384 // | ^ missing `fn`, `type`, or `const`
6386 // ^^ `sp` below will point to this
6387 let sp = prev_span.between(self.prev_span);
6388 let mut err = self.diagnostic().struct_span_err(
6390 &format!("{} for {}-item declaration",
6391 expected_kinds, item_type));
6392 err.span_label(sp, expected_kinds);
6396 /// Parse a method or a macro invocation in a trait impl.
6397 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6398 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6399 ast::ImplItemKind)> {
6400 // code copied from parse_macro_use_or_failure... abstraction!
6401 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6403 Ok((Ident::invalid(), vec![], ast::Generics::default(),
6404 ast::ImplItemKind::Macro(mac)))
6406 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6407 let ident = self.parse_ident()?;
6408 let mut generics = self.parse_generics()?;
6409 let mut decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6410 generics.where_clause = self.parse_where_clause()?;
6411 self.construct_async_arguments(&mut asyncness, &mut decl);
6413 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6414 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6415 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6416 ast::MethodSig { header, decl },
6422 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6423 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6424 let ident = self.parse_ident()?;
6425 let mut tps = self.parse_generics()?;
6427 // Parse optional colon and supertrait bounds.
6428 let bounds = if self.eat(&token::Colon) {
6429 self.parse_generic_bounds(Some(self.prev_span))?
6434 if self.eat(&token::Eq) {
6435 // it's a trait alias
6436 let bounds = self.parse_generic_bounds(None)?;
6437 tps.where_clause = self.parse_where_clause()?;
6438 self.expect(&token::Semi)?;
6439 if is_auto == IsAuto::Yes {
6440 let msg = "trait aliases cannot be `auto`";
6441 self.struct_span_err(self.prev_span, msg)
6442 .span_label(self.prev_span, msg)
6445 if unsafety != Unsafety::Normal {
6446 let msg = "trait aliases cannot be `unsafe`";
6447 self.struct_span_err(self.prev_span, msg)
6448 .span_label(self.prev_span, msg)
6451 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6453 // it's a normal trait
6454 tps.where_clause = self.parse_where_clause()?;
6455 self.expect(&token::OpenDelim(token::Brace))?;
6456 let mut trait_items = vec![];
6457 while !self.eat(&token::CloseDelim(token::Brace)) {
6458 if let token::DocComment(_) = self.token {
6459 if self.look_ahead(1,
6460 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6461 let mut err = self.diagnostic().struct_span_err_with_code(
6463 "found a documentation comment that doesn't document anything",
6464 DiagnosticId::Error("E0584".into()),
6466 err.help("doc comments must come before what they document, maybe a \
6467 comment was intended with `//`?",
6474 let mut at_end = false;
6475 match self.parse_trait_item(&mut at_end) {
6476 Ok(item) => trait_items.push(item),
6480 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6485 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6489 fn choose_generics_over_qpath(&self) -> bool {
6490 // There's an ambiguity between generic parameters and qualified paths in impls.
6491 // If we see `<` it may start both, so we have to inspect some following tokens.
6492 // The following combinations can only start generics,
6493 // but not qualified paths (with one exception):
6494 // `<` `>` - empty generic parameters
6495 // `<` `#` - generic parameters with attributes
6496 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6497 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6498 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6499 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6500 // `<` const - generic const parameter
6501 // The only truly ambiguous case is
6502 // `<` IDENT `>` `::` IDENT ...
6503 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6504 // because this is what almost always expected in practice, qualified paths in impls
6505 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6506 self.token == token::Lt &&
6507 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6508 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6509 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6510 t == &token::Colon || t == &token::Eq) ||
6511 self.look_ahead(1, |t| t.is_keyword(kw::Const)))
6514 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6515 self.expect(&token::OpenDelim(token::Brace))?;
6516 let attrs = self.parse_inner_attributes()?;
6518 let mut impl_items = Vec::new();
6519 while !self.eat(&token::CloseDelim(token::Brace)) {
6520 let mut at_end = false;
6521 match self.parse_impl_item(&mut at_end) {
6522 Ok(impl_item) => impl_items.push(impl_item),
6526 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6531 Ok((impl_items, attrs))
6534 /// Parses an implementation item, `impl` keyword is already parsed.
6536 /// impl<'a, T> TYPE { /* impl items */ }
6537 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6538 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6540 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6541 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6542 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6543 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6544 -> PResult<'a, ItemInfo> {
6545 // First, parse generic parameters if necessary.
6546 let mut generics = if self.choose_generics_over_qpath() {
6547 self.parse_generics()?
6549 ast::Generics::default()
6552 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6553 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6555 ast::ImplPolarity::Negative
6557 ast::ImplPolarity::Positive
6560 // Parse both types and traits as a type, then reinterpret if necessary.
6561 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
6562 let ty_first = if self.token.is_keyword(kw::For) &&
6563 self.look_ahead(1, |t| t != &token::Lt) {
6564 let span = self.prev_span.between(self.span);
6565 self.struct_span_err(span, "missing trait in a trait impl").emit();
6566 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6571 // If `for` is missing we try to recover.
6572 let has_for = self.eat_keyword(kw::For);
6573 let missing_for_span = self.prev_span.between(self.span);
6575 let ty_second = if self.token == token::DotDot {
6576 // We need to report this error after `cfg` expansion for compatibility reasons
6577 self.bump(); // `..`, do not add it to expected tokens
6578 Some(DummyResult::raw_ty(self.prev_span, true))
6579 } else if has_for || self.token.can_begin_type() {
6580 Some(self.parse_ty()?)
6585 generics.where_clause = self.parse_where_clause()?;
6587 let (impl_items, attrs) = self.parse_impl_body()?;
6589 let item_kind = match ty_second {
6590 Some(ty_second) => {
6591 // impl Trait for Type
6593 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6594 .span_suggestion_short(
6597 " for ".to_string(),
6598 Applicability::MachineApplicable,
6602 let ty_first = ty_first.into_inner();
6603 let path = match ty_first.node {
6604 // This notably includes paths passed through `ty` macro fragments (#46438).
6605 TyKind::Path(None, path) => path,
6607 self.span_err(ty_first.span, "expected a trait, found type");
6608 err_path(ty_first.span)
6611 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6613 ItemKind::Impl(unsafety, polarity, defaultness,
6614 generics, Some(trait_ref), ty_second, impl_items)
6618 ItemKind::Impl(unsafety, polarity, defaultness,
6619 generics, None, ty_first, impl_items)
6623 Ok((Ident::invalid(), item_kind, Some(attrs)))
6626 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6627 if self.eat_keyword(kw::For) {
6629 let params = self.parse_generic_params()?;
6631 // We rely on AST validation to rule out invalid cases: There must not be type
6632 // parameters, and the lifetime parameters must not have bounds.
6639 /// Parses `struct Foo { ... }`.
6640 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6641 let class_name = self.parse_ident()?;
6643 let mut generics = self.parse_generics()?;
6645 // There is a special case worth noting here, as reported in issue #17904.
6646 // If we are parsing a tuple struct it is the case that the where clause
6647 // should follow the field list. Like so:
6649 // struct Foo<T>(T) where T: Copy;
6651 // If we are parsing a normal record-style struct it is the case
6652 // that the where clause comes before the body, and after the generics.
6653 // So if we look ahead and see a brace or a where-clause we begin
6654 // parsing a record style struct.
6656 // Otherwise if we look ahead and see a paren we parse a tuple-style
6659 let vdata = if self.token.is_keyword(kw::Where) {
6660 generics.where_clause = self.parse_where_clause()?;
6661 if self.eat(&token::Semi) {
6662 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6663 VariantData::Unit(ast::DUMMY_NODE_ID)
6665 // If we see: `struct Foo<T> where T: Copy { ... }`
6666 let (fields, recovered) = self.parse_record_struct_body()?;
6667 VariantData::Struct(fields, recovered)
6669 // No `where` so: `struct Foo<T>;`
6670 } else if self.eat(&token::Semi) {
6671 VariantData::Unit(ast::DUMMY_NODE_ID)
6672 // Record-style struct definition
6673 } else if self.token == token::OpenDelim(token::Brace) {
6674 let (fields, recovered) = self.parse_record_struct_body()?;
6675 VariantData::Struct(fields, recovered)
6676 // Tuple-style struct definition with optional where-clause.
6677 } else if self.token == token::OpenDelim(token::Paren) {
6678 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6679 generics.where_clause = self.parse_where_clause()?;
6680 self.expect(&token::Semi)?;
6683 let token_str = self.this_token_descr();
6684 let mut err = self.fatal(&format!(
6685 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6688 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6692 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6695 /// Parses `union Foo { ... }`.
6696 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6697 let class_name = self.parse_ident()?;
6699 let mut generics = self.parse_generics()?;
6701 let vdata = if self.token.is_keyword(kw::Where) {
6702 generics.where_clause = self.parse_where_clause()?;
6703 let (fields, recovered) = self.parse_record_struct_body()?;
6704 VariantData::Struct(fields, recovered)
6705 } else if self.token == token::OpenDelim(token::Brace) {
6706 let (fields, recovered) = self.parse_record_struct_body()?;
6707 VariantData::Struct(fields, recovered)
6709 let token_str = self.this_token_descr();
6710 let mut err = self.fatal(&format!(
6711 "expected `where` or `{{` after union name, found {}", token_str));
6712 err.span_label(self.span, "expected `where` or `{` after union name");
6716 Ok((class_name, ItemKind::Union(vdata, generics), None))
6719 fn parse_record_struct_body(
6721 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6722 let mut fields = Vec::new();
6723 let mut recovered = false;
6724 if self.eat(&token::OpenDelim(token::Brace)) {
6725 while self.token != token::CloseDelim(token::Brace) {
6726 let field = self.parse_struct_decl_field().map_err(|e| {
6727 self.recover_stmt();
6732 Ok(field) => fields.push(field),
6738 self.eat(&token::CloseDelim(token::Brace));
6740 let token_str = self.this_token_descr();
6741 let mut err = self.fatal(&format!(
6742 "expected `where`, or `{{` after struct name, found {}", token_str));
6743 err.span_label(self.span, "expected `where`, or `{` after struct name");
6747 Ok((fields, recovered))
6750 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6751 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6752 // Unit like structs are handled in parse_item_struct function
6753 let fields = self.parse_unspanned_seq(
6754 &token::OpenDelim(token::Paren),
6755 &token::CloseDelim(token::Paren),
6756 SeqSep::trailing_allowed(token::Comma),
6758 let attrs = p.parse_outer_attributes()?;
6760 let vis = p.parse_visibility(true)?;
6761 let ty = p.parse_ty()?;
6763 span: lo.to(ty.span),
6766 id: ast::DUMMY_NODE_ID,
6775 /// Parses a structure field declaration.
6776 fn parse_single_struct_field(&mut self,
6779 attrs: Vec<Attribute> )
6780 -> PResult<'a, StructField> {
6781 let mut seen_comma: bool = false;
6782 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6783 if self.token == token::Comma {
6790 token::CloseDelim(token::Brace) => {}
6791 token::DocComment(_) => {
6792 let previous_span = self.prev_span;
6793 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6794 self.bump(); // consume the doc comment
6795 let comma_after_doc_seen = self.eat(&token::Comma);
6796 // `seen_comma` is always false, because we are inside doc block
6797 // condition is here to make code more readable
6798 if seen_comma == false && comma_after_doc_seen == true {
6801 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6804 if seen_comma == false {
6805 let sp = self.sess.source_map().next_point(previous_span);
6806 err.span_suggestion(
6808 "missing comma here",
6810 Applicability::MachineApplicable
6817 let sp = self.sess.source_map().next_point(self.prev_span);
6818 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6819 self.this_token_descr()));
6820 if self.token.is_ident() {
6821 // This is likely another field; emit the diagnostic and keep going
6822 err.span_suggestion(
6824 "try adding a comma",
6826 Applicability::MachineApplicable,
6837 /// Parses an element of a struct declaration.
6838 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6839 let attrs = self.parse_outer_attributes()?;
6841 let vis = self.parse_visibility(false)?;
6842 self.parse_single_struct_field(lo, vis, attrs)
6845 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6846 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6847 /// If the following element can't be a tuple (i.e., it's a function definition), then
6848 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6849 /// so emit a proper diagnostic.
6850 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6851 maybe_whole!(self, NtVis, |x| x);
6853 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
6854 if self.is_crate_vis() {
6855 self.bump(); // `crate`
6856 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6859 if !self.eat_keyword(kw::Pub) {
6860 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6861 // keyword to grab a span from for inherited visibility; an empty span at the
6862 // beginning of the current token would seem to be the "Schelling span".
6863 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6865 let lo = self.prev_span;
6867 if self.check(&token::OpenDelim(token::Paren)) {
6868 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6869 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6870 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6871 // by the following tokens.
6872 if self.look_ahead(1, |t| t.is_keyword(kw::Crate)) &&
6873 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
6877 self.bump(); // `crate`
6878 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6880 lo.to(self.prev_span),
6881 VisibilityKind::Crate(CrateSugar::PubCrate),
6884 } else if self.look_ahead(1, |t| t.is_keyword(kw::In)) {
6887 self.bump(); // `in`
6888 let path = self.parse_path(PathStyle::Mod)?; // `path`
6889 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6890 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6892 id: ast::DUMMY_NODE_ID,
6895 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6896 self.look_ahead(1, |t| t.is_keyword(kw::Super) ||
6897 t.is_keyword(kw::SelfLower))
6899 // `pub(self)` or `pub(super)`
6901 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6902 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6903 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6905 id: ast::DUMMY_NODE_ID,
6908 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6909 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6911 let msg = "incorrect visibility restriction";
6912 let suggestion = r##"some possible visibility restrictions are:
6913 `pub(crate)`: visible only on the current crate
6914 `pub(super)`: visible only in the current module's parent
6915 `pub(in path::to::module)`: visible only on the specified path"##;
6916 let path = self.parse_path(PathStyle::Mod)?;
6918 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6919 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6920 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6921 err.help(suggestion);
6922 err.span_suggestion(
6923 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6925 err.emit(); // emit diagnostic, but continue with public visibility
6929 Ok(respan(lo, VisibilityKind::Public))
6932 /// Parses defaultness (i.e., `default` or nothing).
6933 fn parse_defaultness(&mut self) -> Defaultness {
6934 // `pub` is included for better error messages
6935 if self.check_keyword(kw::Default) &&
6936 self.look_ahead(1, |t| t.is_keyword(kw::Impl) ||
6937 t.is_keyword(kw::Const) ||
6938 t.is_keyword(kw::Fn) ||
6939 t.is_keyword(kw::Unsafe) ||
6940 t.is_keyword(kw::Extern) ||
6941 t.is_keyword(kw::Type) ||
6942 t.is_keyword(kw::Pub)) {
6943 self.bump(); // `default`
6944 Defaultness::Default
6950 /// Given a termination token, parses all of the items in a module.
6951 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6952 let mut items = vec![];
6953 while let Some(item) = self.parse_item()? {
6955 self.maybe_consume_incorrect_semicolon(&items);
6958 if !self.eat(term) {
6959 let token_str = self.this_token_descr();
6960 if !self.maybe_consume_incorrect_semicolon(&items) {
6961 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6962 err.span_label(self.span, "expected item");
6967 let hi = if self.span.is_dummy() {
6974 inner: inner_lo.to(hi),
6980 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6981 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6982 self.expect(&token::Colon)?;
6983 let ty = self.parse_ty()?;
6984 self.expect(&token::Eq)?;
6985 let e = self.parse_expr()?;
6986 self.expect(&token::Semi)?;
6987 let item = match m {
6988 Some(m) => ItemKind::Static(ty, m, e),
6989 None => ItemKind::Const(ty, e),
6991 Ok((id, item, None))
6994 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6995 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6996 let (in_cfg, outer_attrs) = {
6997 let mut strip_unconfigured = crate::config::StripUnconfigured {
6999 features: None, // don't perform gated feature checking
7001 let mut outer_attrs = outer_attrs.to_owned();
7002 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7003 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7006 let id_span = self.span;
7007 let id = self.parse_ident()?;
7008 if self.eat(&token::Semi) {
7009 if in_cfg && self.recurse_into_file_modules {
7010 // This mod is in an external file. Let's go get it!
7011 let ModulePathSuccess { path, directory_ownership, warn } =
7012 self.submod_path(id, &outer_attrs, id_span)?;
7013 let (module, mut attrs) =
7014 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7015 // Record that we fetched the mod from an external file
7017 let attr = Attribute {
7018 id: attr::mk_attr_id(),
7019 style: ast::AttrStyle::Outer,
7020 path: ast::Path::from_ident(
7021 Ident::with_empty_ctxt(sym::warn_directory_ownership)),
7022 tokens: TokenStream::empty(),
7023 is_sugared_doc: false,
7024 span: syntax_pos::DUMMY_SP,
7026 attr::mark_known(&attr);
7029 Ok((id, ItemKind::Mod(module), Some(attrs)))
7031 let placeholder = ast::Mod {
7032 inner: syntax_pos::DUMMY_SP,
7036 Ok((id, ItemKind::Mod(placeholder), None))
7039 let old_directory = self.directory.clone();
7040 self.push_directory(id, &outer_attrs);
7042 self.expect(&token::OpenDelim(token::Brace))?;
7043 let mod_inner_lo = self.span;
7044 let attrs = self.parse_inner_attributes()?;
7045 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7047 self.directory = old_directory;
7048 Ok((id, ItemKind::Mod(module), Some(attrs)))
7052 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7053 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
7054 self.directory.path.to_mut().push(&path.as_str());
7055 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7057 // We have to push on the current module name in the case of relative
7058 // paths in order to ensure that any additional module paths from inline
7059 // `mod x { ... }` come after the relative extension.
7061 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7062 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7063 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7064 if let Some(ident) = relative.take() { // remove the relative offset
7065 self.directory.path.to_mut().push(ident.as_str());
7068 self.directory.path.to_mut().push(&id.as_str());
7072 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7073 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
7076 // On windows, the base path might have the form
7077 // `\\?\foo\bar` in which case it does not tolerate
7078 // mixed `/` and `\` separators, so canonicalize
7081 let s = s.replace("/", "\\");
7082 Some(dir_path.join(s))
7088 /// Returns a path to a module.
7089 pub fn default_submod_path(
7091 relative: Option<ast::Ident>,
7093 source_map: &SourceMap) -> ModulePath
7095 // If we're in a foo.rs file instead of a mod.rs file,
7096 // we need to look for submodules in
7097 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7098 // `./<id>.rs` and `./<id>/mod.rs`.
7099 let relative_prefix_string;
7100 let relative_prefix = if let Some(ident) = relative {
7101 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7102 &relative_prefix_string
7107 let mod_name = id.to_string();
7108 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7109 let secondary_path_str = format!("{}{}{}mod.rs",
7110 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7111 let default_path = dir_path.join(&default_path_str);
7112 let secondary_path = dir_path.join(&secondary_path_str);
7113 let default_exists = source_map.file_exists(&default_path);
7114 let secondary_exists = source_map.file_exists(&secondary_path);
7116 let result = match (default_exists, secondary_exists) {
7117 (true, false) => Ok(ModulePathSuccess {
7119 directory_ownership: DirectoryOwnership::Owned {
7124 (false, true) => Ok(ModulePathSuccess {
7125 path: secondary_path,
7126 directory_ownership: DirectoryOwnership::Owned {
7131 (false, false) => Err(Error::FileNotFoundForModule {
7132 mod_name: mod_name.clone(),
7133 default_path: default_path_str,
7134 secondary_path: secondary_path_str,
7135 dir_path: dir_path.display().to_string(),
7137 (true, true) => Err(Error::DuplicatePaths {
7138 mod_name: mod_name.clone(),
7139 default_path: default_path_str,
7140 secondary_path: secondary_path_str,
7146 path_exists: default_exists || secondary_exists,
7151 fn submod_path(&mut self,
7153 outer_attrs: &[Attribute],
7155 -> PResult<'a, ModulePathSuccess> {
7156 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7157 return Ok(ModulePathSuccess {
7158 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7159 // All `#[path]` files are treated as though they are a `mod.rs` file.
7160 // This means that `mod foo;` declarations inside `#[path]`-included
7161 // files are siblings,
7163 // Note that this will produce weirdness when a file named `foo.rs` is
7164 // `#[path]` included and contains a `mod foo;` declaration.
7165 // If you encounter this, it's your own darn fault :P
7166 Some(_) => DirectoryOwnership::Owned { relative: None },
7167 _ => DirectoryOwnership::UnownedViaMod(true),
7174 let relative = match self.directory.ownership {
7175 DirectoryOwnership::Owned { relative } => relative,
7176 DirectoryOwnership::UnownedViaBlock |
7177 DirectoryOwnership::UnownedViaMod(_) => None,
7179 let paths = Parser::default_submod_path(
7180 id, relative, &self.directory.path, self.sess.source_map());
7182 match self.directory.ownership {
7183 DirectoryOwnership::Owned { .. } => {
7184 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7186 DirectoryOwnership::UnownedViaBlock => {
7188 "Cannot declare a non-inline module inside a block \
7189 unless it has a path attribute";
7190 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7191 if paths.path_exists {
7192 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7194 err.span_note(id_sp, &msg);
7198 DirectoryOwnership::UnownedViaMod(warn) => {
7200 if let Ok(result) = paths.result {
7201 return Ok(ModulePathSuccess { warn: true, ..result });
7204 let mut err = self.diagnostic().struct_span_err(id_sp,
7205 "cannot declare a new module at this location");
7206 if !id_sp.is_dummy() {
7207 let src_path = self.sess.source_map().span_to_filename(id_sp);
7208 if let FileName::Real(src_path) = src_path {
7209 if let Some(stem) = src_path.file_stem() {
7210 let mut dest_path = src_path.clone();
7211 dest_path.set_file_name(stem);
7212 dest_path.push("mod.rs");
7213 err.span_note(id_sp,
7214 &format!("maybe move this module `{}` to its own \
7215 directory via `{}`", src_path.display(),
7216 dest_path.display()));
7220 if paths.path_exists {
7221 err.span_note(id_sp,
7222 &format!("... or maybe `use` the module `{}` instead \
7223 of possibly redeclaring it",
7231 /// Reads a module from a source file.
7232 fn eval_src_mod(&mut self,
7234 directory_ownership: DirectoryOwnership,
7237 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7238 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7239 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7240 let mut err = String::from("circular modules: ");
7241 let len = included_mod_stack.len();
7242 for p in &included_mod_stack[i.. len] {
7243 err.push_str(&p.to_string_lossy());
7244 err.push_str(" -> ");
7246 err.push_str(&path.to_string_lossy());
7247 return Err(self.span_fatal(id_sp, &err[..]));
7249 included_mod_stack.push(path.clone());
7250 drop(included_mod_stack);
7253 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7254 p0.cfg_mods = self.cfg_mods;
7255 let mod_inner_lo = p0.span;
7256 let mod_attrs = p0.parse_inner_attributes()?;
7257 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7259 self.sess.included_mod_stack.borrow_mut().pop();
7263 /// Parses a function declaration from a foreign module.
7264 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7265 -> PResult<'a, ForeignItem> {
7266 self.expect_keyword(kw::Fn)?;
7268 let (ident, mut generics) = self.parse_fn_header()?;
7269 let decl = self.parse_fn_decl(true)?;
7270 generics.where_clause = self.parse_where_clause()?;
7272 self.expect(&token::Semi)?;
7273 Ok(ast::ForeignItem {
7276 node: ForeignItemKind::Fn(decl, generics),
7277 id: ast::DUMMY_NODE_ID,
7283 /// Parses a static item from a foreign module.
7284 /// Assumes that the `static` keyword is already parsed.
7285 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7286 -> PResult<'a, ForeignItem> {
7287 let mutbl = self.parse_mutability();
7288 let ident = self.parse_ident()?;
7289 self.expect(&token::Colon)?;
7290 let ty = self.parse_ty()?;
7292 self.expect(&token::Semi)?;
7296 node: ForeignItemKind::Static(ty, mutbl),
7297 id: ast::DUMMY_NODE_ID,
7303 /// Parses a type from a foreign module.
7304 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7305 -> PResult<'a, ForeignItem> {
7306 self.expect_keyword(kw::Type)?;
7308 let ident = self.parse_ident()?;
7310 self.expect(&token::Semi)?;
7311 Ok(ast::ForeignItem {
7314 node: ForeignItemKind::Ty,
7315 id: ast::DUMMY_NODE_ID,
7321 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7322 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7323 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7325 let mut ident = if self.token.is_keyword(kw::SelfLower) {
7326 self.parse_path_segment_ident()
7330 let mut idents = vec![];
7331 let mut replacement = vec![];
7332 let mut fixed_crate_name = false;
7333 // Accept `extern crate name-like-this` for better diagnostics
7334 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7335 if self.token == dash { // Do not include `-` as part of the expected tokens list
7336 while self.eat(&dash) {
7337 fixed_crate_name = true;
7338 replacement.push((self.prev_span, "_".to_string()));
7339 idents.push(self.parse_ident()?);
7342 if fixed_crate_name {
7343 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7344 let mut fixed_name = format!("{}", ident.name);
7345 for part in idents {
7346 fixed_name.push_str(&format!("_{}", part.name));
7348 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7350 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7351 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7352 err.multipart_suggestion(
7355 Applicability::MachineApplicable,
7362 /// Parses `extern crate` links.
7367 /// extern crate foo;
7368 /// extern crate bar as foo;
7370 fn parse_item_extern_crate(&mut self,
7372 visibility: Visibility,
7373 attrs: Vec<Attribute>)
7374 -> PResult<'a, P<Item>> {
7375 // Accept `extern crate name-like-this` for better diagnostics
7376 let orig_name = self.parse_crate_name_with_dashes()?;
7377 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7378 (rename, Some(orig_name.name))
7382 self.expect(&token::Semi)?;
7384 let span = lo.to(self.prev_span);
7385 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7388 /// Parses `extern` for foreign ABIs modules.
7390 /// `extern` is expected to have been
7391 /// consumed before calling this method.
7395 /// ```ignore (only-for-syntax-highlight)
7399 fn parse_item_foreign_mod(&mut self,
7401 opt_abi: Option<Abi>,
7402 visibility: Visibility,
7403 mut attrs: Vec<Attribute>)
7404 -> PResult<'a, P<Item>> {
7405 self.expect(&token::OpenDelim(token::Brace))?;
7407 let abi = opt_abi.unwrap_or(Abi::C);
7409 attrs.extend(self.parse_inner_attributes()?);
7411 let mut foreign_items = vec![];
7412 while !self.eat(&token::CloseDelim(token::Brace)) {
7413 foreign_items.push(self.parse_foreign_item()?);
7416 let prev_span = self.prev_span;
7417 let m = ast::ForeignMod {
7419 items: foreign_items
7421 let invalid = Ident::invalid();
7422 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7425 /// Parses `type Foo = Bar;`
7427 /// `existential type Foo: Bar;`
7430 /// without modifying the parser state.
7431 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7432 // This parses the grammar:
7433 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7434 if self.check_keyword(kw::Type) ||
7435 self.check_keyword(kw::Existential) &&
7436 self.look_ahead(1, |t| t.is_keyword(kw::Type)) {
7437 let existential = self.eat_keyword(kw::Existential);
7438 assert!(self.eat_keyword(kw::Type));
7439 Some(self.parse_existential_or_alias(existential))
7445 /// Parses a type alias or existential type.
7446 fn parse_existential_or_alias(
7449 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7450 let ident = self.parse_ident()?;
7451 let mut tps = self.parse_generics()?;
7452 tps.where_clause = self.parse_where_clause()?;
7453 let alias = if existential {
7454 self.expect(&token::Colon)?;
7455 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7456 AliasKind::Existential(bounds)
7458 self.expect(&token::Eq)?;
7459 let ty = self.parse_ty()?;
7462 self.expect(&token::Semi)?;
7463 Ok((ident, alias, tps))
7466 /// Parses the part of an enum declaration following the `{`.
7467 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7468 let mut variants = Vec::new();
7469 let mut any_disr = vec![];
7470 while self.token != token::CloseDelim(token::Brace) {
7471 let variant_attrs = self.parse_outer_attributes()?;
7472 let vlo = self.span;
7475 let mut disr_expr = None;
7477 let ident = self.parse_ident()?;
7478 if self.check(&token::OpenDelim(token::Brace)) {
7479 // Parse a struct variant.
7480 let (fields, recovered) = self.parse_record_struct_body()?;
7481 struct_def = VariantData::Struct(fields, recovered);
7482 } else if self.check(&token::OpenDelim(token::Paren)) {
7483 struct_def = VariantData::Tuple(
7484 self.parse_tuple_struct_body()?,
7487 } else if self.eat(&token::Eq) {
7488 disr_expr = Some(AnonConst {
7489 id: ast::DUMMY_NODE_ID,
7490 value: self.parse_expr()?,
7492 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7495 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7497 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7500 let vr = ast::Variant_ {
7502 id: ast::DUMMY_NODE_ID,
7503 attrs: variant_attrs,
7507 variants.push(respan(vlo.to(self.prev_span), vr));
7509 if !self.eat(&token::Comma) {
7510 if self.token.is_ident() && !self.token.is_reserved_ident() {
7511 let sp = self.sess.source_map().next_point(self.prev_span);
7512 let mut err = self.struct_span_err(sp, "missing comma");
7513 err.span_suggestion_short(
7517 Applicability::MaybeIncorrect,
7525 self.expect(&token::CloseDelim(token::Brace))?;
7526 self.maybe_report_invalid_custom_discriminants(any_disr, &variants);
7528 Ok(ast::EnumDef { variants })
7531 /// Parses an enum declaration.
7532 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7533 let id = self.parse_ident()?;
7534 let mut generics = self.parse_generics()?;
7535 generics.where_clause = self.parse_where_clause()?;
7536 self.expect(&token::OpenDelim(token::Brace))?;
7538 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7539 self.recover_stmt();
7540 self.eat(&token::CloseDelim(token::Brace));
7543 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7546 /// Parses a string as an ABI spec on an extern type or module. Consumes
7547 /// the `extern` keyword, if one is found.
7548 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7550 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
7551 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
7553 self.expect_no_suffix(sp, "an ABI spec", suffix);
7555 match abi::lookup(&symbol.as_str()) {
7556 Some(abi) => Ok(Some(abi)),
7558 let prev_span = self.prev_span;
7559 let mut err = struct_span_err!(
7560 self.sess.span_diagnostic,
7563 "invalid ABI: found `{}`",
7565 err.span_label(prev_span, "invalid ABI");
7566 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7577 fn is_static_global(&mut self) -> bool {
7578 if self.check_keyword(kw::Static) {
7579 // Check if this could be a closure
7580 !self.look_ahead(1, |token| {
7581 if token.is_keyword(kw::Move) {
7585 token::BinOp(token::Or) | token::OrOr => true,
7596 attrs: Vec<Attribute>,
7597 macros_allowed: bool,
7598 attributes_allowed: bool,
7599 ) -> PResult<'a, Option<P<Item>>> {
7600 let mut unclosed_delims = vec![];
7601 let (ret, tokens) = self.collect_tokens(|this| {
7602 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7603 unclosed_delims.append(&mut this.unclosed_delims);
7606 self.unclosed_delims.append(&mut unclosed_delims);
7608 // Once we've parsed an item and recorded the tokens we got while
7609 // parsing we may want to store `tokens` into the item we're about to
7610 // return. Note, though, that we specifically didn't capture tokens
7611 // related to outer attributes. The `tokens` field here may later be
7612 // used with procedural macros to convert this item back into a token
7613 // stream, but during expansion we may be removing attributes as we go
7616 // If we've got inner attributes then the `tokens` we've got above holds
7617 // these inner attributes. If an inner attribute is expanded we won't
7618 // actually remove it from the token stream, so we'll just keep yielding
7619 // it (bad!). To work around this case for now we just avoid recording
7620 // `tokens` if we detect any inner attributes. This should help keep
7621 // expansion correct, but we should fix this bug one day!
7624 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7625 i.tokens = Some(tokens);
7632 /// Parses one of the items allowed by the flags.
7633 fn parse_item_implementation(
7635 attrs: Vec<Attribute>,
7636 macros_allowed: bool,
7637 attributes_allowed: bool,
7638 ) -> PResult<'a, Option<P<Item>>> {
7639 maybe_whole!(self, NtItem, |item| {
7640 let mut item = item.into_inner();
7641 let mut attrs = attrs;
7642 mem::swap(&mut item.attrs, &mut attrs);
7643 item.attrs.extend(attrs);
7649 let visibility = self.parse_visibility(false)?;
7651 if self.eat_keyword(kw::Use) {
7653 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7654 self.expect(&token::Semi)?;
7656 let span = lo.to(self.prev_span);
7658 self.mk_item(span, Ident::invalid(), item_, visibility, attrs);
7659 return Ok(Some(item));
7662 if self.eat_keyword(kw::Extern) {
7663 if self.eat_keyword(kw::Crate) {
7664 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7667 let opt_abi = self.parse_opt_abi()?;
7669 if self.eat_keyword(kw::Fn) {
7670 // EXTERN FUNCTION ITEM
7671 let fn_span = self.prev_span;
7672 let abi = opt_abi.unwrap_or(Abi::C);
7673 let (ident, item_, extra_attrs) =
7674 self.parse_item_fn(Unsafety::Normal,
7675 respan(fn_span, IsAsync::NotAsync),
7676 respan(fn_span, Constness::NotConst),
7678 let prev_span = self.prev_span;
7679 let item = self.mk_item(lo.to(prev_span),
7683 maybe_append(attrs, extra_attrs));
7684 return Ok(Some(item));
7685 } else if self.check(&token::OpenDelim(token::Brace)) {
7686 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7692 if self.is_static_global() {
7695 let m = if self.eat_keyword(kw::Mut) {
7698 Mutability::Immutable
7700 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7701 let prev_span = self.prev_span;
7702 let item = self.mk_item(lo.to(prev_span),
7706 maybe_append(attrs, extra_attrs));
7707 return Ok(Some(item));
7709 if self.eat_keyword(kw::Const) {
7710 let const_span = self.prev_span;
7711 if self.check_keyword(kw::Fn)
7712 || (self.check_keyword(kw::Unsafe)
7713 && self.look_ahead(1, |t| t.is_keyword(kw::Fn))) {
7714 // CONST FUNCTION ITEM
7715 let unsafety = self.parse_unsafety();
7717 let (ident, item_, extra_attrs) =
7718 self.parse_item_fn(unsafety,
7719 respan(const_span, IsAsync::NotAsync),
7720 respan(const_span, Constness::Const),
7722 let prev_span = self.prev_span;
7723 let item = self.mk_item(lo.to(prev_span),
7727 maybe_append(attrs, extra_attrs));
7728 return Ok(Some(item));
7732 if self.eat_keyword(kw::Mut) {
7733 let prev_span = self.prev_span;
7734 let mut err = self.diagnostic()
7735 .struct_span_err(prev_span, "const globals cannot be mutable");
7736 err.span_label(prev_span, "cannot be mutable");
7737 err.span_suggestion(
7739 "you might want to declare a static instead",
7740 "static".to_owned(),
7741 Applicability::MaybeIncorrect,
7745 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7746 let prev_span = self.prev_span;
7747 let item = self.mk_item(lo.to(prev_span),
7751 maybe_append(attrs, extra_attrs));
7752 return Ok(Some(item));
7755 // `unsafe async fn` or `async fn`
7757 self.check_keyword(kw::Unsafe) &&
7758 self.look_ahead(1, |t| t.is_keyword(kw::Async))
7760 self.check_keyword(kw::Async) &&
7761 self.look_ahead(1, |t| t.is_keyword(kw::Fn))
7764 // ASYNC FUNCTION ITEM
7765 let unsafety = self.parse_unsafety();
7766 self.expect_keyword(kw::Async)?;
7767 let async_span = self.prev_span;
7768 self.expect_keyword(kw::Fn)?;
7769 let fn_span = self.prev_span;
7770 let (ident, item_, extra_attrs) =
7771 self.parse_item_fn(unsafety,
7772 respan(async_span, IsAsync::Async {
7773 closure_id: ast::DUMMY_NODE_ID,
7774 return_impl_trait_id: ast::DUMMY_NODE_ID,
7775 arguments: Vec::new(),
7777 respan(fn_span, Constness::NotConst),
7779 let prev_span = self.prev_span;
7780 let item = self.mk_item(lo.to(prev_span),
7784 maybe_append(attrs, extra_attrs));
7785 if self.span.rust_2015() {
7786 self.diagnostic().struct_span_err_with_code(
7788 "`async fn` is not permitted in the 2015 edition",
7789 DiagnosticId::Error("E0670".into())
7792 return Ok(Some(item));
7794 if self.check_keyword(kw::Unsafe) &&
7795 (self.look_ahead(1, |t| t.is_keyword(kw::Trait)) ||
7796 self.look_ahead(1, |t| t.is_keyword(kw::Auto)))
7798 // UNSAFE TRAIT ITEM
7799 self.bump(); // `unsafe`
7800 let is_auto = if self.eat_keyword(kw::Trait) {
7803 self.expect_keyword(kw::Auto)?;
7804 self.expect_keyword(kw::Trait)?;
7807 let (ident, item_, extra_attrs) =
7808 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7809 let prev_span = self.prev_span;
7810 let item = self.mk_item(lo.to(prev_span),
7814 maybe_append(attrs, extra_attrs));
7815 return Ok(Some(item));
7817 if self.check_keyword(kw::Impl) ||
7818 self.check_keyword(kw::Unsafe) &&
7819 self.look_ahead(1, |t| t.is_keyword(kw::Impl)) ||
7820 self.check_keyword(kw::Default) &&
7821 self.look_ahead(1, |t| t.is_keyword(kw::Impl)) ||
7822 self.check_keyword(kw::Default) &&
7823 self.look_ahead(1, |t| t.is_keyword(kw::Unsafe)) {
7825 let defaultness = self.parse_defaultness();
7826 let unsafety = self.parse_unsafety();
7827 self.expect_keyword(kw::Impl)?;
7828 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7829 let span = lo.to(self.prev_span);
7830 return Ok(Some(self.mk_item(span, ident, item, visibility,
7831 maybe_append(attrs, extra_attrs))));
7833 if self.check_keyword(kw::Fn) {
7836 let fn_span = self.prev_span;
7837 let (ident, item_, extra_attrs) =
7838 self.parse_item_fn(Unsafety::Normal,
7839 respan(fn_span, IsAsync::NotAsync),
7840 respan(fn_span, Constness::NotConst),
7842 let prev_span = self.prev_span;
7843 let item = self.mk_item(lo.to(prev_span),
7847 maybe_append(attrs, extra_attrs));
7848 return Ok(Some(item));
7850 if self.check_keyword(kw::Unsafe)
7851 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7852 // UNSAFE FUNCTION ITEM
7853 self.bump(); // `unsafe`
7854 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7855 self.check(&token::OpenDelim(token::Brace));
7856 let abi = if self.eat_keyword(kw::Extern) {
7857 self.parse_opt_abi()?.unwrap_or(Abi::C)
7861 self.expect_keyword(kw::Fn)?;
7862 let fn_span = self.prev_span;
7863 let (ident, item_, extra_attrs) =
7864 self.parse_item_fn(Unsafety::Unsafe,
7865 respan(fn_span, IsAsync::NotAsync),
7866 respan(fn_span, Constness::NotConst),
7868 let prev_span = self.prev_span;
7869 let item = self.mk_item(lo.to(prev_span),
7873 maybe_append(attrs, extra_attrs));
7874 return Ok(Some(item));
7876 if self.eat_keyword(kw::Mod) {
7878 let (ident, item_, extra_attrs) =
7879 self.parse_item_mod(&attrs[..])?;
7880 let prev_span = self.prev_span;
7881 let item = self.mk_item(lo.to(prev_span),
7885 maybe_append(attrs, extra_attrs));
7886 return Ok(Some(item));
7888 if let Some(type_) = self.eat_type() {
7889 let (ident, alias, generics) = type_?;
7891 let item_ = match alias {
7892 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7893 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7895 let prev_span = self.prev_span;
7896 let item = self.mk_item(lo.to(prev_span),
7901 return Ok(Some(item));
7903 if self.eat_keyword(kw::Enum) {
7905 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
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.check_keyword(kw::Trait)
7915 || (self.check_keyword(kw::Auto)
7916 && self.look_ahead(1, |t| t.is_keyword(kw::Trait)))
7918 let is_auto = if self.eat_keyword(kw::Trait) {
7921 self.expect_keyword(kw::Auto)?;
7922 self.expect_keyword(kw::Trait)?;
7926 let (ident, item_, extra_attrs) =
7927 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7928 let prev_span = self.prev_span;
7929 let item = self.mk_item(lo.to(prev_span),
7933 maybe_append(attrs, extra_attrs));
7934 return Ok(Some(item));
7936 if self.eat_keyword(kw::Struct) {
7938 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7939 let prev_span = self.prev_span;
7940 let item = self.mk_item(lo.to(prev_span),
7944 maybe_append(attrs, extra_attrs));
7945 return Ok(Some(item));
7947 if self.is_union_item() {
7950 let (ident, item_, extra_attrs) = self.parse_item_union()?;
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));
7959 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7960 return Ok(Some(macro_def));
7963 // Verify whether we have encountered a struct or method definition where the user forgot to
7964 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7965 if visibility.node.is_pub() &&
7966 self.check_ident() &&
7967 self.look_ahead(1, |t| *t != token::Not)
7969 // Space between `pub` keyword and the identifier
7972 // ^^^ `sp` points here
7973 let sp = self.prev_span.between(self.span);
7974 let full_sp = self.prev_span.to(self.span);
7975 let ident_sp = self.span;
7976 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7977 // possible public struct definition where `struct` was forgotten
7978 let ident = self.parse_ident().unwrap();
7979 let msg = format!("add `struct` here to parse `{}` as a public struct",
7981 let mut err = self.diagnostic()
7982 .struct_span_err(sp, "missing `struct` for struct definition");
7983 err.span_suggestion_short(
7984 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7987 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7988 let ident = self.parse_ident().unwrap();
7990 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
7995 self.consume_block(token::Paren);
7996 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7997 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7999 ("fn", kw_name, false)
8000 } else if self.check(&token::OpenDelim(token::Brace)) {
8002 ("fn", kw_name, false)
8003 } else if self.check(&token::Colon) {
8007 ("fn` or `struct", "function or struct", true)
8010 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8011 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8013 self.consume_block(token::Brace);
8014 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8018 err.span_suggestion_short(
8019 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8022 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8023 err.span_suggestion(
8025 "if you meant to call a macro, try",
8026 format!("{}!", snippet),
8027 // this is the `ambiguous` conditional branch
8028 Applicability::MaybeIncorrect
8031 err.help("if you meant to call a macro, remove the `pub` \
8032 and add a trailing `!` after the identifier");
8036 } else if self.look_ahead(1, |t| *t == token::Lt) {
8037 let ident = self.parse_ident().unwrap();
8038 self.eat_to_tokens(&[&token::Gt]);
8040 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8041 if let Ok(Some(_)) = self.parse_self_arg() {
8042 ("fn", "method", false)
8044 ("fn", "function", false)
8046 } else if self.check(&token::OpenDelim(token::Brace)) {
8047 ("struct", "struct", false)
8049 ("fn` or `struct", "function or struct", true)
8051 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8052 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8054 err.span_suggestion_short(
8056 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8057 format!(" {} ", kw),
8058 Applicability::MachineApplicable,
8064 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8067 /// Parses a foreign item.
8068 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8069 maybe_whole!(self, NtForeignItem, |ni| ni);
8071 let attrs = self.parse_outer_attributes()?;
8073 let visibility = self.parse_visibility(false)?;
8075 // FOREIGN STATIC ITEM
8076 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8077 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
8078 if self.token.is_keyword(kw::Const) {
8080 .struct_span_err(self.span, "extern items cannot be `const`")
8083 "try using a static value",
8084 "static".to_owned(),
8085 Applicability::MachineApplicable
8088 self.bump(); // `static` or `const`
8089 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8091 // FOREIGN FUNCTION ITEM
8092 if self.check_keyword(kw::Fn) {
8093 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8095 // FOREIGN TYPE ITEM
8096 if self.check_keyword(kw::Type) {
8097 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8100 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8104 ident: Ident::invalid(),
8105 span: lo.to(self.prev_span),
8106 id: ast::DUMMY_NODE_ID,
8109 node: ForeignItemKind::Macro(mac),
8114 if !attrs.is_empty() {
8115 self.expected_item_err(&attrs)?;
8123 /// This is the fall-through for parsing items.
8124 fn parse_macro_use_or_failure(
8126 attrs: Vec<Attribute> ,
8127 macros_allowed: bool,
8128 attributes_allowed: bool,
8130 visibility: Visibility
8131 ) -> PResult<'a, Option<P<Item>>> {
8132 if macros_allowed && self.token.is_path_start() &&
8133 !(self.is_async_fn() && self.span.rust_2015()) {
8134 // MACRO INVOCATION ITEM
8136 let prev_span = self.prev_span;
8137 self.complain_if_pub_macro(&visibility.node, prev_span);
8139 let mac_lo = self.span;
8142 let pth = self.parse_path(PathStyle::Mod)?;
8143 self.expect(&token::Not)?;
8145 // a 'special' identifier (like what `macro_rules!` uses)
8146 // is optional. We should eventually unify invoc syntax
8148 let id = if self.token.is_ident() {
8151 Ident::invalid() // no special identifier
8153 // eat a matched-delimiter token tree:
8154 let (delim, tts) = self.expect_delimited_token_tree()?;
8155 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8156 self.report_invalid_macro_expansion_item();
8159 let hi = self.prev_span;
8160 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8161 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8162 return Ok(Some(item));
8165 // FAILURE TO PARSE ITEM
8166 match visibility.node {
8167 VisibilityKind::Inherited => {}
8169 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8173 if !attributes_allowed && !attrs.is_empty() {
8174 self.expected_item_err(&attrs)?;
8179 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8180 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8181 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8183 if self.token.is_path_start() &&
8184 !(self.is_async_fn() && self.span.rust_2015()) {
8185 let prev_span = self.prev_span;
8187 let pth = self.parse_path(PathStyle::Mod)?;
8189 if pth.segments.len() == 1 {
8190 if !self.eat(&token::Not) {
8191 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8194 self.expect(&token::Not)?;
8197 if let Some(vis) = vis {
8198 self.complain_if_pub_macro(&vis.node, prev_span);
8203 // eat a matched-delimiter token tree:
8204 let (delim, tts) = self.expect_delimited_token_tree()?;
8205 if delim != MacDelimiter::Brace {
8206 self.expect(&token::Semi)?;
8209 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8215 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8216 where F: FnOnce(&mut Self) -> PResult<'a, R>
8218 // Record all tokens we parse when parsing this item.
8219 let mut tokens = Vec::new();
8220 let prev_collecting = match self.token_cursor.frame.last_token {
8221 LastToken::Collecting(ref mut list) => {
8222 Some(mem::replace(list, Vec::new()))
8224 LastToken::Was(ref mut last) => {
8225 tokens.extend(last.take());
8229 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8230 let prev = self.token_cursor.stack.len();
8232 let last_token = if self.token_cursor.stack.len() == prev {
8233 &mut self.token_cursor.frame.last_token
8235 &mut self.token_cursor.stack[prev].last_token
8238 // Pull out the tokens that we've collected from the call to `f` above.
8239 let mut collected_tokens = match *last_token {
8240 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8241 LastToken::Was(_) => panic!("our vector went away?"),
8244 // If we're not at EOF our current token wasn't actually consumed by
8245 // `f`, but it'll still be in our list that we pulled out. In that case
8247 let extra_token = if self.token != token::Eof {
8248 collected_tokens.pop()
8253 // If we were previously collecting tokens, then this was a recursive
8254 // call. In that case we need to record all the tokens we collected in
8255 // our parent list as well. To do that we push a clone of our stream
8256 // onto the previous list.
8257 match prev_collecting {
8259 list.extend(collected_tokens.iter().cloned());
8260 list.extend(extra_token);
8261 *last_token = LastToken::Collecting(list);
8264 *last_token = LastToken::Was(extra_token);
8268 Ok((ret?, TokenStream::new(collected_tokens)))
8271 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8272 let attrs = self.parse_outer_attributes()?;
8273 self.parse_item_(attrs, true, false)
8277 fn is_import_coupler(&mut self) -> bool {
8278 self.check(&token::ModSep) &&
8279 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8280 *t == token::BinOp(token::Star))
8283 /// Parses a `UseTree`.
8286 /// USE_TREE = [`::`] `*` |
8287 /// [`::`] `{` USE_TREE_LIST `}` |
8289 /// PATH `::` `{` USE_TREE_LIST `}` |
8290 /// PATH [`as` IDENT]
8292 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8295 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8296 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8297 self.check(&token::BinOp(token::Star)) ||
8298 self.is_import_coupler() {
8299 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8300 let mod_sep_ctxt = self.span.ctxt();
8301 if self.eat(&token::ModSep) {
8302 prefix.segments.push(
8303 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8307 if self.eat(&token::BinOp(token::Star)) {
8310 UseTreeKind::Nested(self.parse_use_tree_list()?)
8313 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8314 prefix = self.parse_path(PathStyle::Mod)?;
8316 if self.eat(&token::ModSep) {
8317 if self.eat(&token::BinOp(token::Star)) {
8320 UseTreeKind::Nested(self.parse_use_tree_list()?)
8323 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8327 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8330 /// Parses a `UseTreeKind::Nested(list)`.
8333 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8335 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8336 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8337 &token::CloseDelim(token::Brace),
8338 SeqSep::trailing_allowed(token::Comma), |this| {
8339 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8343 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8344 if self.eat_keyword(kw::As) {
8345 self.parse_ident_or_underscore().map(Some)
8351 /// Parses a source module as a crate. This is the main entry point for the parser.
8352 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8354 let krate = Ok(ast::Crate {
8355 attrs: self.parse_inner_attributes()?,
8356 module: self.parse_mod_items(&token::Eof, lo)?,
8357 span: lo.to(self.span),
8362 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8363 let ret = match self.token {
8364 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
8365 (symbol, ast::StrStyle::Cooked, suffix),
8366 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
8367 (symbol, ast::StrStyle::Raw(n), suffix),
8374 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8375 match self.parse_optional_str() {
8376 Some((s, style, suf)) => {
8377 let sp = self.prev_span;
8378 self.expect_no_suffix(sp, "a string literal", suf);
8382 let msg = "expected string literal";
8383 let mut err = self.fatal(msg);
8384 err.span_label(self.span, msg);
8390 fn report_invalid_macro_expansion_item(&self) {
8391 self.struct_span_err(
8393 "macros that expand to items must be delimited with braces or followed by a semicolon",
8394 ).multipart_suggestion(
8395 "change the delimiters to curly braces",
8397 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8398 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8400 Applicability::MaybeIncorrect,
8402 self.sess.source_map.next_point(self.prev_span),
8405 Applicability::MaybeIncorrect,
8409 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8410 /// into the generated closure so that they are dropped when the future is polled and not when
8413 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8414 /// this function and the statements created here are inserted at the top of the closure body.
8415 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &mut FnDecl) {
8416 // FIXME(davidtwco): This function should really live in the HIR lowering but because
8417 // the types constructed here need to be used in parts of resolve so that the correct
8418 // locals are considered upvars, it is currently easier for it to live here in the parser,
8419 // where it can be constructed once.
8420 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8421 for (index, input) in decl.inputs.iter_mut().enumerate() {
8422 let id = ast::DUMMY_NODE_ID;
8423 let span = input.pat.span;
8425 // Construct a name for our temporary argument.
8426 let name = format!("__arg{}", index);
8427 let ident = Ident::from_str(&name).gensym();
8429 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
8430 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
8432 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
8433 PatKind::Ident(binding_mode @ BindingMode::ByValue(_), ident, _) => {
8434 // Simple patterns like this don't have a generated argument, but they are
8435 // moved into the closure with a statement, so any `mut` bindings on the
8436 // argument will be unused. This binding mode can't be removed, because
8437 // this would affect the input to procedural macros, but they can have
8438 // their span marked as being the result of a compiler desugaring so
8439 // that they aren't linted against.
8440 input.pat.span = self.sess.source_map().mark_span_with_reason(
8441 CompilerDesugaringKind::Async, span, None);
8443 (binding_mode, ident, true)
8445 _ => (BindingMode::ByValue(Mutability::Mutable), ident, false),
8448 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8449 // async function if it isn't a simple pattern.
8450 let arg = if is_simple_pattern {
8454 ty: input.ty.clone(),
8458 node: PatKind::Ident(
8459 BindingMode::ByValue(Mutability::Immutable), ident, None,
8463 source: ArgSource::AsyncFn(input.pat.clone()),
8467 // Construct a `let __argN = __argN;` statement to insert at the top of the
8468 // async closure. This makes sure that the argument is captured by the closure and
8469 // that the drop order is correct.
8470 let move_local = Local {
8473 node: PatKind::Ident(binding_mode, ident, None),
8476 // We explicitly do not specify the type for this statement. When the user's
8477 // argument type is `impl Trait` then this would require the
8478 // `impl_trait_in_bindings` feature to also be present for that same type to
8479 // be valid in this binding. At the time of writing (13 Mar 19),
8480 // `impl_trait_in_bindings` is not stable.
8484 node: ExprKind::Path(None, ast::Path {
8486 segments: vec![PathSegment { ident, id, args: None }],
8489 attrs: ThinVec::new(),
8493 attrs: ThinVec::new(),
8494 source: LocalSource::AsyncFn,
8497 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8498 // async closure if this isn't a simple pattern.
8499 let pat_stmt = if is_simple_pattern {
8504 node: StmtKind::Local(P(Local {
8505 pat: input.pat.clone(),
8506 ..move_local.clone()
8512 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
8513 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
8519 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8520 for unmatched in unclosed_delims.iter() {
8521 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8522 "incorrect close delimiter: `{}`",
8523 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8525 err.span_label(unmatched.found_span, "incorrect close delimiter");
8526 if let Some(sp) = unmatched.candidate_span {
8527 err.span_label(sp, "close delimiter possibly meant for this");
8529 if let Some(sp) = unmatched.unclosed_span {
8530 err.span_label(sp, "un-closed delimiter");
8534 unclosed_delims.clear();