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(
355 [TokenTree::Token(sp, token::Ident(ast::Ident::with_empty_ctxt(sym::doc), false)),
356 TokenTree::Token(sp, token::Eq),
357 TokenTree::Token(sp, token::Literal(
358 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
360 .iter().cloned().collect::<TokenStream>().into(),
363 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
366 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
367 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
368 .iter().cloned().collect::<TokenStream>().into()
370 [TokenTree::Token(sp, token::Pound), body]
371 .iter().cloned().collect::<TokenStream>().into()
379 #[derive(Clone, PartialEq)]
380 crate enum TokenType {
392 crate fn to_string(&self) -> String {
394 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
395 TokenType::Keyword(kw) => format!("`{}`", kw),
396 TokenType::Operator => "an operator".to_string(),
397 TokenType::Lifetime => "lifetime".to_string(),
398 TokenType::Ident => "identifier".to_string(),
399 TokenType::Path => "path".to_string(),
400 TokenType::Type => "type".to_string(),
401 TokenType::Const => "const".to_string(),
406 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
407 /// `IDENT<<u8 as Trait>::AssocTy>`.
409 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
410 /// that `IDENT` is not the ident of a fn trait.
411 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
412 t == &token::ModSep || t == &token::Lt ||
413 t == &token::BinOp(token::Shl)
416 /// Information about the path to a module.
417 pub struct ModulePath {
420 pub result: Result<ModulePathSuccess, Error>,
423 pub struct ModulePathSuccess {
425 pub directory_ownership: DirectoryOwnership,
430 FileNotFoundForModule {
432 default_path: String,
433 secondary_path: String,
438 default_path: String,
439 secondary_path: String,
442 InclusiveRangeWithNoEnd,
446 fn span_err<S: Into<MultiSpan>>(self,
448 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
450 Error::FileNotFoundForModule { ref mod_name,
454 let mut err = struct_span_err!(handler, sp, E0583,
455 "file not found for module `{}`", mod_name);
456 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
462 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
463 let mut err = struct_span_err!(handler, sp, E0584,
464 "file for module `{}` found at both {} and {}",
468 err.help("delete or rename one of them to remove the ambiguity");
471 Error::UselessDocComment => {
472 let mut err = struct_span_err!(handler, sp, E0585,
473 "found a documentation comment that doesn't document anything");
474 err.help("doc comments must come before what they document, maybe a comment was \
475 intended with `//`?");
478 Error::InclusiveRangeWithNoEnd => {
479 let mut err = struct_span_err!(handler, sp, E0586,
480 "inclusive range with no end");
481 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
491 AttributesParsed(ThinVec<Attribute>),
492 AlreadyParsed(P<Expr>),
495 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
496 fn from(o: Option<ThinVec<Attribute>>) -> Self {
497 if let Some(attrs) = o {
498 LhsExpr::AttributesParsed(attrs)
500 LhsExpr::NotYetParsed
505 impl From<P<Expr>> for LhsExpr {
506 fn from(expr: P<Expr>) -> Self {
507 LhsExpr::AlreadyParsed(expr)
511 /// Creates a placeholder argument.
512 fn dummy_arg(span: Span) -> Arg {
513 let ident = Ident::new(kw::Invalid, span);
515 id: ast::DUMMY_NODE_ID,
516 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
522 id: ast::DUMMY_NODE_ID
524 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal }
527 #[derive(Copy, Clone, Debug)]
528 enum TokenExpectType {
533 impl<'a> Parser<'a> {
534 pub fn new(sess: &'a ParseSess,
536 directory: Option<Directory<'a>>,
537 recurse_into_file_modules: bool,
538 desugar_doc_comments: bool)
540 let mut parser = Parser {
542 token: token::Whitespace,
543 span: syntax_pos::DUMMY_SP,
544 prev_span: syntax_pos::DUMMY_SP,
546 prev_token_kind: PrevTokenKind::Other,
547 restrictions: Restrictions::empty(),
548 recurse_into_file_modules,
549 directory: Directory {
550 path: Cow::from(PathBuf::new()),
551 ownership: DirectoryOwnership::Owned { relative: None }
553 root_module_name: None,
554 expected_tokens: Vec::new(),
555 token_cursor: TokenCursor {
556 frame: TokenCursorFrame::new(
563 desugar_doc_comments,
565 unmatched_angle_bracket_count: 0,
566 max_angle_bracket_count: 0,
567 unclosed_delims: Vec::new(),
568 last_unexpected_token_span: None,
571 let tok = parser.next_tok();
572 parser.token = tok.tok;
573 parser.span = tok.sp;
575 if let Some(directory) = directory {
576 parser.directory = directory;
577 } else if !parser.span.is_dummy() {
578 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
580 parser.directory.path = Cow::from(path);
584 parser.process_potential_macro_variable();
588 fn next_tok(&mut self) -> TokenAndSpan {
589 let mut next = if self.desugar_doc_comments {
590 self.token_cursor.next_desugared()
592 self.token_cursor.next()
594 if next.sp.is_dummy() {
595 // Tweak the location for better diagnostics, but keep syntactic context intact.
596 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
601 /// Converts the current token to a string using `self`'s reader.
602 pub fn this_token_to_string(&self) -> String {
603 pprust::token_to_string(&self.token)
606 fn token_descr(&self) -> Option<&'static str> {
607 Some(match &self.token {
608 t if t.is_special_ident() => "reserved identifier",
609 t if t.is_used_keyword() => "keyword",
610 t if t.is_unused_keyword() => "reserved keyword",
611 token::DocComment(..) => "doc comment",
616 crate fn this_token_descr(&self) -> String {
617 if let Some(prefix) = self.token_descr() {
618 format!("{} `{}`", prefix, self.this_token_to_string())
620 format!("`{}`", self.this_token_to_string())
624 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
625 match self.expect_one_of(&[], &[]) {
627 Ok(_) => unreachable!(),
631 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
632 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
633 if self.expected_tokens.is_empty() {
634 if self.token == *t {
638 let token_str = pprust::token_to_string(t);
639 let this_token_str = self.this_token_descr();
640 let mut err = self.fatal(&format!("expected `{}`, found {}",
644 let sp = if self.token == token::Token::Eof {
645 // EOF, don't want to point at the following char, but rather the last token
648 self.sess.source_map().next_point(self.prev_span)
650 let label_exp = format!("expected `{}`", token_str);
651 match self.recover_closing_delimiter(&[t.clone()], err) {
654 return Ok(recovered);
657 let cm = self.sess.source_map();
658 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
659 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
660 // When the spans are in the same line, it means that the only content
661 // between them is whitespace, point only at the found token.
662 err.span_label(self.span, label_exp);
665 err.span_label(sp, label_exp);
666 err.span_label(self.span, "unexpected token");
672 self.expect_one_of(slice::from_ref(t), &[])
676 /// Expect next token to be edible or inedible token. If edible,
677 /// then consume it; if inedible, then return without consuming
678 /// anything. Signal a fatal error if next token is unexpected.
679 pub fn expect_one_of(
681 edible: &[token::Token],
682 inedible: &[token::Token],
683 ) -> PResult<'a, bool /* recovered */> {
684 fn tokens_to_string(tokens: &[TokenType]) -> String {
685 let mut i = tokens.iter();
686 // This might be a sign we need a connect method on Iterator.
688 .map_or(String::new(), |t| t.to_string());
689 i.enumerate().fold(b, |mut b, (i, a)| {
690 if tokens.len() > 2 && i == tokens.len() - 2 {
692 } else if tokens.len() == 2 && i == tokens.len() - 2 {
697 b.push_str(&a.to_string());
701 if edible.contains(&self.token) {
704 } else if inedible.contains(&self.token) {
705 // leave it in the input
707 } else if self.last_unexpected_token_span == Some(self.span) {
710 let mut expected = edible.iter()
711 .map(|x| TokenType::Token(x.clone()))
712 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
713 .chain(self.expected_tokens.iter().cloned())
714 .collect::<Vec<_>>();
715 expected.sort_by_cached_key(|x| x.to_string());
717 let expect = tokens_to_string(&expected[..]);
718 let actual = self.this_token_to_string();
719 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
720 let short_expect = if expected.len() > 6 {
721 format!("{} possible tokens", expected.len())
725 (format!("expected one of {}, found `{}`", expect, actual),
726 (self.sess.source_map().next_point(self.prev_span),
727 format!("expected one of {} here", short_expect)))
728 } else if expected.is_empty() {
729 (format!("unexpected token: `{}`", actual),
730 (self.prev_span, "unexpected token after this".to_string()))
732 (format!("expected {}, found `{}`", expect, actual),
733 (self.sess.source_map().next_point(self.prev_span),
734 format!("expected {} here", expect)))
736 self.last_unexpected_token_span = Some(self.span);
737 let mut err = self.fatal(&msg_exp);
738 if self.token.is_ident_named("and") {
739 err.span_suggestion_short(
741 "use `&&` instead of `and` for the boolean operator",
743 Applicability::MaybeIncorrect,
746 if self.token.is_ident_named("or") {
747 err.span_suggestion_short(
749 "use `||` instead of `or` for the boolean operator",
751 Applicability::MaybeIncorrect,
754 let sp = if self.token == token::Token::Eof {
755 // This is EOF, don't want to point at the following char, but rather the last token
760 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
761 TokenType::Token(t) => Some(t.clone()),
763 }).collect::<Vec<_>>(), err) {
766 return Ok(recovered);
770 let is_semi_suggestable = expected.iter().any(|t| match t {
771 TokenType::Token(token::Semi) => true, // we expect a `;` here
773 }) && ( // a `;` would be expected before the current keyword
774 self.token.is_keyword(kw::Break) ||
775 self.token.is_keyword(kw::Continue) ||
776 self.token.is_keyword(kw::For) ||
777 self.token.is_keyword(kw::If) ||
778 self.token.is_keyword(kw::Let) ||
779 self.token.is_keyword(kw::Loop) ||
780 self.token.is_keyword(kw::Match) ||
781 self.token.is_keyword(kw::Return) ||
782 self.token.is_keyword(kw::While)
784 let cm = self.sess.source_map();
785 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
786 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
787 // The spans are in different lines, expected `;` and found `let` or `return`.
788 // High likelihood that it is only a missing `;`.
789 err.span_suggestion_short(
791 "a semicolon may be missing here",
793 Applicability::MaybeIncorrect,
798 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
799 // When the spans are in the same line, it means that the only content between
800 // them is whitespace, point at the found token in that case:
802 // X | () => { syntax error };
803 // | ^^^^^ expected one of 8 possible tokens here
805 // instead of having:
807 // X | () => { syntax error };
808 // | -^^^^^ unexpected token
810 // | expected one of 8 possible tokens here
811 err.span_label(self.span, label_exp);
813 _ if self.prev_span == syntax_pos::DUMMY_SP => {
814 // Account for macro context where the previous span might not be
815 // available to avoid incorrect output (#54841).
816 err.span_label(self.span, "unexpected token");
819 err.span_label(sp, label_exp);
820 err.span_label(self.span, "unexpected token");
827 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
828 fn interpolated_or_expr_span(&self,
829 expr: PResult<'a, P<Expr>>)
830 -> PResult<'a, (Span, P<Expr>)> {
832 if self.prev_token_kind == PrevTokenKind::Interpolated {
840 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
841 let mut err = self.struct_span_err(self.span,
842 &format!("expected identifier, found {}",
843 self.this_token_descr()));
844 if let token::Ident(ident, false) = &self.token {
845 if ident.is_raw_guess() {
848 "you can escape reserved keywords to use them as identifiers",
849 format!("r#{}", ident),
850 Applicability::MaybeIncorrect,
854 if let Some(token_descr) = self.token_descr() {
855 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
857 err.span_label(self.span, "expected identifier");
858 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
863 Applicability::MachineApplicable,
870 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
871 self.parse_ident_common(true)
874 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
876 token::Ident(ident, _) => {
877 if self.token.is_reserved_ident() {
878 let mut err = self.expected_ident_found();
885 let span = self.span;
887 Ok(Ident::new(ident.name, span))
890 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
891 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
893 self.expected_ident_found()
899 /// Checks if the next token is `tok`, and returns `true` if so.
901 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
903 crate fn check(&mut self, tok: &token::Token) -> bool {
904 let is_present = self.token == *tok;
905 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
909 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
910 pub fn eat(&mut self, tok: &token::Token) -> bool {
911 let is_present = self.check(tok);
912 if is_present { self.bump() }
916 fn check_keyword(&mut self, kw: Symbol) -> bool {
917 self.expected_tokens.push(TokenType::Keyword(kw));
918 self.token.is_keyword(kw)
921 /// If the next token is the given keyword, eats it and returns
922 /// `true`. Otherwise, returns `false`.
923 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
924 if self.check_keyword(kw) {
932 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
933 if self.token.is_keyword(kw) {
941 /// If the given word is not a keyword, signals an error.
942 /// If the next token is not the given word, signals an error.
943 /// Otherwise, eats it.
944 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
945 if !self.eat_keyword(kw) {
952 fn check_ident(&mut self) -> bool {
953 if self.token.is_ident() {
956 self.expected_tokens.push(TokenType::Ident);
961 fn check_path(&mut self) -> bool {
962 if self.token.is_path_start() {
965 self.expected_tokens.push(TokenType::Path);
970 fn check_type(&mut self) -> bool {
971 if self.token.can_begin_type() {
974 self.expected_tokens.push(TokenType::Type);
979 fn check_const_arg(&mut self) -> bool {
980 if self.token.can_begin_const_arg() {
983 self.expected_tokens.push(TokenType::Const);
988 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
989 /// and continues. If a `+` is not seen, returns `false`.
991 /// This is used when token-splitting `+=` into `+`.
992 /// See issue #47856 for an example of when this may occur.
993 fn eat_plus(&mut self) -> bool {
994 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
996 token::BinOp(token::Plus) => {
1000 token::BinOpEq(token::Plus) => {
1001 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1002 self.bump_with(token::Eq, span);
1010 /// Checks to see if the next token is either `+` or `+=`.
1011 /// Otherwise returns `false`.
1012 fn check_plus(&mut self) -> bool {
1013 if self.token.is_like_plus() {
1017 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1022 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1023 /// `&` and continues. If an `&` is not seen, signals an error.
1024 fn expect_and(&mut self) -> PResult<'a, ()> {
1025 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1027 token::BinOp(token::And) => {
1032 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1033 Ok(self.bump_with(token::BinOp(token::And), span))
1035 _ => self.unexpected()
1039 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1040 /// `|` and continues. If an `|` is not seen, signals an error.
1041 fn expect_or(&mut self) -> PResult<'a, ()> {
1042 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1044 token::BinOp(token::Or) => {
1049 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1050 Ok(self.bump_with(token::BinOp(token::Or), span))
1052 _ => self.unexpected()
1056 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1057 literal::expect_no_suffix(sp, &self.sess.span_diagnostic, kind, suffix)
1060 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1061 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1062 /// and continue. If a `<` is not seen, returns false.
1064 /// This is meant to be used when parsing generics on a path to get the
1066 fn eat_lt(&mut self) -> bool {
1067 self.expected_tokens.push(TokenType::Token(token::Lt));
1068 let ate = match self.token {
1073 token::BinOp(token::Shl) => {
1074 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1075 self.bump_with(token::Lt, span);
1079 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1080 self.bump_with(token::BinOp(token::Minus), span);
1087 // See doc comment for `unmatched_angle_bracket_count`.
1088 self.unmatched_angle_bracket_count += 1;
1089 self.max_angle_bracket_count += 1;
1090 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1096 fn expect_lt(&mut self) -> PResult<'a, ()> {
1104 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1105 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1106 fn expect_gt(&mut self) -> PResult<'a, ()> {
1107 self.expected_tokens.push(TokenType::Token(token::Gt));
1108 let ate = match self.token {
1113 token::BinOp(token::Shr) => {
1114 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1115 Some(self.bump_with(token::Gt, span))
1117 token::BinOpEq(token::Shr) => {
1118 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1119 Some(self.bump_with(token::Ge, span))
1122 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1123 Some(self.bump_with(token::Eq, span))
1130 // See doc comment for `unmatched_angle_bracket_count`.
1131 if self.unmatched_angle_bracket_count > 0 {
1132 self.unmatched_angle_bracket_count -= 1;
1133 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1138 None => self.unexpected(),
1142 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1143 /// passes through any errors encountered. Used for error recovery.
1144 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1145 let handler = self.diagnostic();
1147 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1149 TokenExpectType::Expect,
1150 |p| Ok(p.parse_token_tree())) {
1151 handler.cancel(err);
1155 /// Parses a sequence, including the closing delimiter. The function
1156 /// `f` must consume tokens until reaching the next separator or
1157 /// closing bracket.
1158 pub fn parse_seq_to_end<T, F>(&mut self,
1162 -> PResult<'a, Vec<T>> where
1163 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1165 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1172 /// Parses a sequence, not including the closing delimiter. The function
1173 /// `f` must consume tokens until reaching the next separator or
1174 /// closing bracket.
1175 pub fn parse_seq_to_before_end<T, F>(
1180 ) -> PResult<'a, (Vec<T>, bool)>
1181 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1183 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1186 fn parse_seq_to_before_tokens<T, F>(
1188 kets: &[&token::Token],
1190 expect: TokenExpectType,
1192 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1193 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1195 let mut first = true;
1196 let mut recovered = false;
1198 while !kets.iter().any(|k| {
1200 TokenExpectType::Expect => self.check(k),
1201 TokenExpectType::NoExpect => self.token == **k,
1205 token::CloseDelim(..) | token::Eof => break,
1208 if let Some(ref t) = sep.sep {
1212 match self.expect(t) {
1219 // Attempt to keep parsing if it was a similar separator
1220 if let Some(ref tokens) = t.similar_tokens() {
1221 if tokens.contains(&self.token) {
1226 // Attempt to keep parsing if it was an omitted separator
1241 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1243 TokenExpectType::Expect => self.check(k),
1244 TokenExpectType::NoExpect => self.token == **k,
1257 /// Parses a sequence, including the closing delimiter. The function
1258 /// `f` must consume tokens until reaching the next separator or
1259 /// closing bracket.
1260 fn parse_unspanned_seq<T, F>(
1266 ) -> PResult<'a, Vec<T>> where
1267 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1270 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1277 /// Advance the parser by one token
1278 pub fn bump(&mut self) {
1279 if self.prev_token_kind == PrevTokenKind::Eof {
1280 // Bumping after EOF is a bad sign, usually an infinite loop.
1281 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1284 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1286 // Record last token kind for possible error recovery.
1287 self.prev_token_kind = match self.token {
1288 token::DocComment(..) => PrevTokenKind::DocComment,
1289 token::Comma => PrevTokenKind::Comma,
1290 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1291 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1292 token::Interpolated(..) => PrevTokenKind::Interpolated,
1293 token::Eof => PrevTokenKind::Eof,
1294 token::Ident(..) => PrevTokenKind::Ident,
1295 _ => PrevTokenKind::Other,
1298 let next = self.next_tok();
1299 self.span = next.sp;
1300 self.token = next.tok;
1301 self.expected_tokens.clear();
1302 // check after each token
1303 self.process_potential_macro_variable();
1306 /// Advance the parser using provided token as a next one. Use this when
1307 /// consuming a part of a token. For example a single `<` from `<<`.
1308 fn bump_with(&mut self, next: token::Token, span: Span) {
1309 self.prev_span = self.span.with_hi(span.lo());
1310 // It would be incorrect to record the kind of the current token, but
1311 // fortunately for tokens currently using `bump_with`, the
1312 // prev_token_kind will be of no use anyway.
1313 self.prev_token_kind = PrevTokenKind::Other;
1316 self.expected_tokens.clear();
1319 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1320 F: FnOnce(&token::Token) -> R,
1323 return f(&self.token)
1326 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1327 Some(tree) => match tree {
1328 TokenTree::Token(_, tok) => tok,
1329 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1331 None => token::CloseDelim(self.token_cursor.frame.delim),
1335 crate fn look_ahead_span(&self, dist: usize) -> Span {
1340 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1341 Some(TokenTree::Token(span, _)) => span,
1342 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1343 None => self.look_ahead_span(dist - 1),
1346 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1347 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1349 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1350 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1352 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1353 err.span_err(sp, self.diagnostic())
1355 fn bug(&self, m: &str) -> ! {
1356 self.sess.span_diagnostic.span_bug(self.span, m)
1358 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1359 self.sess.span_diagnostic.span_err(sp, m)
1361 crate fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1362 self.sess.span_diagnostic.struct_span_err(sp, m)
1364 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1365 self.sess.span_diagnostic.span_bug(sp, m)
1368 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1369 self.sess.span_diagnostic.cancel(err)
1372 crate fn diagnostic(&self) -> &'a errors::Handler {
1373 &self.sess.span_diagnostic
1376 /// Is the current token one of the keywords that signals a bare function type?
1377 fn token_is_bare_fn_keyword(&mut self) -> bool {
1378 self.check_keyword(kw::Fn) ||
1379 self.check_keyword(kw::Unsafe) ||
1380 self.check_keyword(kw::Extern)
1383 /// Parses a `TyKind::BareFn` type.
1384 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1387 [unsafe] [extern "ABI"] fn (S) -> T
1397 let unsafety = self.parse_unsafety();
1398 let abi = if self.eat_keyword(kw::Extern) {
1399 self.parse_opt_abi()?.unwrap_or(Abi::C)
1404 self.expect_keyword(kw::Fn)?;
1405 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1406 let ret_ty = self.parse_ret_ty(false)?;
1407 let decl = P(FnDecl {
1412 Ok(TyKind::BareFn(P(BareFnTy {
1420 /// Parses asyncness: `async` or nothing.
1421 fn parse_asyncness(&mut self) -> IsAsync {
1422 if self.eat_keyword(kw::Async) {
1424 closure_id: ast::DUMMY_NODE_ID,
1425 return_impl_trait_id: ast::DUMMY_NODE_ID,
1426 arguments: Vec::new(),
1433 /// Parses unsafety: `unsafe` or nothing.
1434 fn parse_unsafety(&mut self) -> Unsafety {
1435 if self.eat_keyword(kw::Unsafe) {
1442 /// Parses the items in a trait declaration.
1443 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1444 maybe_whole!(self, NtTraitItem, |x| x);
1445 let attrs = self.parse_outer_attributes()?;
1446 let mut unclosed_delims = vec![];
1447 let (mut item, tokens) = self.collect_tokens(|this| {
1448 let item = this.parse_trait_item_(at_end, attrs);
1449 unclosed_delims.append(&mut this.unclosed_delims);
1452 self.unclosed_delims.append(&mut unclosed_delims);
1453 // See `parse_item` for why this clause is here.
1454 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1455 item.tokens = Some(tokens);
1460 fn parse_trait_item_(&mut self,
1462 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1465 let (name, node, generics) = if self.eat_keyword(kw::Type) {
1466 self.parse_trait_item_assoc_ty()?
1467 } else if self.is_const_item() {
1468 self.expect_keyword(kw::Const)?;
1469 let ident = self.parse_ident()?;
1470 self.expect(&token::Colon)?;
1471 let ty = self.parse_ty()?;
1472 let default = if self.eat(&token::Eq) {
1473 let expr = self.parse_expr()?;
1474 self.expect(&token::Semi)?;
1477 self.expect(&token::Semi)?;
1480 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1481 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1482 // trait item macro.
1483 (Ident::invalid(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1485 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
1487 let ident = self.parse_ident()?;
1488 let mut generics = self.parse_generics()?;
1490 let mut decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1491 // This is somewhat dubious; We don't want to allow
1492 // argument names to be left off if there is a
1495 // We don't allow argument names to be left off in edition 2018.
1496 p.parse_arg_general(p.span.rust_2018(), true, false)
1498 generics.where_clause = self.parse_where_clause()?;
1499 self.construct_async_arguments(&mut asyncness, &mut decl);
1501 let sig = ast::MethodSig {
1511 let body = match self.token {
1515 debug!("parse_trait_methods(): parsing required method");
1518 token::OpenDelim(token::Brace) => {
1519 debug!("parse_trait_methods(): parsing provided method");
1521 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1522 attrs.extend(inner_attrs.iter().cloned());
1525 token::Interpolated(ref nt) => {
1527 token::NtBlock(..) => {
1529 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1530 attrs.extend(inner_attrs.iter().cloned());
1534 let token_str = self.this_token_descr();
1535 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1537 err.span_label(self.span, "expected `;` or `{`");
1543 let token_str = self.this_token_descr();
1544 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1546 err.span_label(self.span, "expected `;` or `{`");
1550 (ident, ast::TraitItemKind::Method(sig, body), generics)
1554 id: ast::DUMMY_NODE_ID,
1559 span: lo.to(self.prev_span),
1564 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1565 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1566 if self.eat(&token::RArrow) {
1567 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1569 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1574 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1575 self.parse_ty_common(true, true, false)
1578 /// Parses a type in restricted contexts where `+` is not permitted.
1580 /// Example 1: `&'a TYPE`
1581 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1582 /// Example 2: `value1 as TYPE + value2`
1583 /// `+` is prohibited to avoid interactions with expression grammar.
1584 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1585 self.parse_ty_common(false, true, false)
1588 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1589 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1590 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1591 maybe_whole!(self, NtTy, |x| x);
1594 let mut impl_dyn_multi = false;
1595 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1596 // `(TYPE)` is a parenthesized type.
1597 // `(TYPE,)` is a tuple with a single field of type TYPE.
1598 let mut ts = vec![];
1599 let mut last_comma = false;
1600 while self.token != token::CloseDelim(token::Paren) {
1601 ts.push(self.parse_ty()?);
1602 if self.eat(&token::Comma) {
1609 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1610 self.expect(&token::CloseDelim(token::Paren))?;
1612 if ts.len() == 1 && !last_comma {
1613 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1614 let maybe_bounds = allow_plus && self.token.is_like_plus();
1616 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1617 TyKind::Path(None, ref path) if maybe_bounds => {
1618 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1620 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1621 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1622 let path = match bounds[0] {
1623 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1624 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1626 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1629 _ => TyKind::Paren(P(ty))
1634 } else if self.eat(&token::Not) {
1637 } else if self.eat(&token::BinOp(token::Star)) {
1639 TyKind::Ptr(self.parse_ptr()?)
1640 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1642 let t = self.parse_ty()?;
1643 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1644 let t = match self.maybe_parse_fixed_length_of_vec()? {
1645 None => TyKind::Slice(t),
1646 Some(length) => TyKind::Array(t, AnonConst {
1647 id: ast::DUMMY_NODE_ID,
1651 self.expect(&token::CloseDelim(token::Bracket))?;
1653 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1656 self.parse_borrowed_pointee()?
1657 } else if self.eat_keyword_noexpect(kw::Typeof) {
1659 // In order to not be ambiguous, the type must be surrounded by parens.
1660 self.expect(&token::OpenDelim(token::Paren))?;
1662 id: ast::DUMMY_NODE_ID,
1663 value: self.parse_expr()?,
1665 self.expect(&token::CloseDelim(token::Paren))?;
1667 } else if self.eat_keyword(kw::Underscore) {
1668 // A type to be inferred `_`
1670 } else if self.token_is_bare_fn_keyword() {
1671 // Function pointer type
1672 self.parse_ty_bare_fn(Vec::new())?
1673 } else if self.check_keyword(kw::For) {
1674 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1675 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1676 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1678 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1679 if self.token_is_bare_fn_keyword() {
1680 self.parse_ty_bare_fn(lifetime_defs)?
1682 let path = self.parse_path(PathStyle::Type)?;
1683 let parse_plus = allow_plus && self.check_plus();
1684 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1686 } else if self.eat_keyword(kw::Impl) {
1687 // Always parse bounds greedily for better error recovery.
1688 let bounds = self.parse_generic_bounds(None)?;
1689 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1690 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1691 } else if self.check_keyword(kw::Dyn) &&
1692 (self.span.rust_2018() ||
1693 self.look_ahead(1, |t| t.can_begin_bound() &&
1694 !can_continue_type_after_non_fn_ident(t))) {
1695 self.bump(); // `dyn`
1696 // Always parse bounds greedily for better error recovery.
1697 let bounds = self.parse_generic_bounds(None)?;
1698 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1699 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1700 } else if self.check(&token::Question) ||
1701 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1702 // Bound list (trait object type)
1703 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1704 TraitObjectSyntax::None)
1705 } else if self.eat_lt() {
1707 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1708 TyKind::Path(Some(qself), path)
1709 } else if self.token.is_path_start() {
1711 let path = self.parse_path(PathStyle::Type)?;
1712 if self.eat(&token::Not) {
1713 // Macro invocation in type position
1714 let (delim, tts) = self.expect_delimited_token_tree()?;
1715 let node = Mac_ { path, tts, delim };
1716 TyKind::Mac(respan(lo.to(self.prev_span), node))
1718 // Just a type path or bound list (trait object type) starting with a trait.
1720 // `Trait1 + Trait2 + 'a`
1721 if allow_plus && self.check_plus() {
1722 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1724 TyKind::Path(None, path)
1727 } else if self.check(&token::DotDotDot) {
1728 if allow_c_variadic {
1729 self.eat(&token::DotDotDot);
1732 return Err(self.fatal(
1733 "only foreign functions are allowed to be C-variadic"
1737 let msg = format!("expected type, found {}", self.this_token_descr());
1738 return Err(self.fatal(&msg));
1741 let span = lo.to(self.prev_span);
1742 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1744 // Try to recover from use of `+` with incorrect priority.
1745 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1746 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1747 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1750 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1751 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1752 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1753 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1755 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1756 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1758 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1761 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1762 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1763 let mutbl = self.parse_mutability();
1764 let ty = self.parse_ty_no_plus()?;
1765 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1768 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1769 let mutbl = if self.eat_keyword(kw::Mut) {
1771 } else if self.eat_keyword(kw::Const) {
1772 Mutability::Immutable
1774 let span = self.prev_span;
1775 let msg = "expected mut or const in raw pointer type";
1776 self.struct_span_err(span, msg)
1777 .span_label(span, msg)
1778 .help("use `*mut T` or `*const T` as appropriate")
1780 Mutability::Immutable
1782 let t = self.parse_ty_no_plus()?;
1783 Ok(MutTy { ty: t, mutbl: mutbl })
1786 fn is_named_argument(&self) -> bool {
1787 let offset = match self.token {
1788 token::Interpolated(ref nt) => match **nt {
1789 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1792 token::BinOp(token::And) | token::AndAnd => 1,
1793 _ if self.token.is_keyword(kw::Mut) => 1,
1797 self.look_ahead(offset, |t| t.is_ident()) &&
1798 self.look_ahead(offset + 1, |t| t == &token::Colon)
1801 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1803 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1804 if let token::DocComment(_) = self.token {
1805 let mut err = self.diagnostic().struct_span_err(
1807 &format!("documentation comments cannot be applied to {}", applied_to),
1809 err.span_label(self.span, "doc comments are not allowed here");
1812 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1813 *t == token::OpenDelim(token::Bracket)
1816 // Skip every token until next possible arg.
1817 while self.token != token::CloseDelim(token::Bracket) {
1820 let sp = lo.to(self.span);
1822 let mut err = self.diagnostic().struct_span_err(
1824 &format!("attributes cannot be applied to {}", applied_to),
1826 err.span_label(sp, "attributes are not allowed here");
1831 /// This version of parse arg doesn't necessarily require identifier names.
1832 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
1833 allow_c_variadic: bool) -> PResult<'a, Arg> {
1834 if let Ok(Some(_)) = self.parse_self_arg() {
1835 let mut err = self.struct_span_err(self.prev_span,
1836 "unexpected `self` argument in function");
1837 err.span_label(self.prev_span,
1838 "`self` is only valid as the first argument of an associated function");
1842 let (pat, ty) = if require_name || self.is_named_argument() {
1843 debug!("parse_arg_general parse_pat (require_name:{})",
1845 self.eat_incorrect_doc_comment("method arguments");
1846 let pat = self.parse_pat(Some("argument name"))?;
1848 if let Err(mut err) = self.expect(&token::Colon) {
1849 // If we find a pattern followed by an identifier, it could be an (incorrect)
1850 // C-style parameter declaration.
1851 if self.check_ident() && self.look_ahead(1, |t| {
1852 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1854 let ident = self.parse_ident().unwrap();
1855 let span = pat.span.with_hi(ident.span.hi());
1857 err.span_suggestion(
1859 "declare the type after the parameter binding",
1860 String::from("<identifier>: <type>"),
1861 Applicability::HasPlaceholders,
1863 } else if require_name && is_trait_item {
1864 if let PatKind::Ident(_, ident, _) = pat.node {
1865 err.span_suggestion(
1867 "explicitly ignore parameter",
1868 format!("_: {}", ident),
1869 Applicability::MachineApplicable,
1873 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1879 self.eat_incorrect_doc_comment("a method argument's type");
1880 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1882 debug!("parse_arg_general ident_to_pat");
1883 let parser_snapshot_before_ty = self.clone();
1884 self.eat_incorrect_doc_comment("a method argument's type");
1885 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1886 if ty.is_ok() && self.token != token::Comma &&
1887 self.token != token::CloseDelim(token::Paren) {
1888 // This wasn't actually a type, but a pattern looking like a type,
1889 // so we are going to rollback and re-parse for recovery.
1890 ty = self.unexpected();
1894 let ident = Ident::new(kw::Invalid, self.prev_span);
1896 id: ast::DUMMY_NODE_ID,
1897 node: PatKind::Ident(
1898 BindingMode::ByValue(Mutability::Immutable), ident, None),
1904 // If this is a C-variadic argument and we hit an error, return the
1906 if self.token == token::DotDotDot {
1909 // Recover from attempting to parse the argument as a type without pattern.
1911 mem::replace(self, parser_snapshot_before_ty);
1912 let pat = self.parse_pat(Some("argument name"))?;
1913 self.expect(&token::Colon)?;
1914 let ty = self.parse_ty()?;
1916 let mut err = self.diagnostic().struct_span_err_with_code(
1918 "patterns aren't allowed in methods without bodies",
1919 DiagnosticId::Error("E0642".into()),
1921 err.span_suggestion_short(
1923 "give this argument a name or use an underscore to ignore it",
1925 Applicability::MachineApplicable,
1929 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1931 node: PatKind::Wild,
1933 id: ast::DUMMY_NODE_ID
1940 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
1943 /// Parses a single function argument.
1944 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1945 self.parse_arg_general(true, false, false)
1948 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
1949 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1950 let pat = self.parse_pat(Some("argument name"))?;
1951 let t = if self.eat(&token::Colon) {
1955 id: ast::DUMMY_NODE_ID,
1956 node: TyKind::Infer,
1957 span: self.prev_span,
1963 id: ast::DUMMY_NODE_ID,
1964 source: ast::ArgSource::Normal,
1968 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1969 if self.eat(&token::Semi) {
1970 Ok(Some(self.parse_expr()?))
1976 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1977 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1978 maybe_whole_expr!(self);
1980 let minus_lo = self.span;
1981 let minus_present = self.eat(&token::BinOp(token::Minus));
1983 let literal = self.parse_lit()?;
1984 let hi = self.prev_span;
1985 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1988 let minus_hi = self.prev_span;
1989 let unary = self.mk_unary(UnOp::Neg, expr);
1990 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1996 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1998 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1999 let span = self.span;
2001 Ok(Ident::new(ident.name, span))
2003 _ => self.parse_ident(),
2007 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2009 token::Ident(ident, false) if ident.name == kw::Underscore => {
2010 let span = self.span;
2012 Ok(Ident::new(ident.name, span))
2014 _ => self.parse_ident(),
2018 /// Parses a qualified path.
2019 /// Assumes that the leading `<` has been parsed already.
2021 /// `qualified_path = <type [as trait_ref]>::path`
2026 /// `<T as U>::F::a<S>` (without disambiguator)
2027 /// `<T as U>::F::a::<S>` (with disambiguator)
2028 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2029 let lo = self.prev_span;
2030 let ty = self.parse_ty()?;
2032 // `path` will contain the prefix of the path up to the `>`,
2033 // if any (e.g., `U` in the `<T as U>::*` examples
2034 // above). `path_span` has the span of that path, or an empty
2035 // span in the case of something like `<T>::Bar`.
2036 let (mut path, path_span);
2037 if self.eat_keyword(kw::As) {
2038 let path_lo = self.span;
2039 path = self.parse_path(PathStyle::Type)?;
2040 path_span = path_lo.to(self.prev_span);
2042 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2043 path_span = self.span.to(self.span);
2046 // See doc comment for `unmatched_angle_bracket_count`.
2047 self.expect(&token::Gt)?;
2048 if self.unmatched_angle_bracket_count > 0 {
2049 self.unmatched_angle_bracket_count -= 1;
2050 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2053 self.expect(&token::ModSep)?;
2055 let qself = QSelf { ty, path_span, position: path.segments.len() };
2056 self.parse_path_segments(&mut path.segments, style)?;
2058 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2061 /// Parses simple paths.
2063 /// `path = [::] segment+`
2064 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2067 /// `a::b::C<D>` (without disambiguator)
2068 /// `a::b::C::<D>` (with disambiguator)
2069 /// `Fn(Args)` (without disambiguator)
2070 /// `Fn::(Args)` (with disambiguator)
2071 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2072 maybe_whole!(self, NtPath, |path| {
2073 if style == PathStyle::Mod &&
2074 path.segments.iter().any(|segment| segment.args.is_some()) {
2075 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2080 let lo = self.meta_var_span.unwrap_or(self.span);
2081 let mut segments = Vec::new();
2082 let mod_sep_ctxt = self.span.ctxt();
2083 if self.eat(&token::ModSep) {
2084 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2086 self.parse_path_segments(&mut segments, style)?;
2088 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2091 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2092 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2094 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2095 let meta_ident = match self.token {
2096 token::Interpolated(ref nt) => match **nt {
2097 token::NtMeta(ref meta) => match meta.node {
2098 ast::MetaItemKind::Word => Some(meta.path.clone()),
2105 if let Some(path) = meta_ident {
2109 self.parse_path(style)
2112 crate fn parse_path_segments(&mut self,
2113 segments: &mut Vec<PathSegment>,
2115 -> PResult<'a, ()> {
2117 let segment = self.parse_path_segment(style)?;
2118 if style == PathStyle::Expr {
2119 // In order to check for trailing angle brackets, we must have finished
2120 // recursing (`parse_path_segment` can indirectly call this function),
2121 // that is, the next token must be the highlighted part of the below example:
2123 // `Foo::<Bar as Baz<T>>::Qux`
2126 // As opposed to the below highlight (if we had only finished the first
2129 // `Foo::<Bar as Baz<T>>::Qux`
2132 // `PathStyle::Expr` is only provided at the root invocation and never in
2133 // `parse_path_segment` to recurse and therefore can be checked to maintain
2135 self.check_trailing_angle_brackets(&segment, token::ModSep);
2137 segments.push(segment);
2139 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2145 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2146 let ident = self.parse_path_segment_ident()?;
2148 let is_args_start = |token: &token::Token| match *token {
2149 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
2150 | token::LArrow => true,
2153 let check_args_start = |this: &mut Self| {
2154 this.expected_tokens.extend_from_slice(
2155 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2157 is_args_start(&this.token)
2160 Ok(if style == PathStyle::Type && check_args_start(self) ||
2161 style != PathStyle::Mod && self.check(&token::ModSep)
2162 && self.look_ahead(1, |t| is_args_start(t)) {
2163 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2164 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2165 // parsing a new path.
2166 if style == PathStyle::Expr {
2167 self.unmatched_angle_bracket_count = 0;
2168 self.max_angle_bracket_count = 0;
2171 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2172 self.eat(&token::ModSep);
2174 let args = if self.eat_lt() {
2176 let (args, bindings) =
2177 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2179 let span = lo.to(self.prev_span);
2180 AngleBracketedArgs { args, bindings, span }.into()
2184 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2185 &[&token::CloseDelim(token::Paren)],
2186 SeqSep::trailing_allowed(token::Comma),
2187 TokenExpectType::Expect,
2192 let span = lo.to(self.prev_span);
2193 let output = if self.eat(&token::RArrow) {
2194 Some(self.parse_ty_common(false, false, false)?)
2198 ParenthesizedArgs { inputs, output, span }.into()
2201 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2203 // Generic arguments are not found.
2204 PathSegment::from_ident(ident)
2208 crate fn check_lifetime(&mut self) -> bool {
2209 self.expected_tokens.push(TokenType::Lifetime);
2210 self.token.is_lifetime()
2213 /// Parses a single lifetime `'a` or panics.
2214 crate fn expect_lifetime(&mut self) -> Lifetime {
2215 if let Some(ident) = self.token.lifetime() {
2216 let span = self.span;
2218 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2220 self.span_bug(self.span, "not a lifetime")
2224 fn eat_label(&mut self) -> Option<Label> {
2225 if let Some(ident) = self.token.lifetime() {
2226 let span = self.span;
2228 Some(Label { ident: Ident::new(ident.name, span) })
2234 /// Parses mutability (`mut` or nothing).
2235 fn parse_mutability(&mut self) -> Mutability {
2236 if self.eat_keyword(kw::Mut) {
2239 Mutability::Immutable
2243 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2244 if let token::Literal(token::Integer(name), suffix) = self.token {
2245 self.expect_no_suffix(self.span, "a tuple index", suffix);
2247 Ok(Ident::new(name, self.prev_span))
2249 self.parse_ident_common(false)
2253 /// Parse ident (COLON expr)?
2254 fn parse_field(&mut self) -> PResult<'a, Field> {
2255 let attrs = self.parse_outer_attributes()?;
2258 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2259 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2260 t == &token::Colon || t == &token::Eq
2262 let fieldname = self.parse_field_name()?;
2264 // Check for an equals token. This means the source incorrectly attempts to
2265 // initialize a field with an eq rather than a colon.
2266 if self.token == token::Eq {
2268 .struct_span_err(self.span, "expected `:`, found `=`")
2270 fieldname.span.shrink_to_hi().to(self.span),
2271 "replace equals symbol with a colon",
2273 Applicability::MachineApplicable,
2278 (fieldname, self.parse_expr()?, false)
2280 let fieldname = self.parse_ident_common(false)?;
2282 // Mimic `x: x` for the `x` field shorthand.
2283 let path = ast::Path::from_ident(fieldname);
2284 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2285 (fieldname, expr, true)
2289 span: lo.to(expr.span),
2292 attrs: attrs.into(),
2296 crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2297 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2300 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2301 ExprKind::Unary(unop, expr)
2304 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2305 ExprKind::Binary(binop, lhs, rhs)
2308 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2309 ExprKind::Call(f, args)
2312 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2313 ExprKind::Index(expr, idx)
2317 start: Option<P<Expr>>,
2318 end: Option<P<Expr>>,
2319 limits: RangeLimits)
2320 -> PResult<'a, ast::ExprKind> {
2321 if end.is_none() && limits == RangeLimits::Closed {
2322 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2324 Ok(ExprKind::Range(start, end, limits))
2328 fn mk_assign_op(&self, binop: ast::BinOp,
2329 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2330 ExprKind::AssignOp(binop, lhs, rhs)
2333 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2334 let delim = match self.token {
2335 token::OpenDelim(delim) => delim,
2337 let msg = "expected open delimiter";
2338 let mut err = self.fatal(msg);
2339 err.span_label(self.span, msg);
2343 let tts = match self.parse_token_tree() {
2344 TokenTree::Delimited(_, _, tts) => tts,
2345 _ => unreachable!(),
2347 let delim = match delim {
2348 token::Paren => MacDelimiter::Parenthesis,
2349 token::Bracket => MacDelimiter::Bracket,
2350 token::Brace => MacDelimiter::Brace,
2351 token::NoDelim => self.bug("unexpected no delimiter"),
2353 Ok((delim, tts.into()))
2356 /// At the bottom (top?) of the precedence hierarchy,
2357 /// Parses things like parenthesized exprs, macros, `return`, etc.
2359 /// N.B., this does not parse outer attributes, and is private because it only works
2360 /// correctly if called from `parse_dot_or_call_expr()`.
2361 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2362 maybe_recover_from_interpolated_ty_qpath!(self, true);
2363 maybe_whole_expr!(self);
2365 // Outer attributes are already parsed and will be
2366 // added to the return value after the fact.
2368 // Therefore, prevent sub-parser from parsing
2369 // attributes by giving them a empty "already parsed" list.
2370 let mut attrs = ThinVec::new();
2373 let mut hi = self.span;
2377 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2379 token::OpenDelim(token::Paren) => {
2382 attrs.extend(self.parse_inner_attributes()?);
2384 // (e) is parenthesized e
2385 // (e,) is a tuple with only one field, e
2386 let mut es = vec![];
2387 let mut trailing_comma = false;
2388 let mut recovered = false;
2389 while self.token != token::CloseDelim(token::Paren) {
2390 es.push(match self.parse_expr() {
2393 // recover from parse error in tuple list
2394 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2397 recovered = self.expect_one_of(
2399 &[token::Comma, token::CloseDelim(token::Paren)],
2401 if self.eat(&token::Comma) {
2402 trailing_comma = true;
2404 trailing_comma = false;
2412 hi = self.prev_span;
2413 ex = if es.len() == 1 && !trailing_comma {
2414 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2419 token::OpenDelim(token::Brace) => {
2420 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2422 token::BinOp(token::Or) | token::OrOr => {
2423 return self.parse_lambda_expr(attrs);
2425 token::OpenDelim(token::Bracket) => {
2428 attrs.extend(self.parse_inner_attributes()?);
2430 if self.eat(&token::CloseDelim(token::Bracket)) {
2432 ex = ExprKind::Array(Vec::new());
2435 let first_expr = self.parse_expr()?;
2436 if self.eat(&token::Semi) {
2437 // Repeating array syntax: [ 0; 512 ]
2438 let count = AnonConst {
2439 id: ast::DUMMY_NODE_ID,
2440 value: self.parse_expr()?,
2442 self.expect(&token::CloseDelim(token::Bracket))?;
2443 ex = ExprKind::Repeat(first_expr, count);
2444 } else if self.eat(&token::Comma) {
2445 // Vector with two or more elements.
2446 let remaining_exprs = self.parse_seq_to_end(
2447 &token::CloseDelim(token::Bracket),
2448 SeqSep::trailing_allowed(token::Comma),
2449 |p| Ok(p.parse_expr()?)
2451 let mut exprs = vec![first_expr];
2452 exprs.extend(remaining_exprs);
2453 ex = ExprKind::Array(exprs);
2455 // Vector with one element.
2456 self.expect(&token::CloseDelim(token::Bracket))?;
2457 ex = ExprKind::Array(vec![first_expr]);
2460 hi = self.prev_span;
2464 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2466 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2468 if self.span.rust_2018() && self.check_keyword(kw::Async) {
2469 return if self.is_async_block() { // check for `async {` and `async move {`
2470 self.parse_async_block(attrs)
2472 self.parse_lambda_expr(attrs)
2475 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
2476 return self.parse_lambda_expr(attrs);
2478 if self.eat_keyword(kw::If) {
2479 return self.parse_if_expr(attrs);
2481 if self.eat_keyword(kw::For) {
2482 let lo = self.prev_span;
2483 return self.parse_for_expr(None, lo, attrs);
2485 if self.eat_keyword(kw::While) {
2486 let lo = self.prev_span;
2487 return self.parse_while_expr(None, lo, attrs);
2489 if let Some(label) = self.eat_label() {
2490 let lo = label.ident.span;
2491 self.expect(&token::Colon)?;
2492 if self.eat_keyword(kw::While) {
2493 return self.parse_while_expr(Some(label), lo, attrs)
2495 if self.eat_keyword(kw::For) {
2496 return self.parse_for_expr(Some(label), lo, attrs)
2498 if self.eat_keyword(kw::Loop) {
2499 return self.parse_loop_expr(Some(label), lo, attrs)
2501 if self.token == token::OpenDelim(token::Brace) {
2502 return self.parse_block_expr(Some(label),
2504 BlockCheckMode::Default,
2507 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2508 let mut err = self.fatal(msg);
2509 err.span_label(self.span, msg);
2512 if self.eat_keyword(kw::Loop) {
2513 let lo = self.prev_span;
2514 return self.parse_loop_expr(None, lo, attrs);
2516 if self.eat_keyword(kw::Continue) {
2517 let label = self.eat_label();
2518 let ex = ExprKind::Continue(label);
2519 let hi = self.prev_span;
2520 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2522 if self.eat_keyword(kw::Match) {
2523 let match_sp = self.prev_span;
2524 return self.parse_match_expr(attrs).map_err(|mut err| {
2525 err.span_label(match_sp, "while parsing this match expression");
2529 if self.eat_keyword(kw::Unsafe) {
2530 return self.parse_block_expr(
2533 BlockCheckMode::Unsafe(ast::UserProvided),
2536 if self.is_do_catch_block() {
2537 let mut db = self.fatal("found removed `do catch` syntax");
2538 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2541 if self.is_try_block() {
2543 assert!(self.eat_keyword(kw::Try));
2544 return self.parse_try_block(lo, attrs);
2546 if self.eat_keyword(kw::Return) {
2547 if self.token.can_begin_expr() {
2548 let e = self.parse_expr()?;
2550 ex = ExprKind::Ret(Some(e));
2552 ex = ExprKind::Ret(None);
2554 } else if self.eat_keyword(kw::Break) {
2555 let label = self.eat_label();
2556 let e = if self.token.can_begin_expr()
2557 && !(self.token == token::OpenDelim(token::Brace)
2558 && self.restrictions.contains(
2559 Restrictions::NO_STRUCT_LITERAL)) {
2560 Some(self.parse_expr()?)
2564 ex = ExprKind::Break(label, e);
2565 hi = self.prev_span;
2566 } else if self.eat_keyword(kw::Yield) {
2567 if self.token.can_begin_expr() {
2568 let e = self.parse_expr()?;
2570 ex = ExprKind::Yield(Some(e));
2572 ex = ExprKind::Yield(None);
2574 } else if self.token.is_keyword(kw::Let) {
2575 // Catch this syntax error here, instead of in `parse_ident`, so
2576 // that we can explicitly mention that let is not to be used as an expression
2577 let mut db = self.fatal("expected expression, found statement (`let`)");
2578 db.span_label(self.span, "expected expression");
2579 db.note("variable declaration using `let` is a statement");
2581 } else if self.span.rust_2018() && self.eat_keyword(kw::Await) {
2582 let (await_hi, e_kind) = self.parse_await_macro_or_alt(lo, self.prev_span)?;
2585 } else if self.token.is_path_start() {
2586 let path = self.parse_path(PathStyle::Expr)?;
2588 // `!`, as an operator, is prefix, so we know this isn't that
2589 if self.eat(&token::Not) {
2590 // MACRO INVOCATION expression
2591 let (delim, tts) = self.expect_delimited_token_tree()?;
2592 hi = self.prev_span;
2593 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2594 } else if self.check(&token::OpenDelim(token::Brace)) {
2595 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2599 ex = ExprKind::Path(None, path);
2603 ex = ExprKind::Path(None, path);
2606 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2607 // Don't complain about bare semicolons after unclosed braces
2608 // recovery in order to keep the error count down. Fixing the
2609 // delimiters will possibly also fix the bare semicolon found in
2610 // expression context. For example, silence the following error:
2612 // error: expected expression, found `;`
2616 // | ^ expected expression
2619 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2621 match self.parse_literal_maybe_minus() {
2624 ex = expr.node.clone();
2627 self.cancel(&mut err);
2628 let msg = format!("expected expression, found {}",
2629 self.this_token_descr());
2630 let mut err = self.fatal(&msg);
2631 let sp = self.sess.source_map().start_point(self.span);
2632 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow()
2635 self.sess.expr_parentheses_needed(&mut err, *sp, None);
2637 err.span_label(self.span, "expected expression");
2645 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2646 self.maybe_recover_from_bad_qpath(expr, true)
2649 /// Parse `await!(<expr>)` calls, or alternatively recover from incorrect but reasonable
2650 /// alternative syntaxes `await <expr>`, `await? <expr>`, `await(<expr>)` and
2651 /// `await { <expr> }`.
2652 fn parse_await_macro_or_alt(
2656 ) -> PResult<'a, (Span, ExprKind)> {
2657 if self.token == token::Not {
2658 // Handle correct `await!(<expr>)`.
2659 // FIXME: make this an error when `await!` is no longer supported
2660 // https://github.com/rust-lang/rust/issues/60610
2661 self.expect(&token::Not)?;
2662 self.expect(&token::OpenDelim(token::Paren))?;
2663 let expr = self.parse_expr().map_err(|mut err| {
2664 err.span_label(await_sp, "while parsing this await macro call");
2667 self.expect(&token::CloseDelim(token::Paren))?;
2668 Ok((self.prev_span, ExprKind::Await(ast::AwaitOrigin::MacroLike, expr)))
2669 } else { // Handle `await <expr>`.
2670 self.parse_incorrect_await_syntax(lo, await_sp)
2674 fn maybe_parse_struct_expr(
2678 attrs: &ThinVec<Attribute>,
2679 ) -> Option<PResult<'a, P<Expr>>> {
2680 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2681 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2682 // `{ ident, ` cannot start a block
2683 self.look_ahead(2, |t| t == &token::Comma) ||
2684 self.look_ahead(2, |t| t == &token::Colon) && (
2685 // `{ ident: token, ` cannot start a block
2686 self.look_ahead(4, |t| t == &token::Comma) ||
2687 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2688 self.look_ahead(3, |t| !t.can_begin_type())
2692 if struct_allowed || certainly_not_a_block() {
2693 // This is a struct literal, but we don't can't accept them here
2694 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2695 if let (Ok(expr), false) = (&expr, struct_allowed) {
2696 let mut err = self.diagnostic().struct_span_err(
2698 "struct literals are not allowed here",
2700 err.multipart_suggestion(
2701 "surround the struct literal with parentheses",
2703 (lo.shrink_to_lo(), "(".to_string()),
2704 (expr.span.shrink_to_hi(), ")".to_string()),
2706 Applicability::MachineApplicable,
2715 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2716 -> PResult<'a, P<Expr>> {
2717 let struct_sp = lo.to(self.prev_span);
2719 let mut fields = Vec::new();
2720 let mut base = None;
2722 attrs.extend(self.parse_inner_attributes()?);
2724 while self.token != token::CloseDelim(token::Brace) {
2725 if self.eat(&token::DotDot) {
2726 let exp_span = self.prev_span;
2727 match self.parse_expr() {
2733 self.recover_stmt();
2736 if self.token == token::Comma {
2737 let mut err = self.sess.span_diagnostic.mut_span_err(
2738 exp_span.to(self.prev_span),
2739 "cannot use a comma after the base struct",
2741 err.span_suggestion_short(
2743 "remove this comma",
2745 Applicability::MachineApplicable
2747 err.note("the base struct must always be the last field");
2749 self.recover_stmt();
2754 let mut recovery_field = None;
2755 if let token::Ident(ident, _) = self.token {
2756 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2757 // Use in case of error after field-looking code: `S { foo: () with a }`
2758 let mut ident = ident.clone();
2759 ident.span = self.span;
2760 recovery_field = Some(ast::Field {
2763 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2764 is_shorthand: false,
2765 attrs: ThinVec::new(),
2769 let mut parsed_field = None;
2770 match self.parse_field() {
2771 Ok(f) => parsed_field = Some(f),
2773 e.span_label(struct_sp, "while parsing this struct");
2776 // If the next token is a comma, then try to parse
2777 // what comes next as additional fields, rather than
2778 // bailing out until next `}`.
2779 if self.token != token::Comma {
2780 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2781 if self.token != token::Comma {
2788 match self.expect_one_of(&[token::Comma],
2789 &[token::CloseDelim(token::Brace)]) {
2790 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2791 // only include the field if there's no parse error for the field name
2795 if let Some(f) = recovery_field {
2798 e.span_label(struct_sp, "while parsing this struct");
2800 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2801 self.eat(&token::Comma);
2806 let span = lo.to(self.span);
2807 self.expect(&token::CloseDelim(token::Brace))?;
2808 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2811 fn parse_or_use_outer_attributes(&mut self,
2812 already_parsed_attrs: Option<ThinVec<Attribute>>)
2813 -> PResult<'a, ThinVec<Attribute>> {
2814 if let Some(attrs) = already_parsed_attrs {
2817 self.parse_outer_attributes().map(|a| a.into())
2821 /// Parses a block or unsafe block.
2822 crate fn parse_block_expr(
2824 opt_label: Option<Label>,
2826 blk_mode: BlockCheckMode,
2827 outer_attrs: ThinVec<Attribute>,
2828 ) -> PResult<'a, P<Expr>> {
2829 self.expect(&token::OpenDelim(token::Brace))?;
2831 let mut attrs = outer_attrs;
2832 attrs.extend(self.parse_inner_attributes()?);
2834 let blk = self.parse_block_tail(lo, blk_mode)?;
2835 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2838 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2839 fn parse_dot_or_call_expr(&mut self,
2840 already_parsed_attrs: Option<ThinVec<Attribute>>)
2841 -> PResult<'a, P<Expr>> {
2842 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2844 let b = self.parse_bottom_expr();
2845 let (span, b) = self.interpolated_or_expr_span(b)?;
2846 self.parse_dot_or_call_expr_with(b, span, attrs)
2849 fn parse_dot_or_call_expr_with(&mut self,
2852 mut attrs: ThinVec<Attribute>)
2853 -> PResult<'a, P<Expr>> {
2854 // Stitch the list of outer attributes onto the return value.
2855 // A little bit ugly, but the best way given the current code
2857 self.parse_dot_or_call_expr_with_(e0, lo)
2859 expr.map(|mut expr| {
2860 attrs.extend::<Vec<_>>(expr.attrs.into());
2863 ExprKind::If(..) | ExprKind::IfLet(..) => {
2864 if !expr.attrs.is_empty() {
2865 // Just point to the first attribute in there...
2866 let span = expr.attrs[0].span;
2869 "attributes are not yet allowed on `if` \
2880 // Assuming we have just parsed `.`, continue parsing into an expression.
2881 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2882 if self.span.rust_2018() && self.eat_keyword(kw::Await) {
2883 let span = lo.to(self.prev_span);
2884 let await_expr = self.mk_expr(
2886 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
2889 self.recover_from_await_method_call();
2890 return Ok(await_expr);
2892 let segment = self.parse_path_segment(PathStyle::Expr)?;
2893 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2895 Ok(match self.token {
2896 token::OpenDelim(token::Paren) => {
2897 // Method call `expr.f()`
2898 let mut args = self.parse_unspanned_seq(
2899 &token::OpenDelim(token::Paren),
2900 &token::CloseDelim(token::Paren),
2901 SeqSep::trailing_allowed(token::Comma),
2902 |p| Ok(p.parse_expr()?)
2904 args.insert(0, self_arg);
2906 let span = lo.to(self.prev_span);
2907 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2910 // Field access `expr.f`
2911 if let Some(args) = segment.args {
2912 self.span_err(args.span(),
2913 "field expressions may not have generic arguments");
2916 let span = lo.to(self.prev_span);
2917 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2922 /// This function checks if there are trailing angle brackets and produces
2923 /// a diagnostic to suggest removing them.
2925 /// ```ignore (diagnostic)
2926 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
2927 /// ^^ help: remove extra angle brackets
2929 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
2930 // This function is intended to be invoked after parsing a path segment where there are two
2933 // 1. A specific token is expected after the path segment.
2934 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
2935 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
2936 // 2. No specific token is expected after the path segment.
2937 // eg. `x.foo` (field access)
2939 // This function is called after parsing `.foo` and before parsing the token `end` (if
2940 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
2943 // We only care about trailing angle brackets if we previously parsed angle bracket
2944 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
2945 // removed in this case:
2947 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
2949 // This case is particularly tricky as we won't notice it just looking at the tokens -
2950 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
2951 // have already been parsed):
2953 // `x.foo::<u32>>>(3)`
2954 let parsed_angle_bracket_args = segment.args
2956 .map(|args| args.is_angle_bracketed())
2960 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
2961 parsed_angle_bracket_args,
2963 if !parsed_angle_bracket_args {
2967 // Keep the span at the start so we can highlight the sequence of `>` characters to be
2971 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
2972 // (since we might have the field access case and the characters we're eating are
2973 // actual operators and not trailing characters - ie `x.foo >> 3`).
2974 let mut position = 0;
2976 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
2977 // many of each (so we can correctly pluralize our error messages) and continue to
2979 let mut number_of_shr = 0;
2980 let mut number_of_gt = 0;
2981 while self.look_ahead(position, |t| {
2982 trace!("check_trailing_angle_brackets: t={:?}", t);
2983 if *t == token::BinOp(token::BinOpToken::Shr) {
2986 } else if *t == token::Gt {
2996 // If we didn't find any trailing `>` characters, then we have nothing to error about.
2998 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
2999 number_of_gt, number_of_shr,
3001 if number_of_gt < 1 && number_of_shr < 1 {
3005 // Finally, double check that we have our end token as otherwise this is the
3007 if self.look_ahead(position, |t| {
3008 trace!("check_trailing_angle_brackets: t={:?}", t);
3011 // Eat from where we started until the end token so that parsing can continue
3012 // as if we didn't have those extra angle brackets.
3013 self.eat_to_tokens(&[&end]);
3014 let span = lo.until(self.span);
3016 let plural = number_of_gt > 1 || number_of_shr >= 1;
3020 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3024 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3026 Applicability::MachineApplicable,
3032 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3037 while self.eat(&token::Question) {
3038 let hi = self.prev_span;
3039 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3043 if self.eat(&token::Dot) {
3045 token::Ident(..) => {
3046 e = self.parse_dot_suffix(e, lo)?;
3048 token::Literal(token::Integer(name), suffix) => {
3049 let span = self.span;
3051 let field = ExprKind::Field(e, Ident::new(name, span));
3052 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3054 self.expect_no_suffix(span, "a tuple index", suffix);
3056 token::Literal(token::Float(n), _suf) => {
3058 let fstr = n.as_str();
3059 let mut err = self.diagnostic()
3060 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3061 err.span_label(self.prev_span, "unexpected token");
3062 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3063 let float = match fstr.parse::<f64>().ok() {
3067 let sugg = pprust::to_string(|s| {
3068 use crate::print::pprust::PrintState;
3072 s.print_usize(float.trunc() as usize)?;
3075 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3077 err.span_suggestion(
3078 lo.to(self.prev_span),
3079 "try parenthesizing the first index",
3081 Applicability::MachineApplicable
3088 // FIXME Could factor this out into non_fatal_unexpected or something.
3089 let actual = self.this_token_to_string();
3090 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3095 if self.expr_is_complete(&e) { break; }
3098 token::OpenDelim(token::Paren) => {
3099 let seq = self.parse_unspanned_seq(
3100 &token::OpenDelim(token::Paren),
3101 &token::CloseDelim(token::Paren),
3102 SeqSep::trailing_allowed(token::Comma),
3103 |p| Ok(p.parse_expr()?)
3105 let nd = self.mk_call(e, es);
3106 let hi = self.prev_span;
3107 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3109 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3113 // Could be either an index expression or a slicing expression.
3114 token::OpenDelim(token::Bracket) => {
3116 let ix = self.parse_expr()?;
3118 self.expect(&token::CloseDelim(token::Bracket))?;
3119 let index = self.mk_index(e, ix);
3120 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3128 crate fn process_potential_macro_variable(&mut self) {
3129 let (token, span) = match self.token {
3130 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3131 self.look_ahead(1, |t| t.is_ident()) => {
3133 let name = match self.token {
3134 token::Ident(ident, _) => ident,
3137 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3138 err.span_label(self.span, "unknown macro variable");
3143 token::Interpolated(ref nt) => {
3144 self.meta_var_span = Some(self.span);
3145 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3146 // and lifetime tokens, so the former are never encountered during normal parsing.
3148 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3149 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3159 /// Parses a single token tree from the input.
3160 crate fn parse_token_tree(&mut self) -> TokenTree {
3162 token::OpenDelim(..) => {
3163 let frame = mem::replace(&mut self.token_cursor.frame,
3164 self.token_cursor.stack.pop().unwrap());
3165 self.span = frame.span.entire();
3167 TokenTree::Delimited(
3170 frame.tree_cursor.stream.into(),
3173 token::CloseDelim(_) | token::Eof => unreachable!(),
3175 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3177 TokenTree::Token(span, token)
3182 // parse a stream of tokens into a list of TokenTree's,
3184 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3185 let mut tts = Vec::new();
3186 while self.token != token::Eof {
3187 tts.push(self.parse_token_tree());
3192 pub fn parse_tokens(&mut self) -> TokenStream {
3193 let mut result = Vec::new();
3196 token::Eof | token::CloseDelim(..) => break,
3197 _ => result.push(self.parse_token_tree().into()),
3200 TokenStream::new(result)
3203 /// Parse a prefix-unary-operator expr
3204 fn parse_prefix_expr(&mut self,
3205 already_parsed_attrs: Option<ThinVec<Attribute>>)
3206 -> PResult<'a, P<Expr>> {
3207 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3209 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3210 let (hi, ex) = match self.token {
3213 let e = self.parse_prefix_expr(None);
3214 let (span, e) = self.interpolated_or_expr_span(e)?;
3215 (lo.to(span), self.mk_unary(UnOp::Not, e))
3217 // Suggest `!` for bitwise negation when encountering a `~`
3220 let e = self.parse_prefix_expr(None);
3221 let (span, e) = self.interpolated_or_expr_span(e)?;
3222 let span_of_tilde = lo;
3223 let mut err = self.diagnostic()
3224 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3225 err.span_suggestion_short(
3227 "use `!` to perform bitwise negation",
3229 Applicability::MachineApplicable
3232 (lo.to(span), self.mk_unary(UnOp::Not, e))
3234 token::BinOp(token::Minus) => {
3236 let e = self.parse_prefix_expr(None);
3237 let (span, e) = self.interpolated_or_expr_span(e)?;
3238 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3240 token::BinOp(token::Star) => {
3242 let e = self.parse_prefix_expr(None);
3243 let (span, e) = self.interpolated_or_expr_span(e)?;
3244 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3246 token::BinOp(token::And) | token::AndAnd => {
3248 let m = self.parse_mutability();
3249 let e = self.parse_prefix_expr(None);
3250 let (span, e) = self.interpolated_or_expr_span(e)?;
3251 (lo.to(span), ExprKind::AddrOf(m, e))
3253 token::Ident(..) if self.token.is_keyword(kw::In) => {
3255 let place = self.parse_expr_res(
3256 Restrictions::NO_STRUCT_LITERAL,
3259 let blk = self.parse_block()?;
3260 let span = blk.span;
3261 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3262 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3264 token::Ident(..) if self.token.is_keyword(kw::Box) => {
3266 let e = self.parse_prefix_expr(None);
3267 let (span, e) = self.interpolated_or_expr_span(e)?;
3268 (lo.to(span), ExprKind::Box(e))
3270 token::Ident(..) if self.token.is_ident_named("not") => {
3271 // `not` is just an ordinary identifier in Rust-the-language,
3272 // but as `rustc`-the-compiler, we can issue clever diagnostics
3273 // for confused users who really want to say `!`
3274 let token_cannot_continue_expr = |t: &token::Token| match *t {
3275 // These tokens can start an expression after `!`, but
3276 // can't continue an expression after an ident
3277 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3278 token::Literal(..) | token::Pound => true,
3279 token::Interpolated(ref nt) => match **nt {
3280 token::NtIdent(..) | token::NtExpr(..) |
3281 token::NtBlock(..) | token::NtPath(..) => true,
3286 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3287 if cannot_continue_expr {
3289 // Emit the error ...
3290 let mut err = self.diagnostic()
3291 .struct_span_err(self.span,
3292 &format!("unexpected {} after identifier",
3293 self.this_token_descr()));
3294 // span the `not` plus trailing whitespace to avoid
3295 // trailing whitespace after the `!` in our suggestion
3296 let to_replace = self.sess.source_map()
3297 .span_until_non_whitespace(lo.to(self.span));
3298 err.span_suggestion_short(
3300 "use `!` to perform logical negation",
3302 Applicability::MachineApplicable
3305 // —and recover! (just as if we were in the block
3306 // for the `token::Not` arm)
3307 let e = self.parse_prefix_expr(None);
3308 let (span, e) = self.interpolated_or_expr_span(e)?;
3309 (lo.to(span), self.mk_unary(UnOp::Not, e))
3311 return self.parse_dot_or_call_expr(Some(attrs));
3314 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3316 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3319 /// Parses an associative expression.
3321 /// This parses an expression accounting for associativity and precedence of the operators in
3324 fn parse_assoc_expr(&mut self,
3325 already_parsed_attrs: Option<ThinVec<Attribute>>)
3326 -> PResult<'a, P<Expr>> {
3327 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3330 /// Parses an associative expression with operators of at least `min_prec` precedence.
3331 fn parse_assoc_expr_with(&mut self,
3334 -> PResult<'a, P<Expr>> {
3335 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3338 let attrs = match lhs {
3339 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3342 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3343 return self.parse_prefix_range_expr(attrs);
3345 self.parse_prefix_expr(attrs)?
3349 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
3351 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3354 (false, _) => {} // continue parsing the expression
3355 // An exhaustive check is done in the following block, but these are checked first
3356 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
3357 // want to keep their span info to improve diagnostics in these cases in a later stage.
3358 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
3359 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
3360 (true, Some(AssocOp::Add)) => { // `{ 42 } + 42
3361 // These cases are ambiguous and can't be identified in the parser alone
3362 let sp = self.sess.source_map().start_point(self.span);
3363 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
3366 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
3369 (true, Some(_)) => {
3370 // We've found an expression that would be parsed as a statement, but the next
3371 // token implies this should be parsed as an expression.
3372 // For example: `if let Some(x) = x { x } else { 0 } / 2`
3373 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
3374 "expected expression, found `{}`",
3375 pprust::token_to_string(&self.token),
3377 err.span_label(self.span, "expected expression");
3378 self.sess.expr_parentheses_needed(
3381 Some(pprust::expr_to_string(&lhs),
3386 self.expected_tokens.push(TokenType::Operator);
3387 while let Some(op) = AssocOp::from_token(&self.token) {
3389 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3390 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3391 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3392 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3393 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3394 (PrevTokenKind::Interpolated, _) => self.prev_span,
3395 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3396 if path.segments.len() == 1 => self.prev_span,
3400 let cur_op_span = self.span;
3401 let restrictions = if op.is_assign_like() {
3402 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3406 let prec = op.precedence();
3407 if prec < min_prec {
3410 // Check for deprecated `...` syntax
3411 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3412 self.err_dotdotdot_syntax(self.span);
3416 if op.is_comparison() {
3417 self.check_no_chained_comparison(&lhs, &op);
3420 if op == AssocOp::As {
3421 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3423 } else if op == AssocOp::Colon {
3424 let maybe_path = self.could_ascription_be_path(&lhs.node);
3425 let next_sp = self.span;
3427 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3430 self.bad_type_ascription(
3441 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3442 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3443 // generalise it to the Fixity::None code.
3445 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3446 // two variants are handled with `parse_prefix_range_expr` call above.
3447 let rhs = if self.is_at_start_of_range_notation_rhs() {
3448 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
3452 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3457 let limits = if op == AssocOp::DotDot {
3458 RangeLimits::HalfOpen
3463 let r = self.mk_range(Some(lhs), rhs, limits)?;
3464 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3468 let fixity = op.fixity();
3469 let prec_adjustment = match fixity {
3472 // We currently have no non-associative operators that are not handled above by
3473 // the special cases. The code is here only for future convenience.
3476 let rhs = self.with_res(
3477 restrictions - Restrictions::STMT_EXPR,
3478 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
3481 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3482 // including the attributes.
3486 .filter(|a| a.style == AttrStyle::Outer)
3488 .map_or(lhs_span, |a| a.span);
3489 let span = lhs_span.to(rhs.span);
3491 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3492 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3493 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3494 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3495 AssocOp::Greater | AssocOp::GreaterEqual => {
3496 let ast_op = op.to_ast_binop().unwrap();
3497 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3498 self.mk_expr(span, binary, ThinVec::new())
3500 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3501 AssocOp::ObsoleteInPlace =>
3502 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3503 AssocOp::AssignOp(k) => {
3505 token::Plus => BinOpKind::Add,
3506 token::Minus => BinOpKind::Sub,
3507 token::Star => BinOpKind::Mul,
3508 token::Slash => BinOpKind::Div,
3509 token::Percent => BinOpKind::Rem,
3510 token::Caret => BinOpKind::BitXor,
3511 token::And => BinOpKind::BitAnd,
3512 token::Or => BinOpKind::BitOr,
3513 token::Shl => BinOpKind::Shl,
3514 token::Shr => BinOpKind::Shr,
3516 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3517 self.mk_expr(span, aopexpr, ThinVec::new())
3519 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3520 self.bug("AssocOp should have been handled by special case")
3524 if let Fixity::None = fixity { break }
3529 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3530 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3531 -> PResult<'a, P<Expr>> {
3532 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3533 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3536 // Save the state of the parser before parsing type normally, in case there is a
3537 // LessThan comparison after this cast.
3538 let parser_snapshot_before_type = self.clone();
3539 match self.parse_ty_no_plus() {
3541 Ok(mk_expr(self, rhs))
3543 Err(mut type_err) => {
3544 // Rewind to before attempting to parse the type with generics, to recover
3545 // from situations like `x as usize < y` in which we first tried to parse
3546 // `usize < y` as a type with generic arguments.
3547 let parser_snapshot_after_type = self.clone();
3548 mem::replace(self, parser_snapshot_before_type);
3550 match self.parse_path(PathStyle::Expr) {
3552 let (op_noun, op_verb) = match self.token {
3553 token::Lt => ("comparison", "comparing"),
3554 token::BinOp(token::Shl) => ("shift", "shifting"),
3556 // We can end up here even without `<` being the next token, for
3557 // example because `parse_ty_no_plus` returns `Err` on keywords,
3558 // but `parse_path` returns `Ok` on them due to error recovery.
3559 // Return original error and parser state.
3560 mem::replace(self, parser_snapshot_after_type);
3561 return Err(type_err);
3565 // Successfully parsed the type path leaving a `<` yet to parse.
3568 // Report non-fatal diagnostics, keep `x as usize` as an expression
3569 // in AST and continue parsing.
3570 let msg = format!("`<` is interpreted as a start of generic \
3571 arguments for `{}`, not a {}", path, op_noun);
3572 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3573 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3574 "interpreted as generic arguments");
3575 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3577 let expr = mk_expr(self, P(Ty {
3579 node: TyKind::Path(None, path),
3580 id: ast::DUMMY_NODE_ID
3583 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3584 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3585 err.span_suggestion(
3587 &format!("try {} the cast value", op_verb),
3588 format!("({})", expr_str),
3589 Applicability::MachineApplicable
3595 Err(mut path_err) => {
3596 // Couldn't parse as a path, return original error and parser state.
3598 mem::replace(self, parser_snapshot_after_type);
3606 /// Produce an error if comparison operators are chained (RFC #558).
3607 /// We only need to check lhs, not rhs, because all comparison ops
3608 /// have same precedence and are left-associative
3609 fn check_no_chained_comparison(&self, lhs: &Expr, outer_op: &AssocOp) {
3610 debug_assert!(outer_op.is_comparison(),
3611 "check_no_chained_comparison: {:?} is not comparison",
3614 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3615 // respan to include both operators
3616 let op_span = op.span.to(self.span);
3617 let mut err = self.diagnostic().struct_span_err(op_span,
3618 "chained comparison operators require parentheses");
3619 if op.node == BinOpKind::Lt &&
3620 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3621 *outer_op == AssocOp::Greater // even in a case like the following:
3622 { // Foo<Bar<Baz<Qux, ()>>>
3624 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3625 err.help("or use `(...)` if you meant to specify fn arguments");
3633 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3634 fn parse_prefix_range_expr(&mut self,
3635 already_parsed_attrs: Option<ThinVec<Attribute>>)
3636 -> PResult<'a, P<Expr>> {
3637 // Check for deprecated `...` syntax
3638 if self.token == token::DotDotDot {
3639 self.err_dotdotdot_syntax(self.span);
3642 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3643 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3645 let tok = self.token.clone();
3646 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3648 let mut hi = self.span;
3650 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3651 // RHS must be parsed with more associativity than the dots.
3652 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3653 Some(self.parse_assoc_expr_with(next_prec,
3654 LhsExpr::NotYetParsed)
3662 let limits = if tok == token::DotDot {
3663 RangeLimits::HalfOpen
3668 let r = self.mk_range(None, opt_end, limits)?;
3669 Ok(self.mk_expr(lo.to(hi), r, attrs))
3672 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3673 if self.token.can_begin_expr() {
3674 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3675 if self.token == token::OpenDelim(token::Brace) {
3676 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3684 /// Parses an `if` or `if let` expression (`if` token already eaten).
3685 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3686 if self.check_keyword(kw::Let) {
3687 return self.parse_if_let_expr(attrs);
3689 let lo = self.prev_span;
3690 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3692 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3693 // verify that the last statement is either an implicit return (no `;`) or an explicit
3694 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3695 // the dead code lint.
3696 if self.eat_keyword(kw::Else) || !cond.returns() {
3697 let sp = self.sess.source_map().next_point(lo);
3698 let mut err = self.diagnostic()
3699 .struct_span_err(sp, "missing condition for `if` statemement");
3700 err.span_label(sp, "expected if condition here");
3703 let not_block = self.token != token::OpenDelim(token::Brace);
3704 let thn = self.parse_block().map_err(|mut err| {
3706 err.span_label(lo, "this `if` statement has a condition, but no block");
3710 let mut els: Option<P<Expr>> = None;
3711 let mut hi = thn.span;
3712 if self.eat_keyword(kw::Else) {
3713 let elexpr = self.parse_else_expr()?;
3717 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3720 /// Parses an `if let` expression (`if` token already eaten).
3721 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3722 -> PResult<'a, P<Expr>> {
3723 let lo = self.prev_span;
3724 self.expect_keyword(kw::Let)?;
3725 let pats = self.parse_pats()?;
3726 self.expect(&token::Eq)?;
3727 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3728 let thn = self.parse_block()?;
3729 let (hi, els) = if self.eat_keyword(kw::Else) {
3730 let expr = self.parse_else_expr()?;
3731 (expr.span, Some(expr))
3735 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3738 /// Parses `move |args| expr`.
3739 fn parse_lambda_expr(&mut self,
3740 attrs: ThinVec<Attribute>)
3741 -> PResult<'a, P<Expr>>
3744 let movability = if self.eat_keyword(kw::Static) {
3749 let asyncness = if self.span.rust_2018() {
3750 self.parse_asyncness()
3754 let capture_clause = if self.eat_keyword(kw::Move) {
3759 let decl = self.parse_fn_block_decl()?;
3760 let decl_hi = self.prev_span;
3761 let body = match decl.output {
3762 FunctionRetTy::Default(_) => {
3763 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3764 self.parse_expr_res(restrictions, None)?
3767 // If an explicit return type is given, require a
3768 // block to appear (RFC 968).
3769 let body_lo = self.span;
3770 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3776 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3780 // `else` token already eaten
3781 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3782 if self.eat_keyword(kw::If) {
3783 return self.parse_if_expr(ThinVec::new());
3785 let blk = self.parse_block()?;
3786 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3790 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3791 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3793 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3794 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3796 let pat = self.parse_top_level_pat()?;
3797 if !self.eat_keyword(kw::In) {
3798 let in_span = self.prev_span.between(self.span);
3799 let mut err = self.sess.span_diagnostic
3800 .struct_span_err(in_span, "missing `in` in `for` loop");
3801 err.span_suggestion_short(
3802 in_span, "try adding `in` here", " in ".into(),
3803 // has been misleading, at least in the past (closed Issue #48492)
3804 Applicability::MaybeIncorrect
3808 let in_span = self.prev_span;
3809 if self.eat_keyword(kw::In) {
3810 // a common typo: `for _ in in bar {}`
3811 let mut err = self.sess.span_diagnostic.struct_span_err(
3813 "expected iterable, found keyword `in`",
3815 err.span_suggestion_short(
3816 in_span.until(self.prev_span),
3817 "remove the duplicated `in`",
3819 Applicability::MachineApplicable,
3821 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3822 err.note("for more information on the status of emplacement syntax, see <\
3823 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3826 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3827 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3828 attrs.extend(iattrs);
3830 let hi = self.prev_span;
3831 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3834 /// Parses a `while` or `while let` expression (`while` token already eaten).
3835 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3837 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3838 if self.token.is_keyword(kw::Let) {
3839 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3841 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3842 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3843 attrs.extend(iattrs);
3844 let span = span_lo.to(body.span);
3845 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3848 /// Parses a `while let` expression (`while` token already eaten).
3849 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3851 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3852 self.expect_keyword(kw::Let)?;
3853 let pats = self.parse_pats()?;
3854 self.expect(&token::Eq)?;
3855 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3856 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3857 attrs.extend(iattrs);
3858 let span = span_lo.to(body.span);
3859 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3862 // parse `loop {...}`, `loop` token already eaten
3863 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3865 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3866 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3867 attrs.extend(iattrs);
3868 let span = span_lo.to(body.span);
3869 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3872 /// Parses an `async move {...}` expression.
3873 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3874 -> PResult<'a, P<Expr>>
3876 let span_lo = self.span;
3877 self.expect_keyword(kw::Async)?;
3878 let capture_clause = if self.eat_keyword(kw::Move) {
3883 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3884 attrs.extend(iattrs);
3886 span_lo.to(body.span),
3887 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3890 /// Parses a `try {...}` expression (`try` token already eaten).
3891 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3892 -> PResult<'a, P<Expr>>
3894 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3895 attrs.extend(iattrs);
3896 if self.eat_keyword(kw::Catch) {
3897 let mut error = self.struct_span_err(self.prev_span,
3898 "keyword `catch` cannot follow a `try` block");
3899 error.help("try using `match` on the result of the `try` block instead");
3903 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3907 // `match` token already eaten
3908 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3909 let match_span = self.prev_span;
3910 let lo = self.prev_span;
3911 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3913 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3914 if self.token == token::Token::Semi {
3915 e.span_suggestion_short(
3917 "try removing this `match`",
3919 Applicability::MaybeIncorrect // speculative
3924 attrs.extend(self.parse_inner_attributes()?);
3926 let mut arms: Vec<Arm> = Vec::new();
3927 while self.token != token::CloseDelim(token::Brace) {
3928 match self.parse_arm() {
3929 Ok(arm) => arms.push(arm),
3931 // Recover by skipping to the end of the block.
3933 self.recover_stmt();
3934 let span = lo.to(self.span);
3935 if self.token == token::CloseDelim(token::Brace) {
3938 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3944 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3947 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3948 let attrs = self.parse_outer_attributes()?;
3950 let pats = self.parse_pats()?;
3951 let guard = if self.eat_keyword(kw::If) {
3952 Some(Guard::If(self.parse_expr()?))
3956 let arrow_span = self.span;
3957 self.expect(&token::FatArrow)?;
3958 let arm_start_span = self.span;
3960 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3961 .map_err(|mut err| {
3962 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3966 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3967 && self.token != token::CloseDelim(token::Brace);
3972 let cm = self.sess.source_map();
3973 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3974 .map_err(|mut err| {
3975 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3976 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3977 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3978 && expr_lines.lines.len() == 2
3979 && self.token == token::FatArrow => {
3980 // We check whether there's any trailing code in the parse span,
3981 // if there isn't, we very likely have the following:
3984 // | -- - missing comma
3990 // | parsed until here as `"y" & X`
3991 err.span_suggestion_short(
3992 cm.next_point(arm_start_span),
3993 "missing a comma here to end this `match` arm",
3995 Applicability::MachineApplicable
3999 err.span_label(arrow_span,
4000 "while parsing the `match` arm starting here");
4006 self.eat(&token::Comma);
4018 /// Parses an expression.
4020 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4021 self.parse_expr_res(Restrictions::empty(), None)
4024 /// Evaluates the closure with restrictions in place.
4026 /// Afters the closure is evaluated, restrictions are reset.
4027 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4028 where F: FnOnce(&mut Self) -> T
4030 let old = self.restrictions;
4031 self.restrictions = r;
4033 self.restrictions = old;
4038 /// Parses an expression, subject to the given restrictions.
4040 fn parse_expr_res(&mut self, r: Restrictions,
4041 already_parsed_attrs: Option<ThinVec<Attribute>>)
4042 -> PResult<'a, P<Expr>> {
4043 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4046 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4047 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4048 if self.eat(&token::Eq) {
4049 Ok(Some(self.parse_expr()?))
4051 Ok(Some(self.parse_expr()?))
4057 /// Parses patterns, separated by '|' s.
4058 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4059 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4060 self.eat(&token::BinOp(token::Or));
4062 let mut pats = Vec::new();
4064 pats.push(self.parse_top_level_pat()?);
4066 if self.token == token::OrOr {
4067 let mut err = self.struct_span_err(self.span,
4068 "unexpected token `||` after pattern");
4069 err.span_suggestion(
4071 "use a single `|` to specify multiple patterns",
4073 Applicability::MachineApplicable
4077 } else if self.eat(&token::BinOp(token::Or)) {
4078 // This is a No-op. Continue the loop to parse the next
4086 // Parses a parenthesized list of patterns like
4087 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4088 // - a vector of the patterns that were parsed
4089 // - an option indicating the index of the `..` element
4090 // - a boolean indicating whether a trailing comma was present.
4091 // Trailing commas are significant because (p) and (p,) are different patterns.
4092 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4093 self.expect(&token::OpenDelim(token::Paren))?;
4094 let result = match self.parse_pat_list() {
4095 Ok(result) => result,
4096 Err(mut err) => { // recover from parse error in tuple pattern list
4098 self.consume_block(token::Paren);
4099 return Ok((vec![], Some(0), false));
4102 self.expect(&token::CloseDelim(token::Paren))?;
4106 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4107 let mut fields = Vec::new();
4108 let mut ddpos = None;
4109 let mut prev_dd_sp = None;
4110 let mut trailing_comma = false;
4112 if self.eat(&token::DotDot) {
4113 if ddpos.is_none() {
4114 ddpos = Some(fields.len());
4115 prev_dd_sp = Some(self.prev_span);
4117 // Emit a friendly error, ignore `..` and continue parsing
4118 let mut err = self.struct_span_err(
4120 "`..` can only be used once per tuple or tuple struct pattern",
4122 err.span_label(self.prev_span, "can only be used once per pattern");
4123 if let Some(sp) = prev_dd_sp {
4124 err.span_label(sp, "previously present here");
4128 } else if !self.check(&token::CloseDelim(token::Paren)) {
4129 fields.push(self.parse_pat(None)?);
4134 trailing_comma = self.eat(&token::Comma);
4135 if !trailing_comma {
4140 if ddpos == Some(fields.len()) && trailing_comma {
4141 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4142 let msg = "trailing comma is not permitted after `..`";
4143 self.struct_span_err(self.prev_span, msg)
4144 .span_label(self.prev_span, msg)
4148 Ok((fields, ddpos, trailing_comma))
4151 fn parse_pat_vec_elements(
4153 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4154 let mut before = Vec::new();
4155 let mut slice = None;
4156 let mut after = Vec::new();
4157 let mut first = true;
4158 let mut before_slice = true;
4160 while self.token != token::CloseDelim(token::Bracket) {
4164 self.expect(&token::Comma)?;
4166 if self.token == token::CloseDelim(token::Bracket)
4167 && (before_slice || !after.is_empty()) {
4173 if self.eat(&token::DotDot) {
4175 if self.check(&token::Comma) ||
4176 self.check(&token::CloseDelim(token::Bracket)) {
4177 slice = Some(P(Pat {
4178 id: ast::DUMMY_NODE_ID,
4179 node: PatKind::Wild,
4180 span: self.prev_span,
4182 before_slice = false;
4188 let subpat = self.parse_pat(None)?;
4189 if before_slice && self.eat(&token::DotDot) {
4190 slice = Some(subpat);
4191 before_slice = false;
4192 } else if before_slice {
4193 before.push(subpat);
4199 Ok((before, slice, after))
4205 attrs: Vec<Attribute>
4206 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4207 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4209 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4210 // Parsing a pattern of the form "fieldname: pat"
4211 let fieldname = self.parse_field_name()?;
4213 let pat = self.parse_pat(None)?;
4215 (pat, fieldname, false)
4217 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4218 let is_box = self.eat_keyword(kw::Box);
4219 let boxed_span = self.span;
4220 let is_ref = self.eat_keyword(kw::Ref);
4221 let is_mut = self.eat_keyword(kw::Mut);
4222 let fieldname = self.parse_ident()?;
4223 hi = self.prev_span;
4225 let bind_type = match (is_ref, is_mut) {
4226 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4227 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4228 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4229 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4231 let fieldpat = P(Pat {
4232 id: ast::DUMMY_NODE_ID,
4233 node: PatKind::Ident(bind_type, fieldname, None),
4234 span: boxed_span.to(hi),
4237 let subpat = if is_box {
4239 id: ast::DUMMY_NODE_ID,
4240 node: PatKind::Box(fieldpat),
4246 (subpat, fieldname, true)
4249 Ok(source_map::Spanned {
4251 node: ast::FieldPat {
4255 attrs: attrs.into(),
4260 /// Parses the fields of a struct-like pattern.
4261 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4262 let mut fields = Vec::new();
4263 let mut etc = false;
4264 let mut ate_comma = true;
4265 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4266 let mut etc_span = None;
4268 while self.token != token::CloseDelim(token::Brace) {
4269 let attrs = self.parse_outer_attributes()?;
4272 // check that a comma comes after every field
4274 let err = self.struct_span_err(self.prev_span, "expected `,`");
4275 if let Some(mut delayed) = delayed_err {
4282 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4284 let mut etc_sp = self.span;
4286 if self.token == token::DotDotDot { // Issue #46718
4287 // Accept `...` as if it were `..` to avoid further errors
4288 let mut err = self.struct_span_err(self.span,
4289 "expected field pattern, found `...`");
4290 err.span_suggestion(
4292 "to omit remaining fields, use one fewer `.`",
4294 Applicability::MachineApplicable
4298 self.bump(); // `..` || `...`
4300 if self.token == token::CloseDelim(token::Brace) {
4301 etc_span = Some(etc_sp);
4304 let token_str = self.this_token_descr();
4305 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4307 err.span_label(self.span, "expected `}`");
4308 let mut comma_sp = None;
4309 if self.token == token::Comma { // Issue #49257
4310 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4311 err.span_label(etc_sp,
4312 "`..` must be at the end and cannot have a trailing comma");
4313 comma_sp = Some(self.span);
4318 etc_span = Some(etc_sp.until(self.span));
4319 if self.token == token::CloseDelim(token::Brace) {
4320 // If the struct looks otherwise well formed, recover and continue.
4321 if let Some(sp) = comma_sp {
4322 err.span_suggestion_short(
4324 "remove this comma",
4326 Applicability::MachineApplicable,
4331 } else if self.token.is_ident() && ate_comma {
4332 // Accept fields coming after `..,`.
4333 // This way we avoid "pattern missing fields" errors afterwards.
4334 // We delay this error until the end in order to have a span for a
4336 if let Some(mut delayed_err) = delayed_err {
4340 delayed_err = Some(err);
4343 if let Some(mut err) = delayed_err {
4350 fields.push(match self.parse_pat_field(lo, attrs) {
4353 if let Some(mut delayed_err) = delayed_err {
4359 ate_comma = self.eat(&token::Comma);
4362 if let Some(mut err) = delayed_err {
4363 if let Some(etc_span) = etc_span {
4364 err.multipart_suggestion(
4365 "move the `..` to the end of the field list",
4367 (etc_span, String::new()),
4368 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4370 Applicability::MachineApplicable,
4375 return Ok((fields, etc));
4378 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4379 if self.token.is_path_start() {
4381 let (qself, path) = if self.eat_lt() {
4382 // Parse a qualified path
4383 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4386 // Parse an unqualified path
4387 (None, self.parse_path(PathStyle::Expr)?)
4389 let hi = self.prev_span;
4390 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4392 self.parse_literal_maybe_minus()
4396 // helper function to decide whether to parse as ident binding or to try to do
4397 // something more complex like range patterns
4398 fn parse_as_ident(&mut self) -> bool {
4399 self.look_ahead(1, |t| match *t {
4400 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4401 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4402 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4403 // range pattern branch
4404 token::DotDot => None,
4406 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4407 token::Comma | token::CloseDelim(token::Bracket) => true,
4412 /// A wrapper around `parse_pat` with some special error handling for the
4413 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4414 /// to subpatterns within such).
4415 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4416 let pat = self.parse_pat(None)?;
4417 if self.token == token::Comma {
4418 // An unexpected comma after a top-level pattern is a clue that the
4419 // user (perhaps more accustomed to some other language) forgot the
4420 // parentheses in what should have been a tuple pattern; return a
4421 // suggestion-enhanced error here rather than choking on the comma
4423 let comma_span = self.span;
4425 if let Err(mut err) = self.parse_pat_list() {
4426 // We didn't expect this to work anyway; we just wanted
4427 // to advance to the end of the comma-sequence so we know
4428 // the span to suggest parenthesizing
4431 let seq_span = pat.span.to(self.prev_span);
4432 let mut err = self.struct_span_err(comma_span,
4433 "unexpected `,` in pattern");
4434 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4435 err.span_suggestion(
4437 "try adding parentheses to match on a tuple..",
4438 format!("({})", seq_snippet),
4439 Applicability::MachineApplicable
4442 "..or a vertical bar to match on multiple alternatives",
4443 format!("{}", seq_snippet.replace(",", " |")),
4444 Applicability::MachineApplicable
4452 /// Parses a pattern.
4453 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4454 self.parse_pat_with_range_pat(true, expected)
4457 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4459 fn parse_pat_with_range_pat(
4461 allow_range_pat: bool,
4462 expected: Option<&'static str>,
4463 ) -> PResult<'a, P<Pat>> {
4464 maybe_recover_from_interpolated_ty_qpath!(self, true);
4465 maybe_whole!(self, NtPat, |x| x);
4470 token::BinOp(token::And) | token::AndAnd => {
4471 // Parse &pat / &mut pat
4473 let mutbl = self.parse_mutability();
4474 if let token::Lifetime(ident) = self.token {
4475 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4477 err.span_label(self.span, "unexpected lifetime");
4480 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4481 pat = PatKind::Ref(subpat, mutbl);
4483 token::OpenDelim(token::Paren) => {
4484 // Parse (pat,pat,pat,...) as tuple pattern
4485 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4486 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4487 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4489 PatKind::Tuple(fields, ddpos)
4492 token::OpenDelim(token::Bracket) => {
4493 // Parse [pat,pat,...] as slice pattern
4495 let (before, slice, after) = self.parse_pat_vec_elements()?;
4496 self.expect(&token::CloseDelim(token::Bracket))?;
4497 pat = PatKind::Slice(before, slice, after);
4499 // At this point, token != &, &&, (, [
4500 _ => if self.eat_keyword(kw::Underscore) {
4502 pat = PatKind::Wild;
4503 } else if self.eat_keyword(kw::Mut) {
4504 // Parse mut ident @ pat / mut ref ident @ pat
4505 let mutref_span = self.prev_span.to(self.span);
4506 let binding_mode = if self.eat_keyword(kw::Ref) {
4508 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4511 "try switching the order",
4513 Applicability::MachineApplicable
4515 BindingMode::ByRef(Mutability::Mutable)
4517 BindingMode::ByValue(Mutability::Mutable)
4519 pat = self.parse_pat_ident(binding_mode)?;
4520 } else if self.eat_keyword(kw::Ref) {
4521 // Parse ref ident @ pat / ref mut ident @ pat
4522 let mutbl = self.parse_mutability();
4523 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4524 } else if self.eat_keyword(kw::Box) {
4526 let subpat = self.parse_pat_with_range_pat(false, None)?;
4527 pat = PatKind::Box(subpat);
4528 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4529 self.parse_as_ident() {
4530 // Parse ident @ pat
4531 // This can give false positives and parse nullary enums,
4532 // they are dealt with later in resolve
4533 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4534 pat = self.parse_pat_ident(binding_mode)?;
4535 } else if self.token.is_path_start() {
4536 // Parse pattern starting with a path
4537 let (qself, path) = if self.eat_lt() {
4538 // Parse a qualified path
4539 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4542 // Parse an unqualified path
4543 (None, self.parse_path(PathStyle::Expr)?)
4546 token::Not if qself.is_none() => {
4547 // Parse macro invocation
4549 let (delim, tts) = self.expect_delimited_token_tree()?;
4550 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4551 pat = PatKind::Mac(mac);
4553 token::DotDotDot | token::DotDotEq | token::DotDot => {
4554 let end_kind = match self.token {
4555 token::DotDot => RangeEnd::Excluded,
4556 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4557 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4558 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4561 let op_span = self.span;
4563 let span = lo.to(self.prev_span);
4564 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4566 let end = self.parse_pat_range_end()?;
4567 let op = Spanned { span: op_span, node: end_kind };
4568 pat = PatKind::Range(begin, end, op);
4570 token::OpenDelim(token::Brace) => {
4571 if qself.is_some() {
4572 let msg = "unexpected `{` after qualified path";
4573 let mut err = self.fatal(msg);
4574 err.span_label(self.span, msg);
4577 // Parse struct pattern
4579 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4581 self.recover_stmt();
4585 pat = PatKind::Struct(path, fields, etc);
4587 token::OpenDelim(token::Paren) => {
4588 if qself.is_some() {
4589 let msg = "unexpected `(` after qualified path";
4590 let mut err = self.fatal(msg);
4591 err.span_label(self.span, msg);
4594 // Parse tuple struct or enum pattern
4595 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4596 pat = PatKind::TupleStruct(path, fields, ddpos)
4598 _ => pat = PatKind::Path(qself, path),
4601 // Try to parse everything else as literal with optional minus
4602 match self.parse_literal_maybe_minus() {
4604 let op_span = self.span;
4605 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4606 self.check(&token::DotDotDot) {
4607 let end_kind = if self.eat(&token::DotDotDot) {
4608 RangeEnd::Included(RangeSyntax::DotDotDot)
4609 } else if self.eat(&token::DotDotEq) {
4610 RangeEnd::Included(RangeSyntax::DotDotEq)
4611 } else if self.eat(&token::DotDot) {
4614 panic!("impossible case: we already matched \
4615 on a range-operator token")
4617 let end = self.parse_pat_range_end()?;
4618 let op = Spanned { span: op_span, node: end_kind };
4619 pat = PatKind::Range(begin, end, op);
4621 pat = PatKind::Lit(begin);
4625 self.cancel(&mut err);
4626 let expected = expected.unwrap_or("pattern");
4628 "expected {}, found {}",
4630 self.this_token_descr(),
4632 let mut err = self.fatal(&msg);
4633 err.span_label(self.span, format!("expected {}", expected));
4634 let sp = self.sess.source_map().start_point(self.span);
4635 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4636 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4644 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4645 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4647 if !allow_range_pat {
4650 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4652 PatKind::Range(..) => {
4653 let mut err = self.struct_span_err(
4655 "the range pattern here has ambiguous interpretation",
4657 err.span_suggestion(
4659 "add parentheses to clarify the precedence",
4660 format!("({})", pprust::pat_to_string(&pat)),
4661 // "ambiguous interpretation" implies that we have to be guessing
4662 Applicability::MaybeIncorrect
4673 /// Parses `ident` or `ident @ pat`.
4674 /// used by the copy foo and ref foo patterns to give a good
4675 /// error message when parsing mistakes like `ref foo(a, b)`.
4676 fn parse_pat_ident(&mut self,
4677 binding_mode: ast::BindingMode)
4678 -> PResult<'a, PatKind> {
4679 let ident = self.parse_ident()?;
4680 let sub = if self.eat(&token::At) {
4681 Some(self.parse_pat(Some("binding pattern"))?)
4686 // just to be friendly, if they write something like
4688 // we end up here with ( as the current token. This shortly
4689 // leads to a parse error. Note that if there is no explicit
4690 // binding mode then we do not end up here, because the lookahead
4691 // will direct us over to parse_enum_variant()
4692 if self.token == token::OpenDelim(token::Paren) {
4693 return Err(self.span_fatal(
4695 "expected identifier, found enum pattern"))
4698 Ok(PatKind::Ident(binding_mode, ident, sub))
4701 /// Parses a local variable declaration.
4702 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4703 let lo = self.prev_span;
4704 let pat = self.parse_top_level_pat()?;
4706 let (err, ty) = if self.eat(&token::Colon) {
4707 // Save the state of the parser before parsing type normally, in case there is a `:`
4708 // instead of an `=` typo.
4709 let parser_snapshot_before_type = self.clone();
4710 let colon_sp = self.prev_span;
4711 match self.parse_ty() {
4712 Ok(ty) => (None, Some(ty)),
4714 // Rewind to before attempting to parse the type and continue parsing
4715 let parser_snapshot_after_type = self.clone();
4716 mem::replace(self, parser_snapshot_before_type);
4718 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4719 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4720 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4726 let init = match (self.parse_initializer(err.is_some()), err) {
4727 (Ok(init), None) => { // init parsed, ty parsed
4730 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4731 // Could parse the type as if it were the initializer, it is likely there was a
4732 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4733 err.span_suggestion_short(
4735 "use `=` if you meant to assign",
4737 Applicability::MachineApplicable
4740 // As this was parsed successfully, continue as if the code has been fixed for the
4741 // rest of the file. It will still fail due to the emitted error, but we avoid
4745 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4747 // Couldn't parse the type nor the initializer, only raise the type error and
4748 // return to the parser state before parsing the type as the initializer.
4749 // let x: <parse_error>;
4750 mem::replace(self, snapshot);
4753 (Err(err), None) => { // init error, ty parsed
4754 // Couldn't parse the initializer and we're not attempting to recover a failed
4755 // parse of the type, return the error.
4759 let hi = if self.token == token::Semi {
4768 id: ast::DUMMY_NODE_ID,
4771 source: LocalSource::Normal,
4775 /// Parses a structure field.
4776 fn parse_name_and_ty(&mut self,
4779 attrs: Vec<Attribute>)
4780 -> PResult<'a, StructField> {
4781 let name = self.parse_ident()?;
4782 self.expect(&token::Colon)?;
4783 let ty = self.parse_ty()?;
4785 span: lo.to(self.prev_span),
4788 id: ast::DUMMY_NODE_ID,
4794 /// Emits an expected-item-after-attributes error.
4795 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4796 let message = match attrs.last() {
4797 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4798 _ => "expected item after attributes",
4801 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4802 if attrs.last().unwrap().is_sugared_doc {
4803 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4808 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4809 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4810 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4811 Ok(self.parse_stmt_(true))
4814 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4815 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4817 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4822 fn is_async_block(&self) -> bool {
4823 self.token.is_keyword(kw::Async) &&
4826 self.look_ahead(1, |t| t.is_keyword(kw::Move)) &&
4827 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4829 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4834 fn is_async_fn(&self) -> bool {
4835 self.token.is_keyword(kw::Async) &&
4836 self.look_ahead(1, |t| t.is_keyword(kw::Fn))
4839 fn is_do_catch_block(&self) -> bool {
4840 self.token.is_keyword(kw::Do) &&
4841 self.look_ahead(1, |t| t.is_keyword(kw::Catch)) &&
4842 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4843 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4846 fn is_try_block(&self) -> bool {
4847 self.token.is_keyword(kw::Try) &&
4848 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4849 self.span.rust_2018() &&
4850 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4851 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4854 fn is_union_item(&self) -> bool {
4855 self.token.is_keyword(kw::Union) &&
4856 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4859 fn is_crate_vis(&self) -> bool {
4860 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4863 fn is_existential_type_decl(&self) -> bool {
4864 self.token.is_keyword(kw::Existential) &&
4865 self.look_ahead(1, |t| t.is_keyword(kw::Type))
4868 fn is_auto_trait_item(&self) -> bool {
4870 (self.token.is_keyword(kw::Auto)
4871 && self.look_ahead(1, |t| t.is_keyword(kw::Trait)))
4872 || // unsafe auto trait
4873 (self.token.is_keyword(kw::Unsafe) &&
4874 self.look_ahead(1, |t| t.is_keyword(kw::Auto)) &&
4875 self.look_ahead(2, |t| t.is_keyword(kw::Trait)))
4878 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4879 -> PResult<'a, Option<P<Item>>> {
4880 let token_lo = self.span;
4881 let (ident, def) = match self.token {
4882 token::Ident(ident, false) if ident.name == kw::Macro => {
4884 let ident = self.parse_ident()?;
4885 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4886 match self.parse_token_tree() {
4887 TokenTree::Delimited(_, _, tts) => tts,
4888 _ => unreachable!(),
4890 } else if self.check(&token::OpenDelim(token::Paren)) {
4891 let args = self.parse_token_tree();
4892 let body = if self.check(&token::OpenDelim(token::Brace)) {
4893 self.parse_token_tree()
4898 TokenStream::new(vec![
4900 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4908 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4910 token::Ident(ident, _) if ident.name == sym::macro_rules &&
4911 self.look_ahead(1, |t| *t == token::Not) => {
4912 let prev_span = self.prev_span;
4913 self.complain_if_pub_macro(&vis.node, prev_span);
4917 let ident = self.parse_ident()?;
4918 let (delim, tokens) = self.expect_delimited_token_tree()?;
4919 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
4920 self.report_invalid_macro_expansion_item();
4923 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4925 _ => return Ok(None),
4928 let span = lo.to(self.prev_span);
4929 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4932 fn parse_stmt_without_recovery(&mut self,
4933 macro_legacy_warnings: bool)
4934 -> PResult<'a, Option<Stmt>> {
4935 maybe_whole!(self, NtStmt, |x| Some(x));
4937 let attrs = self.parse_outer_attributes()?;
4940 Ok(Some(if self.eat_keyword(kw::Let) {
4942 id: ast::DUMMY_NODE_ID,
4943 node: StmtKind::Local(self.parse_local(attrs.into())?),
4944 span: lo.to(self.prev_span),
4946 } else if let Some(macro_def) = self.eat_macro_def(
4948 &source_map::respan(lo, VisibilityKind::Inherited),
4952 id: ast::DUMMY_NODE_ID,
4953 node: StmtKind::Item(macro_def),
4954 span: lo.to(self.prev_span),
4956 // Starts like a simple path, being careful to avoid contextual keywords
4957 // such as a union items, item with `crate` visibility or auto trait items.
4958 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4959 // like a path (1 token), but it fact not a path.
4960 // `union::b::c` - path, `union U { ... }` - not a path.
4961 // `crate::b::c` - path, `crate struct S;` - not a path.
4962 } else if self.token.is_path_start() &&
4963 !self.token.is_qpath_start() &&
4964 !self.is_union_item() &&
4965 !self.is_crate_vis() &&
4966 !self.is_existential_type_decl() &&
4967 !self.is_auto_trait_item() &&
4968 !self.is_async_fn() {
4969 let pth = self.parse_path(PathStyle::Expr)?;
4971 if !self.eat(&token::Not) {
4972 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4973 self.parse_struct_expr(lo, pth, ThinVec::new())?
4975 let hi = self.prev_span;
4976 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4979 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4980 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4981 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4984 return Ok(Some(Stmt {
4985 id: ast::DUMMY_NODE_ID,
4986 node: StmtKind::Expr(expr),
4987 span: lo.to(self.prev_span),
4991 // it's a macro invocation
4992 let id = match self.token {
4993 token::OpenDelim(_) => Ident::invalid(), // no special identifier
4994 _ => self.parse_ident()?,
4997 // check that we're pointing at delimiters (need to check
4998 // again after the `if`, because of `parse_ident`
4999 // consuming more tokens).
5001 token::OpenDelim(_) => {}
5003 // we only expect an ident if we didn't parse one
5005 let ident_str = if id.name == kw::Invalid {
5010 let tok_str = self.this_token_descr();
5011 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5014 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5019 let (delim, tts) = self.expect_delimited_token_tree()?;
5020 let hi = self.prev_span;
5022 let style = if delim == MacDelimiter::Brace {
5023 MacStmtStyle::Braces
5025 MacStmtStyle::NoBraces
5028 if id.name == kw::Invalid {
5029 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5030 let node = if delim == MacDelimiter::Brace ||
5031 self.token == token::Semi || self.token == token::Eof {
5032 StmtKind::Mac(P((mac, style, attrs.into())))
5034 // We used to incorrectly stop parsing macro-expanded statements here.
5035 // If the next token will be an error anyway but could have parsed with the
5036 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5037 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5038 // These can continue an expression, so we can't stop parsing and warn.
5039 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5040 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5041 token::BinOp(token::And) | token::BinOp(token::Or) |
5042 token::AndAnd | token::OrOr |
5043 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5046 self.warn_missing_semicolon();
5047 StmtKind::Mac(P((mac, style, attrs.into())))
5049 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5050 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5051 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5052 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5056 id: ast::DUMMY_NODE_ID,
5061 // if it has a special ident, it's definitely an item
5063 // Require a semicolon or braces.
5064 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5065 self.report_invalid_macro_expansion_item();
5067 let span = lo.to(hi);
5069 id: ast::DUMMY_NODE_ID,
5071 node: StmtKind::Item({
5073 span, id /*id is good here*/,
5074 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5075 respan(lo, VisibilityKind::Inherited),
5081 // FIXME: Bad copy of attrs
5082 let old_directory_ownership =
5083 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5084 let item = self.parse_item_(attrs.clone(), false, true)?;
5085 self.directory.ownership = old_directory_ownership;
5089 id: ast::DUMMY_NODE_ID,
5090 span: lo.to(i.span),
5091 node: StmtKind::Item(i),
5094 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5095 if !attrs.is_empty() {
5096 if s.prev_token_kind == PrevTokenKind::DocComment {
5097 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5098 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5099 s.span_err(s.span, "expected statement after outer attribute");
5104 // Do not attempt to parse an expression if we're done here.
5105 if self.token == token::Semi {
5106 unused_attrs(&attrs, self);
5111 if self.token == token::CloseDelim(token::Brace) {
5112 unused_attrs(&attrs, self);
5116 // Remainder are line-expr stmts.
5117 let e = self.parse_expr_res(
5118 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5120 id: ast::DUMMY_NODE_ID,
5121 span: lo.to(e.span),
5122 node: StmtKind::Expr(e),
5129 /// Checks if this expression is a successfully parsed statement.
5130 fn expr_is_complete(&self, e: &Expr) -> bool {
5131 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5132 !classify::expr_requires_semi_to_be_stmt(e)
5135 /// Parses a block. No inner attributes are allowed.
5136 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5137 maybe_whole!(self, NtBlock, |x| x);
5141 if !self.eat(&token::OpenDelim(token::Brace)) {
5143 let tok = self.this_token_descr();
5144 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5145 let do_not_suggest_help =
5146 self.token.is_keyword(kw::In) || self.token == token::Colon;
5148 if self.token.is_ident_named("and") {
5149 e.span_suggestion_short(
5151 "use `&&` instead of `and` for the boolean operator",
5153 Applicability::MaybeIncorrect,
5156 if self.token.is_ident_named("or") {
5157 e.span_suggestion_short(
5159 "use `||` instead of `or` for the boolean operator",
5161 Applicability::MaybeIncorrect,
5165 // Check to see if the user has written something like
5170 // Which is valid in other languages, but not Rust.
5171 match self.parse_stmt_without_recovery(false) {
5173 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5174 || do_not_suggest_help {
5175 // if the next token is an open brace (e.g., `if a b {`), the place-
5176 // inside-a-block suggestion would be more likely wrong than right
5177 e.span_label(sp, "expected `{`");
5180 let mut stmt_span = stmt.span;
5181 // expand the span to include the semicolon, if it exists
5182 if self.eat(&token::Semi) {
5183 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5185 let sugg = pprust::to_string(|s| {
5186 use crate::print::pprust::{PrintState, INDENT_UNIT};
5187 s.ibox(INDENT_UNIT)?;
5189 s.print_stmt(&stmt)?;
5190 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5194 "try placing this code inside a block",
5196 // speculative, has been misleading in the past (closed Issue #46836)
5197 Applicability::MaybeIncorrect
5201 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5202 self.cancel(&mut e);
5206 e.span_label(sp, "expected `{`");
5210 self.parse_block_tail(lo, BlockCheckMode::Default)
5213 /// Parses a block. Inner attributes are allowed.
5214 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5215 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5218 self.expect(&token::OpenDelim(token::Brace))?;
5219 Ok((self.parse_inner_attributes()?,
5220 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5223 /// Parses the rest of a block expression or function body.
5224 /// Precondition: already parsed the '{'.
5225 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5226 let mut stmts = vec![];
5227 while !self.eat(&token::CloseDelim(token::Brace)) {
5228 let stmt = match self.parse_full_stmt(false) {
5231 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5233 id: ast::DUMMY_NODE_ID,
5234 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5240 if let Some(stmt) = stmt {
5242 } else if self.token == token::Eof {
5245 // Found only `;` or `}`.
5251 id: ast::DUMMY_NODE_ID,
5253 span: lo.to(self.prev_span),
5257 /// Parses a statement, including the trailing semicolon.
5258 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5259 // skip looking for a trailing semicolon when we have an interpolated statement
5260 maybe_whole!(self, NtStmt, |x| Some(x));
5262 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5264 None => return Ok(None),
5268 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5269 // expression without semicolon
5270 if classify::expr_requires_semi_to_be_stmt(expr) {
5271 // Just check for errors and recover; do not eat semicolon yet.
5273 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5276 self.recover_stmt();
5280 StmtKind::Local(..) => {
5281 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5282 if macro_legacy_warnings && self.token != token::Semi {
5283 self.warn_missing_semicolon();
5285 self.expect_one_of(&[], &[token::Semi])?;
5291 if self.eat(&token::Semi) {
5292 stmt = stmt.add_trailing_semicolon();
5295 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5299 fn warn_missing_semicolon(&self) {
5300 self.diagnostic().struct_span_warn(self.span, {
5301 &format!("expected `;`, found {}", self.this_token_descr())
5303 "This was erroneously allowed and will become a hard error in a future release"
5307 fn err_dotdotdot_syntax(&self, span: Span) {
5308 self.diagnostic().struct_span_err(span, {
5309 "unexpected token: `...`"
5311 span, "use `..` for an exclusive range", "..".to_owned(),
5312 Applicability::MaybeIncorrect
5314 span, "or `..=` for an inclusive range", "..=".to_owned(),
5315 Applicability::MaybeIncorrect
5319 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5322 /// BOUND = TY_BOUND | LT_BOUND
5323 /// LT_BOUND = LIFETIME (e.g., `'a`)
5324 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5325 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5327 fn parse_generic_bounds_common(&mut self,
5329 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5330 let mut bounds = Vec::new();
5331 let mut negative_bounds = Vec::new();
5332 let mut last_plus_span = None;
5333 let mut was_negative = false;
5335 // This needs to be synchronized with `Token::can_begin_bound`.
5336 let is_bound_start = self.check_path() || self.check_lifetime() ||
5337 self.check(&token::Not) || // used for error reporting only
5338 self.check(&token::Question) ||
5339 self.check_keyword(kw::For) ||
5340 self.check(&token::OpenDelim(token::Paren));
5343 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5344 let inner_lo = self.span;
5345 let is_negative = self.eat(&token::Not);
5346 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5347 if self.token.is_lifetime() {
5348 if let Some(question_span) = question {
5349 self.span_err(question_span,
5350 "`?` may only modify trait bounds, not lifetime bounds");
5352 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5354 let inner_span = inner_lo.to(self.prev_span);
5355 self.expect(&token::CloseDelim(token::Paren))?;
5356 let mut err = self.struct_span_err(
5357 lo.to(self.prev_span),
5358 "parenthesized lifetime bounds are not supported"
5360 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5361 err.span_suggestion_short(
5362 lo.to(self.prev_span),
5363 "remove the parentheses",
5365 Applicability::MachineApplicable
5371 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5372 let path = self.parse_path(PathStyle::Type)?;
5374 self.expect(&token::CloseDelim(token::Paren))?;
5376 let poly_span = lo.to(self.prev_span);
5378 was_negative = true;
5379 if let Some(sp) = last_plus_span.or(colon_span) {
5380 negative_bounds.push(sp.to(poly_span));
5383 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5384 let modifier = if question.is_some() {
5385 TraitBoundModifier::Maybe
5387 TraitBoundModifier::None
5389 bounds.push(GenericBound::Trait(poly_trait, modifier));
5396 if !allow_plus || !self.eat_plus() {
5399 last_plus_span = Some(self.prev_span);
5403 if !negative_bounds.is_empty() || was_negative {
5404 let plural = negative_bounds.len() > 1;
5405 let last_span = negative_bounds.last().map(|sp| *sp);
5406 let mut err = self.struct_span_err(
5408 "negative trait bounds are not supported",
5410 if let Some(sp) = last_span {
5411 err.span_label(sp, "negative trait bounds are not supported");
5413 if let Some(bound_list) = colon_span {
5414 let bound_list = bound_list.to(self.prev_span);
5415 let mut new_bound_list = String::new();
5416 if !bounds.is_empty() {
5417 let mut snippets = bounds.iter().map(|bound| bound.span())
5418 .map(|span| self.sess.source_map().span_to_snippet(span));
5419 while let Some(Ok(snippet)) = snippets.next() {
5420 new_bound_list.push_str(" + ");
5421 new_bound_list.push_str(&snippet);
5423 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5425 err.span_suggestion_hidden(
5427 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5429 Applicability::MachineApplicable,
5438 crate fn parse_generic_bounds(&mut self,
5439 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5440 self.parse_generic_bounds_common(true, colon_span)
5443 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5446 /// BOUND = LT_BOUND (e.g., `'a`)
5448 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5449 let mut lifetimes = Vec::new();
5450 while self.check_lifetime() {
5451 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5453 if !self.eat_plus() {
5460 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5461 fn parse_ty_param(&mut self,
5462 preceding_attrs: Vec<Attribute>)
5463 -> PResult<'a, GenericParam> {
5464 let ident = self.parse_ident()?;
5466 // Parse optional colon and param bounds.
5467 let bounds = if self.eat(&token::Colon) {
5468 self.parse_generic_bounds(Some(self.prev_span))?
5473 let default = if self.eat(&token::Eq) {
5474 Some(self.parse_ty()?)
5481 id: ast::DUMMY_NODE_ID,
5482 attrs: preceding_attrs.into(),
5484 kind: GenericParamKind::Type {
5490 /// Parses the following grammar:
5492 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5493 fn parse_trait_item_assoc_ty(&mut self)
5494 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5495 let ident = self.parse_ident()?;
5496 let mut generics = self.parse_generics()?;
5498 // Parse optional colon and param bounds.
5499 let bounds = if self.eat(&token::Colon) {
5500 self.parse_generic_bounds(None)?
5504 generics.where_clause = self.parse_where_clause()?;
5506 let default = if self.eat(&token::Eq) {
5507 Some(self.parse_ty()?)
5511 self.expect(&token::Semi)?;
5513 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5516 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5517 self.expect_keyword(kw::Const)?;
5518 let ident = self.parse_ident()?;
5519 self.expect(&token::Colon)?;
5520 let ty = self.parse_ty()?;
5524 id: ast::DUMMY_NODE_ID,
5525 attrs: preceding_attrs.into(),
5527 kind: GenericParamKind::Const {
5533 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5534 /// a trailing comma and erroneous trailing attributes.
5535 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5536 let mut params = Vec::new();
5538 let attrs = self.parse_outer_attributes()?;
5539 if self.check_lifetime() {
5540 let lifetime = self.expect_lifetime();
5541 // Parse lifetime parameter.
5542 let bounds = if self.eat(&token::Colon) {
5543 self.parse_lt_param_bounds()
5547 params.push(ast::GenericParam {
5548 ident: lifetime.ident,
5550 attrs: attrs.into(),
5552 kind: ast::GenericParamKind::Lifetime,
5554 } else if self.check_keyword(kw::Const) {
5555 // Parse const parameter.
5556 params.push(self.parse_const_param(attrs)?);
5557 } else if self.check_ident() {
5558 // Parse type parameter.
5559 params.push(self.parse_ty_param(attrs)?);
5561 // Check for trailing attributes and stop parsing.
5562 if !attrs.is_empty() {
5563 if !params.is_empty() {
5564 self.struct_span_err(
5566 &format!("trailing attribute after generic parameter"),
5568 .span_label(attrs[0].span, "attributes must go before parameters")
5571 self.struct_span_err(
5573 &format!("attribute without generic parameters"),
5577 "attributes are only permitted when preceding parameters",
5585 if !self.eat(&token::Comma) {
5592 /// Parses a set of optional generic type parameter declarations. Where
5593 /// clauses are not parsed here, and must be added later via
5594 /// `parse_where_clause()`.
5596 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5597 /// | ( < lifetimes , typaramseq ( , )? > )
5598 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5599 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5600 let span_lo = self.span;
5602 let params = self.parse_generic_params()?;
5606 where_clause: WhereClause {
5607 id: ast::DUMMY_NODE_ID,
5608 predicates: Vec::new(),
5609 span: syntax_pos::DUMMY_SP,
5611 span: span_lo.to(self.prev_span),
5614 Ok(ast::Generics::default())
5618 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5619 /// For the purposes of understanding the parsing logic of generic arguments, this function
5620 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5621 /// had the correct amount of leading angle brackets.
5623 /// ```ignore (diagnostics)
5624 /// bar::<<<<T as Foo>::Output>();
5625 /// ^^ help: remove extra angle brackets
5627 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5631 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5632 // We need to detect whether there are extra leading left angle brackets and produce an
5633 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5634 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5635 // then there won't be matching `>` tokens to find.
5637 // To explain how this detection works, consider the following example:
5639 // ```ignore (diagnostics)
5640 // bar::<<<<T as Foo>::Output>();
5641 // ^^ help: remove extra angle brackets
5644 // Parsing of the left angle brackets starts in this function. We start by parsing the
5645 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5648 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5649 // *Unmatched count:* 1
5650 // *`parse_path_segment` calls deep:* 0
5652 // This has the effect of recursing as this function is called if a `<` character
5653 // is found within the expected generic arguments:
5655 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5656 // *Unmatched count:* 2
5657 // *`parse_path_segment` calls deep:* 1
5659 // Eventually we will have recursed until having consumed all of the `<` tokens and
5660 // this will be reflected in the count:
5662 // *Upcoming tokens:* `T as Foo>::Output>;`
5663 // *Unmatched count:* 4
5664 // `parse_path_segment` calls deep:* 3
5666 // The parser will continue until reaching the first `>` - this will decrement the
5667 // unmatched angle bracket count and return to the parent invocation of this function
5668 // having succeeded in parsing:
5670 // *Upcoming tokens:* `::Output>;`
5671 // *Unmatched count:* 3
5672 // *`parse_path_segment` calls deep:* 2
5674 // This will continue until the next `>` character which will also return successfully
5675 // to the parent invocation of this function and decrement the count:
5677 // *Upcoming tokens:* `;`
5678 // *Unmatched count:* 2
5679 // *`parse_path_segment` calls deep:* 1
5681 // At this point, this function will expect to find another matching `>` character but
5682 // won't be able to and will return an error. This will continue all the way up the
5683 // call stack until the first invocation:
5685 // *Upcoming tokens:* `;`
5686 // *Unmatched count:* 2
5687 // *`parse_path_segment` calls deep:* 0
5689 // In doing this, we have managed to work out how many unmatched leading left angle
5690 // brackets there are, but we cannot recover as the unmatched angle brackets have
5691 // already been consumed. To remedy this, we keep a snapshot of the parser state
5692 // before we do the above. We can then inspect whether we ended up with a parsing error
5693 // and unmatched left angle brackets and if so, restore the parser state before we
5694 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5695 // recover by attempting to parse again.
5697 // In practice, the recursion of this function is indirect and there will be other
5698 // locations that consume some `<` characters - as long as we update the count when
5699 // this happens, it isn't an issue.
5701 let is_first_invocation = style == PathStyle::Expr;
5702 // Take a snapshot before attempting to parse - we can restore this later.
5703 let snapshot = if is_first_invocation {
5709 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5710 match self.parse_generic_args() {
5711 Ok(value) => Ok(value),
5712 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5713 // Cancel error from being unable to find `>`. We know the error
5714 // must have been this due to a non-zero unmatched angle bracket
5718 // Swap `self` with our backup of the parser state before attempting to parse
5719 // generic arguments.
5720 let snapshot = mem::replace(self, snapshot.unwrap());
5723 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5724 snapshot.count={:?}",
5725 snapshot.unmatched_angle_bracket_count,
5728 // Eat the unmatched angle brackets.
5729 for _ in 0..snapshot.unmatched_angle_bracket_count {
5733 // Make a span over ${unmatched angle bracket count} characters.
5734 let span = lo.with_hi(
5735 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5737 let plural = snapshot.unmatched_angle_bracket_count > 1;
5742 "unmatched angle bracket{}",
5743 if plural { "s" } else { "" }
5749 "remove extra angle bracket{}",
5750 if plural { "s" } else { "" }
5753 Applicability::MachineApplicable,
5757 // Try again without unmatched angle bracket characters.
5758 self.parse_generic_args()
5764 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5765 /// possibly including trailing comma.
5766 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5767 let mut args = Vec::new();
5768 let mut bindings = Vec::new();
5769 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
5770 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
5772 let args_lo = self.span;
5775 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5776 // Parse lifetime argument.
5777 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5778 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5779 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5780 // Parse associated type binding.
5782 let ident = self.parse_ident()?;
5784 let ty = self.parse_ty()?;
5785 let span = lo.to(self.prev_span);
5786 bindings.push(TypeBinding {
5787 id: ast::DUMMY_NODE_ID,
5792 assoc_ty_bindings.push(span);
5793 } else if self.check_const_arg() {
5794 // Parse const argument.
5795 let expr = if let token::OpenDelim(token::Brace) = self.token {
5796 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
5797 } else if self.token.is_ident() {
5798 // FIXME(const_generics): to distinguish between idents for types and consts,
5799 // we should introduce a GenericArg::Ident in the AST and distinguish when
5800 // lowering to the HIR. For now, idents for const args are not permitted.
5802 self.fatal("identifiers may currently not be used for const generics")
5805 self.parse_literal_maybe_minus()?
5807 let value = AnonConst {
5808 id: ast::DUMMY_NODE_ID,
5811 args.push(GenericArg::Const(value));
5812 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5813 } else if self.check_type() {
5814 // Parse type argument.
5815 args.push(GenericArg::Type(self.parse_ty()?));
5816 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5821 if !self.eat(&token::Comma) {
5826 // FIXME: we would like to report this in ast_validation instead, but we currently do not
5827 // preserve ordering of generic parameters with respect to associated type binding, so we
5828 // lose that information after parsing.
5829 if misplaced_assoc_ty_bindings.len() > 0 {
5830 let mut err = self.struct_span_err(
5831 args_lo.to(self.prev_span),
5832 "associated type bindings must be declared after generic parameters",
5834 for span in misplaced_assoc_ty_bindings {
5837 "this associated type binding should be moved after the generic parameters",
5843 Ok((args, bindings))
5846 /// Parses an optional where-clause and places it in `generics`.
5848 /// ```ignore (only-for-syntax-highlight)
5849 /// where T : Trait<U, V> + 'b, 'a : 'b
5851 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5852 let mut where_clause = WhereClause {
5853 id: ast::DUMMY_NODE_ID,
5854 predicates: Vec::new(),
5855 span: syntax_pos::DUMMY_SP,
5858 if !self.eat_keyword(kw::Where) {
5859 return Ok(where_clause);
5861 let lo = self.prev_span;
5863 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5864 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5865 // change we parse those generics now, but report an error.
5866 if self.choose_generics_over_qpath() {
5867 let generics = self.parse_generics()?;
5868 self.struct_span_err(
5870 "generic parameters on `where` clauses are reserved for future use",
5872 .span_label(generics.span, "currently unsupported")
5878 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5879 let lifetime = self.expect_lifetime();
5880 // Bounds starting with a colon are mandatory, but possibly empty.
5881 self.expect(&token::Colon)?;
5882 let bounds = self.parse_lt_param_bounds();
5883 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5884 ast::WhereRegionPredicate {
5885 span: lo.to(self.prev_span),
5890 } else if self.check_type() {
5891 // Parse optional `for<'a, 'b>`.
5892 // This `for` is parsed greedily and applies to the whole predicate,
5893 // the bounded type can have its own `for` applying only to it.
5894 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5895 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5896 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5897 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5899 // Parse type with mandatory colon and (possibly empty) bounds,
5900 // or with mandatory equality sign and the second type.
5901 let ty = self.parse_ty()?;
5902 if self.eat(&token::Colon) {
5903 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
5904 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5905 ast::WhereBoundPredicate {
5906 span: lo.to(self.prev_span),
5907 bound_generic_params: lifetime_defs,
5912 // FIXME: Decide what should be used here, `=` or `==`.
5913 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5914 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5915 let rhs_ty = self.parse_ty()?;
5916 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5917 ast::WhereEqPredicate {
5918 span: lo.to(self.prev_span),
5921 id: ast::DUMMY_NODE_ID,
5925 return self.unexpected();
5931 if !self.eat(&token::Comma) {
5936 where_clause.span = lo.to(self.prev_span);
5940 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
5941 -> PResult<'a, (Vec<Arg> , bool)> {
5942 self.expect(&token::OpenDelim(token::Paren))?;
5945 let mut c_variadic = false;
5946 let (args, recovered): (Vec<Option<Arg>>, bool) =
5947 self.parse_seq_to_before_end(
5948 &token::CloseDelim(token::Paren),
5949 SeqSep::trailing_allowed(token::Comma),
5951 // If the argument is a C-variadic argument we should not
5952 // enforce named arguments.
5953 let enforce_named_args = if p.token == token::DotDotDot {
5958 match p.parse_arg_general(enforce_named_args, false,
5961 if let TyKind::CVarArgs = arg.ty.node {
5963 if p.token != token::CloseDelim(token::Paren) {
5966 "`...` must be the last argument of a C-variadic function");
5977 let lo = p.prev_span;
5978 // Skip every token until next possible arg or end.
5979 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5980 // Create a placeholder argument for proper arg count (issue #34264).
5981 let span = lo.to(p.prev_span);
5982 Ok(Some(dummy_arg(span)))
5989 self.eat(&token::CloseDelim(token::Paren));
5992 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5994 if c_variadic && args.is_empty() {
5996 "C-variadic function must be declared with at least one named argument");
5999 Ok((args, c_variadic))
6002 /// Parses the argument list and result type of a function declaration.
6003 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6005 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6006 let ret_ty = self.parse_ret_ty(true)?;
6015 /// Returns the parsed optional self argument and whether a self shortcut was used.
6016 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6017 let expect_ident = |this: &mut Self| match this.token {
6018 // Preserve hygienic context.
6019 token::Ident(ident, _) =>
6020 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6023 let isolated_self = |this: &mut Self, n| {
6024 this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
6025 this.look_ahead(n + 1, |t| t != &token::ModSep)
6028 // Parse optional self parameter of a method.
6029 // Only a limited set of initial token sequences is considered self parameters, anything
6030 // else is parsed as a normal function parameter list, so some lookahead is required.
6031 let eself_lo = self.span;
6032 let (eself, eself_ident, eself_hi) = match self.token {
6033 token::BinOp(token::And) => {
6039 (if isolated_self(self, 1) {
6041 SelfKind::Region(None, Mutability::Immutable)
6042 } else if self.look_ahead(1, |t| t.is_keyword(kw::Mut)) &&
6043 isolated_self(self, 2) {
6046 SelfKind::Region(None, Mutability::Mutable)
6047 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6048 isolated_self(self, 2) {
6050 let lt = self.expect_lifetime();
6051 SelfKind::Region(Some(lt), Mutability::Immutable)
6052 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6053 self.look_ahead(2, |t| t.is_keyword(kw::Mut)) &&
6054 isolated_self(self, 3) {
6056 let lt = self.expect_lifetime();
6058 SelfKind::Region(Some(lt), Mutability::Mutable)
6061 }, expect_ident(self), self.prev_span)
6063 token::BinOp(token::Star) => {
6068 // Emit special error for `self` cases.
6069 let msg = "cannot pass `self` by raw pointer";
6070 (if isolated_self(self, 1) {
6072 self.struct_span_err(self.span, msg)
6073 .span_label(self.span, msg)
6075 SelfKind::Value(Mutability::Immutable)
6076 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6077 isolated_self(self, 2) {
6080 self.struct_span_err(self.span, msg)
6081 .span_label(self.span, msg)
6083 SelfKind::Value(Mutability::Immutable)
6086 }, expect_ident(self), self.prev_span)
6088 token::Ident(..) => {
6089 if isolated_self(self, 0) {
6092 let eself_ident = expect_ident(self);
6093 let eself_hi = self.prev_span;
6094 (if self.eat(&token::Colon) {
6095 let ty = self.parse_ty()?;
6096 SelfKind::Explicit(ty, Mutability::Immutable)
6098 SelfKind::Value(Mutability::Immutable)
6099 }, eself_ident, eself_hi)
6100 } else if self.token.is_keyword(kw::Mut) &&
6101 isolated_self(self, 1) {
6105 let eself_ident = expect_ident(self);
6106 let eself_hi = self.prev_span;
6107 (if self.eat(&token::Colon) {
6108 let ty = self.parse_ty()?;
6109 SelfKind::Explicit(ty, Mutability::Mutable)
6111 SelfKind::Value(Mutability::Mutable)
6112 }, eself_ident, eself_hi)
6117 _ => return Ok(None),
6120 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6121 Ok(Some(Arg::from_self(eself, eself_ident)))
6124 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6125 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6126 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6128 self.expect(&token::OpenDelim(token::Paren))?;
6130 // Parse optional self argument
6131 let self_arg = self.parse_self_arg()?;
6133 // Parse the rest of the function parameter list.
6134 let sep = SeqSep::trailing_allowed(token::Comma);
6135 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6136 if self.check(&token::CloseDelim(token::Paren)) {
6137 (vec![self_arg], false)
6138 } else if self.eat(&token::Comma) {
6139 let mut fn_inputs = vec![self_arg];
6140 let (mut input, recovered) = self.parse_seq_to_before_end(
6141 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6142 fn_inputs.append(&mut input);
6143 (fn_inputs, recovered)
6145 match self.expect_one_of(&[], &[]) {
6146 Err(err) => return Err(err),
6147 Ok(recovered) => (vec![self_arg], recovered),
6151 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6155 // Parse closing paren and return type.
6156 self.expect(&token::CloseDelim(token::Paren))?;
6160 output: self.parse_ret_ty(true)?,
6165 /// Parses the `|arg, arg|` header of a closure.
6166 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6167 let inputs_captures = {
6168 if self.eat(&token::OrOr) {
6171 self.expect(&token::BinOp(token::Or))?;
6172 let args = self.parse_seq_to_before_tokens(
6173 &[&token::BinOp(token::Or), &token::OrOr],
6174 SeqSep::trailing_allowed(token::Comma),
6175 TokenExpectType::NoExpect,
6176 |p| p.parse_fn_block_arg()
6182 let output = self.parse_ret_ty(true)?;
6185 inputs: inputs_captures,
6191 /// Parses the name and optional generic types of a function header.
6192 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6193 let id = self.parse_ident()?;
6194 let generics = self.parse_generics()?;
6198 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6199 attrs: Vec<Attribute>) -> P<Item> {
6203 id: ast::DUMMY_NODE_ID,
6211 /// Parses an item-position function declaration.
6212 fn parse_item_fn(&mut self,
6214 mut asyncness: Spanned<IsAsync>,
6215 constness: Spanned<Constness>,
6217 -> PResult<'a, ItemInfo> {
6218 let (ident, mut generics) = self.parse_fn_header()?;
6219 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6220 let mut decl = self.parse_fn_decl(allow_c_variadic)?;
6221 generics.where_clause = self.parse_where_clause()?;
6222 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6223 self.construct_async_arguments(&mut asyncness, &mut decl);
6224 let header = FnHeader { unsafety, asyncness, constness, abi };
6225 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6228 /// Returns `true` if we are looking at `const ID`
6229 /// (returns `false` for things like `const fn`, etc.).
6230 fn is_const_item(&self) -> bool {
6231 self.token.is_keyword(kw::Const) &&
6232 !self.look_ahead(1, |t| t.is_keyword(kw::Fn)) &&
6233 !self.look_ahead(1, |t| t.is_keyword(kw::Unsafe))
6236 /// Parses all the "front matter" for a `fn` declaration, up to
6237 /// and including the `fn` keyword:
6241 /// - `const unsafe fn`
6244 fn parse_fn_front_matter(&mut self)
6252 let is_const_fn = self.eat_keyword(kw::Const);
6253 let const_span = self.prev_span;
6254 let unsafety = self.parse_unsafety();
6255 let asyncness = self.parse_asyncness();
6256 let asyncness = respan(self.prev_span, asyncness);
6257 let (constness, unsafety, abi) = if is_const_fn {
6258 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6260 let abi = if self.eat_keyword(kw::Extern) {
6261 self.parse_opt_abi()?.unwrap_or(Abi::C)
6265 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6267 if !self.eat_keyword(kw::Fn) {
6268 // It is possible for `expect_one_of` to recover given the contents of
6269 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6270 // account for this.
6271 if !self.expect_one_of(&[], &[])? { unreachable!() }
6273 Ok((constness, unsafety, asyncness, abi))
6276 /// Parses an impl item.
6277 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6278 maybe_whole!(self, NtImplItem, |x| x);
6279 let attrs = self.parse_outer_attributes()?;
6280 let mut unclosed_delims = vec![];
6281 let (mut item, tokens) = self.collect_tokens(|this| {
6282 let item = this.parse_impl_item_(at_end, attrs);
6283 unclosed_delims.append(&mut this.unclosed_delims);
6286 self.unclosed_delims.append(&mut unclosed_delims);
6288 // See `parse_item` for why this clause is here.
6289 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6290 item.tokens = Some(tokens);
6295 fn parse_impl_item_(&mut self,
6297 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6299 let vis = self.parse_visibility(false)?;
6300 let defaultness = self.parse_defaultness();
6301 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6302 let (name, alias, generics) = type_?;
6303 let kind = match alias {
6304 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6305 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6307 (name, kind, generics)
6308 } else if self.is_const_item() {
6309 // This parses the grammar:
6310 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6311 self.expect_keyword(kw::Const)?;
6312 let name = self.parse_ident()?;
6313 self.expect(&token::Colon)?;
6314 let typ = self.parse_ty()?;
6315 self.expect(&token::Eq)?;
6316 let expr = self.parse_expr()?;
6317 self.expect(&token::Semi)?;
6318 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6320 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6321 attrs.extend(inner_attrs);
6322 (name, node, generics)
6326 id: ast::DUMMY_NODE_ID,
6327 span: lo.to(self.prev_span),
6338 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
6340 VisibilityKind::Inherited => {}
6342 let is_macro_rules: bool = match self.token {
6343 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6346 let mut err = if is_macro_rules {
6347 let mut err = self.diagnostic()
6348 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6349 err.span_suggestion(
6351 "try exporting the macro",
6352 "#[macro_export]".to_owned(),
6353 Applicability::MaybeIncorrect // speculative
6357 let mut err = self.diagnostic()
6358 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6359 err.help("try adjusting the macro to put `pub` inside the invocation");
6367 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
6368 -> DiagnosticBuilder<'a>
6370 let expected_kinds = if item_type == "extern" {
6371 "missing `fn`, `type`, or `static`"
6373 "missing `fn`, `type`, or `const`"
6376 // Given this code `path(`, it seems like this is not
6377 // setting the visibility of a macro invocation, but rather
6378 // a mistyped method declaration.
6379 // Create a diagnostic pointing out that `fn` is missing.
6381 // x | pub path(&self) {
6382 // | ^ missing `fn`, `type`, or `const`
6384 // ^^ `sp` below will point to this
6385 let sp = prev_span.between(self.prev_span);
6386 let mut err = self.diagnostic().struct_span_err(
6388 &format!("{} for {}-item declaration",
6389 expected_kinds, item_type));
6390 err.span_label(sp, expected_kinds);
6394 /// Parse a method or a macro invocation in a trait impl.
6395 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6396 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6397 ast::ImplItemKind)> {
6398 // code copied from parse_macro_use_or_failure... abstraction!
6399 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6401 Ok((Ident::invalid(), vec![], ast::Generics::default(),
6402 ast::ImplItemKind::Macro(mac)))
6404 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6405 let ident = self.parse_ident()?;
6406 let mut generics = self.parse_generics()?;
6407 let mut decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6408 generics.where_clause = self.parse_where_clause()?;
6409 self.construct_async_arguments(&mut asyncness, &mut decl);
6411 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6412 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6413 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6414 ast::MethodSig { header, decl },
6420 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6421 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6422 let ident = self.parse_ident()?;
6423 let mut tps = self.parse_generics()?;
6425 // Parse optional colon and supertrait bounds.
6426 let bounds = if self.eat(&token::Colon) {
6427 self.parse_generic_bounds(Some(self.prev_span))?
6432 if self.eat(&token::Eq) {
6433 // it's a trait alias
6434 let bounds = self.parse_generic_bounds(None)?;
6435 tps.where_clause = self.parse_where_clause()?;
6436 self.expect(&token::Semi)?;
6437 if is_auto == IsAuto::Yes {
6438 let msg = "trait aliases cannot be `auto`";
6439 self.struct_span_err(self.prev_span, msg)
6440 .span_label(self.prev_span, msg)
6443 if unsafety != Unsafety::Normal {
6444 let msg = "trait aliases cannot be `unsafe`";
6445 self.struct_span_err(self.prev_span, msg)
6446 .span_label(self.prev_span, msg)
6449 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6451 // it's a normal trait
6452 tps.where_clause = self.parse_where_clause()?;
6453 self.expect(&token::OpenDelim(token::Brace))?;
6454 let mut trait_items = vec![];
6455 while !self.eat(&token::CloseDelim(token::Brace)) {
6456 if let token::DocComment(_) = self.token {
6457 if self.look_ahead(1,
6458 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6459 let mut err = self.diagnostic().struct_span_err_with_code(
6461 "found a documentation comment that doesn't document anything",
6462 DiagnosticId::Error("E0584".into()),
6464 err.help("doc comments must come before what they document, maybe a \
6465 comment was intended with `//`?",
6472 let mut at_end = false;
6473 match self.parse_trait_item(&mut at_end) {
6474 Ok(item) => trait_items.push(item),
6478 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6483 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6487 fn choose_generics_over_qpath(&self) -> bool {
6488 // There's an ambiguity between generic parameters and qualified paths in impls.
6489 // If we see `<` it may start both, so we have to inspect some following tokens.
6490 // The following combinations can only start generics,
6491 // but not qualified paths (with one exception):
6492 // `<` `>` - empty generic parameters
6493 // `<` `#` - generic parameters with attributes
6494 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6495 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6496 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6497 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6498 // `<` const - generic const parameter
6499 // The only truly ambiguous case is
6500 // `<` IDENT `>` `::` IDENT ...
6501 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6502 // because this is what almost always expected in practice, qualified paths in impls
6503 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6504 self.token == token::Lt &&
6505 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6506 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6507 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6508 t == &token::Colon || t == &token::Eq) ||
6509 self.look_ahead(1, |t| t.is_keyword(kw::Const)))
6512 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6513 self.expect(&token::OpenDelim(token::Brace))?;
6514 let attrs = self.parse_inner_attributes()?;
6516 let mut impl_items = Vec::new();
6517 while !self.eat(&token::CloseDelim(token::Brace)) {
6518 let mut at_end = false;
6519 match self.parse_impl_item(&mut at_end) {
6520 Ok(impl_item) => impl_items.push(impl_item),
6524 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6529 Ok((impl_items, attrs))
6532 /// Parses an implementation item, `impl` keyword is already parsed.
6534 /// impl<'a, T> TYPE { /* impl items */ }
6535 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6536 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6538 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6539 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6540 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6541 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6542 -> PResult<'a, ItemInfo> {
6543 // First, parse generic parameters if necessary.
6544 let mut generics = if self.choose_generics_over_qpath() {
6545 self.parse_generics()?
6547 ast::Generics::default()
6550 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6551 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6553 ast::ImplPolarity::Negative
6555 ast::ImplPolarity::Positive
6558 // Parse both types and traits as a type, then reinterpret if necessary.
6559 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
6560 let ty_first = if self.token.is_keyword(kw::For) &&
6561 self.look_ahead(1, |t| t != &token::Lt) {
6562 let span = self.prev_span.between(self.span);
6563 self.struct_span_err(span, "missing trait in a trait impl").emit();
6564 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6569 // If `for` is missing we try to recover.
6570 let has_for = self.eat_keyword(kw::For);
6571 let missing_for_span = self.prev_span.between(self.span);
6573 let ty_second = if self.token == token::DotDot {
6574 // We need to report this error after `cfg` expansion for compatibility reasons
6575 self.bump(); // `..`, do not add it to expected tokens
6576 Some(DummyResult::raw_ty(self.prev_span, true))
6577 } else if has_for || self.token.can_begin_type() {
6578 Some(self.parse_ty()?)
6583 generics.where_clause = self.parse_where_clause()?;
6585 let (impl_items, attrs) = self.parse_impl_body()?;
6587 let item_kind = match ty_second {
6588 Some(ty_second) => {
6589 // impl Trait for Type
6591 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6592 .span_suggestion_short(
6595 " for ".to_string(),
6596 Applicability::MachineApplicable,
6600 let ty_first = ty_first.into_inner();
6601 let path = match ty_first.node {
6602 // This notably includes paths passed through `ty` macro fragments (#46438).
6603 TyKind::Path(None, path) => path,
6605 self.span_err(ty_first.span, "expected a trait, found type");
6606 err_path(ty_first.span)
6609 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6611 ItemKind::Impl(unsafety, polarity, defaultness,
6612 generics, Some(trait_ref), ty_second, impl_items)
6616 ItemKind::Impl(unsafety, polarity, defaultness,
6617 generics, None, ty_first, impl_items)
6621 Ok((Ident::invalid(), item_kind, Some(attrs)))
6624 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6625 if self.eat_keyword(kw::For) {
6627 let params = self.parse_generic_params()?;
6629 // We rely on AST validation to rule out invalid cases: There must not be type
6630 // parameters, and the lifetime parameters must not have bounds.
6637 /// Parses `struct Foo { ... }`.
6638 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6639 let class_name = self.parse_ident()?;
6641 let mut generics = self.parse_generics()?;
6643 // There is a special case worth noting here, as reported in issue #17904.
6644 // If we are parsing a tuple struct it is the case that the where clause
6645 // should follow the field list. Like so:
6647 // struct Foo<T>(T) where T: Copy;
6649 // If we are parsing a normal record-style struct it is the case
6650 // that the where clause comes before the body, and after the generics.
6651 // So if we look ahead and see a brace or a where-clause we begin
6652 // parsing a record style struct.
6654 // Otherwise if we look ahead and see a paren we parse a tuple-style
6657 let vdata = if self.token.is_keyword(kw::Where) {
6658 generics.where_clause = self.parse_where_clause()?;
6659 if self.eat(&token::Semi) {
6660 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6661 VariantData::Unit(ast::DUMMY_NODE_ID)
6663 // If we see: `struct Foo<T> where T: Copy { ... }`
6664 let (fields, recovered) = self.parse_record_struct_body()?;
6665 VariantData::Struct(fields, recovered)
6667 // No `where` so: `struct Foo<T>;`
6668 } else if self.eat(&token::Semi) {
6669 VariantData::Unit(ast::DUMMY_NODE_ID)
6670 // Record-style struct definition
6671 } else if self.token == token::OpenDelim(token::Brace) {
6672 let (fields, recovered) = self.parse_record_struct_body()?;
6673 VariantData::Struct(fields, recovered)
6674 // Tuple-style struct definition with optional where-clause.
6675 } else if self.token == token::OpenDelim(token::Paren) {
6676 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6677 generics.where_clause = self.parse_where_clause()?;
6678 self.expect(&token::Semi)?;
6681 let token_str = self.this_token_descr();
6682 let mut err = self.fatal(&format!(
6683 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6686 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6690 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6693 /// Parses `union Foo { ... }`.
6694 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6695 let class_name = self.parse_ident()?;
6697 let mut generics = self.parse_generics()?;
6699 let vdata = if self.token.is_keyword(kw::Where) {
6700 generics.where_clause = self.parse_where_clause()?;
6701 let (fields, recovered) = self.parse_record_struct_body()?;
6702 VariantData::Struct(fields, recovered)
6703 } else if self.token == token::OpenDelim(token::Brace) {
6704 let (fields, recovered) = self.parse_record_struct_body()?;
6705 VariantData::Struct(fields, recovered)
6707 let token_str = self.this_token_descr();
6708 let mut err = self.fatal(&format!(
6709 "expected `where` or `{{` after union name, found {}", token_str));
6710 err.span_label(self.span, "expected `where` or `{` after union name");
6714 Ok((class_name, ItemKind::Union(vdata, generics), None))
6717 fn parse_record_struct_body(
6719 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6720 let mut fields = Vec::new();
6721 let mut recovered = false;
6722 if self.eat(&token::OpenDelim(token::Brace)) {
6723 while self.token != token::CloseDelim(token::Brace) {
6724 let field = self.parse_struct_decl_field().map_err(|e| {
6725 self.recover_stmt();
6730 Ok(field) => fields.push(field),
6736 self.eat(&token::CloseDelim(token::Brace));
6738 let token_str = self.this_token_descr();
6739 let mut err = self.fatal(&format!(
6740 "expected `where`, or `{{` after struct name, found {}", token_str));
6741 err.span_label(self.span, "expected `where`, or `{` after struct name");
6745 Ok((fields, recovered))
6748 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6749 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6750 // Unit like structs are handled in parse_item_struct function
6751 let fields = self.parse_unspanned_seq(
6752 &token::OpenDelim(token::Paren),
6753 &token::CloseDelim(token::Paren),
6754 SeqSep::trailing_allowed(token::Comma),
6756 let attrs = p.parse_outer_attributes()?;
6758 let vis = p.parse_visibility(true)?;
6759 let ty = p.parse_ty()?;
6761 span: lo.to(ty.span),
6764 id: ast::DUMMY_NODE_ID,
6773 /// Parses a structure field declaration.
6774 fn parse_single_struct_field(&mut self,
6777 attrs: Vec<Attribute> )
6778 -> PResult<'a, StructField> {
6779 let mut seen_comma: bool = false;
6780 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6781 if self.token == token::Comma {
6788 token::CloseDelim(token::Brace) => {}
6789 token::DocComment(_) => {
6790 let previous_span = self.prev_span;
6791 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6792 self.bump(); // consume the doc comment
6793 let comma_after_doc_seen = self.eat(&token::Comma);
6794 // `seen_comma` is always false, because we are inside doc block
6795 // condition is here to make code more readable
6796 if seen_comma == false && comma_after_doc_seen == true {
6799 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6802 if seen_comma == false {
6803 let sp = self.sess.source_map().next_point(previous_span);
6804 err.span_suggestion(
6806 "missing comma here",
6808 Applicability::MachineApplicable
6815 let sp = self.sess.source_map().next_point(self.prev_span);
6816 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6817 self.this_token_descr()));
6818 if self.token.is_ident() {
6819 // This is likely another field; emit the diagnostic and keep going
6820 err.span_suggestion(
6822 "try adding a comma",
6824 Applicability::MachineApplicable,
6835 /// Parses an element of a struct declaration.
6836 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6837 let attrs = self.parse_outer_attributes()?;
6839 let vis = self.parse_visibility(false)?;
6840 self.parse_single_struct_field(lo, vis, attrs)
6843 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6844 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6845 /// If the following element can't be a tuple (i.e., it's a function definition), then
6846 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6847 /// so emit a proper diagnostic.
6848 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6849 maybe_whole!(self, NtVis, |x| x);
6851 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
6852 if self.is_crate_vis() {
6853 self.bump(); // `crate`
6854 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6857 if !self.eat_keyword(kw::Pub) {
6858 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6859 // keyword to grab a span from for inherited visibility; an empty span at the
6860 // beginning of the current token would seem to be the "Schelling span".
6861 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6863 let lo = self.prev_span;
6865 if self.check(&token::OpenDelim(token::Paren)) {
6866 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6867 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6868 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6869 // by the following tokens.
6870 if self.look_ahead(1, |t| t.is_keyword(kw::Crate)) &&
6871 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
6875 self.bump(); // `crate`
6876 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6878 lo.to(self.prev_span),
6879 VisibilityKind::Crate(CrateSugar::PubCrate),
6882 } else if self.look_ahead(1, |t| t.is_keyword(kw::In)) {
6885 self.bump(); // `in`
6886 let path = self.parse_path(PathStyle::Mod)?; // `path`
6887 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6888 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6890 id: ast::DUMMY_NODE_ID,
6893 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6894 self.look_ahead(1, |t| t.is_keyword(kw::Super) ||
6895 t.is_keyword(kw::SelfLower))
6897 // `pub(self)` or `pub(super)`
6899 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6900 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6901 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6903 id: ast::DUMMY_NODE_ID,
6906 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6907 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6909 let msg = "incorrect visibility restriction";
6910 let suggestion = r##"some possible visibility restrictions are:
6911 `pub(crate)`: visible only on the current crate
6912 `pub(super)`: visible only in the current module's parent
6913 `pub(in path::to::module)`: visible only on the specified path"##;
6914 let path = self.parse_path(PathStyle::Mod)?;
6916 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6917 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6918 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6919 err.help(suggestion);
6920 err.span_suggestion(
6921 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6923 err.emit(); // emit diagnostic, but continue with public visibility
6927 Ok(respan(lo, VisibilityKind::Public))
6930 /// Parses defaultness (i.e., `default` or nothing).
6931 fn parse_defaultness(&mut self) -> Defaultness {
6932 // `pub` is included for better error messages
6933 if self.check_keyword(kw::Default) &&
6934 self.look_ahead(1, |t| t.is_keyword(kw::Impl) ||
6935 t.is_keyword(kw::Const) ||
6936 t.is_keyword(kw::Fn) ||
6937 t.is_keyword(kw::Unsafe) ||
6938 t.is_keyword(kw::Extern) ||
6939 t.is_keyword(kw::Type) ||
6940 t.is_keyword(kw::Pub)) {
6941 self.bump(); // `default`
6942 Defaultness::Default
6948 /// Given a termination token, parses all of the items in a module.
6949 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6950 let mut items = vec![];
6951 while let Some(item) = self.parse_item()? {
6953 self.maybe_consume_incorrect_semicolon(&items);
6956 if !self.eat(term) {
6957 let token_str = self.this_token_descr();
6958 if !self.maybe_consume_incorrect_semicolon(&items) {
6959 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6960 err.span_label(self.span, "expected item");
6965 let hi = if self.span.is_dummy() {
6972 inner: inner_lo.to(hi),
6978 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6979 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6980 self.expect(&token::Colon)?;
6981 let ty = self.parse_ty()?;
6982 self.expect(&token::Eq)?;
6983 let e = self.parse_expr()?;
6984 self.expect(&token::Semi)?;
6985 let item = match m {
6986 Some(m) => ItemKind::Static(ty, m, e),
6987 None => ItemKind::Const(ty, e),
6989 Ok((id, item, None))
6992 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6993 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6994 let (in_cfg, outer_attrs) = {
6995 let mut strip_unconfigured = crate::config::StripUnconfigured {
6997 features: None, // don't perform gated feature checking
6999 let mut outer_attrs = outer_attrs.to_owned();
7000 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7001 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7004 let id_span = self.span;
7005 let id = self.parse_ident()?;
7006 if self.eat(&token::Semi) {
7007 if in_cfg && self.recurse_into_file_modules {
7008 // This mod is in an external file. Let's go get it!
7009 let ModulePathSuccess { path, directory_ownership, warn } =
7010 self.submod_path(id, &outer_attrs, id_span)?;
7011 let (module, mut attrs) =
7012 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7013 // Record that we fetched the mod from an external file
7015 let attr = Attribute {
7016 id: attr::mk_attr_id(),
7017 style: ast::AttrStyle::Outer,
7018 path: ast::Path::from_ident(
7019 Ident::with_empty_ctxt(sym::warn_directory_ownership)),
7020 tokens: TokenStream::empty(),
7021 is_sugared_doc: false,
7022 span: syntax_pos::DUMMY_SP,
7024 attr::mark_known(&attr);
7027 Ok((id, ItemKind::Mod(module), Some(attrs)))
7029 let placeholder = ast::Mod {
7030 inner: syntax_pos::DUMMY_SP,
7034 Ok((id, ItemKind::Mod(placeholder), None))
7037 let old_directory = self.directory.clone();
7038 self.push_directory(id, &outer_attrs);
7040 self.expect(&token::OpenDelim(token::Brace))?;
7041 let mod_inner_lo = self.span;
7042 let attrs = self.parse_inner_attributes()?;
7043 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7045 self.directory = old_directory;
7046 Ok((id, ItemKind::Mod(module), Some(attrs)))
7050 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7051 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
7052 self.directory.path.to_mut().push(&path.as_str());
7053 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7055 // We have to push on the current module name in the case of relative
7056 // paths in order to ensure that any additional module paths from inline
7057 // `mod x { ... }` come after the relative extension.
7059 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7060 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7061 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7062 if let Some(ident) = relative.take() { // remove the relative offset
7063 self.directory.path.to_mut().push(ident.as_str());
7066 self.directory.path.to_mut().push(&id.as_str());
7070 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7071 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
7074 // On windows, the base path might have the form
7075 // `\\?\foo\bar` in which case it does not tolerate
7076 // mixed `/` and `\` separators, so canonicalize
7079 let s = s.replace("/", "\\");
7080 Some(dir_path.join(s))
7086 /// Returns a path to a module.
7087 pub fn default_submod_path(
7089 relative: Option<ast::Ident>,
7091 source_map: &SourceMap) -> ModulePath
7093 // If we're in a foo.rs file instead of a mod.rs file,
7094 // we need to look for submodules in
7095 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7096 // `./<id>.rs` and `./<id>/mod.rs`.
7097 let relative_prefix_string;
7098 let relative_prefix = if let Some(ident) = relative {
7099 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7100 &relative_prefix_string
7105 let mod_name = id.to_string();
7106 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7107 let secondary_path_str = format!("{}{}{}mod.rs",
7108 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7109 let default_path = dir_path.join(&default_path_str);
7110 let secondary_path = dir_path.join(&secondary_path_str);
7111 let default_exists = source_map.file_exists(&default_path);
7112 let secondary_exists = source_map.file_exists(&secondary_path);
7114 let result = match (default_exists, secondary_exists) {
7115 (true, false) => Ok(ModulePathSuccess {
7117 directory_ownership: DirectoryOwnership::Owned {
7122 (false, true) => Ok(ModulePathSuccess {
7123 path: secondary_path,
7124 directory_ownership: DirectoryOwnership::Owned {
7129 (false, false) => Err(Error::FileNotFoundForModule {
7130 mod_name: mod_name.clone(),
7131 default_path: default_path_str,
7132 secondary_path: secondary_path_str,
7133 dir_path: dir_path.display().to_string(),
7135 (true, true) => Err(Error::DuplicatePaths {
7136 mod_name: mod_name.clone(),
7137 default_path: default_path_str,
7138 secondary_path: secondary_path_str,
7144 path_exists: default_exists || secondary_exists,
7149 fn submod_path(&mut self,
7151 outer_attrs: &[Attribute],
7153 -> PResult<'a, ModulePathSuccess> {
7154 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7155 return Ok(ModulePathSuccess {
7156 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7157 // All `#[path]` files are treated as though they are a `mod.rs` file.
7158 // This means that `mod foo;` declarations inside `#[path]`-included
7159 // files are siblings,
7161 // Note that this will produce weirdness when a file named `foo.rs` is
7162 // `#[path]` included and contains a `mod foo;` declaration.
7163 // If you encounter this, it's your own darn fault :P
7164 Some(_) => DirectoryOwnership::Owned { relative: None },
7165 _ => DirectoryOwnership::UnownedViaMod(true),
7172 let relative = match self.directory.ownership {
7173 DirectoryOwnership::Owned { relative } => relative,
7174 DirectoryOwnership::UnownedViaBlock |
7175 DirectoryOwnership::UnownedViaMod(_) => None,
7177 let paths = Parser::default_submod_path(
7178 id, relative, &self.directory.path, self.sess.source_map());
7180 match self.directory.ownership {
7181 DirectoryOwnership::Owned { .. } => {
7182 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7184 DirectoryOwnership::UnownedViaBlock => {
7186 "Cannot declare a non-inline module inside a block \
7187 unless it has a path attribute";
7188 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7189 if paths.path_exists {
7190 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7192 err.span_note(id_sp, &msg);
7196 DirectoryOwnership::UnownedViaMod(warn) => {
7198 if let Ok(result) = paths.result {
7199 return Ok(ModulePathSuccess { warn: true, ..result });
7202 let mut err = self.diagnostic().struct_span_err(id_sp,
7203 "cannot declare a new module at this location");
7204 if !id_sp.is_dummy() {
7205 let src_path = self.sess.source_map().span_to_filename(id_sp);
7206 if let FileName::Real(src_path) = src_path {
7207 if let Some(stem) = src_path.file_stem() {
7208 let mut dest_path = src_path.clone();
7209 dest_path.set_file_name(stem);
7210 dest_path.push("mod.rs");
7211 err.span_note(id_sp,
7212 &format!("maybe move this module `{}` to its own \
7213 directory via `{}`", src_path.display(),
7214 dest_path.display()));
7218 if paths.path_exists {
7219 err.span_note(id_sp,
7220 &format!("... or maybe `use` the module `{}` instead \
7221 of possibly redeclaring it",
7229 /// Reads a module from a source file.
7230 fn eval_src_mod(&mut self,
7232 directory_ownership: DirectoryOwnership,
7235 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7236 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7237 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7238 let mut err = String::from("circular modules: ");
7239 let len = included_mod_stack.len();
7240 for p in &included_mod_stack[i.. len] {
7241 err.push_str(&p.to_string_lossy());
7242 err.push_str(" -> ");
7244 err.push_str(&path.to_string_lossy());
7245 return Err(self.span_fatal(id_sp, &err[..]));
7247 included_mod_stack.push(path.clone());
7248 drop(included_mod_stack);
7251 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7252 p0.cfg_mods = self.cfg_mods;
7253 let mod_inner_lo = p0.span;
7254 let mod_attrs = p0.parse_inner_attributes()?;
7255 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7257 self.sess.included_mod_stack.borrow_mut().pop();
7261 /// Parses a function declaration from a foreign module.
7262 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7263 -> PResult<'a, ForeignItem> {
7264 self.expect_keyword(kw::Fn)?;
7266 let (ident, mut generics) = self.parse_fn_header()?;
7267 let decl = self.parse_fn_decl(true)?;
7268 generics.where_clause = self.parse_where_clause()?;
7270 self.expect(&token::Semi)?;
7271 Ok(ast::ForeignItem {
7274 node: ForeignItemKind::Fn(decl, generics),
7275 id: ast::DUMMY_NODE_ID,
7281 /// Parses a static item from a foreign module.
7282 /// Assumes that the `static` keyword is already parsed.
7283 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7284 -> PResult<'a, ForeignItem> {
7285 let mutbl = self.parse_mutability();
7286 let ident = self.parse_ident()?;
7287 self.expect(&token::Colon)?;
7288 let ty = self.parse_ty()?;
7290 self.expect(&token::Semi)?;
7294 node: ForeignItemKind::Static(ty, mutbl),
7295 id: ast::DUMMY_NODE_ID,
7301 /// Parses a type from a foreign module.
7302 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7303 -> PResult<'a, ForeignItem> {
7304 self.expect_keyword(kw::Type)?;
7306 let ident = self.parse_ident()?;
7308 self.expect(&token::Semi)?;
7309 Ok(ast::ForeignItem {
7312 node: ForeignItemKind::Ty,
7313 id: ast::DUMMY_NODE_ID,
7319 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7320 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7321 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7323 let mut ident = if self.token.is_keyword(kw::SelfLower) {
7324 self.parse_path_segment_ident()
7328 let mut idents = vec![];
7329 let mut replacement = vec![];
7330 let mut fixed_crate_name = false;
7331 // Accept `extern crate name-like-this` for better diagnostics
7332 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7333 if self.token == dash { // Do not include `-` as part of the expected tokens list
7334 while self.eat(&dash) {
7335 fixed_crate_name = true;
7336 replacement.push((self.prev_span, "_".to_string()));
7337 idents.push(self.parse_ident()?);
7340 if fixed_crate_name {
7341 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7342 let mut fixed_name = format!("{}", ident.name);
7343 for part in idents {
7344 fixed_name.push_str(&format!("_{}", part.name));
7346 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7348 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7349 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7350 err.multipart_suggestion(
7353 Applicability::MachineApplicable,
7360 /// Parses `extern crate` links.
7365 /// extern crate foo;
7366 /// extern crate bar as foo;
7368 fn parse_item_extern_crate(&mut self,
7370 visibility: Visibility,
7371 attrs: Vec<Attribute>)
7372 -> PResult<'a, P<Item>> {
7373 // Accept `extern crate name-like-this` for better diagnostics
7374 let orig_name = self.parse_crate_name_with_dashes()?;
7375 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7376 (rename, Some(orig_name.name))
7380 self.expect(&token::Semi)?;
7382 let span = lo.to(self.prev_span);
7383 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7386 /// Parses `extern` for foreign ABIs modules.
7388 /// `extern` is expected to have been
7389 /// consumed before calling this method.
7393 /// ```ignore (only-for-syntax-highlight)
7397 fn parse_item_foreign_mod(&mut self,
7399 opt_abi: Option<Abi>,
7400 visibility: Visibility,
7401 mut attrs: Vec<Attribute>)
7402 -> PResult<'a, P<Item>> {
7403 self.expect(&token::OpenDelim(token::Brace))?;
7405 let abi = opt_abi.unwrap_or(Abi::C);
7407 attrs.extend(self.parse_inner_attributes()?);
7409 let mut foreign_items = vec![];
7410 while !self.eat(&token::CloseDelim(token::Brace)) {
7411 foreign_items.push(self.parse_foreign_item()?);
7414 let prev_span = self.prev_span;
7415 let m = ast::ForeignMod {
7417 items: foreign_items
7419 let invalid = Ident::invalid();
7420 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7423 /// Parses `type Foo = Bar;`
7425 /// `existential type Foo: Bar;`
7428 /// without modifying the parser state.
7429 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7430 // This parses the grammar:
7431 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7432 if self.check_keyword(kw::Type) ||
7433 self.check_keyword(kw::Existential) &&
7434 self.look_ahead(1, |t| t.is_keyword(kw::Type)) {
7435 let existential = self.eat_keyword(kw::Existential);
7436 assert!(self.eat_keyword(kw::Type));
7437 Some(self.parse_existential_or_alias(existential))
7443 /// Parses a type alias or existential type.
7444 fn parse_existential_or_alias(
7447 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7448 let ident = self.parse_ident()?;
7449 let mut tps = self.parse_generics()?;
7450 tps.where_clause = self.parse_where_clause()?;
7451 let alias = if existential {
7452 self.expect(&token::Colon)?;
7453 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7454 AliasKind::Existential(bounds)
7456 self.expect(&token::Eq)?;
7457 let ty = self.parse_ty()?;
7460 self.expect(&token::Semi)?;
7461 Ok((ident, alias, tps))
7464 /// Parses the part of an enum declaration following the `{`.
7465 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7466 let mut variants = Vec::new();
7467 let mut all_nullary = true;
7468 let mut any_disr = vec![];
7469 while self.token != token::CloseDelim(token::Brace) {
7470 let variant_attrs = self.parse_outer_attributes()?;
7471 let vlo = self.span;
7474 let mut disr_expr = None;
7476 let ident = self.parse_ident()?;
7477 if self.check(&token::OpenDelim(token::Brace)) {
7478 // Parse a struct variant.
7479 all_nullary = false;
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 all_nullary = false;
7484 struct_def = VariantData::Tuple(
7485 self.parse_tuple_struct_body()?,
7488 } else if self.eat(&token::Eq) {
7489 disr_expr = Some(AnonConst {
7490 id: ast::DUMMY_NODE_ID,
7491 value: self.parse_expr()?,
7493 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7496 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7498 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7501 let vr = ast::Variant_ {
7503 id: ast::DUMMY_NODE_ID,
7504 attrs: variant_attrs,
7508 variants.push(respan(vlo.to(self.prev_span), vr));
7510 if !self.eat(&token::Comma) {
7511 if self.token.is_ident() && !self.token.is_reserved_ident() {
7512 let sp = self.sess.source_map().next_point(self.prev_span);
7513 let mut err = self.struct_span_err(sp, "missing comma");
7514 err.span_suggestion_short(
7518 Applicability::MaybeIncorrect,
7526 self.expect(&token::CloseDelim(token::Brace))?;
7527 if !any_disr.is_empty() && !all_nullary {
7528 let mut err = self.struct_span_err(
7530 "discriminator values can only be used with a field-less enum",
7532 for sp in any_disr {
7533 err.span_label(sp, "only valid in field-less enums");
7538 Ok(ast::EnumDef { variants })
7541 /// Parses an enum declaration.
7542 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7543 let id = self.parse_ident()?;
7544 let mut generics = self.parse_generics()?;
7545 generics.where_clause = self.parse_where_clause()?;
7546 self.expect(&token::OpenDelim(token::Brace))?;
7548 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7549 self.recover_stmt();
7550 self.eat(&token::CloseDelim(token::Brace));
7553 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7556 /// Parses a string as an ABI spec on an extern type or module. Consumes
7557 /// the `extern` keyword, if one is found.
7558 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7560 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7562 self.expect_no_suffix(sp, "an ABI spec", suf);
7564 match abi::lookup(&s.as_str()) {
7565 Some(abi) => Ok(Some(abi)),
7567 let prev_span = self.prev_span;
7568 let mut err = struct_span_err!(
7569 self.sess.span_diagnostic,
7572 "invalid ABI: found `{}`",
7574 err.span_label(prev_span, "invalid ABI");
7575 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7586 fn is_static_global(&mut self) -> bool {
7587 if self.check_keyword(kw::Static) {
7588 // Check if this could be a closure
7589 !self.look_ahead(1, |token| {
7590 if token.is_keyword(kw::Move) {
7594 token::BinOp(token::Or) | token::OrOr => true,
7605 attrs: Vec<Attribute>,
7606 macros_allowed: bool,
7607 attributes_allowed: bool,
7608 ) -> PResult<'a, Option<P<Item>>> {
7609 let mut unclosed_delims = vec![];
7610 let (ret, tokens) = self.collect_tokens(|this| {
7611 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7612 unclosed_delims.append(&mut this.unclosed_delims);
7615 self.unclosed_delims.append(&mut unclosed_delims);
7617 // Once we've parsed an item and recorded the tokens we got while
7618 // parsing we may want to store `tokens` into the item we're about to
7619 // return. Note, though, that we specifically didn't capture tokens
7620 // related to outer attributes. The `tokens` field here may later be
7621 // used with procedural macros to convert this item back into a token
7622 // stream, but during expansion we may be removing attributes as we go
7625 // If we've got inner attributes then the `tokens` we've got above holds
7626 // these inner attributes. If an inner attribute is expanded we won't
7627 // actually remove it from the token stream, so we'll just keep yielding
7628 // it (bad!). To work around this case for now we just avoid recording
7629 // `tokens` if we detect any inner attributes. This should help keep
7630 // expansion correct, but we should fix this bug one day!
7633 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7634 i.tokens = Some(tokens);
7641 /// Parses one of the items allowed by the flags.
7642 fn parse_item_implementation(
7644 attrs: Vec<Attribute>,
7645 macros_allowed: bool,
7646 attributes_allowed: bool,
7647 ) -> PResult<'a, Option<P<Item>>> {
7648 maybe_whole!(self, NtItem, |item| {
7649 let mut item = item.into_inner();
7650 let mut attrs = attrs;
7651 mem::swap(&mut item.attrs, &mut attrs);
7652 item.attrs.extend(attrs);
7658 let visibility = self.parse_visibility(false)?;
7660 if self.eat_keyword(kw::Use) {
7662 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7663 self.expect(&token::Semi)?;
7665 let span = lo.to(self.prev_span);
7667 self.mk_item(span, Ident::invalid(), item_, visibility, attrs);
7668 return Ok(Some(item));
7671 if self.eat_keyword(kw::Extern) {
7672 if self.eat_keyword(kw::Crate) {
7673 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7676 let opt_abi = self.parse_opt_abi()?;
7678 if self.eat_keyword(kw::Fn) {
7679 // EXTERN FUNCTION ITEM
7680 let fn_span = self.prev_span;
7681 let abi = opt_abi.unwrap_or(Abi::C);
7682 let (ident, item_, extra_attrs) =
7683 self.parse_item_fn(Unsafety::Normal,
7684 respan(fn_span, IsAsync::NotAsync),
7685 respan(fn_span, Constness::NotConst),
7687 let prev_span = self.prev_span;
7688 let item = self.mk_item(lo.to(prev_span),
7692 maybe_append(attrs, extra_attrs));
7693 return Ok(Some(item));
7694 } else if self.check(&token::OpenDelim(token::Brace)) {
7695 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7701 if self.is_static_global() {
7704 let m = if self.eat_keyword(kw::Mut) {
7707 Mutability::Immutable
7709 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7710 let prev_span = self.prev_span;
7711 let item = self.mk_item(lo.to(prev_span),
7715 maybe_append(attrs, extra_attrs));
7716 return Ok(Some(item));
7718 if self.eat_keyword(kw::Const) {
7719 let const_span = self.prev_span;
7720 if self.check_keyword(kw::Fn)
7721 || (self.check_keyword(kw::Unsafe)
7722 && self.look_ahead(1, |t| t.is_keyword(kw::Fn))) {
7723 // CONST FUNCTION ITEM
7724 let unsafety = self.parse_unsafety();
7726 let (ident, item_, extra_attrs) =
7727 self.parse_item_fn(unsafety,
7728 respan(const_span, IsAsync::NotAsync),
7729 respan(const_span, Constness::Const),
7731 let prev_span = self.prev_span;
7732 let item = self.mk_item(lo.to(prev_span),
7736 maybe_append(attrs, extra_attrs));
7737 return Ok(Some(item));
7741 if self.eat_keyword(kw::Mut) {
7742 let prev_span = self.prev_span;
7743 let mut err = self.diagnostic()
7744 .struct_span_err(prev_span, "const globals cannot be mutable");
7745 err.span_label(prev_span, "cannot be mutable");
7746 err.span_suggestion(
7748 "you might want to declare a static instead",
7749 "static".to_owned(),
7750 Applicability::MaybeIncorrect,
7754 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7755 let prev_span = self.prev_span;
7756 let item = self.mk_item(lo.to(prev_span),
7760 maybe_append(attrs, extra_attrs));
7761 return Ok(Some(item));
7764 // `unsafe async fn` or `async fn`
7766 self.check_keyword(kw::Unsafe) &&
7767 self.look_ahead(1, |t| t.is_keyword(kw::Async))
7769 self.check_keyword(kw::Async) &&
7770 self.look_ahead(1, |t| t.is_keyword(kw::Fn))
7773 // ASYNC FUNCTION ITEM
7774 let unsafety = self.parse_unsafety();
7775 self.expect_keyword(kw::Async)?;
7776 let async_span = self.prev_span;
7777 self.expect_keyword(kw::Fn)?;
7778 let fn_span = self.prev_span;
7779 let (ident, item_, extra_attrs) =
7780 self.parse_item_fn(unsafety,
7781 respan(async_span, IsAsync::Async {
7782 closure_id: ast::DUMMY_NODE_ID,
7783 return_impl_trait_id: ast::DUMMY_NODE_ID,
7784 arguments: Vec::new(),
7786 respan(fn_span, Constness::NotConst),
7788 let prev_span = self.prev_span;
7789 let item = self.mk_item(lo.to(prev_span),
7793 maybe_append(attrs, extra_attrs));
7794 if self.span.rust_2015() {
7795 self.diagnostic().struct_span_err_with_code(
7797 "`async fn` is not permitted in the 2015 edition",
7798 DiagnosticId::Error("E0670".into())
7801 return Ok(Some(item));
7803 if self.check_keyword(kw::Unsafe) &&
7804 (self.look_ahead(1, |t| t.is_keyword(kw::Trait)) ||
7805 self.look_ahead(1, |t| t.is_keyword(kw::Auto)))
7807 // UNSAFE TRAIT ITEM
7808 self.bump(); // `unsafe`
7809 let is_auto = if self.eat_keyword(kw::Trait) {
7812 self.expect_keyword(kw::Auto)?;
7813 self.expect_keyword(kw::Trait)?;
7816 let (ident, item_, extra_attrs) =
7817 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7818 let prev_span = self.prev_span;
7819 let item = self.mk_item(lo.to(prev_span),
7823 maybe_append(attrs, extra_attrs));
7824 return Ok(Some(item));
7826 if self.check_keyword(kw::Impl) ||
7827 self.check_keyword(kw::Unsafe) &&
7828 self.look_ahead(1, |t| t.is_keyword(kw::Impl)) ||
7829 self.check_keyword(kw::Default) &&
7830 self.look_ahead(1, |t| t.is_keyword(kw::Impl)) ||
7831 self.check_keyword(kw::Default) &&
7832 self.look_ahead(1, |t| t.is_keyword(kw::Unsafe)) {
7834 let defaultness = self.parse_defaultness();
7835 let unsafety = self.parse_unsafety();
7836 self.expect_keyword(kw::Impl)?;
7837 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7838 let span = lo.to(self.prev_span);
7839 return Ok(Some(self.mk_item(span, ident, item, visibility,
7840 maybe_append(attrs, extra_attrs))));
7842 if self.check_keyword(kw::Fn) {
7845 let fn_span = self.prev_span;
7846 let (ident, item_, extra_attrs) =
7847 self.parse_item_fn(Unsafety::Normal,
7848 respan(fn_span, IsAsync::NotAsync),
7849 respan(fn_span, Constness::NotConst),
7851 let prev_span = self.prev_span;
7852 let item = self.mk_item(lo.to(prev_span),
7856 maybe_append(attrs, extra_attrs));
7857 return Ok(Some(item));
7859 if self.check_keyword(kw::Unsafe)
7860 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7861 // UNSAFE FUNCTION ITEM
7862 self.bump(); // `unsafe`
7863 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7864 self.check(&token::OpenDelim(token::Brace));
7865 let abi = if self.eat_keyword(kw::Extern) {
7866 self.parse_opt_abi()?.unwrap_or(Abi::C)
7870 self.expect_keyword(kw::Fn)?;
7871 let fn_span = self.prev_span;
7872 let (ident, item_, extra_attrs) =
7873 self.parse_item_fn(Unsafety::Unsafe,
7874 respan(fn_span, IsAsync::NotAsync),
7875 respan(fn_span, Constness::NotConst),
7877 let prev_span = self.prev_span;
7878 let item = self.mk_item(lo.to(prev_span),
7882 maybe_append(attrs, extra_attrs));
7883 return Ok(Some(item));
7885 if self.eat_keyword(kw::Mod) {
7887 let (ident, item_, extra_attrs) =
7888 self.parse_item_mod(&attrs[..])?;
7889 let prev_span = self.prev_span;
7890 let item = self.mk_item(lo.to(prev_span),
7894 maybe_append(attrs, extra_attrs));
7895 return Ok(Some(item));
7897 if let Some(type_) = self.eat_type() {
7898 let (ident, alias, generics) = type_?;
7900 let item_ = match alias {
7901 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7902 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7904 let prev_span = self.prev_span;
7905 let item = self.mk_item(lo.to(prev_span),
7910 return Ok(Some(item));
7912 if self.eat_keyword(kw::Enum) {
7914 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7915 let prev_span = self.prev_span;
7916 let item = self.mk_item(lo.to(prev_span),
7920 maybe_append(attrs, extra_attrs));
7921 return Ok(Some(item));
7923 if self.check_keyword(kw::Trait)
7924 || (self.check_keyword(kw::Auto)
7925 && self.look_ahead(1, |t| t.is_keyword(kw::Trait)))
7927 let is_auto = if self.eat_keyword(kw::Trait) {
7930 self.expect_keyword(kw::Auto)?;
7931 self.expect_keyword(kw::Trait)?;
7935 let (ident, item_, extra_attrs) =
7936 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7937 let prev_span = self.prev_span;
7938 let item = self.mk_item(lo.to(prev_span),
7942 maybe_append(attrs, extra_attrs));
7943 return Ok(Some(item));
7945 if self.eat_keyword(kw::Struct) {
7947 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7948 let prev_span = self.prev_span;
7949 let item = self.mk_item(lo.to(prev_span),
7953 maybe_append(attrs, extra_attrs));
7954 return Ok(Some(item));
7956 if self.is_union_item() {
7959 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7960 let prev_span = self.prev_span;
7961 let item = self.mk_item(lo.to(prev_span),
7965 maybe_append(attrs, extra_attrs));
7966 return Ok(Some(item));
7968 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7969 return Ok(Some(macro_def));
7972 // Verify whether we have encountered a struct or method definition where the user forgot to
7973 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7974 if visibility.node.is_pub() &&
7975 self.check_ident() &&
7976 self.look_ahead(1, |t| *t != token::Not)
7978 // Space between `pub` keyword and the identifier
7981 // ^^^ `sp` points here
7982 let sp = self.prev_span.between(self.span);
7983 let full_sp = self.prev_span.to(self.span);
7984 let ident_sp = self.span;
7985 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7986 // possible public struct definition where `struct` was forgotten
7987 let ident = self.parse_ident().unwrap();
7988 let msg = format!("add `struct` here to parse `{}` as a public struct",
7990 let mut err = self.diagnostic()
7991 .struct_span_err(sp, "missing `struct` for struct definition");
7992 err.span_suggestion_short(
7993 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7996 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7997 let ident = self.parse_ident().unwrap();
7999 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8004 self.consume_block(token::Paren);
8005 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8006 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8008 ("fn", kw_name, false)
8009 } else if self.check(&token::OpenDelim(token::Brace)) {
8011 ("fn", kw_name, false)
8012 } else if self.check(&token::Colon) {
8016 ("fn` or `struct", "function or struct", true)
8019 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8020 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8022 self.consume_block(token::Brace);
8023 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8027 err.span_suggestion_short(
8028 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8031 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8032 err.span_suggestion(
8034 "if you meant to call a macro, try",
8035 format!("{}!", snippet),
8036 // this is the `ambiguous` conditional branch
8037 Applicability::MaybeIncorrect
8040 err.help("if you meant to call a macro, remove the `pub` \
8041 and add a trailing `!` after the identifier");
8045 } else if self.look_ahead(1, |t| *t == token::Lt) {
8046 let ident = self.parse_ident().unwrap();
8047 self.eat_to_tokens(&[&token::Gt]);
8049 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8050 if let Ok(Some(_)) = self.parse_self_arg() {
8051 ("fn", "method", false)
8053 ("fn", "function", false)
8055 } else if self.check(&token::OpenDelim(token::Brace)) {
8056 ("struct", "struct", false)
8058 ("fn` or `struct", "function or struct", true)
8060 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8061 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8063 err.span_suggestion_short(
8065 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8066 format!(" {} ", kw),
8067 Applicability::MachineApplicable,
8073 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8076 /// Parses a foreign item.
8077 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8078 maybe_whole!(self, NtForeignItem, |ni| ni);
8080 let attrs = self.parse_outer_attributes()?;
8082 let visibility = self.parse_visibility(false)?;
8084 // FOREIGN STATIC ITEM
8085 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8086 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
8087 if self.token.is_keyword(kw::Const) {
8089 .struct_span_err(self.span, "extern items cannot be `const`")
8092 "try using a static value",
8093 "static".to_owned(),
8094 Applicability::MachineApplicable
8097 self.bump(); // `static` or `const`
8098 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8100 // FOREIGN FUNCTION ITEM
8101 if self.check_keyword(kw::Fn) {
8102 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8104 // FOREIGN TYPE ITEM
8105 if self.check_keyword(kw::Type) {
8106 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8109 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8113 ident: Ident::invalid(),
8114 span: lo.to(self.prev_span),
8115 id: ast::DUMMY_NODE_ID,
8118 node: ForeignItemKind::Macro(mac),
8123 if !attrs.is_empty() {
8124 self.expected_item_err(&attrs)?;
8132 /// This is the fall-through for parsing items.
8133 fn parse_macro_use_or_failure(
8135 attrs: Vec<Attribute> ,
8136 macros_allowed: bool,
8137 attributes_allowed: bool,
8139 visibility: Visibility
8140 ) -> PResult<'a, Option<P<Item>>> {
8141 if macros_allowed && self.token.is_path_start() &&
8142 !(self.is_async_fn() && self.span.rust_2015()) {
8143 // MACRO INVOCATION ITEM
8145 let prev_span = self.prev_span;
8146 self.complain_if_pub_macro(&visibility.node, prev_span);
8148 let mac_lo = self.span;
8151 let pth = self.parse_path(PathStyle::Mod)?;
8152 self.expect(&token::Not)?;
8154 // a 'special' identifier (like what `macro_rules!` uses)
8155 // is optional. We should eventually unify invoc syntax
8157 let id = if self.token.is_ident() {
8160 Ident::invalid() // no special identifier
8162 // eat a matched-delimiter token tree:
8163 let (delim, tts) = self.expect_delimited_token_tree()?;
8164 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8165 self.report_invalid_macro_expansion_item();
8168 let hi = self.prev_span;
8169 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8170 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8171 return Ok(Some(item));
8174 // FAILURE TO PARSE ITEM
8175 match visibility.node {
8176 VisibilityKind::Inherited => {}
8178 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8182 if !attributes_allowed && !attrs.is_empty() {
8183 self.expected_item_err(&attrs)?;
8188 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8189 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8190 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8192 if self.token.is_path_start() &&
8193 !(self.is_async_fn() && self.span.rust_2015()) {
8194 let prev_span = self.prev_span;
8196 let pth = self.parse_path(PathStyle::Mod)?;
8198 if pth.segments.len() == 1 {
8199 if !self.eat(&token::Not) {
8200 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8203 self.expect(&token::Not)?;
8206 if let Some(vis) = vis {
8207 self.complain_if_pub_macro(&vis.node, prev_span);
8212 // eat a matched-delimiter token tree:
8213 let (delim, tts) = self.expect_delimited_token_tree()?;
8214 if delim != MacDelimiter::Brace {
8215 self.expect(&token::Semi)?;
8218 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8224 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8225 where F: FnOnce(&mut Self) -> PResult<'a, R>
8227 // Record all tokens we parse when parsing this item.
8228 let mut tokens = Vec::new();
8229 let prev_collecting = match self.token_cursor.frame.last_token {
8230 LastToken::Collecting(ref mut list) => {
8231 Some(mem::replace(list, Vec::new()))
8233 LastToken::Was(ref mut last) => {
8234 tokens.extend(last.take());
8238 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8239 let prev = self.token_cursor.stack.len();
8241 let last_token = if self.token_cursor.stack.len() == prev {
8242 &mut self.token_cursor.frame.last_token
8244 &mut self.token_cursor.stack[prev].last_token
8247 // Pull out the tokens that we've collected from the call to `f` above.
8248 let mut collected_tokens = match *last_token {
8249 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8250 LastToken::Was(_) => panic!("our vector went away?"),
8253 // If we're not at EOF our current token wasn't actually consumed by
8254 // `f`, but it'll still be in our list that we pulled out. In that case
8256 let extra_token = if self.token != token::Eof {
8257 collected_tokens.pop()
8262 // If we were previously collecting tokens, then this was a recursive
8263 // call. In that case we need to record all the tokens we collected in
8264 // our parent list as well. To do that we push a clone of our stream
8265 // onto the previous list.
8266 match prev_collecting {
8268 list.extend(collected_tokens.iter().cloned());
8269 list.extend(extra_token);
8270 *last_token = LastToken::Collecting(list);
8273 *last_token = LastToken::Was(extra_token);
8277 Ok((ret?, TokenStream::new(collected_tokens)))
8280 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8281 let attrs = self.parse_outer_attributes()?;
8282 self.parse_item_(attrs, true, false)
8286 fn is_import_coupler(&mut self) -> bool {
8287 self.check(&token::ModSep) &&
8288 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8289 *t == token::BinOp(token::Star))
8292 /// Parses a `UseTree`.
8295 /// USE_TREE = [`::`] `*` |
8296 /// [`::`] `{` USE_TREE_LIST `}` |
8298 /// PATH `::` `{` USE_TREE_LIST `}` |
8299 /// PATH [`as` IDENT]
8301 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8304 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8305 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8306 self.check(&token::BinOp(token::Star)) ||
8307 self.is_import_coupler() {
8308 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8309 let mod_sep_ctxt = self.span.ctxt();
8310 if self.eat(&token::ModSep) {
8311 prefix.segments.push(
8312 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8316 if self.eat(&token::BinOp(token::Star)) {
8319 UseTreeKind::Nested(self.parse_use_tree_list()?)
8322 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8323 prefix = self.parse_path(PathStyle::Mod)?;
8325 if self.eat(&token::ModSep) {
8326 if self.eat(&token::BinOp(token::Star)) {
8329 UseTreeKind::Nested(self.parse_use_tree_list()?)
8332 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8336 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8339 /// Parses a `UseTreeKind::Nested(list)`.
8342 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8344 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8345 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8346 &token::CloseDelim(token::Brace),
8347 SeqSep::trailing_allowed(token::Comma), |this| {
8348 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8352 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8353 if self.eat_keyword(kw::As) {
8354 self.parse_ident_or_underscore().map(Some)
8360 /// Parses a source module as a crate. This is the main entry point for the parser.
8361 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8363 let krate = Ok(ast::Crate {
8364 attrs: self.parse_inner_attributes()?,
8365 module: self.parse_mod_items(&token::Eof, lo)?,
8366 span: lo.to(self.span),
8371 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8372 let ret = match self.token {
8373 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8374 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8381 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8382 match self.parse_optional_str() {
8383 Some((s, style, suf)) => {
8384 let sp = self.prev_span;
8385 self.expect_no_suffix(sp, "a string literal", suf);
8389 let msg = "expected string literal";
8390 let mut err = self.fatal(msg);
8391 err.span_label(self.span, msg);
8397 fn report_invalid_macro_expansion_item(&self) {
8398 self.struct_span_err(
8400 "macros that expand to items must be delimited with braces or followed by a semicolon",
8401 ).multipart_suggestion(
8402 "change the delimiters to curly braces",
8404 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8405 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8407 Applicability::MaybeIncorrect,
8409 self.sess.source_map.next_point(self.prev_span),
8412 Applicability::MaybeIncorrect,
8416 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8417 /// into the generated closure so that they are dropped when the future is polled and not when
8420 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8421 /// this function and the statements created here are inserted at the top of the closure body.
8422 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &mut FnDecl) {
8423 // FIXME(davidtwco): This function should really live in the HIR lowering but because
8424 // the types constructed here need to be used in parts of resolve so that the correct
8425 // locals are considered upvars, it is currently easier for it to live here in the parser,
8426 // where it can be constructed once.
8427 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8428 for (index, input) in decl.inputs.iter_mut().enumerate() {
8429 let id = ast::DUMMY_NODE_ID;
8430 let span = input.pat.span;
8432 // Construct a name for our temporary argument.
8433 let name = format!("__arg{}", index);
8434 let ident = Ident::from_str(&name).gensym();
8436 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
8437 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
8439 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
8440 PatKind::Ident(binding_mode @ BindingMode::ByValue(_), ident, _) => {
8441 // Simple patterns like this don't have a generated argument, but they are
8442 // moved into the closure with a statement, so any `mut` bindings on the
8443 // argument will be unused. This binding mode can't be removed, because
8444 // this would affect the input to procedural macros, but they can have
8445 // their span marked as being the result of a compiler desugaring so
8446 // that they aren't linted against.
8447 input.pat.span = self.sess.source_map().mark_span_with_reason(
8448 CompilerDesugaringKind::Async, span, None);
8450 (binding_mode, ident, true)
8452 _ => (BindingMode::ByValue(Mutability::Mutable), ident, false),
8455 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8456 // async function if it isn't a simple pattern.
8457 let arg = if is_simple_pattern {
8461 ty: input.ty.clone(),
8465 node: PatKind::Ident(
8466 BindingMode::ByValue(Mutability::Immutable), ident, None,
8470 source: ArgSource::AsyncFn(input.pat.clone()),
8474 // Construct a `let __argN = __argN;` statement to insert at the top of the
8475 // async closure. This makes sure that the argument is captured by the closure and
8476 // that the drop order is correct.
8477 let move_local = Local {
8480 node: PatKind::Ident(binding_mode, ident, None),
8483 // We explicitly do not specify the type for this statement. When the user's
8484 // argument type is `impl Trait` then this would require the
8485 // `impl_trait_in_bindings` feature to also be present for that same type to
8486 // be valid in this binding. At the time of writing (13 Mar 19),
8487 // `impl_trait_in_bindings` is not stable.
8491 node: ExprKind::Path(None, ast::Path {
8493 segments: vec![PathSegment { ident, id, args: None }],
8496 attrs: ThinVec::new(),
8500 attrs: ThinVec::new(),
8501 source: LocalSource::AsyncFn,
8504 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8505 // async closure if this isn't a simple pattern.
8506 let pat_stmt = if is_simple_pattern {
8511 node: StmtKind::Local(P(Local {
8512 pat: input.pat.clone(),
8513 ..move_local.clone()
8519 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
8520 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
8526 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8527 for unmatched in unclosed_delims.iter() {
8528 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8529 "incorrect close delimiter: `{}`",
8530 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8532 err.span_label(unmatched.found_span, "incorrect close delimiter");
8533 if let Some(sp) = unmatched.candidate_span {
8534 err.span_label(sp, "close delimiter possibly meant for this");
8536 if let Some(sp) = unmatched.unclosed_span {
8537 err.span_label(sp, "un-closed delimiter");
8541 unclosed_delims.clear();