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, Lit, LitKind};
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::{self, SeqSep, classify, 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::{Symbol, keywords};
51 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
52 use rustc_target::spec::abi::{self, Abi};
54 Span, MultiSpan, BytePos, FileName,
55 hygiene::CompilerDesugaringKind,
57 use log::{debug, trace};
62 use std::path::{self, Path, PathBuf};
66 /// Whether the type alias or associated type is a concrete type or an existential type
68 /// Just a new name for the same type
70 /// Only trait impls of the type will be usable, not the actual type itself
71 Existential(GenericBounds),
75 struct Restrictions: u8 {
76 const STMT_EXPR = 1 << 0;
77 const NO_STRUCT_LITERAL = 1 << 1;
81 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
83 /// Specifies how to parse a path.
84 #[derive(Copy, Clone, PartialEq)]
86 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
87 /// with something else. For example, in expressions `segment < ....` can be interpreted
88 /// as a comparison and `segment ( ....` can be interpreted as a function call.
89 /// In all such contexts the non-path interpretation is preferred by default for practical
90 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
91 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
93 /// In other contexts, notably in types, no ambiguity exists and paths can be written
94 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
95 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
97 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
98 /// visibilities or attributes.
99 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
100 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
101 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
102 /// tokens when something goes wrong.
106 #[derive(Clone, Copy, PartialEq, Debug)]
113 #[derive(Clone, Copy, PartialEq, Debug)]
119 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
120 /// dropped into the token stream, which happens while parsing the result of
121 /// macro expansion). Placement of these is not as complex as I feared it would
122 /// be. The important thing is to make sure that lookahead doesn't balk at
123 /// `token::Interpolated` tokens.
124 macro_rules! maybe_whole_expr {
126 if let token::Interpolated(nt) = &$p.token {
128 token::NtExpr(e) | token::NtLiteral(e) => {
133 token::NtPath(path) => {
134 let path = path.clone();
136 return Ok($p.mk_expr($p.span, ExprKind::Path(None, path), ThinVec::new()));
138 token::NtBlock(block) => {
139 let block = block.clone();
141 return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
149 /// As maybe_whole_expr, but for things other than expressions
150 macro_rules! maybe_whole {
151 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
152 if let token::Interpolated(nt) = &$p.token {
153 if let token::$constructor(x) = &**nt {
162 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
163 macro_rules! maybe_recover_from_interpolated_ty_qpath {
164 ($self: expr, $allow_qpath_recovery: expr) => {
165 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
166 if let token::Interpolated(nt) = &$self.token {
167 if let token::NtTy(ty) = &**nt {
170 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
177 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
178 if let Some(ref mut rhs) = rhs {
184 #[derive(Debug, Clone, Copy, PartialEq)]
196 /* ident is handled by common.rs */
199 pub struct Parser<'a> {
200 pub sess: &'a ParseSess,
201 /// the current token:
202 pub token: token::Token,
203 /// the span of the current token:
205 /// the span of the previous token:
206 meta_var_span: Option<Span>,
208 /// the previous token kind
209 prev_token_kind: PrevTokenKind,
210 restrictions: Restrictions,
211 /// Used to determine the path to externally loaded source files
212 crate directory: Directory<'a>,
213 /// Whether to parse sub-modules in other files.
214 pub recurse_into_file_modules: bool,
215 /// Name of the root module this parser originated from. If `None`, then the
216 /// name is not known. This does not change while the parser is descending
217 /// into modules, and sub-parsers have new values for this name.
218 pub root_module_name: Option<String>,
219 crate expected_tokens: Vec<TokenType>,
220 token_cursor: TokenCursor,
221 desugar_doc_comments: bool,
222 /// Whether we should configure out of line modules as we parse.
224 /// This field is used to keep track of how many left angle brackets we have seen. This is
225 /// required in order to detect extra leading left angle brackets (`<` characters) and error
228 /// See the comments in the `parse_path_segment` function for more details.
229 crate unmatched_angle_bracket_count: u32,
230 crate max_angle_bracket_count: u32,
231 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
232 /// it gets removed from here. Every entry left at the end gets emitted as an independent
234 crate unclosed_delims: Vec<UnmatchedBrace>,
235 last_unexpected_token_span: Option<Span>,
238 impl<'a> Drop for Parser<'a> {
240 let diag = self.diagnostic();
241 emit_unclosed_delims(&mut self.unclosed_delims, diag);
247 frame: TokenCursorFrame,
248 stack: Vec<TokenCursorFrame>,
252 struct TokenCursorFrame {
253 delim: token::DelimToken,
256 tree_cursor: tokenstream::Cursor,
258 last_token: LastToken,
261 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
262 /// by the parser, and then that's transitively used to record the tokens that
263 /// each parse AST item is created with.
265 /// Right now this has two states, either collecting tokens or not collecting
266 /// tokens. If we're collecting tokens we just save everything off into a local
267 /// `Vec`. This should eventually though likely save tokens from the original
268 /// token stream and just use slicing of token streams to avoid creation of a
269 /// whole new vector.
271 /// The second state is where we're passively not recording tokens, but the last
272 /// token is still tracked for when we want to start recording tokens. This
273 /// "last token" means that when we start recording tokens we'll want to ensure
274 /// that this, the first token, is included in the output.
276 /// You can find some more example usage of this in the `collect_tokens` method
280 Collecting(Vec<TreeAndJoint>),
281 Was(Option<TreeAndJoint>),
284 impl TokenCursorFrame {
285 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
289 open_delim: delim == token::NoDelim,
290 tree_cursor: tts.clone().into_trees(),
291 close_delim: delim == token::NoDelim,
292 last_token: LastToken::Was(None),
298 fn next(&mut self) -> TokenAndSpan {
300 let tree = if !self.frame.open_delim {
301 self.frame.open_delim = true;
302 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
303 } else if let Some(tree) = self.frame.tree_cursor.next() {
305 } else if !self.frame.close_delim {
306 self.frame.close_delim = true;
307 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
308 } else if let Some(frame) = self.stack.pop() {
312 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
315 match self.frame.last_token {
316 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
317 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
321 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
322 TokenTree::Delimited(sp, delim, tts) => {
323 let frame = TokenCursorFrame::new(sp, delim, &tts);
324 self.stack.push(mem::replace(&mut self.frame, frame));
330 fn next_desugared(&mut self) -> TokenAndSpan {
331 let (sp, name) = match self.next() {
332 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
336 let stripped = strip_doc_comment_decoration(&name.as_str());
338 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
339 // required to wrap the text.
340 let mut num_of_hashes = 0;
342 for ch in stripped.chars() {
345 '#' if count > 0 => count + 1,
348 num_of_hashes = cmp::max(num_of_hashes, count);
351 let delim_span = DelimSpan::from_single(sp);
352 let body = TokenTree::Delimited(
355 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
356 TokenTree::Token(sp, token::Eq),
357 TokenTree::Token(sp, token::Literal(
358 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
360 .iter().cloned().collect::<TokenStream>().into(),
363 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
366 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
367 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
368 .iter().cloned().collect::<TokenStream>().into()
370 [TokenTree::Token(sp, token::Pound), body]
371 .iter().cloned().collect::<TokenStream>().into()
379 #[derive(Clone, PartialEq)]
380 crate enum TokenType {
382 Keyword(keywords::Keyword),
392 fn to_string(&self) -> String {
394 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
395 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
396 TokenType::Operator => "an operator".to_string(),
397 TokenType::Lifetime => "lifetime".to_string(),
398 TokenType::Ident => "identifier".to_string(),
399 TokenType::Path => "path".to_string(),
400 TokenType::Type => "type".to_string(),
401 TokenType::Const => "const".to_string(),
406 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
407 /// `IDENT<<u8 as Trait>::AssocTy>`.
409 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
410 /// that `IDENT` is not the ident of a fn trait.
411 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
412 t == &token::ModSep || t == &token::Lt ||
413 t == &token::BinOp(token::Shl)
416 /// Information about the path to a module.
417 pub struct ModulePath {
420 pub result: Result<ModulePathSuccess, Error>,
423 pub struct ModulePathSuccess {
425 pub directory_ownership: DirectoryOwnership,
430 FileNotFoundForModule {
432 default_path: String,
433 secondary_path: String,
438 default_path: String,
439 secondary_path: String,
442 InclusiveRangeWithNoEnd,
446 fn span_err<S: Into<MultiSpan>>(self,
448 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
450 Error::FileNotFoundForModule { ref mod_name,
454 let mut err = struct_span_err!(handler, sp, E0583,
455 "file not found for module `{}`", mod_name);
456 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
462 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
463 let mut err = struct_span_err!(handler, sp, E0584,
464 "file for module `{}` found at both {} and {}",
468 err.help("delete or rename one of them to remove the ambiguity");
471 Error::UselessDocComment => {
472 let mut err = struct_span_err!(handler, sp, E0585,
473 "found a documentation comment that doesn't document anything");
474 err.help("doc comments must come before what they document, maybe a comment was \
475 intended with `//`?");
478 Error::InclusiveRangeWithNoEnd => {
479 let mut err = struct_span_err!(handler, sp, E0586,
480 "inclusive range with no end");
481 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
491 AttributesParsed(ThinVec<Attribute>),
492 AlreadyParsed(P<Expr>),
495 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
496 fn from(o: Option<ThinVec<Attribute>>) -> Self {
497 if let Some(attrs) = o {
498 LhsExpr::AttributesParsed(attrs)
500 LhsExpr::NotYetParsed
505 impl From<P<Expr>> for LhsExpr {
506 fn from(expr: P<Expr>) -> Self {
507 LhsExpr::AlreadyParsed(expr)
511 /// Creates a placeholder argument.
512 fn dummy_arg(span: Span) -> Arg {
513 let ident = Ident::new(keywords::Invalid.name(), span);
515 id: ast::DUMMY_NODE_ID,
516 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
522 id: ast::DUMMY_NODE_ID
524 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal }
527 #[derive(Copy, Clone, Debug)]
528 enum TokenExpectType {
533 impl<'a> Parser<'a> {
534 pub fn new(sess: &'a ParseSess,
536 directory: Option<Directory<'a>>,
537 recurse_into_file_modules: bool,
538 desugar_doc_comments: bool)
540 let mut parser = Parser {
542 token: token::Whitespace,
543 span: syntax_pos::DUMMY_SP,
544 prev_span: syntax_pos::DUMMY_SP,
546 prev_token_kind: PrevTokenKind::Other,
547 restrictions: Restrictions::empty(),
548 recurse_into_file_modules,
549 directory: Directory {
550 path: Cow::from(PathBuf::new()),
551 ownership: DirectoryOwnership::Owned { relative: None }
553 root_module_name: None,
554 expected_tokens: Vec::new(),
555 token_cursor: TokenCursor {
556 frame: TokenCursorFrame::new(
563 desugar_doc_comments,
565 unmatched_angle_bracket_count: 0,
566 max_angle_bracket_count: 0,
567 unclosed_delims: Vec::new(),
568 last_unexpected_token_span: None,
571 let tok = parser.next_tok();
572 parser.token = tok.tok;
573 parser.span = tok.sp;
575 if let Some(directory) = directory {
576 parser.directory = directory;
577 } else if !parser.span.is_dummy() {
578 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
580 parser.directory.path = Cow::from(path);
584 parser.process_potential_macro_variable();
588 fn next_tok(&mut self) -> TokenAndSpan {
589 let mut next = if self.desugar_doc_comments {
590 self.token_cursor.next_desugared()
592 self.token_cursor.next()
594 if next.sp.is_dummy() {
595 // Tweak the location for better diagnostics, but keep syntactic context intact.
596 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
601 /// Converts the current token to a string using `self`'s reader.
602 pub fn this_token_to_string(&self) -> String {
603 pprust::token_to_string(&self.token)
606 fn token_descr(&self) -> Option<&'static str> {
607 Some(match &self.token {
608 t if t.is_special_ident() => "reserved identifier",
609 t if t.is_used_keyword() => "keyword",
610 t if t.is_unused_keyword() => "reserved keyword",
611 token::DocComment(..) => "doc comment",
616 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 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
625 let token_str = pprust::token_to_string(t);
626 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
629 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
630 match self.expect_one_of(&[], &[]) {
632 Ok(_) => unreachable!(),
636 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
637 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
638 if self.expected_tokens.is_empty() {
639 if self.token == *t {
643 let token_str = pprust::token_to_string(t);
644 let this_token_str = self.this_token_descr();
645 let mut err = self.fatal(&format!("expected `{}`, found {}",
649 let sp = if self.token == token::Token::Eof {
650 // EOF, don't want to point at the following char, but rather the last token
653 self.sess.source_map().next_point(self.prev_span)
655 let label_exp = format!("expected `{}`", token_str);
656 match self.recover_closing_delimiter(&[t.clone()], err) {
659 return Ok(recovered);
662 let cm = self.sess.source_map();
663 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
664 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
665 // When the spans are in the same line, it means that the only content
666 // between them is whitespace, point only at the found token.
667 err.span_label(self.span, label_exp);
670 err.span_label(sp, label_exp);
671 err.span_label(self.span, "unexpected token");
677 self.expect_one_of(slice::from_ref(t), &[])
681 fn recover_closing_delimiter(
683 tokens: &[token::Token],
684 mut err: DiagnosticBuilder<'a>,
685 ) -> PResult<'a, bool> {
687 // we want to use the last closing delim that would apply
688 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
689 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
690 && Some(self.span) > unmatched.unclosed_span
697 // Recover and assume that the detected unclosed delimiter was meant for
698 // this location. Emit the diagnostic and act as if the delimiter was
699 // present for the parser's sake.
701 // Don't attempt to recover from this unclosed delimiter more than once.
702 let unmatched = self.unclosed_delims.remove(pos);
703 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
705 // We want to suggest the inclusion of the closing delimiter where it makes
706 // the most sense, which is immediately after the last token:
711 // | help: `)` may belong here (FIXME: #58270)
713 // unclosed delimiter
714 if let Some(sp) = unmatched.unclosed_span {
715 err.span_label(sp, "unclosed delimiter");
717 err.span_suggestion_short(
718 self.sess.source_map().next_point(self.prev_span),
719 &format!("{} may belong here", delim.to_string()),
721 Applicability::MaybeIncorrect,
724 self.expected_tokens.clear(); // reduce errors
731 /// Expect next token to be edible or inedible token. If edible,
732 /// then consume it; if inedible, then return without consuming
733 /// anything. Signal a fatal error if next token is unexpected.
734 pub fn expect_one_of(
736 edible: &[token::Token],
737 inedible: &[token::Token],
738 ) -> PResult<'a, bool /* recovered */> {
739 fn tokens_to_string(tokens: &[TokenType]) -> String {
740 let mut i = tokens.iter();
741 // This might be a sign we need a connect method on Iterator.
743 .map_or(String::new(), |t| t.to_string());
744 i.enumerate().fold(b, |mut b, (i, a)| {
745 if tokens.len() > 2 && i == tokens.len() - 2 {
747 } else if tokens.len() == 2 && i == tokens.len() - 2 {
752 b.push_str(&a.to_string());
756 if edible.contains(&self.token) {
759 } else if inedible.contains(&self.token) {
760 // leave it in the input
762 } else if self.last_unexpected_token_span == Some(self.span) {
765 let mut expected = edible.iter()
766 .map(|x| TokenType::Token(x.clone()))
767 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
768 .chain(self.expected_tokens.iter().cloned())
769 .collect::<Vec<_>>();
770 expected.sort_by_cached_key(|x| x.to_string());
772 let expect = tokens_to_string(&expected[..]);
773 let actual = self.this_token_to_string();
774 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
775 let short_expect = if expected.len() > 6 {
776 format!("{} possible tokens", expected.len())
780 (format!("expected one of {}, found `{}`", expect, actual),
781 (self.sess.source_map().next_point(self.prev_span),
782 format!("expected one of {} here", short_expect)))
783 } else if expected.is_empty() {
784 (format!("unexpected token: `{}`", actual),
785 (self.prev_span, "unexpected token after this".to_string()))
787 (format!("expected {}, found `{}`", expect, actual),
788 (self.sess.source_map().next_point(self.prev_span),
789 format!("expected {} here", expect)))
791 self.last_unexpected_token_span = Some(self.span);
792 let mut err = self.fatal(&msg_exp);
793 if self.token.is_ident_named("and") {
794 err.span_suggestion_short(
796 "use `&&` instead of `and` for the boolean operator",
798 Applicability::MaybeIncorrect,
801 if self.token.is_ident_named("or") {
802 err.span_suggestion_short(
804 "use `||` instead of `or` for the boolean operator",
806 Applicability::MaybeIncorrect,
809 let sp = if self.token == token::Token::Eof {
810 // This is EOF, don't want to point at the following char, but rather the last token
815 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
816 TokenType::Token(t) => Some(t.clone()),
818 }).collect::<Vec<_>>(), err) {
821 return Ok(recovered);
825 let is_semi_suggestable = expected.iter().any(|t| match t {
826 TokenType::Token(token::Semi) => true, // we expect a `;` here
828 }) && ( // a `;` would be expected before the current keyword
829 self.token.is_keyword(keywords::Break) ||
830 self.token.is_keyword(keywords::Continue) ||
831 self.token.is_keyword(keywords::For) ||
832 self.token.is_keyword(keywords::If) ||
833 self.token.is_keyword(keywords::Let) ||
834 self.token.is_keyword(keywords::Loop) ||
835 self.token.is_keyword(keywords::Match) ||
836 self.token.is_keyword(keywords::Return) ||
837 self.token.is_keyword(keywords::While)
839 let cm = self.sess.source_map();
840 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
841 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
842 // The spans are in different lines, expected `;` and found `let` or `return`.
843 // High likelihood that it is only a missing `;`.
844 err.span_suggestion_short(
846 "a semicolon may be missing here",
848 Applicability::MaybeIncorrect,
853 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
854 // When the spans are in the same line, it means that the only content between
855 // them is whitespace, point at the found token in that case:
857 // X | () => { syntax error };
858 // | ^^^^^ expected one of 8 possible tokens here
860 // instead of having:
862 // X | () => { syntax error };
863 // | -^^^^^ unexpected token
865 // | expected one of 8 possible tokens here
866 err.span_label(self.span, label_exp);
868 _ if self.prev_span == syntax_pos::DUMMY_SP => {
869 // Account for macro context where the previous span might not be
870 // available to avoid incorrect output (#54841).
871 err.span_label(self.span, "unexpected token");
874 err.span_label(sp, label_exp);
875 err.span_label(self.span, "unexpected token");
882 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
883 fn interpolated_or_expr_span(&self,
884 expr: PResult<'a, P<Expr>>)
885 -> PResult<'a, (Span, P<Expr>)> {
887 if self.prev_token_kind == PrevTokenKind::Interpolated {
895 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
896 let mut err = self.struct_span_err(self.span,
897 &format!("expected identifier, found {}",
898 self.this_token_descr()));
899 if let token::Ident(ident, false) = &self.token {
900 if ident.is_raw_guess() {
903 "you can escape reserved keywords to use them as identifiers",
904 format!("r#{}", ident),
905 Applicability::MaybeIncorrect,
909 if let Some(token_descr) = self.token_descr() {
910 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
912 err.span_label(self.span, "expected identifier");
913 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
918 Applicability::MachineApplicable,
925 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
926 self.parse_ident_common(true)
929 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
931 token::Ident(ident, _) => {
932 if self.token.is_reserved_ident() {
933 let mut err = self.expected_ident_found();
940 let span = self.span;
942 Ok(Ident::new(ident.name, span))
945 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
946 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
948 self.expected_ident_found()
954 /// Checks if the next token is `tok`, and returns `true` if so.
956 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
958 crate fn check(&mut self, tok: &token::Token) -> bool {
959 let is_present = self.token == *tok;
960 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
964 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
965 pub fn eat(&mut self, tok: &token::Token) -> bool {
966 let is_present = self.check(tok);
967 if is_present { self.bump() }
971 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
972 self.expected_tokens.push(TokenType::Keyword(kw));
973 self.token.is_keyword(kw)
976 /// If the next token is the given keyword, eats it and returns
977 /// `true`. Otherwise, returns `false`.
978 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
979 if self.check_keyword(kw) {
987 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
988 if self.token.is_keyword(kw) {
996 /// If the given word is not a keyword, signals an error.
997 /// If the next token is not the given word, signals an error.
998 /// Otherwise, eats it.
999 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
1000 if !self.eat_keyword(kw) {
1007 fn check_ident(&mut self) -> bool {
1008 if self.token.is_ident() {
1011 self.expected_tokens.push(TokenType::Ident);
1016 fn check_path(&mut self) -> bool {
1017 if self.token.is_path_start() {
1020 self.expected_tokens.push(TokenType::Path);
1025 fn check_type(&mut self) -> bool {
1026 if self.token.can_begin_type() {
1029 self.expected_tokens.push(TokenType::Type);
1034 fn check_const_arg(&mut self) -> bool {
1035 if self.token.can_begin_const_arg() {
1038 self.expected_tokens.push(TokenType::Const);
1043 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
1044 /// and continues. If a `+` is not seen, returns `false`.
1046 /// This is used when token-splitting `+=` into `+`.
1047 /// See issue #47856 for an example of when this may occur.
1048 fn eat_plus(&mut self) -> bool {
1049 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1051 token::BinOp(token::Plus) => {
1055 token::BinOpEq(token::Plus) => {
1056 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1057 self.bump_with(token::Eq, span);
1065 /// Checks to see if the next token is either `+` or `+=`.
1066 /// Otherwise returns `false`.
1067 fn check_plus(&mut self) -> bool {
1068 if self.token.is_like_plus() {
1072 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1077 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1078 /// `&` and continues. If an `&` is not seen, signals an error.
1079 fn expect_and(&mut self) -> PResult<'a, ()> {
1080 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1082 token::BinOp(token::And) => {
1087 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1088 Ok(self.bump_with(token::BinOp(token::And), span))
1090 _ => self.unexpected()
1094 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1095 /// `|` and continues. If an `|` is not seen, signals an error.
1096 fn expect_or(&mut self) -> PResult<'a, ()> {
1097 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1099 token::BinOp(token::Or) => {
1104 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1105 Ok(self.bump_with(token::BinOp(token::Or), span))
1107 _ => self.unexpected()
1111 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1113 None => {/* everything ok */}
1115 let text = suf.as_str();
1116 if text.is_empty() {
1117 self.span_bug(sp, "found empty literal suffix in Some")
1119 let mut err = if kind == "a tuple index" &&
1120 ["i32", "u32", "isize", "usize"].contains(&text.to_string().as_str())
1122 // #59553: warn instead of reject out of hand to allow the fix to percolate
1123 // through the ecosystem when people fix their macros
1124 let mut err = self.struct_span_warn(
1126 &format!("suffixes on {} are invalid", kind),
1129 "`{}` is *temporarily* accepted on tuple index fields as it was \
1130 incorrectly accepted on stable for a few releases",
1134 "on proc macros, you'll want to use `syn::Index::from` or \
1135 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1136 to tuple field access",
1139 "for more context, see https://github.com/rust-lang/rust/issues/60210",
1143 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1145 err.span_label(sp, format!("invalid suffix `{}`", text));
1151 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1152 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1153 /// and continue. If a `<` is not seen, returns false.
1155 /// This is meant to be used when parsing generics on a path to get the
1157 fn eat_lt(&mut self) -> bool {
1158 self.expected_tokens.push(TokenType::Token(token::Lt));
1159 let ate = match self.token {
1164 token::BinOp(token::Shl) => {
1165 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1166 self.bump_with(token::Lt, span);
1170 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1171 self.bump_with(token::BinOp(token::Minus), span);
1178 // See doc comment for `unmatched_angle_bracket_count`.
1179 self.unmatched_angle_bracket_count += 1;
1180 self.max_angle_bracket_count += 1;
1181 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1187 fn expect_lt(&mut self) -> PResult<'a, ()> {
1195 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1196 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1197 fn expect_gt(&mut self) -> PResult<'a, ()> {
1198 self.expected_tokens.push(TokenType::Token(token::Gt));
1199 let ate = match self.token {
1204 token::BinOp(token::Shr) => {
1205 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1206 Some(self.bump_with(token::Gt, span))
1208 token::BinOpEq(token::Shr) => {
1209 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1210 Some(self.bump_with(token::Ge, span))
1213 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1214 Some(self.bump_with(token::Eq, span))
1221 // See doc comment for `unmatched_angle_bracket_count`.
1222 if self.unmatched_angle_bracket_count > 0 {
1223 self.unmatched_angle_bracket_count -= 1;
1224 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1229 None => self.unexpected(),
1233 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1234 /// passes through any errors encountered. Used for error recovery.
1235 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1236 let handler = self.diagnostic();
1238 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1240 TokenExpectType::Expect,
1241 |p| Ok(p.parse_token_tree())) {
1242 handler.cancel(err);
1246 /// Parses a sequence, including the closing delimiter. The function
1247 /// `f` must consume tokens until reaching the next separator or
1248 /// closing bracket.
1249 pub fn parse_seq_to_end<T, F>(&mut self,
1253 -> PResult<'a, Vec<T>> where
1254 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1256 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1263 /// Parses a sequence, not including the closing delimiter. The function
1264 /// `f` must consume tokens until reaching the next separator or
1265 /// closing bracket.
1266 pub fn parse_seq_to_before_end<T, F>(
1271 ) -> PResult<'a, (Vec<T>, bool)>
1272 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1274 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1277 fn parse_seq_to_before_tokens<T, F>(
1279 kets: &[&token::Token],
1281 expect: TokenExpectType,
1283 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1284 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1286 let mut first = true;
1287 let mut recovered = false;
1289 while !kets.iter().any(|k| {
1291 TokenExpectType::Expect => self.check(k),
1292 TokenExpectType::NoExpect => self.token == **k,
1296 token::CloseDelim(..) | token::Eof => break,
1299 if let Some(ref t) = sep.sep {
1303 match self.expect(t) {
1310 // Attempt to keep parsing if it was a similar separator
1311 if let Some(ref tokens) = t.similar_tokens() {
1312 if tokens.contains(&self.token) {
1317 // Attempt to keep parsing if it was an omitted separator
1332 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1334 TokenExpectType::Expect => self.check(k),
1335 TokenExpectType::NoExpect => self.token == **k,
1348 /// Parses a sequence, including the closing delimiter. The function
1349 /// `f` must consume tokens until reaching the next separator or
1350 /// closing bracket.
1351 fn parse_unspanned_seq<T, F>(
1357 ) -> PResult<'a, Vec<T>> where
1358 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1361 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1368 /// Advance the parser by one token
1369 pub fn bump(&mut self) {
1370 if self.prev_token_kind == PrevTokenKind::Eof {
1371 // Bumping after EOF is a bad sign, usually an infinite loop.
1372 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1375 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1377 // Record last token kind for possible error recovery.
1378 self.prev_token_kind = match self.token {
1379 token::DocComment(..) => PrevTokenKind::DocComment,
1380 token::Comma => PrevTokenKind::Comma,
1381 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1382 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1383 token::Interpolated(..) => PrevTokenKind::Interpolated,
1384 token::Eof => PrevTokenKind::Eof,
1385 token::Ident(..) => PrevTokenKind::Ident,
1386 _ => PrevTokenKind::Other,
1389 let next = self.next_tok();
1390 self.span = next.sp;
1391 self.token = next.tok;
1392 self.expected_tokens.clear();
1393 // check after each token
1394 self.process_potential_macro_variable();
1397 /// Advance the parser using provided token as a next one. Use this when
1398 /// consuming a part of a token. For example a single `<` from `<<`.
1399 fn bump_with(&mut self, next: token::Token, span: Span) {
1400 self.prev_span = self.span.with_hi(span.lo());
1401 // It would be incorrect to record the kind of the current token, but
1402 // fortunately for tokens currently using `bump_with`, the
1403 // prev_token_kind will be of no use anyway.
1404 self.prev_token_kind = PrevTokenKind::Other;
1407 self.expected_tokens.clear();
1410 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1411 F: FnOnce(&token::Token) -> R,
1414 return f(&self.token)
1417 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1418 Some(tree) => match tree {
1419 TokenTree::Token(_, tok) => tok,
1420 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1422 None => token::CloseDelim(self.token_cursor.frame.delim),
1426 fn look_ahead_span(&self, dist: usize) -> Span {
1431 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1432 Some(TokenTree::Token(span, _)) => span,
1433 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1434 None => self.look_ahead_span(dist - 1),
1437 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1438 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1440 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1441 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1443 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1444 err.span_err(sp, self.diagnostic())
1446 fn bug(&self, m: &str) -> ! {
1447 self.sess.span_diagnostic.span_bug(self.span, m)
1449 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1450 self.sess.span_diagnostic.span_err(sp, m)
1452 crate fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1453 self.sess.span_diagnostic.struct_span_err(sp, m)
1455 fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1456 self.sess.span_diagnostic.struct_span_warn(sp, m)
1458 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1459 self.sess.span_diagnostic.span_bug(sp, m)
1462 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1463 self.sess.span_diagnostic.cancel(err)
1466 crate fn diagnostic(&self) -> &'a errors::Handler {
1467 &self.sess.span_diagnostic
1470 /// Is the current token one of the keywords that signals a bare function type?
1471 fn token_is_bare_fn_keyword(&mut self) -> bool {
1472 self.check_keyword(keywords::Fn) ||
1473 self.check_keyword(keywords::Unsafe) ||
1474 self.check_keyword(keywords::Extern)
1477 /// Parses a `TyKind::BareFn` type.
1478 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1481 [unsafe] [extern "ABI"] fn (S) -> T
1491 let unsafety = self.parse_unsafety();
1492 let abi = if self.eat_keyword(keywords::Extern) {
1493 self.parse_opt_abi()?.unwrap_or(Abi::C)
1498 self.expect_keyword(keywords::Fn)?;
1499 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1500 let ret_ty = self.parse_ret_ty(false)?;
1501 let decl = P(FnDecl {
1506 Ok(TyKind::BareFn(P(BareFnTy {
1514 /// Parses asyncness: `async` or nothing.
1515 fn parse_asyncness(&mut self) -> IsAsync {
1516 if self.eat_keyword(keywords::Async) {
1518 closure_id: ast::DUMMY_NODE_ID,
1519 return_impl_trait_id: ast::DUMMY_NODE_ID,
1520 arguments: Vec::new(),
1527 /// Parses unsafety: `unsafe` or nothing.
1528 fn parse_unsafety(&mut self) -> Unsafety {
1529 if self.eat_keyword(keywords::Unsafe) {
1536 /// Parses the items in a trait declaration.
1537 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1538 maybe_whole!(self, NtTraitItem, |x| x);
1539 let attrs = self.parse_outer_attributes()?;
1540 let mut unclosed_delims = vec![];
1541 let (mut item, tokens) = self.collect_tokens(|this| {
1542 let item = this.parse_trait_item_(at_end, attrs);
1543 unclosed_delims.append(&mut this.unclosed_delims);
1546 self.unclosed_delims.append(&mut unclosed_delims);
1547 // See `parse_item` for why this clause is here.
1548 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1549 item.tokens = Some(tokens);
1554 fn parse_trait_item_(&mut self,
1556 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1559 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1560 self.parse_trait_item_assoc_ty()?
1561 } else if self.is_const_item() {
1562 self.expect_keyword(keywords::Const)?;
1563 let ident = self.parse_ident()?;
1564 self.expect(&token::Colon)?;
1565 let ty = self.parse_ty()?;
1566 let default = if self.eat(&token::Eq) {
1567 let expr = self.parse_expr()?;
1568 self.expect(&token::Semi)?;
1571 self.expect(&token::Semi)?;
1574 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1575 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1576 // trait item macro.
1577 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1579 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
1581 let ident = self.parse_ident()?;
1582 let mut generics = self.parse_generics()?;
1584 let mut decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1585 // This is somewhat dubious; We don't want to allow
1586 // argument names to be left off if there is a
1589 // We don't allow argument names to be left off in edition 2018.
1590 p.parse_arg_general(p.span.rust_2018(), true, false)
1592 generics.where_clause = self.parse_where_clause()?;
1593 self.construct_async_arguments(&mut asyncness, &mut decl);
1595 let sig = ast::MethodSig {
1605 let body = match self.token {
1609 debug!("parse_trait_methods(): parsing required method");
1612 token::OpenDelim(token::Brace) => {
1613 debug!("parse_trait_methods(): parsing provided method");
1615 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1616 attrs.extend(inner_attrs.iter().cloned());
1619 token::Interpolated(ref nt) => {
1621 token::NtBlock(..) => {
1623 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1624 attrs.extend(inner_attrs.iter().cloned());
1628 let token_str = self.this_token_descr();
1629 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1631 err.span_label(self.span, "expected `;` or `{`");
1637 let token_str = self.this_token_descr();
1638 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1640 err.span_label(self.span, "expected `;` or `{`");
1644 (ident, ast::TraitItemKind::Method(sig, body), generics)
1648 id: ast::DUMMY_NODE_ID,
1653 span: lo.to(self.prev_span),
1658 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1659 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1660 if self.eat(&token::RArrow) {
1661 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1663 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1668 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1669 self.parse_ty_common(true, true, false)
1672 /// Parses a type in restricted contexts where `+` is not permitted.
1674 /// Example 1: `&'a TYPE`
1675 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1676 /// Example 2: `value1 as TYPE + value2`
1677 /// `+` is prohibited to avoid interactions with expression grammar.
1678 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1679 self.parse_ty_common(false, true, false)
1682 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1683 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1684 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1685 maybe_whole!(self, NtTy, |x| x);
1688 let mut impl_dyn_multi = false;
1689 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1690 // `(TYPE)` is a parenthesized type.
1691 // `(TYPE,)` is a tuple with a single field of type TYPE.
1692 let mut ts = vec![];
1693 let mut last_comma = false;
1694 while self.token != token::CloseDelim(token::Paren) {
1695 ts.push(self.parse_ty()?);
1696 if self.eat(&token::Comma) {
1703 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1704 self.expect(&token::CloseDelim(token::Paren))?;
1706 if ts.len() == 1 && !last_comma {
1707 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1708 let maybe_bounds = allow_plus && self.token.is_like_plus();
1710 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1711 TyKind::Path(None, ref path) if maybe_bounds => {
1712 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1714 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1715 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1716 let path = match bounds[0] {
1717 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1718 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1720 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1723 _ => TyKind::Paren(P(ty))
1728 } else if self.eat(&token::Not) {
1731 } else if self.eat(&token::BinOp(token::Star)) {
1733 TyKind::Ptr(self.parse_ptr()?)
1734 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1736 let t = self.parse_ty()?;
1737 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1738 let t = match self.maybe_parse_fixed_length_of_vec()? {
1739 None => TyKind::Slice(t),
1740 Some(length) => TyKind::Array(t, AnonConst {
1741 id: ast::DUMMY_NODE_ID,
1745 self.expect(&token::CloseDelim(token::Bracket))?;
1747 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1750 self.parse_borrowed_pointee()?
1751 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1753 // In order to not be ambiguous, the type must be surrounded by parens.
1754 self.expect(&token::OpenDelim(token::Paren))?;
1756 id: ast::DUMMY_NODE_ID,
1757 value: self.parse_expr()?,
1759 self.expect(&token::CloseDelim(token::Paren))?;
1761 } else if self.eat_keyword(keywords::Underscore) {
1762 // A type to be inferred `_`
1764 } else if self.token_is_bare_fn_keyword() {
1765 // Function pointer type
1766 self.parse_ty_bare_fn(Vec::new())?
1767 } else if self.check_keyword(keywords::For) {
1768 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1769 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1770 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1772 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1773 if self.token_is_bare_fn_keyword() {
1774 self.parse_ty_bare_fn(lifetime_defs)?
1776 let path = self.parse_path(PathStyle::Type)?;
1777 let parse_plus = allow_plus && self.check_plus();
1778 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1780 } else if self.eat_keyword(keywords::Impl) {
1781 // Always parse bounds greedily for better error recovery.
1782 let bounds = self.parse_generic_bounds(None)?;
1783 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1784 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1785 } else if self.check_keyword(keywords::Dyn) &&
1786 (self.span.rust_2018() ||
1787 self.look_ahead(1, |t| t.can_begin_bound() &&
1788 !can_continue_type_after_non_fn_ident(t))) {
1789 self.bump(); // `dyn`
1790 // Always parse bounds greedily for better error recovery.
1791 let bounds = self.parse_generic_bounds(None)?;
1792 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1793 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1794 } else if self.check(&token::Question) ||
1795 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1796 // Bound list (trait object type)
1797 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1798 TraitObjectSyntax::None)
1799 } else if self.eat_lt() {
1801 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1802 TyKind::Path(Some(qself), path)
1803 } else if self.token.is_path_start() {
1805 let path = self.parse_path(PathStyle::Type)?;
1806 if self.eat(&token::Not) {
1807 // Macro invocation in type position
1808 let (delim, tts) = self.expect_delimited_token_tree()?;
1809 let node = Mac_ { path, tts, delim };
1810 TyKind::Mac(respan(lo.to(self.prev_span), node))
1812 // Just a type path or bound list (trait object type) starting with a trait.
1814 // `Trait1 + Trait2 + 'a`
1815 if allow_plus && self.check_plus() {
1816 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1818 TyKind::Path(None, path)
1821 } else if self.check(&token::DotDotDot) {
1822 if allow_c_variadic {
1823 self.eat(&token::DotDotDot);
1826 return Err(self.fatal(
1827 "only foreign functions are allowed to be C-variadic"
1831 let msg = format!("expected type, found {}", self.this_token_descr());
1832 return Err(self.fatal(&msg));
1835 let span = lo.to(self.prev_span);
1836 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1838 // Try to recover from use of `+` with incorrect priority.
1839 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1840 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1841 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1844 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1845 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1846 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1847 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1849 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1850 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1852 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1855 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1856 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1857 let mutbl = self.parse_mutability();
1858 let ty = self.parse_ty_no_plus()?;
1859 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1862 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1863 let mutbl = if self.eat_keyword(keywords::Mut) {
1865 } else if self.eat_keyword(keywords::Const) {
1866 Mutability::Immutable
1868 let span = self.prev_span;
1869 let msg = "expected mut or const in raw pointer type";
1870 self.struct_span_err(span, msg)
1871 .span_label(span, msg)
1872 .help("use `*mut T` or `*const T` as appropriate")
1874 Mutability::Immutable
1876 let t = self.parse_ty_no_plus()?;
1877 Ok(MutTy { ty: t, mutbl: mutbl })
1880 fn is_named_argument(&mut self) -> bool {
1881 let offset = match self.token {
1882 token::Interpolated(ref nt) => match **nt {
1883 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1886 token::BinOp(token::And) | token::AndAnd => 1,
1887 _ if self.token.is_keyword(keywords::Mut) => 1,
1891 self.look_ahead(offset, |t| t.is_ident()) &&
1892 self.look_ahead(offset + 1, |t| t == &token::Colon)
1895 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1897 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1898 if let token::DocComment(_) = self.token {
1899 let mut err = self.diagnostic().struct_span_err(
1901 &format!("documentation comments cannot be applied to {}", applied_to),
1903 err.span_label(self.span, "doc comments are not allowed here");
1906 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1907 *t == token::OpenDelim(token::Bracket)
1910 // Skip every token until next possible arg.
1911 while self.token != token::CloseDelim(token::Bracket) {
1914 let sp = lo.to(self.span);
1916 let mut err = self.diagnostic().struct_span_err(
1918 &format!("attributes cannot be applied to {}", applied_to),
1920 err.span_label(sp, "attributes are not allowed here");
1925 /// This version of parse arg doesn't necessarily require identifier names.
1926 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
1927 allow_c_variadic: bool) -> PResult<'a, Arg> {
1928 if let Ok(Some(_)) = self.parse_self_arg() {
1929 let mut err = self.struct_span_err(self.prev_span,
1930 "unexpected `self` argument in function");
1931 err.span_label(self.prev_span,
1932 "`self` is only valid as the first argument of an associated function");
1936 let (pat, ty) = if require_name || self.is_named_argument() {
1937 debug!("parse_arg_general parse_pat (require_name:{})",
1939 self.eat_incorrect_doc_comment("method arguments");
1940 let pat = self.parse_pat(Some("argument name"))?;
1942 if let Err(mut err) = self.expect(&token::Colon) {
1943 // If we find a pattern followed by an identifier, it could be an (incorrect)
1944 // C-style parameter declaration.
1945 if self.check_ident() && self.look_ahead(1, |t| {
1946 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1948 let ident = self.parse_ident().unwrap();
1949 let span = pat.span.with_hi(ident.span.hi());
1951 err.span_suggestion(
1953 "declare the type after the parameter binding",
1954 String::from("<identifier>: <type>"),
1955 Applicability::HasPlaceholders,
1957 } else if require_name && is_trait_item {
1958 if let PatKind::Ident(_, ident, _) = pat.node {
1959 err.span_suggestion(
1961 "explicitly ignore parameter",
1962 format!("_: {}", ident),
1963 Applicability::MachineApplicable,
1967 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1973 self.eat_incorrect_doc_comment("a method argument's type");
1974 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1976 debug!("parse_arg_general ident_to_pat");
1977 let parser_snapshot_before_ty = self.clone();
1978 self.eat_incorrect_doc_comment("a method argument's type");
1979 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1980 if ty.is_ok() && self.token != token::Comma &&
1981 self.token != token::CloseDelim(token::Paren) {
1982 // This wasn't actually a type, but a pattern looking like a type,
1983 // so we are going to rollback and re-parse for recovery.
1984 ty = self.unexpected();
1988 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1990 id: ast::DUMMY_NODE_ID,
1991 node: PatKind::Ident(
1992 BindingMode::ByValue(Mutability::Immutable), ident, None),
1998 // If this is a C-variadic argument and we hit an error, return the
2000 if self.token == token::DotDotDot {
2003 // Recover from attempting to parse the argument as a type without pattern.
2005 mem::replace(self, parser_snapshot_before_ty);
2006 let pat = self.parse_pat(Some("argument name"))?;
2007 self.expect(&token::Colon)?;
2008 let ty = self.parse_ty()?;
2010 let mut err = self.diagnostic().struct_span_err_with_code(
2012 "patterns aren't allowed in methods without bodies",
2013 DiagnosticId::Error("E0642".into()),
2015 err.span_suggestion_short(
2017 "give this argument a name or use an underscore to ignore it",
2019 Applicability::MachineApplicable,
2023 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2025 node: PatKind::Wild,
2027 id: ast::DUMMY_NODE_ID
2034 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
2037 /// Parses a single function argument.
2038 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2039 self.parse_arg_general(true, false, false)
2042 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2043 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2044 let pat = self.parse_pat(Some("argument name"))?;
2045 let t = if self.eat(&token::Colon) {
2049 id: ast::DUMMY_NODE_ID,
2050 node: TyKind::Infer,
2051 span: self.prev_span,
2057 id: ast::DUMMY_NODE_ID,
2058 source: ast::ArgSource::Normal,
2062 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2063 if self.eat(&token::Semi) {
2064 Ok(Some(self.parse_expr()?))
2070 /// Matches `token_lit = LIT_INTEGER | ...`.
2071 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2072 let out = match self.token {
2073 token::Interpolated(ref nt) => match **nt {
2074 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2075 ExprKind::Lit(ref lit) => { lit.node.clone() }
2076 _ => { return self.unexpected_last(&self.token); }
2078 _ => { return self.unexpected_last(&self.token); }
2080 token::Literal(lit, suf) => {
2081 let diag = Some((self.span, &self.sess.span_diagnostic));
2082 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2086 self.expect_no_suffix(sp, &format!("a {}", lit.literal_name()), suf)
2091 token::Dot if self.look_ahead(1, |t| match t {
2092 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2094 }) => { // recover from `let x = .4;`
2097 if let token::Literal(
2098 parse::token::Lit::Integer(val),
2101 let suffix = suffix.and_then(|s| {
2105 } else if s == "f64" {
2112 let sp = lo.to(self.prev_span);
2113 let mut err = self.diagnostic()
2114 .struct_span_err(sp, "float literals must have an integer part");
2115 err.span_suggestion(
2117 "must have an integer part",
2118 format!("0.{}{}", val, suffix),
2119 Applicability::MachineApplicable,
2122 return Ok(match suffix {
2123 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2124 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2125 _ => ast::LitKind::FloatUnsuffixed(val),
2131 _ => { return self.unexpected_last(&self.token); }
2138 /// Matches `lit = true | false | token_lit`.
2139 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2141 let lit = if self.eat_keyword(keywords::True) {
2143 } else if self.eat_keyword(keywords::False) {
2144 LitKind::Bool(false)
2146 let lit = self.parse_lit_token()?;
2149 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2152 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2153 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2154 maybe_whole_expr!(self);
2156 let minus_lo = self.span;
2157 let minus_present = self.eat(&token::BinOp(token::Minus));
2159 let literal = self.parse_lit()?;
2160 let hi = self.prev_span;
2161 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2164 let minus_hi = self.prev_span;
2165 let unary = self.mk_unary(UnOp::Neg, expr);
2166 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2172 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2174 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2175 let span = self.span;
2177 Ok(Ident::new(ident.name, span))
2179 _ => self.parse_ident(),
2183 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2185 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2186 let span = self.span;
2188 Ok(Ident::new(ident.name, span))
2190 _ => self.parse_ident(),
2194 /// Parses a qualified path.
2195 /// Assumes that the leading `<` has been parsed already.
2197 /// `qualified_path = <type [as trait_ref]>::path`
2202 /// `<T as U>::F::a<S>` (without disambiguator)
2203 /// `<T as U>::F::a::<S>` (with disambiguator)
2204 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2205 let lo = self.prev_span;
2206 let ty = self.parse_ty()?;
2208 // `path` will contain the prefix of the path up to the `>`,
2209 // if any (e.g., `U` in the `<T as U>::*` examples
2210 // above). `path_span` has the span of that path, or an empty
2211 // span in the case of something like `<T>::Bar`.
2212 let (mut path, path_span);
2213 if self.eat_keyword(keywords::As) {
2214 let path_lo = self.span;
2215 path = self.parse_path(PathStyle::Type)?;
2216 path_span = path_lo.to(self.prev_span);
2218 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2219 path_span = self.span.to(self.span);
2222 // See doc comment for `unmatched_angle_bracket_count`.
2223 self.expect(&token::Gt)?;
2224 if self.unmatched_angle_bracket_count > 0 {
2225 self.unmatched_angle_bracket_count -= 1;
2226 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2229 self.expect(&token::ModSep)?;
2231 let qself = QSelf { ty, path_span, position: path.segments.len() };
2232 self.parse_path_segments(&mut path.segments, style)?;
2234 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2237 /// Parses simple paths.
2239 /// `path = [::] segment+`
2240 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2243 /// `a::b::C<D>` (without disambiguator)
2244 /// `a::b::C::<D>` (with disambiguator)
2245 /// `Fn(Args)` (without disambiguator)
2246 /// `Fn::(Args)` (with disambiguator)
2247 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2248 maybe_whole!(self, NtPath, |path| {
2249 if style == PathStyle::Mod &&
2250 path.segments.iter().any(|segment| segment.args.is_some()) {
2251 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2256 let lo = self.meta_var_span.unwrap_or(self.span);
2257 let mut segments = Vec::new();
2258 let mod_sep_ctxt = self.span.ctxt();
2259 if self.eat(&token::ModSep) {
2260 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2262 self.parse_path_segments(&mut segments, style)?;
2264 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2267 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2268 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2270 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2271 let meta_ident = match self.token {
2272 token::Interpolated(ref nt) => match **nt {
2273 token::NtMeta(ref meta) => match meta.node {
2274 ast::MetaItemKind::Word => Some(meta.path.clone()),
2281 if let Some(path) = meta_ident {
2285 self.parse_path(style)
2288 crate fn parse_path_segments(&mut self,
2289 segments: &mut Vec<PathSegment>,
2291 -> PResult<'a, ()> {
2293 let segment = self.parse_path_segment(style)?;
2294 if style == PathStyle::Expr {
2295 // In order to check for trailing angle brackets, we must have finished
2296 // recursing (`parse_path_segment` can indirectly call this function),
2297 // that is, the next token must be the highlighted part of the below example:
2299 // `Foo::<Bar as Baz<T>>::Qux`
2302 // As opposed to the below highlight (if we had only finished the first
2305 // `Foo::<Bar as Baz<T>>::Qux`
2308 // `PathStyle::Expr` is only provided at the root invocation and never in
2309 // `parse_path_segment` to recurse and therefore can be checked to maintain
2311 self.check_trailing_angle_brackets(&segment, token::ModSep);
2313 segments.push(segment);
2315 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2321 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2322 let ident = self.parse_path_segment_ident()?;
2324 let is_args_start = |token: &token::Token| match *token {
2325 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
2326 | token::LArrow => true,
2329 let check_args_start = |this: &mut Self| {
2330 this.expected_tokens.extend_from_slice(
2331 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2333 is_args_start(&this.token)
2336 Ok(if style == PathStyle::Type && check_args_start(self) ||
2337 style != PathStyle::Mod && self.check(&token::ModSep)
2338 && self.look_ahead(1, |t| is_args_start(t)) {
2339 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2340 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2341 // parsing a new path.
2342 if style == PathStyle::Expr {
2343 self.unmatched_angle_bracket_count = 0;
2344 self.max_angle_bracket_count = 0;
2347 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2348 self.eat(&token::ModSep);
2350 let args = if self.eat_lt() {
2352 let (args, bindings) =
2353 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2355 let span = lo.to(self.prev_span);
2356 AngleBracketedArgs { args, bindings, span }.into()
2360 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2361 &[&token::CloseDelim(token::Paren)],
2362 SeqSep::trailing_allowed(token::Comma),
2363 TokenExpectType::Expect,
2368 let span = lo.to(self.prev_span);
2369 let output = if self.eat(&token::RArrow) {
2370 Some(self.parse_ty_common(false, false, false)?)
2374 ParenthesizedArgs { inputs, output, span }.into()
2377 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2379 // Generic arguments are not found.
2380 PathSegment::from_ident(ident)
2384 crate fn check_lifetime(&mut self) -> bool {
2385 self.expected_tokens.push(TokenType::Lifetime);
2386 self.token.is_lifetime()
2389 /// Parses a single lifetime `'a` or panics.
2390 crate fn expect_lifetime(&mut self) -> Lifetime {
2391 if let Some(ident) = self.token.lifetime() {
2392 let span = self.span;
2394 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2396 self.span_bug(self.span, "not a lifetime")
2400 fn eat_label(&mut self) -> Option<Label> {
2401 if let Some(ident) = self.token.lifetime() {
2402 let span = self.span;
2404 Some(Label { ident: Ident::new(ident.name, span) })
2410 /// Parses mutability (`mut` or nothing).
2411 fn parse_mutability(&mut self) -> Mutability {
2412 if self.eat_keyword(keywords::Mut) {
2415 Mutability::Immutable
2419 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2420 if let token::Literal(token::Integer(name), suffix) = self.token {
2421 self.expect_no_suffix(self.span, "a tuple index", suffix);
2423 Ok(Ident::new(name, self.prev_span))
2425 self.parse_ident_common(false)
2429 /// Parse ident (COLON expr)?
2430 fn parse_field(&mut self) -> PResult<'a, Field> {
2431 let attrs = self.parse_outer_attributes()?;
2434 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2435 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2436 t == &token::Colon || t == &token::Eq
2438 let fieldname = self.parse_field_name()?;
2440 // Check for an equals token. This means the source incorrectly attempts to
2441 // initialize a field with an eq rather than a colon.
2442 if self.token == token::Eq {
2444 .struct_span_err(self.span, "expected `:`, found `=`")
2446 fieldname.span.shrink_to_hi().to(self.span),
2447 "replace equals symbol with a colon",
2449 Applicability::MachineApplicable,
2454 (fieldname, self.parse_expr()?, false)
2456 let fieldname = self.parse_ident_common(false)?;
2458 // Mimic `x: x` for the `x` field shorthand.
2459 let path = ast::Path::from_ident(fieldname);
2460 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2461 (fieldname, expr, true)
2465 span: lo.to(expr.span),
2468 attrs: attrs.into(),
2472 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2473 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2476 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2477 ExprKind::Unary(unop, expr)
2480 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2481 ExprKind::Binary(binop, lhs, rhs)
2484 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2485 ExprKind::Call(f, args)
2488 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2489 ExprKind::Index(expr, idx)
2492 fn mk_range(&mut self,
2493 start: Option<P<Expr>>,
2494 end: Option<P<Expr>>,
2495 limits: RangeLimits)
2496 -> PResult<'a, ast::ExprKind> {
2497 if end.is_none() && limits == RangeLimits::Closed {
2498 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2500 Ok(ExprKind::Range(start, end, limits))
2504 fn mk_assign_op(&mut self, binop: ast::BinOp,
2505 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2506 ExprKind::AssignOp(binop, lhs, rhs)
2509 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2510 let delim = match self.token {
2511 token::OpenDelim(delim) => delim,
2513 let msg = "expected open delimiter";
2514 let mut err = self.fatal(msg);
2515 err.span_label(self.span, msg);
2519 let tts = match self.parse_token_tree() {
2520 TokenTree::Delimited(_, _, tts) => tts,
2521 _ => unreachable!(),
2523 let delim = match delim {
2524 token::Paren => MacDelimiter::Parenthesis,
2525 token::Bracket => MacDelimiter::Bracket,
2526 token::Brace => MacDelimiter::Brace,
2527 token::NoDelim => self.bug("unexpected no delimiter"),
2529 Ok((delim, tts.into()))
2532 /// At the bottom (top?) of the precedence hierarchy,
2533 /// Parses things like parenthesized exprs, macros, `return`, etc.
2535 /// N.B., this does not parse outer attributes, and is private because it only works
2536 /// correctly if called from `parse_dot_or_call_expr()`.
2537 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2538 maybe_recover_from_interpolated_ty_qpath!(self, true);
2539 maybe_whole_expr!(self);
2541 // Outer attributes are already parsed and will be
2542 // added to the return value after the fact.
2544 // Therefore, prevent sub-parser from parsing
2545 // attributes by giving them a empty "already parsed" list.
2546 let mut attrs = ThinVec::new();
2549 let mut hi = self.span;
2553 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2555 token::OpenDelim(token::Paren) => {
2558 attrs.extend(self.parse_inner_attributes()?);
2560 // (e) is parenthesized e
2561 // (e,) is a tuple with only one field, e
2562 let mut es = vec![];
2563 let mut trailing_comma = false;
2564 let mut recovered = false;
2565 while self.token != token::CloseDelim(token::Paren) {
2566 es.push(match self.parse_expr() {
2569 // recover from parse error in tuple list
2570 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2573 recovered = self.expect_one_of(
2575 &[token::Comma, token::CloseDelim(token::Paren)],
2577 if self.eat(&token::Comma) {
2578 trailing_comma = true;
2580 trailing_comma = false;
2588 hi = self.prev_span;
2589 ex = if es.len() == 1 && !trailing_comma {
2590 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2595 token::OpenDelim(token::Brace) => {
2596 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2598 token::BinOp(token::Or) | token::OrOr => {
2599 return self.parse_lambda_expr(attrs);
2601 token::OpenDelim(token::Bracket) => {
2604 attrs.extend(self.parse_inner_attributes()?);
2606 if self.eat(&token::CloseDelim(token::Bracket)) {
2608 ex = ExprKind::Array(Vec::new());
2611 let first_expr = self.parse_expr()?;
2612 if self.eat(&token::Semi) {
2613 // Repeating array syntax: [ 0; 512 ]
2614 let count = AnonConst {
2615 id: ast::DUMMY_NODE_ID,
2616 value: self.parse_expr()?,
2618 self.expect(&token::CloseDelim(token::Bracket))?;
2619 ex = ExprKind::Repeat(first_expr, count);
2620 } else if self.eat(&token::Comma) {
2621 // Vector with two or more elements.
2622 let remaining_exprs = self.parse_seq_to_end(
2623 &token::CloseDelim(token::Bracket),
2624 SeqSep::trailing_allowed(token::Comma),
2625 |p| Ok(p.parse_expr()?)
2627 let mut exprs = vec![first_expr];
2628 exprs.extend(remaining_exprs);
2629 ex = ExprKind::Array(exprs);
2631 // Vector with one element.
2632 self.expect(&token::CloseDelim(token::Bracket))?;
2633 ex = ExprKind::Array(vec![first_expr]);
2636 hi = self.prev_span;
2640 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2642 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2644 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2646 if self.is_async_block() { // check for `async {` and `async move {`
2647 return self.parse_async_block(attrs);
2649 return self.parse_lambda_expr(attrs);
2652 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2653 return self.parse_lambda_expr(attrs);
2655 if self.eat_keyword(keywords::If) {
2656 return self.parse_if_expr(attrs);
2658 if self.eat_keyword(keywords::For) {
2659 let lo = self.prev_span;
2660 return self.parse_for_expr(None, lo, attrs);
2662 if self.eat_keyword(keywords::While) {
2663 let lo = self.prev_span;
2664 return self.parse_while_expr(None, lo, attrs);
2666 if let Some(label) = self.eat_label() {
2667 let lo = label.ident.span;
2668 self.expect(&token::Colon)?;
2669 if self.eat_keyword(keywords::While) {
2670 return self.parse_while_expr(Some(label), lo, attrs)
2672 if self.eat_keyword(keywords::For) {
2673 return self.parse_for_expr(Some(label), lo, attrs)
2675 if self.eat_keyword(keywords::Loop) {
2676 return self.parse_loop_expr(Some(label), lo, attrs)
2678 if self.token == token::OpenDelim(token::Brace) {
2679 return self.parse_block_expr(Some(label),
2681 BlockCheckMode::Default,
2684 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2685 let mut err = self.fatal(msg);
2686 err.span_label(self.span, msg);
2689 if self.eat_keyword(keywords::Loop) {
2690 let lo = self.prev_span;
2691 return self.parse_loop_expr(None, lo, attrs);
2693 if self.eat_keyword(keywords::Continue) {
2694 let label = self.eat_label();
2695 let ex = ExprKind::Continue(label);
2696 let hi = self.prev_span;
2697 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2699 if self.eat_keyword(keywords::Match) {
2700 let match_sp = self.prev_span;
2701 return self.parse_match_expr(attrs).map_err(|mut err| {
2702 err.span_label(match_sp, "while parsing this match expression");
2706 if self.eat_keyword(keywords::Unsafe) {
2707 return self.parse_block_expr(
2710 BlockCheckMode::Unsafe(ast::UserProvided),
2713 if self.is_do_catch_block() {
2714 let mut db = self.fatal("found removed `do catch` syntax");
2715 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2718 if self.is_try_block() {
2720 assert!(self.eat_keyword(keywords::Try));
2721 return self.parse_try_block(lo, attrs);
2723 if self.eat_keyword(keywords::Return) {
2724 if self.token.can_begin_expr() {
2725 let e = self.parse_expr()?;
2727 ex = ExprKind::Ret(Some(e));
2729 ex = ExprKind::Ret(None);
2731 } else if self.eat_keyword(keywords::Break) {
2732 let label = self.eat_label();
2733 let e = if self.token.can_begin_expr()
2734 && !(self.token == token::OpenDelim(token::Brace)
2735 && self.restrictions.contains(
2736 Restrictions::NO_STRUCT_LITERAL)) {
2737 Some(self.parse_expr()?)
2741 ex = ExprKind::Break(label, e);
2742 hi = self.prev_span;
2743 } else if self.eat_keyword(keywords::Yield) {
2744 if self.token.can_begin_expr() {
2745 let e = self.parse_expr()?;
2747 ex = ExprKind::Yield(Some(e));
2749 ex = ExprKind::Yield(None);
2751 } else if self.token.is_keyword(keywords::Let) {
2752 // Catch this syntax error here, instead of in `parse_ident`, so
2753 // that we can explicitly mention that let is not to be used as an expression
2754 let mut db = self.fatal("expected expression, found statement (`let`)");
2755 db.span_label(self.span, "expected expression");
2756 db.note("variable declaration using `let` is a statement");
2758 } else if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
2759 // FIXME: remove this branch when `await!` is no longer supported
2760 // https://github.com/rust-lang/rust/issues/60610
2761 self.expect(&token::Not)?;
2762 self.expect(&token::OpenDelim(token::Paren))?;
2763 let expr = self.parse_expr()?;
2764 self.expect(&token::CloseDelim(token::Paren))?;
2765 ex = ExprKind::Await(ast::AwaitOrigin::MacroLike, expr);
2766 } else if self.token.is_path_start() {
2767 let path = self.parse_path(PathStyle::Expr)?;
2769 // `!`, as an operator, is prefix, so we know this isn't that
2770 if self.eat(&token::Not) {
2771 // MACRO INVOCATION expression
2772 let (delim, tts) = self.expect_delimited_token_tree()?;
2773 hi = self.prev_span;
2774 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2775 } else if self.check(&token::OpenDelim(token::Brace)) {
2776 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2780 ex = ExprKind::Path(None, path);
2784 ex = ExprKind::Path(None, path);
2787 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2788 // Don't complain about bare semicolons after unclosed braces
2789 // recovery in order to keep the error count down. Fixing the
2790 // delimiters will possibly also fix the bare semicolon found in
2791 // expression context. For example, silence the following error:
2793 // error: expected expression, found `;`
2797 // | ^ expected expression
2800 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2802 match self.parse_literal_maybe_minus() {
2805 ex = expr.node.clone();
2808 self.cancel(&mut err);
2809 let msg = format!("expected expression, found {}",
2810 self.this_token_descr());
2811 let mut err = self.fatal(&msg);
2812 let sp = self.sess.source_map().start_point(self.span);
2813 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow()
2816 self.sess.expr_parentheses_needed(&mut err, *sp, None);
2818 err.span_label(self.span, "expected expression");
2826 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2827 self.maybe_recover_from_bad_qpath(expr, true)
2830 fn maybe_parse_struct_expr(
2834 attrs: &ThinVec<Attribute>,
2835 ) -> Option<PResult<'a, P<Expr>>> {
2836 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2837 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2838 // `{ ident, ` cannot start a block
2839 self.look_ahead(2, |t| t == &token::Comma) ||
2840 self.look_ahead(2, |t| t == &token::Colon) && (
2841 // `{ ident: token, ` cannot start a block
2842 self.look_ahead(4, |t| t == &token::Comma) ||
2843 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2844 self.look_ahead(3, |t| !t.can_begin_type())
2848 if struct_allowed || certainly_not_a_block() {
2849 // This is a struct literal, but we don't can't accept them here
2850 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2851 if let (Ok(expr), false) = (&expr, struct_allowed) {
2852 let mut err = self.diagnostic().struct_span_err(
2854 "struct literals are not allowed here",
2856 err.multipart_suggestion(
2857 "surround the struct literal with parentheses",
2859 (lo.shrink_to_lo(), "(".to_string()),
2860 (expr.span.shrink_to_hi(), ")".to_string()),
2862 Applicability::MachineApplicable,
2871 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2872 -> PResult<'a, P<Expr>> {
2873 let struct_sp = lo.to(self.prev_span);
2875 let mut fields = Vec::new();
2876 let mut base = None;
2878 attrs.extend(self.parse_inner_attributes()?);
2880 while self.token != token::CloseDelim(token::Brace) {
2881 if self.eat(&token::DotDot) {
2882 let exp_span = self.prev_span;
2883 match self.parse_expr() {
2889 self.recover_stmt();
2892 if self.token == token::Comma {
2893 let mut err = self.sess.span_diagnostic.mut_span_err(
2894 exp_span.to(self.prev_span),
2895 "cannot use a comma after the base struct",
2897 err.span_suggestion_short(
2899 "remove this comma",
2901 Applicability::MachineApplicable
2903 err.note("the base struct must always be the last field");
2905 self.recover_stmt();
2910 let mut recovery_field = None;
2911 if let token::Ident(ident, _) = self.token {
2912 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2913 // Use in case of error after field-looking code: `S { foo: () with a }`
2914 let mut ident = ident.clone();
2915 ident.span = self.span;
2916 recovery_field = Some(ast::Field {
2919 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2920 is_shorthand: false,
2921 attrs: ThinVec::new(),
2925 let mut parsed_field = None;
2926 match self.parse_field() {
2927 Ok(f) => parsed_field = Some(f),
2929 e.span_label(struct_sp, "while parsing this struct");
2932 // If the next token is a comma, then try to parse
2933 // what comes next as additional fields, rather than
2934 // bailing out until next `}`.
2935 if self.token != token::Comma {
2936 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2937 if self.token != token::Comma {
2944 match self.expect_one_of(&[token::Comma],
2945 &[token::CloseDelim(token::Brace)]) {
2946 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2947 // only include the field if there's no parse error for the field name
2951 if let Some(f) = recovery_field {
2954 e.span_label(struct_sp, "while parsing this struct");
2956 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2957 self.eat(&token::Comma);
2962 let span = lo.to(self.span);
2963 self.expect(&token::CloseDelim(token::Brace))?;
2964 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2967 fn parse_or_use_outer_attributes(&mut self,
2968 already_parsed_attrs: Option<ThinVec<Attribute>>)
2969 -> PResult<'a, ThinVec<Attribute>> {
2970 if let Some(attrs) = already_parsed_attrs {
2973 self.parse_outer_attributes().map(|a| a.into())
2977 /// Parses a block or unsafe block.
2978 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2979 lo: Span, blk_mode: BlockCheckMode,
2980 outer_attrs: ThinVec<Attribute>)
2981 -> PResult<'a, P<Expr>> {
2982 self.expect(&token::OpenDelim(token::Brace))?;
2984 let mut attrs = outer_attrs;
2985 attrs.extend(self.parse_inner_attributes()?);
2987 let blk = self.parse_block_tail(lo, blk_mode)?;
2988 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2991 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2992 fn parse_dot_or_call_expr(&mut self,
2993 already_parsed_attrs: Option<ThinVec<Attribute>>)
2994 -> PResult<'a, P<Expr>> {
2995 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2997 let b = self.parse_bottom_expr();
2998 let (span, b) = self.interpolated_or_expr_span(b)?;
2999 self.parse_dot_or_call_expr_with(b, span, attrs)
3002 fn parse_dot_or_call_expr_with(&mut self,
3005 mut attrs: ThinVec<Attribute>)
3006 -> PResult<'a, P<Expr>> {
3007 // Stitch the list of outer attributes onto the return value.
3008 // A little bit ugly, but the best way given the current code
3010 self.parse_dot_or_call_expr_with_(e0, lo)
3012 expr.map(|mut expr| {
3013 attrs.extend::<Vec<_>>(expr.attrs.into());
3016 ExprKind::If(..) | ExprKind::IfLet(..) => {
3017 if !expr.attrs.is_empty() {
3018 // Just point to the first attribute in there...
3019 let span = expr.attrs[0].span;
3022 "attributes are not yet allowed on `if` \
3033 // Assuming we have just parsed `.`, continue parsing into an expression.
3034 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3035 if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
3036 let span = lo.to(self.prev_span);
3037 let await_expr = self.mk_expr(
3039 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
3042 return Ok(await_expr);
3044 let segment = self.parse_path_segment(PathStyle::Expr)?;
3045 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3047 Ok(match self.token {
3048 token::OpenDelim(token::Paren) => {
3049 // Method call `expr.f()`
3050 let mut args = self.parse_unspanned_seq(
3051 &token::OpenDelim(token::Paren),
3052 &token::CloseDelim(token::Paren),
3053 SeqSep::trailing_allowed(token::Comma),
3054 |p| Ok(p.parse_expr()?)
3056 args.insert(0, self_arg);
3058 let span = lo.to(self.prev_span);
3059 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3062 // Field access `expr.f`
3063 if let Some(args) = segment.args {
3064 self.span_err(args.span(),
3065 "field expressions may not have generic arguments");
3068 let span = lo.to(self.prev_span);
3069 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3074 /// This function checks if there are trailing angle brackets and produces
3075 /// a diagnostic to suggest removing them.
3077 /// ```ignore (diagnostic)
3078 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3079 /// ^^ help: remove extra angle brackets
3081 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3082 // This function is intended to be invoked after parsing a path segment where there are two
3085 // 1. A specific token is expected after the path segment.
3086 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3087 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3088 // 2. No specific token is expected after the path segment.
3089 // eg. `x.foo` (field access)
3091 // This function is called after parsing `.foo` and before parsing the token `end` (if
3092 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3095 // We only care about trailing angle brackets if we previously parsed angle bracket
3096 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3097 // removed in this case:
3099 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3101 // This case is particularly tricky as we won't notice it just looking at the tokens -
3102 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3103 // have already been parsed):
3105 // `x.foo::<u32>>>(3)`
3106 let parsed_angle_bracket_args = segment.args
3108 .map(|args| args.is_angle_bracketed())
3112 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3113 parsed_angle_bracket_args,
3115 if !parsed_angle_bracket_args {
3119 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3123 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3124 // (since we might have the field access case and the characters we're eating are
3125 // actual operators and not trailing characters - ie `x.foo >> 3`).
3126 let mut position = 0;
3128 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3129 // many of each (so we can correctly pluralize our error messages) and continue to
3131 let mut number_of_shr = 0;
3132 let mut number_of_gt = 0;
3133 while self.look_ahead(position, |t| {
3134 trace!("check_trailing_angle_brackets: t={:?}", t);
3135 if *t == token::BinOp(token::BinOpToken::Shr) {
3138 } else if *t == token::Gt {
3148 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3150 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3151 number_of_gt, number_of_shr,
3153 if number_of_gt < 1 && number_of_shr < 1 {
3157 // Finally, double check that we have our end token as otherwise this is the
3159 if self.look_ahead(position, |t| {
3160 trace!("check_trailing_angle_brackets: t={:?}", t);
3163 // Eat from where we started until the end token so that parsing can continue
3164 // as if we didn't have those extra angle brackets.
3165 self.eat_to_tokens(&[&end]);
3166 let span = lo.until(self.span);
3168 let plural = number_of_gt > 1 || number_of_shr >= 1;
3172 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3176 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3178 Applicability::MachineApplicable,
3184 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3189 while self.eat(&token::Question) {
3190 let hi = self.prev_span;
3191 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3195 if self.eat(&token::Dot) {
3197 token::Ident(..) => {
3198 e = self.parse_dot_suffix(e, lo)?;
3200 token::Literal(token::Integer(name), suffix) => {
3201 let span = self.span;
3203 let field = ExprKind::Field(e, Ident::new(name, span));
3204 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3206 self.expect_no_suffix(span, "a tuple index", suffix);
3208 token::Literal(token::Float(n), _suf) => {
3210 let fstr = n.as_str();
3211 let mut err = self.diagnostic()
3212 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3213 err.span_label(self.prev_span, "unexpected token");
3214 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3215 let float = match fstr.parse::<f64>().ok() {
3219 let sugg = pprust::to_string(|s| {
3220 use crate::print::pprust::PrintState;
3224 s.print_usize(float.trunc() as usize)?;
3227 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3229 err.span_suggestion(
3230 lo.to(self.prev_span),
3231 "try parenthesizing the first index",
3233 Applicability::MachineApplicable
3240 // FIXME Could factor this out into non_fatal_unexpected or something.
3241 let actual = self.this_token_to_string();
3242 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3247 if self.expr_is_complete(&e) { break; }
3250 token::OpenDelim(token::Paren) => {
3251 let seq = self.parse_unspanned_seq(
3252 &token::OpenDelim(token::Paren),
3253 &token::CloseDelim(token::Paren),
3254 SeqSep::trailing_allowed(token::Comma),
3255 |p| Ok(p.parse_expr()?)
3257 let nd = self.mk_call(e, es);
3258 let hi = self.prev_span;
3259 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3261 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3265 // Could be either an index expression or a slicing expression.
3266 token::OpenDelim(token::Bracket) => {
3268 let ix = self.parse_expr()?;
3270 self.expect(&token::CloseDelim(token::Bracket))?;
3271 let index = self.mk_index(e, ix);
3272 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3280 fn recover_seq_parse_error(
3282 delim: token::DelimToken,
3284 result: PResult<'a, P<Expr>>,
3290 // recover from parse error
3291 self.consume_block(delim);
3292 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
3297 crate fn process_potential_macro_variable(&mut self) {
3298 let (token, span) = match self.token {
3299 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3300 self.look_ahead(1, |t| t.is_ident()) => {
3302 let name = match self.token {
3303 token::Ident(ident, _) => ident,
3306 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3307 err.span_label(self.span, "unknown macro variable");
3312 token::Interpolated(ref nt) => {
3313 self.meta_var_span = Some(self.span);
3314 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3315 // and lifetime tokens, so the former are never encountered during normal parsing.
3317 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3318 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3328 /// Parses a single token tree from the input.
3329 crate fn parse_token_tree(&mut self) -> TokenTree {
3331 token::OpenDelim(..) => {
3332 let frame = mem::replace(&mut self.token_cursor.frame,
3333 self.token_cursor.stack.pop().unwrap());
3334 self.span = frame.span.entire();
3336 TokenTree::Delimited(
3339 frame.tree_cursor.stream.into(),
3342 token::CloseDelim(_) | token::Eof => unreachable!(),
3344 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3346 TokenTree::Token(span, token)
3351 // parse a stream of tokens into a list of TokenTree's,
3353 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3354 let mut tts = Vec::new();
3355 while self.token != token::Eof {
3356 tts.push(self.parse_token_tree());
3361 pub fn parse_tokens(&mut self) -> TokenStream {
3362 let mut result = Vec::new();
3365 token::Eof | token::CloseDelim(..) => break,
3366 _ => result.push(self.parse_token_tree().into()),
3369 TokenStream::new(result)
3372 /// Parse a prefix-unary-operator expr
3373 fn parse_prefix_expr(&mut self,
3374 already_parsed_attrs: Option<ThinVec<Attribute>>)
3375 -> PResult<'a, P<Expr>> {
3376 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3378 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3379 let (hi, ex) = match self.token {
3382 let e = self.parse_prefix_expr(None);
3383 let (span, e) = self.interpolated_or_expr_span(e)?;
3384 (lo.to(span), self.mk_unary(UnOp::Not, e))
3386 // Suggest `!` for bitwise negation when encountering a `~`
3389 let e = self.parse_prefix_expr(None);
3390 let (span, e) = self.interpolated_or_expr_span(e)?;
3391 let span_of_tilde = lo;
3392 let mut err = self.diagnostic()
3393 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3394 err.span_suggestion_short(
3396 "use `!` to perform bitwise negation",
3398 Applicability::MachineApplicable
3401 (lo.to(span), self.mk_unary(UnOp::Not, e))
3403 token::BinOp(token::Minus) => {
3405 let e = self.parse_prefix_expr(None);
3406 let (span, e) = self.interpolated_or_expr_span(e)?;
3407 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3409 token::BinOp(token::Star) => {
3411 let e = self.parse_prefix_expr(None);
3412 let (span, e) = self.interpolated_or_expr_span(e)?;
3413 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3415 token::BinOp(token::And) | token::AndAnd => {
3417 let m = self.parse_mutability();
3418 let e = self.parse_prefix_expr(None);
3419 let (span, e) = self.interpolated_or_expr_span(e)?;
3420 (lo.to(span), ExprKind::AddrOf(m, e))
3422 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3424 let place = self.parse_expr_res(
3425 Restrictions::NO_STRUCT_LITERAL,
3428 let blk = self.parse_block()?;
3429 let span = blk.span;
3430 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3431 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3433 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3435 let e = self.parse_prefix_expr(None);
3436 let (span, e) = self.interpolated_or_expr_span(e)?;
3437 (lo.to(span), ExprKind::Box(e))
3439 token::Ident(..) if self.token.is_ident_named("not") => {
3440 // `not` is just an ordinary identifier in Rust-the-language,
3441 // but as `rustc`-the-compiler, we can issue clever diagnostics
3442 // for confused users who really want to say `!`
3443 let token_cannot_continue_expr = |t: &token::Token| match *t {
3444 // These tokens can start an expression after `!`, but
3445 // can't continue an expression after an ident
3446 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3447 token::Literal(..) | token::Pound => true,
3448 token::Interpolated(ref nt) => match **nt {
3449 token::NtIdent(..) | token::NtExpr(..) |
3450 token::NtBlock(..) | token::NtPath(..) => true,
3455 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3456 if cannot_continue_expr {
3458 // Emit the error ...
3459 let mut err = self.diagnostic()
3460 .struct_span_err(self.span,
3461 &format!("unexpected {} after identifier",
3462 self.this_token_descr()));
3463 // span the `not` plus trailing whitespace to avoid
3464 // trailing whitespace after the `!` in our suggestion
3465 let to_replace = self.sess.source_map()
3466 .span_until_non_whitespace(lo.to(self.span));
3467 err.span_suggestion_short(
3469 "use `!` to perform logical negation",
3471 Applicability::MachineApplicable
3474 // —and recover! (just as if we were in the block
3475 // for the `token::Not` arm)
3476 let e = self.parse_prefix_expr(None);
3477 let (span, e) = self.interpolated_or_expr_span(e)?;
3478 (lo.to(span), self.mk_unary(UnOp::Not, e))
3480 return self.parse_dot_or_call_expr(Some(attrs));
3483 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3485 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3488 /// Parses an associative expression.
3490 /// This parses an expression accounting for associativity and precedence of the operators in
3493 fn parse_assoc_expr(&mut self,
3494 already_parsed_attrs: Option<ThinVec<Attribute>>)
3495 -> PResult<'a, P<Expr>> {
3496 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3499 /// Parses an associative expression with operators of at least `min_prec` precedence.
3500 fn parse_assoc_expr_with(&mut self,
3503 -> PResult<'a, P<Expr>> {
3504 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3507 let attrs = match lhs {
3508 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3511 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3512 return self.parse_prefix_range_expr(attrs);
3514 self.parse_prefix_expr(attrs)?
3518 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
3520 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3523 (false, _) => {} // continue parsing the expression
3524 // An exhaustive check is done in the following block, but these are checked first
3525 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
3526 // want to keep their span info to improve diagnostics in these cases in a later stage.
3527 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
3528 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
3529 (true, Some(AssocOp::Add)) => { // `{ 42 } + 42
3530 // These cases are ambiguous and can't be identified in the parser alone
3531 let sp = self.sess.source_map().start_point(self.span);
3532 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
3535 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
3538 (true, Some(_)) => {
3539 // We've found an expression that would be parsed as a statement, but the next
3540 // token implies this should be parsed as an expression.
3541 // For example: `if let Some(x) = x { x } else { 0 } / 2`
3542 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
3543 "expected expression, found `{}`",
3544 pprust::token_to_string(&self.token),
3546 err.span_label(self.span, "expected expression");
3547 self.sess.expr_parentheses_needed(
3550 Some(pprust::expr_to_string(&lhs),
3555 self.expected_tokens.push(TokenType::Operator);
3556 while let Some(op) = AssocOp::from_token(&self.token) {
3558 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3559 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3560 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3561 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3562 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3563 (PrevTokenKind::Interpolated, _) => self.prev_span,
3564 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3565 if path.segments.len() == 1 => self.prev_span,
3569 let cur_op_span = self.span;
3570 let restrictions = if op.is_assign_like() {
3571 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3575 if op.precedence() < min_prec {
3578 // Check for deprecated `...` syntax
3579 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3580 self.err_dotdotdot_syntax(self.span);
3584 if op.is_comparison() {
3585 self.check_no_chained_comparison(&lhs, &op);
3588 if op == AssocOp::As {
3589 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3591 } else if op == AssocOp::Colon {
3592 let maybe_path = self.could_ascription_be_path(&lhs.node);
3593 let next_sp = self.span;
3595 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3598 self.bad_type_ascription(
3609 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3610 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3611 // generalise it to the Fixity::None code.
3613 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3614 // two variants are handled with `parse_prefix_range_expr` call above.
3615 let rhs = if self.is_at_start_of_range_notation_rhs() {
3616 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3617 LhsExpr::NotYetParsed)?)
3621 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3626 let limits = if op == AssocOp::DotDot {
3627 RangeLimits::HalfOpen
3632 let r = self.mk_range(Some(lhs), rhs, limits)?;
3633 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3637 let rhs = match op.fixity() {
3638 Fixity::Right => self.with_res(
3639 restrictions - Restrictions::STMT_EXPR,
3641 this.parse_assoc_expr_with(op.precedence(),
3642 LhsExpr::NotYetParsed)
3644 Fixity::Left => self.with_res(
3645 restrictions - Restrictions::STMT_EXPR,
3647 this.parse_assoc_expr_with(op.precedence() + 1,
3648 LhsExpr::NotYetParsed)
3650 // We currently have no non-associative operators that are not handled above by
3651 // the special cases. The code is here only for future convenience.
3652 Fixity::None => self.with_res(
3653 restrictions - Restrictions::STMT_EXPR,
3655 this.parse_assoc_expr_with(op.precedence() + 1,
3656 LhsExpr::NotYetParsed)
3660 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3661 // including the attributes.
3665 .filter(|a| a.style == AttrStyle::Outer)
3667 .map_or(lhs_span, |a| a.span);
3668 let span = lhs_span.to(rhs.span);
3670 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3671 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3672 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3673 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3674 AssocOp::Greater | AssocOp::GreaterEqual => {
3675 let ast_op = op.to_ast_binop().unwrap();
3676 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3677 self.mk_expr(span, binary, ThinVec::new())
3680 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3681 AssocOp::ObsoleteInPlace =>
3682 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3683 AssocOp::AssignOp(k) => {
3685 token::Plus => BinOpKind::Add,
3686 token::Minus => BinOpKind::Sub,
3687 token::Star => BinOpKind::Mul,
3688 token::Slash => BinOpKind::Div,
3689 token::Percent => BinOpKind::Rem,
3690 token::Caret => BinOpKind::BitXor,
3691 token::And => BinOpKind::BitAnd,
3692 token::Or => BinOpKind::BitOr,
3693 token::Shl => BinOpKind::Shl,
3694 token::Shr => BinOpKind::Shr,
3696 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3697 self.mk_expr(span, aopexpr, ThinVec::new())
3699 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3700 self.bug("AssocOp should have been handled by special case")
3704 if op.fixity() == Fixity::None { break }
3709 fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
3710 self.token.is_ident() &&
3711 if let ast::ExprKind::Path(..) = node { true } else { false } &&
3712 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
3713 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
3714 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
3715 self.look_ahead(2, |t| t.is_ident()) ||
3716 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
3717 self.look_ahead(2, |t| t.is_ident()) ||
3718 self.look_ahead(1, |t| t == &token::ModSep) && // `foo:bar::baz`
3719 self.look_ahead(2, |t| t.is_ident())
3722 fn bad_type_ascription(
3724 err: &mut DiagnosticBuilder<'a>,
3730 err.span_label(self.span, "expecting a type here because of type ascription");
3731 let cm = self.sess.source_map();
3732 let next_pos = cm.lookup_char_pos(next_sp.lo());
3733 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3734 if op_pos.line != next_pos.line {
3735 err.span_suggestion(
3737 "try using a semicolon",
3739 Applicability::MaybeIncorrect,
3743 err.span_suggestion(
3745 "maybe you meant to write a path separator here",
3747 Applicability::MaybeIncorrect,
3750 err.note("type ascription is a nightly-only feature that lets \
3751 you annotate an expression with a type: `<expr>: <type>`");
3754 "this expression expects an ascribed type after the colon",
3756 err.help("this might be indicative of a syntax error elsewhere");
3761 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3762 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3763 -> PResult<'a, P<Expr>> {
3764 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3765 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3768 // Save the state of the parser before parsing type normally, in case there is a
3769 // LessThan comparison after this cast.
3770 let parser_snapshot_before_type = self.clone();
3771 match self.parse_ty_no_plus() {
3773 Ok(mk_expr(self, rhs))
3775 Err(mut type_err) => {
3776 // Rewind to before attempting to parse the type with generics, to recover
3777 // from situations like `x as usize < y` in which we first tried to parse
3778 // `usize < y` as a type with generic arguments.
3779 let parser_snapshot_after_type = self.clone();
3780 mem::replace(self, parser_snapshot_before_type);
3782 match self.parse_path(PathStyle::Expr) {
3784 let (op_noun, op_verb) = match self.token {
3785 token::Lt => ("comparison", "comparing"),
3786 token::BinOp(token::Shl) => ("shift", "shifting"),
3788 // We can end up here even without `<` being the next token, for
3789 // example because `parse_ty_no_plus` returns `Err` on keywords,
3790 // but `parse_path` returns `Ok` on them due to error recovery.
3791 // Return original error and parser state.
3792 mem::replace(self, parser_snapshot_after_type);
3793 return Err(type_err);
3797 // Successfully parsed the type path leaving a `<` yet to parse.
3800 // Report non-fatal diagnostics, keep `x as usize` as an expression
3801 // in AST and continue parsing.
3802 let msg = format!("`<` is interpreted as a start of generic \
3803 arguments for `{}`, not a {}", path, op_noun);
3804 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3805 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3806 "interpreted as generic arguments");
3807 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3809 let expr = mk_expr(self, P(Ty {
3811 node: TyKind::Path(None, path),
3812 id: ast::DUMMY_NODE_ID
3815 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3816 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3817 err.span_suggestion(
3819 &format!("try {} the cast value", op_verb),
3820 format!("({})", expr_str),
3821 Applicability::MachineApplicable
3827 Err(mut path_err) => {
3828 // Couldn't parse as a path, return original error and parser state.
3830 mem::replace(self, parser_snapshot_after_type);
3838 /// Produce an error if comparison operators are chained (RFC #558).
3839 /// We only need to check lhs, not rhs, because all comparison ops
3840 /// have same precedence and are left-associative
3841 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3842 debug_assert!(outer_op.is_comparison(),
3843 "check_no_chained_comparison: {:?} is not comparison",
3846 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3847 // respan to include both operators
3848 let op_span = op.span.to(self.span);
3849 let mut err = self.diagnostic().struct_span_err(op_span,
3850 "chained comparison operators require parentheses");
3851 if op.node == BinOpKind::Lt &&
3852 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3853 *outer_op == AssocOp::Greater // even in a case like the following:
3854 { // Foo<Bar<Baz<Qux, ()>>>
3856 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3857 err.help("or use `(...)` if you meant to specify fn arguments");
3865 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3866 fn parse_prefix_range_expr(&mut self,
3867 already_parsed_attrs: Option<ThinVec<Attribute>>)
3868 -> PResult<'a, P<Expr>> {
3869 // Check for deprecated `...` syntax
3870 if self.token == token::DotDotDot {
3871 self.err_dotdotdot_syntax(self.span);
3874 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3875 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3877 let tok = self.token.clone();
3878 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3880 let mut hi = self.span;
3882 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3883 // RHS must be parsed with more associativity than the dots.
3884 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3885 Some(self.parse_assoc_expr_with(next_prec,
3886 LhsExpr::NotYetParsed)
3894 let limits = if tok == token::DotDot {
3895 RangeLimits::HalfOpen
3900 let r = self.mk_range(None, opt_end, limits)?;
3901 Ok(self.mk_expr(lo.to(hi), r, attrs))
3904 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3905 if self.token.can_begin_expr() {
3906 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3907 if self.token == token::OpenDelim(token::Brace) {
3908 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3916 /// Parses an `if` or `if let` expression (`if` token already eaten).
3917 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3918 if self.check_keyword(keywords::Let) {
3919 return self.parse_if_let_expr(attrs);
3921 let lo = self.prev_span;
3922 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3924 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3925 // verify that the last statement is either an implicit return (no `;`) or an explicit
3926 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3927 // the dead code lint.
3928 if self.eat_keyword(keywords::Else) || !cond.returns() {
3929 let sp = self.sess.source_map().next_point(lo);
3930 let mut err = self.diagnostic()
3931 .struct_span_err(sp, "missing condition for `if` statemement");
3932 err.span_label(sp, "expected if condition here");
3935 let not_block = self.token != token::OpenDelim(token::Brace);
3936 let thn = self.parse_block().map_err(|mut err| {
3938 err.span_label(lo, "this `if` statement has a condition, but no block");
3942 let mut els: Option<P<Expr>> = None;
3943 let mut hi = thn.span;
3944 if self.eat_keyword(keywords::Else) {
3945 let elexpr = self.parse_else_expr()?;
3949 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3952 /// Parses an `if let` expression (`if` token already eaten).
3953 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3954 -> PResult<'a, P<Expr>> {
3955 let lo = self.prev_span;
3956 self.expect_keyword(keywords::Let)?;
3957 let pats = self.parse_pats()?;
3958 self.expect(&token::Eq)?;
3959 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3960 let thn = self.parse_block()?;
3961 let (hi, els) = if self.eat_keyword(keywords::Else) {
3962 let expr = self.parse_else_expr()?;
3963 (expr.span, Some(expr))
3967 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3970 /// Parses `move |args| expr`.
3971 fn parse_lambda_expr(&mut self,
3972 attrs: ThinVec<Attribute>)
3973 -> PResult<'a, P<Expr>>
3976 let movability = if self.eat_keyword(keywords::Static) {
3981 let asyncness = if self.span.rust_2018() {
3982 self.parse_asyncness()
3986 let capture_clause = if self.eat_keyword(keywords::Move) {
3991 let decl = self.parse_fn_block_decl()?;
3992 let decl_hi = self.prev_span;
3993 let body = match decl.output {
3994 FunctionRetTy::Default(_) => {
3995 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3996 self.parse_expr_res(restrictions, None)?
3999 // If an explicit return type is given, require a
4000 // block to appear (RFC 968).
4001 let body_lo = self.span;
4002 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
4008 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
4012 // `else` token already eaten
4013 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
4014 if self.eat_keyword(keywords::If) {
4015 return self.parse_if_expr(ThinVec::new());
4017 let blk = self.parse_block()?;
4018 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
4022 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
4023 fn parse_for_expr(&mut self, opt_label: Option<Label>,
4025 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4026 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
4028 let pat = self.parse_top_level_pat()?;
4029 if !self.eat_keyword(keywords::In) {
4030 let in_span = self.prev_span.between(self.span);
4031 let mut err = self.sess.span_diagnostic
4032 .struct_span_err(in_span, "missing `in` in `for` loop");
4033 err.span_suggestion_short(
4034 in_span, "try adding `in` here", " in ".into(),
4035 // has been misleading, at least in the past (closed Issue #48492)
4036 Applicability::MaybeIncorrect
4040 let in_span = self.prev_span;
4041 if self.eat_keyword(keywords::In) {
4042 // a common typo: `for _ in in bar {}`
4043 let mut err = self.sess.span_diagnostic.struct_span_err(
4045 "expected iterable, found keyword `in`",
4047 err.span_suggestion_short(
4048 in_span.until(self.prev_span),
4049 "remove the duplicated `in`",
4051 Applicability::MachineApplicable,
4053 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
4054 err.note("for more information on the status of emplacement syntax, see <\
4055 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
4058 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4059 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
4060 attrs.extend(iattrs);
4062 let hi = self.prev_span;
4063 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
4066 /// Parses a `while` or `while let` expression (`while` token already eaten).
4067 fn parse_while_expr(&mut self, opt_label: Option<Label>,
4069 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4070 if self.token.is_keyword(keywords::Let) {
4071 return self.parse_while_let_expr(opt_label, span_lo, attrs);
4073 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4074 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4075 attrs.extend(iattrs);
4076 let span = span_lo.to(body.span);
4077 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
4080 /// Parses a `while let` expression (`while` token already eaten).
4081 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
4083 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4084 self.expect_keyword(keywords::Let)?;
4085 let pats = self.parse_pats()?;
4086 self.expect(&token::Eq)?;
4087 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4088 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4089 attrs.extend(iattrs);
4090 let span = span_lo.to(body.span);
4091 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
4094 // parse `loop {...}`, `loop` token already eaten
4095 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
4097 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4098 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4099 attrs.extend(iattrs);
4100 let span = span_lo.to(body.span);
4101 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
4104 /// Parses an `async move {...}` expression.
4105 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4106 -> PResult<'a, P<Expr>>
4108 let span_lo = self.span;
4109 self.expect_keyword(keywords::Async)?;
4110 let capture_clause = if self.eat_keyword(keywords::Move) {
4115 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4116 attrs.extend(iattrs);
4118 span_lo.to(body.span),
4119 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4122 /// Parses a `try {...}` expression (`try` token already eaten).
4123 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4124 -> PResult<'a, P<Expr>>
4126 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4127 attrs.extend(iattrs);
4128 if self.eat_keyword(keywords::Catch) {
4129 let mut error = self.struct_span_err(self.prev_span,
4130 "keyword `catch` cannot follow a `try` block");
4131 error.help("try using `match` on the result of the `try` block instead");
4135 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4139 // `match` token already eaten
4140 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4141 let match_span = self.prev_span;
4142 let lo = self.prev_span;
4143 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4145 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4146 if self.token == token::Token::Semi {
4147 e.span_suggestion_short(
4149 "try removing this `match`",
4151 Applicability::MaybeIncorrect // speculative
4156 attrs.extend(self.parse_inner_attributes()?);
4158 let mut arms: Vec<Arm> = Vec::new();
4159 while self.token != token::CloseDelim(token::Brace) {
4160 match self.parse_arm() {
4161 Ok(arm) => arms.push(arm),
4163 // Recover by skipping to the end of the block.
4165 self.recover_stmt();
4166 let span = lo.to(self.span);
4167 if self.token == token::CloseDelim(token::Brace) {
4170 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4176 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4179 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4180 let attrs = self.parse_outer_attributes()?;
4181 let pats = self.parse_pats()?;
4182 let guard = if self.eat_keyword(keywords::If) {
4183 Some(Guard::If(self.parse_expr()?))
4187 let arrow_span = self.span;
4188 self.expect(&token::FatArrow)?;
4189 let arm_start_span = self.span;
4191 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4192 .map_err(|mut err| {
4193 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4197 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4198 && self.token != token::CloseDelim(token::Brace);
4201 let cm = self.sess.source_map();
4202 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4203 .map_err(|mut err| {
4204 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4205 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4206 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4207 && expr_lines.lines.len() == 2
4208 && self.token == token::FatArrow => {
4209 // We check whether there's any trailing code in the parse span,
4210 // if there isn't, we very likely have the following:
4213 // | -- - missing comma
4219 // | parsed until here as `"y" & X`
4220 err.span_suggestion_short(
4221 cm.next_point(arm_start_span),
4222 "missing a comma here to end this `match` arm",
4224 Applicability::MachineApplicable
4228 err.span_label(arrow_span,
4229 "while parsing the `match` arm starting here");
4235 self.eat(&token::Comma);
4246 /// Parses an expression.
4248 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4249 self.parse_expr_res(Restrictions::empty(), None)
4252 /// Evaluates the closure with restrictions in place.
4254 /// Afters the closure is evaluated, restrictions are reset.
4255 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4256 where F: FnOnce(&mut Self) -> T
4258 let old = self.restrictions;
4259 self.restrictions = r;
4261 self.restrictions = old;
4266 /// Parses an expression, subject to the given restrictions.
4268 fn parse_expr_res(&mut self, r: Restrictions,
4269 already_parsed_attrs: Option<ThinVec<Attribute>>)
4270 -> PResult<'a, P<Expr>> {
4271 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4274 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4275 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4276 if self.eat(&token::Eq) {
4277 Ok(Some(self.parse_expr()?))
4279 Ok(Some(self.parse_expr()?))
4285 /// Parses patterns, separated by '|' s.
4286 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4287 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4288 self.eat(&token::BinOp(token::Or));
4290 let mut pats = Vec::new();
4292 pats.push(self.parse_top_level_pat()?);
4294 if self.token == token::OrOr {
4295 let mut err = self.struct_span_err(self.span,
4296 "unexpected token `||` after pattern");
4297 err.span_suggestion(
4299 "use a single `|` to specify multiple patterns",
4301 Applicability::MachineApplicable
4305 } else if self.eat(&token::BinOp(token::Or)) {
4306 // This is a No-op. Continue the loop to parse the next
4314 // Parses a parenthesized list of patterns like
4315 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4316 // - a vector of the patterns that were parsed
4317 // - an option indicating the index of the `..` element
4318 // - a boolean indicating whether a trailing comma was present.
4319 // Trailing commas are significant because (p) and (p,) are different patterns.
4320 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4321 self.expect(&token::OpenDelim(token::Paren))?;
4322 let result = match self.parse_pat_list() {
4323 Ok(result) => result,
4324 Err(mut err) => { // recover from parse error in tuple pattern list
4326 self.consume_block(token::Paren);
4327 return Ok((vec![], Some(0), false));
4330 self.expect(&token::CloseDelim(token::Paren))?;
4334 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4335 let mut fields = Vec::new();
4336 let mut ddpos = None;
4337 let mut prev_dd_sp = None;
4338 let mut trailing_comma = false;
4340 if self.eat(&token::DotDot) {
4341 if ddpos.is_none() {
4342 ddpos = Some(fields.len());
4343 prev_dd_sp = Some(self.prev_span);
4345 // Emit a friendly error, ignore `..` and continue parsing
4346 let mut err = self.struct_span_err(
4348 "`..` can only be used once per tuple or tuple struct pattern",
4350 err.span_label(self.prev_span, "can only be used once per pattern");
4351 if let Some(sp) = prev_dd_sp {
4352 err.span_label(sp, "previously present here");
4356 } else if !self.check(&token::CloseDelim(token::Paren)) {
4357 fields.push(self.parse_pat(None)?);
4362 trailing_comma = self.eat(&token::Comma);
4363 if !trailing_comma {
4368 if ddpos == Some(fields.len()) && trailing_comma {
4369 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4370 let msg = "trailing comma is not permitted after `..`";
4371 self.struct_span_err(self.prev_span, msg)
4372 .span_label(self.prev_span, msg)
4376 Ok((fields, ddpos, trailing_comma))
4379 fn parse_pat_vec_elements(
4381 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4382 let mut before = Vec::new();
4383 let mut slice = None;
4384 let mut after = Vec::new();
4385 let mut first = true;
4386 let mut before_slice = true;
4388 while self.token != token::CloseDelim(token::Bracket) {
4392 self.expect(&token::Comma)?;
4394 if self.token == token::CloseDelim(token::Bracket)
4395 && (before_slice || !after.is_empty()) {
4401 if self.eat(&token::DotDot) {
4403 if self.check(&token::Comma) ||
4404 self.check(&token::CloseDelim(token::Bracket)) {
4405 slice = Some(P(Pat {
4406 id: ast::DUMMY_NODE_ID,
4407 node: PatKind::Wild,
4408 span: self.prev_span,
4410 before_slice = false;
4416 let subpat = self.parse_pat(None)?;
4417 if before_slice && self.eat(&token::DotDot) {
4418 slice = Some(subpat);
4419 before_slice = false;
4420 } else if before_slice {
4421 before.push(subpat);
4427 Ok((before, slice, after))
4433 attrs: Vec<Attribute>
4434 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4435 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4437 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4438 // Parsing a pattern of the form "fieldname: pat"
4439 let fieldname = self.parse_field_name()?;
4441 let pat = self.parse_pat(None)?;
4443 (pat, fieldname, false)
4445 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4446 let is_box = self.eat_keyword(keywords::Box);
4447 let boxed_span = self.span;
4448 let is_ref = self.eat_keyword(keywords::Ref);
4449 let is_mut = self.eat_keyword(keywords::Mut);
4450 let fieldname = self.parse_ident()?;
4451 hi = self.prev_span;
4453 let bind_type = match (is_ref, is_mut) {
4454 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4455 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4456 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4457 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4459 let fieldpat = P(Pat {
4460 id: ast::DUMMY_NODE_ID,
4461 node: PatKind::Ident(bind_type, fieldname, None),
4462 span: boxed_span.to(hi),
4465 let subpat = if is_box {
4467 id: ast::DUMMY_NODE_ID,
4468 node: PatKind::Box(fieldpat),
4474 (subpat, fieldname, true)
4477 Ok(source_map::Spanned {
4479 node: ast::FieldPat {
4483 attrs: attrs.into(),
4488 /// Parses the fields of a struct-like pattern.
4489 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4490 let mut fields = Vec::new();
4491 let mut etc = false;
4492 let mut ate_comma = true;
4493 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4494 let mut etc_span = None;
4496 while self.token != token::CloseDelim(token::Brace) {
4497 let attrs = self.parse_outer_attributes()?;
4500 // check that a comma comes after every field
4502 let err = self.struct_span_err(self.prev_span, "expected `,`");
4503 if let Some(mut delayed) = delayed_err {
4510 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4512 let mut etc_sp = self.span;
4514 if self.token == token::DotDotDot { // Issue #46718
4515 // Accept `...` as if it were `..` to avoid further errors
4516 let mut err = self.struct_span_err(self.span,
4517 "expected field pattern, found `...`");
4518 err.span_suggestion(
4520 "to omit remaining fields, use one fewer `.`",
4522 Applicability::MachineApplicable
4526 self.bump(); // `..` || `...`
4528 if self.token == token::CloseDelim(token::Brace) {
4529 etc_span = Some(etc_sp);
4532 let token_str = self.this_token_descr();
4533 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4535 err.span_label(self.span, "expected `}`");
4536 let mut comma_sp = None;
4537 if self.token == token::Comma { // Issue #49257
4538 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4539 err.span_label(etc_sp,
4540 "`..` must be at the end and cannot have a trailing comma");
4541 comma_sp = Some(self.span);
4546 etc_span = Some(etc_sp.until(self.span));
4547 if self.token == token::CloseDelim(token::Brace) {
4548 // If the struct looks otherwise well formed, recover and continue.
4549 if let Some(sp) = comma_sp {
4550 err.span_suggestion_short(
4552 "remove this comma",
4554 Applicability::MachineApplicable,
4559 } else if self.token.is_ident() && ate_comma {
4560 // Accept fields coming after `..,`.
4561 // This way we avoid "pattern missing fields" errors afterwards.
4562 // We delay this error until the end in order to have a span for a
4564 if let Some(mut delayed_err) = delayed_err {
4568 delayed_err = Some(err);
4571 if let Some(mut err) = delayed_err {
4578 fields.push(match self.parse_pat_field(lo, attrs) {
4581 if let Some(mut delayed_err) = delayed_err {
4587 ate_comma = self.eat(&token::Comma);
4590 if let Some(mut err) = delayed_err {
4591 if let Some(etc_span) = etc_span {
4592 err.multipart_suggestion(
4593 "move the `..` to the end of the field list",
4595 (etc_span, String::new()),
4596 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4598 Applicability::MachineApplicable,
4603 return Ok((fields, etc));
4606 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4607 if self.token.is_path_start() {
4609 let (qself, path) = if self.eat_lt() {
4610 // Parse a qualified path
4611 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4614 // Parse an unqualified path
4615 (None, self.parse_path(PathStyle::Expr)?)
4617 let hi = self.prev_span;
4618 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4620 self.parse_literal_maybe_minus()
4624 // helper function to decide whether to parse as ident binding or to try to do
4625 // something more complex like range patterns
4626 fn parse_as_ident(&mut self) -> bool {
4627 self.look_ahead(1, |t| match *t {
4628 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4629 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4630 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4631 // range pattern branch
4632 token::DotDot => None,
4634 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4635 token::Comma | token::CloseDelim(token::Bracket) => true,
4640 /// A wrapper around `parse_pat` with some special error handling for the
4641 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4642 /// to subpatterns within such).
4643 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4644 let pat = self.parse_pat(None)?;
4645 if self.token == token::Comma {
4646 // An unexpected comma after a top-level pattern is a clue that the
4647 // user (perhaps more accustomed to some other language) forgot the
4648 // parentheses in what should have been a tuple pattern; return a
4649 // suggestion-enhanced error here rather than choking on the comma
4651 let comma_span = self.span;
4653 if let Err(mut err) = self.parse_pat_list() {
4654 // We didn't expect this to work anyway; we just wanted
4655 // to advance to the end of the comma-sequence so we know
4656 // the span to suggest parenthesizing
4659 let seq_span = pat.span.to(self.prev_span);
4660 let mut err = self.struct_span_err(comma_span,
4661 "unexpected `,` in pattern");
4662 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4663 err.span_suggestion(
4665 "try adding parentheses to match on a tuple..",
4666 format!("({})", seq_snippet),
4667 Applicability::MachineApplicable
4670 "..or a vertical bar to match on multiple alternatives",
4671 format!("{}", seq_snippet.replace(",", " |")),
4672 Applicability::MachineApplicable
4680 /// Parses a pattern.
4681 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4682 self.parse_pat_with_range_pat(true, expected)
4685 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4687 fn parse_pat_with_range_pat(
4689 allow_range_pat: bool,
4690 expected: Option<&'static str>,
4691 ) -> PResult<'a, P<Pat>> {
4692 maybe_recover_from_interpolated_ty_qpath!(self, true);
4693 maybe_whole!(self, NtPat, |x| x);
4698 token::BinOp(token::And) | token::AndAnd => {
4699 // Parse &pat / &mut pat
4701 let mutbl = self.parse_mutability();
4702 if let token::Lifetime(ident) = self.token {
4703 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4705 err.span_label(self.span, "unexpected lifetime");
4708 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4709 pat = PatKind::Ref(subpat, mutbl);
4711 token::OpenDelim(token::Paren) => {
4712 // Parse (pat,pat,pat,...) as tuple pattern
4713 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4714 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4715 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4717 PatKind::Tuple(fields, ddpos)
4720 token::OpenDelim(token::Bracket) => {
4721 // Parse [pat,pat,...] as slice pattern
4723 let (before, slice, after) = self.parse_pat_vec_elements()?;
4724 self.expect(&token::CloseDelim(token::Bracket))?;
4725 pat = PatKind::Slice(before, slice, after);
4727 // At this point, token != &, &&, (, [
4728 _ => if self.eat_keyword(keywords::Underscore) {
4730 pat = PatKind::Wild;
4731 } else if self.eat_keyword(keywords::Mut) {
4732 // Parse mut ident @ pat / mut ref ident @ pat
4733 let mutref_span = self.prev_span.to(self.span);
4734 let binding_mode = if self.eat_keyword(keywords::Ref) {
4736 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4739 "try switching the order",
4741 Applicability::MachineApplicable
4743 BindingMode::ByRef(Mutability::Mutable)
4745 BindingMode::ByValue(Mutability::Mutable)
4747 pat = self.parse_pat_ident(binding_mode)?;
4748 } else if self.eat_keyword(keywords::Ref) {
4749 // Parse ref ident @ pat / ref mut ident @ pat
4750 let mutbl = self.parse_mutability();
4751 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4752 } else if self.eat_keyword(keywords::Box) {
4754 let subpat = self.parse_pat_with_range_pat(false, None)?;
4755 pat = PatKind::Box(subpat);
4756 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4757 self.parse_as_ident() {
4758 // Parse ident @ pat
4759 // This can give false positives and parse nullary enums,
4760 // they are dealt with later in resolve
4761 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4762 pat = self.parse_pat_ident(binding_mode)?;
4763 } else if self.token.is_path_start() {
4764 // Parse pattern starting with a path
4765 let (qself, path) = if self.eat_lt() {
4766 // Parse a qualified path
4767 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4770 // Parse an unqualified path
4771 (None, self.parse_path(PathStyle::Expr)?)
4774 token::Not if qself.is_none() => {
4775 // Parse macro invocation
4777 let (delim, tts) = self.expect_delimited_token_tree()?;
4778 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4779 pat = PatKind::Mac(mac);
4781 token::DotDotDot | token::DotDotEq | token::DotDot => {
4782 let end_kind = match self.token {
4783 token::DotDot => RangeEnd::Excluded,
4784 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4785 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4786 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4789 let op_span = self.span;
4791 let span = lo.to(self.prev_span);
4792 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4794 let end = self.parse_pat_range_end()?;
4795 let op = Spanned { span: op_span, node: end_kind };
4796 pat = PatKind::Range(begin, end, op);
4798 token::OpenDelim(token::Brace) => {
4799 if qself.is_some() {
4800 let msg = "unexpected `{` after qualified path";
4801 let mut err = self.fatal(msg);
4802 err.span_label(self.span, msg);
4805 // Parse struct pattern
4807 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4809 self.recover_stmt();
4813 pat = PatKind::Struct(path, fields, etc);
4815 token::OpenDelim(token::Paren) => {
4816 if qself.is_some() {
4817 let msg = "unexpected `(` after qualified path";
4818 let mut err = self.fatal(msg);
4819 err.span_label(self.span, msg);
4822 // Parse tuple struct or enum pattern
4823 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4824 pat = PatKind::TupleStruct(path, fields, ddpos)
4826 _ => pat = PatKind::Path(qself, path),
4829 // Try to parse everything else as literal with optional minus
4830 match self.parse_literal_maybe_minus() {
4832 let op_span = self.span;
4833 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4834 self.check(&token::DotDotDot) {
4835 let end_kind = if self.eat(&token::DotDotDot) {
4836 RangeEnd::Included(RangeSyntax::DotDotDot)
4837 } else if self.eat(&token::DotDotEq) {
4838 RangeEnd::Included(RangeSyntax::DotDotEq)
4839 } else if self.eat(&token::DotDot) {
4842 panic!("impossible case: we already matched \
4843 on a range-operator token")
4845 let end = self.parse_pat_range_end()?;
4846 let op = Spanned { span: op_span, node: end_kind };
4847 pat = PatKind::Range(begin, end, op);
4849 pat = PatKind::Lit(begin);
4853 self.cancel(&mut err);
4854 let expected = expected.unwrap_or("pattern");
4856 "expected {}, found {}",
4858 self.this_token_descr(),
4860 let mut err = self.fatal(&msg);
4861 err.span_label(self.span, format!("expected {}", expected));
4862 let sp = self.sess.source_map().start_point(self.span);
4863 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4864 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4872 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4873 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4875 if !allow_range_pat {
4878 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4880 PatKind::Range(..) => {
4881 let mut err = self.struct_span_err(
4883 "the range pattern here has ambiguous interpretation",
4885 err.span_suggestion(
4887 "add parentheses to clarify the precedence",
4888 format!("({})", pprust::pat_to_string(&pat)),
4889 // "ambiguous interpretation" implies that we have to be guessing
4890 Applicability::MaybeIncorrect
4901 /// Parses `ident` or `ident @ pat`.
4902 /// used by the copy foo and ref foo patterns to give a good
4903 /// error message when parsing mistakes like `ref foo(a, b)`.
4904 fn parse_pat_ident(&mut self,
4905 binding_mode: ast::BindingMode)
4906 -> PResult<'a, PatKind> {
4907 let ident = self.parse_ident()?;
4908 let sub = if self.eat(&token::At) {
4909 Some(self.parse_pat(Some("binding pattern"))?)
4914 // just to be friendly, if they write something like
4916 // we end up here with ( as the current token. This shortly
4917 // leads to a parse error. Note that if there is no explicit
4918 // binding mode then we do not end up here, because the lookahead
4919 // will direct us over to parse_enum_variant()
4920 if self.token == token::OpenDelim(token::Paren) {
4921 return Err(self.span_fatal(
4923 "expected identifier, found enum pattern"))
4926 Ok(PatKind::Ident(binding_mode, ident, sub))
4929 /// Parses a local variable declaration.
4930 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4931 let lo = self.prev_span;
4932 let pat = self.parse_top_level_pat()?;
4934 let (err, ty) = if self.eat(&token::Colon) {
4935 // Save the state of the parser before parsing type normally, in case there is a `:`
4936 // instead of an `=` typo.
4937 let parser_snapshot_before_type = self.clone();
4938 let colon_sp = self.prev_span;
4939 match self.parse_ty() {
4940 Ok(ty) => (None, Some(ty)),
4942 // Rewind to before attempting to parse the type and continue parsing
4943 let parser_snapshot_after_type = self.clone();
4944 mem::replace(self, parser_snapshot_before_type);
4946 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4947 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4948 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4954 let init = match (self.parse_initializer(err.is_some()), err) {
4955 (Ok(init), None) => { // init parsed, ty parsed
4958 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4959 // Could parse the type as if it were the initializer, it is likely there was a
4960 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4961 err.span_suggestion_short(
4963 "use `=` if you meant to assign",
4965 Applicability::MachineApplicable
4968 // As this was parsed successfully, continue as if the code has been fixed for the
4969 // rest of the file. It will still fail due to the emitted error, but we avoid
4973 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4975 // Couldn't parse the type nor the initializer, only raise the type error and
4976 // return to the parser state before parsing the type as the initializer.
4977 // let x: <parse_error>;
4978 mem::replace(self, snapshot);
4981 (Err(err), None) => { // init error, ty parsed
4982 // Couldn't parse the initializer and we're not attempting to recover a failed
4983 // parse of the type, return the error.
4987 let hi = if self.token == token::Semi {
4996 id: ast::DUMMY_NODE_ID,
4999 source: LocalSource::Normal,
5003 /// Parses a structure field.
5004 fn parse_name_and_ty(&mut self,
5007 attrs: Vec<Attribute>)
5008 -> PResult<'a, StructField> {
5009 let name = self.parse_ident()?;
5010 self.expect(&token::Colon)?;
5011 let ty = self.parse_ty()?;
5013 span: lo.to(self.prev_span),
5016 id: ast::DUMMY_NODE_ID,
5022 /// Emits an expected-item-after-attributes error.
5023 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
5024 let message = match attrs.last() {
5025 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
5026 _ => "expected item after attributes",
5029 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
5030 if attrs.last().unwrap().is_sugared_doc {
5031 err.span_label(self.prev_span, "this doc comment doesn't document anything");
5036 /// Parse a statement. This stops just before trailing semicolons on everything but items.
5037 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
5038 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
5039 Ok(self.parse_stmt_(true))
5042 // Eat tokens until we can be relatively sure we reached the end of the
5043 // statement. This is something of a best-effort heuristic.
5045 // We terminate when we find an unmatched `}` (without consuming it).
5046 fn recover_stmt(&mut self) {
5047 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
5050 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
5051 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
5052 // approximate - it can mean we break too early due to macros, but that
5053 // should only lead to sub-optimal recovery, not inaccurate parsing).
5055 // If `break_on_block` is `Break`, then we will stop consuming tokens
5056 // after finding (and consuming) a brace-delimited block.
5057 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
5058 let mut brace_depth = 0;
5059 let mut bracket_depth = 0;
5060 let mut in_block = false;
5061 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
5062 break_on_semi, break_on_block);
5064 debug!("recover_stmt_ loop {:?}", self.token);
5066 token::OpenDelim(token::DelimToken::Brace) => {
5069 if break_on_block == BlockMode::Break &&
5071 bracket_depth == 0 {
5075 token::OpenDelim(token::DelimToken::Bracket) => {
5079 token::CloseDelim(token::DelimToken::Brace) => {
5080 if brace_depth == 0 {
5081 debug!("recover_stmt_ return - close delim {:?}", self.token);
5086 if in_block && bracket_depth == 0 && brace_depth == 0 {
5087 debug!("recover_stmt_ return - block end {:?}", self.token);
5091 token::CloseDelim(token::DelimToken::Bracket) => {
5093 if bracket_depth < 0 {
5099 debug!("recover_stmt_ return - Eof");
5104 if break_on_semi == SemiColonMode::Break &&
5106 bracket_depth == 0 {
5107 debug!("recover_stmt_ return - Semi");
5112 if break_on_semi == SemiColonMode::Comma &&
5114 bracket_depth == 0 {
5115 debug!("recover_stmt_ return - Semi");
5128 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5129 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5131 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5136 fn is_async_block(&mut self) -> bool {
5137 self.token.is_keyword(keywords::Async) &&
5140 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5141 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5143 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5148 fn is_async_fn(&mut self) -> bool {
5149 self.token.is_keyword(keywords::Async) &&
5150 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5153 fn is_do_catch_block(&mut self) -> bool {
5154 self.token.is_keyword(keywords::Do) &&
5155 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5156 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5157 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5160 fn is_try_block(&mut self) -> bool {
5161 self.token.is_keyword(keywords::Try) &&
5162 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5163 self.span.rust_2018() &&
5164 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5165 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5168 fn is_union_item(&self) -> bool {
5169 self.token.is_keyword(keywords::Union) &&
5170 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5173 fn is_crate_vis(&self) -> bool {
5174 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5177 fn is_existential_type_decl(&self) -> bool {
5178 self.token.is_keyword(keywords::Existential) &&
5179 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5182 fn is_auto_trait_item(&mut self) -> bool {
5184 (self.token.is_keyword(keywords::Auto)
5185 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5186 || // unsafe auto trait
5187 (self.token.is_keyword(keywords::Unsafe) &&
5188 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5189 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5192 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5193 -> PResult<'a, Option<P<Item>>> {
5194 let token_lo = self.span;
5195 let (ident, def) = match self.token {
5196 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5198 let ident = self.parse_ident()?;
5199 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5200 match self.parse_token_tree() {
5201 TokenTree::Delimited(_, _, tts) => tts,
5202 _ => unreachable!(),
5204 } else if self.check(&token::OpenDelim(token::Paren)) {
5205 let args = self.parse_token_tree();
5206 let body = if self.check(&token::OpenDelim(token::Brace)) {
5207 self.parse_token_tree()
5212 TokenStream::new(vec![
5214 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5222 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5224 token::Ident(ident, _) if ident.name == "macro_rules" &&
5225 self.look_ahead(1, |t| *t == token::Not) => {
5226 let prev_span = self.prev_span;
5227 self.complain_if_pub_macro(&vis.node, prev_span);
5231 let ident = self.parse_ident()?;
5232 let (delim, tokens) = self.expect_delimited_token_tree()?;
5233 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5234 self.report_invalid_macro_expansion_item();
5237 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5239 _ => return Ok(None),
5242 let span = lo.to(self.prev_span);
5243 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5246 fn parse_stmt_without_recovery(&mut self,
5247 macro_legacy_warnings: bool)
5248 -> PResult<'a, Option<Stmt>> {
5249 maybe_whole!(self, NtStmt, |x| Some(x));
5251 let attrs = self.parse_outer_attributes()?;
5254 Ok(Some(if self.eat_keyword(keywords::Let) {
5256 id: ast::DUMMY_NODE_ID,
5257 node: StmtKind::Local(self.parse_local(attrs.into())?),
5258 span: lo.to(self.prev_span),
5260 } else if let Some(macro_def) = self.eat_macro_def(
5262 &source_map::respan(lo, VisibilityKind::Inherited),
5266 id: ast::DUMMY_NODE_ID,
5267 node: StmtKind::Item(macro_def),
5268 span: lo.to(self.prev_span),
5270 // Starts like a simple path, being careful to avoid contextual keywords
5271 // such as a union items, item with `crate` visibility or auto trait items.
5272 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5273 // like a path (1 token), but it fact not a path.
5274 // `union::b::c` - path, `union U { ... }` - not a path.
5275 // `crate::b::c` - path, `crate struct S;` - not a path.
5276 } else if self.token.is_path_start() &&
5277 !self.token.is_qpath_start() &&
5278 !self.is_union_item() &&
5279 !self.is_crate_vis() &&
5280 !self.is_existential_type_decl() &&
5281 !self.is_auto_trait_item() &&
5282 !self.is_async_fn() {
5283 let pth = self.parse_path(PathStyle::Expr)?;
5285 if !self.eat(&token::Not) {
5286 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5287 self.parse_struct_expr(lo, pth, ThinVec::new())?
5289 let hi = self.prev_span;
5290 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5293 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5294 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5295 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5298 return Ok(Some(Stmt {
5299 id: ast::DUMMY_NODE_ID,
5300 node: StmtKind::Expr(expr),
5301 span: lo.to(self.prev_span),
5305 // it's a macro invocation
5306 let id = match self.token {
5307 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5308 _ => self.parse_ident()?,
5311 // check that we're pointing at delimiters (need to check
5312 // again after the `if`, because of `parse_ident`
5313 // consuming more tokens).
5315 token::OpenDelim(_) => {}
5317 // we only expect an ident if we didn't parse one
5319 let ident_str = if id.name == keywords::Invalid.name() {
5324 let tok_str = self.this_token_descr();
5325 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5328 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5333 let (delim, tts) = self.expect_delimited_token_tree()?;
5334 let hi = self.prev_span;
5336 let style = if delim == MacDelimiter::Brace {
5337 MacStmtStyle::Braces
5339 MacStmtStyle::NoBraces
5342 if id.name == keywords::Invalid.name() {
5343 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5344 let node = if delim == MacDelimiter::Brace ||
5345 self.token == token::Semi || self.token == token::Eof {
5346 StmtKind::Mac(P((mac, style, attrs.into())))
5348 // We used to incorrectly stop parsing macro-expanded statements here.
5349 // If the next token will be an error anyway but could have parsed with the
5350 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5351 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5352 // These can continue an expression, so we can't stop parsing and warn.
5353 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5354 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5355 token::BinOp(token::And) | token::BinOp(token::Or) |
5356 token::AndAnd | token::OrOr |
5357 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5360 self.warn_missing_semicolon();
5361 StmtKind::Mac(P((mac, style, attrs.into())))
5363 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5364 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5365 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5366 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5370 id: ast::DUMMY_NODE_ID,
5375 // if it has a special ident, it's definitely an item
5377 // Require a semicolon or braces.
5378 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5379 self.report_invalid_macro_expansion_item();
5381 let span = lo.to(hi);
5383 id: ast::DUMMY_NODE_ID,
5385 node: StmtKind::Item({
5387 span, id /*id is good here*/,
5388 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5389 respan(lo, VisibilityKind::Inherited),
5395 // FIXME: Bad copy of attrs
5396 let old_directory_ownership =
5397 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5398 let item = self.parse_item_(attrs.clone(), false, true)?;
5399 self.directory.ownership = old_directory_ownership;
5403 id: ast::DUMMY_NODE_ID,
5404 span: lo.to(i.span),
5405 node: StmtKind::Item(i),
5408 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5409 if !attrs.is_empty() {
5410 if s.prev_token_kind == PrevTokenKind::DocComment {
5411 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5412 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5413 s.span_err(s.span, "expected statement after outer attribute");
5418 // Do not attempt to parse an expression if we're done here.
5419 if self.token == token::Semi {
5420 unused_attrs(&attrs, self);
5425 if self.token == token::CloseDelim(token::Brace) {
5426 unused_attrs(&attrs, self);
5430 // Remainder are line-expr stmts.
5431 let e = self.parse_expr_res(
5432 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5434 id: ast::DUMMY_NODE_ID,
5435 span: lo.to(e.span),
5436 node: StmtKind::Expr(e),
5443 /// Checks if this expression is a successfully parsed statement.
5444 fn expr_is_complete(&mut self, e: &Expr) -> bool {
5445 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5446 !classify::expr_requires_semi_to_be_stmt(e)
5449 /// Parses a block. No inner attributes are allowed.
5450 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5451 maybe_whole!(self, NtBlock, |x| x);
5455 if !self.eat(&token::OpenDelim(token::Brace)) {
5457 let tok = self.this_token_descr();
5458 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5459 let do_not_suggest_help =
5460 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5462 if self.token.is_ident_named("and") {
5463 e.span_suggestion_short(
5465 "use `&&` instead of `and` for the boolean operator",
5467 Applicability::MaybeIncorrect,
5470 if self.token.is_ident_named("or") {
5471 e.span_suggestion_short(
5473 "use `||` instead of `or` for the boolean operator",
5475 Applicability::MaybeIncorrect,
5479 // Check to see if the user has written something like
5484 // Which is valid in other languages, but not Rust.
5485 match self.parse_stmt_without_recovery(false) {
5487 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5488 || do_not_suggest_help {
5489 // if the next token is an open brace (e.g., `if a b {`), the place-
5490 // inside-a-block suggestion would be more likely wrong than right
5491 e.span_label(sp, "expected `{`");
5494 let mut stmt_span = stmt.span;
5495 // expand the span to include the semicolon, if it exists
5496 if self.eat(&token::Semi) {
5497 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5499 let sugg = pprust::to_string(|s| {
5500 use crate::print::pprust::{PrintState, INDENT_UNIT};
5501 s.ibox(INDENT_UNIT)?;
5503 s.print_stmt(&stmt)?;
5504 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5508 "try placing this code inside a block",
5510 // speculative, has been misleading in the past (closed Issue #46836)
5511 Applicability::MaybeIncorrect
5515 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5516 self.cancel(&mut e);
5520 e.span_label(sp, "expected `{`");
5524 self.parse_block_tail(lo, BlockCheckMode::Default)
5527 /// Parses a block. Inner attributes are allowed.
5528 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5529 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5532 self.expect(&token::OpenDelim(token::Brace))?;
5533 Ok((self.parse_inner_attributes()?,
5534 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5537 /// Parses the rest of a block expression or function body.
5538 /// Precondition: already parsed the '{'.
5539 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5540 let mut stmts = vec![];
5541 while !self.eat(&token::CloseDelim(token::Brace)) {
5542 let stmt = match self.parse_full_stmt(false) {
5545 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5547 id: ast::DUMMY_NODE_ID,
5548 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5554 if let Some(stmt) = stmt {
5556 } else if self.token == token::Eof {
5559 // Found only `;` or `}`.
5565 id: ast::DUMMY_NODE_ID,
5567 span: lo.to(self.prev_span),
5571 /// Parses a statement, including the trailing semicolon.
5572 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5573 // skip looking for a trailing semicolon when we have an interpolated statement
5574 maybe_whole!(self, NtStmt, |x| Some(x));
5576 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5578 None => return Ok(None),
5582 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5583 // expression without semicolon
5584 if classify::expr_requires_semi_to_be_stmt(expr) {
5585 // Just check for errors and recover; do not eat semicolon yet.
5587 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5590 self.recover_stmt();
5594 StmtKind::Local(..) => {
5595 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5596 if macro_legacy_warnings && self.token != token::Semi {
5597 self.warn_missing_semicolon();
5599 self.expect_one_of(&[], &[token::Semi])?;
5605 if self.eat(&token::Semi) {
5606 stmt = stmt.add_trailing_semicolon();
5609 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5613 fn warn_missing_semicolon(&self) {
5614 self.diagnostic().struct_span_warn(self.span, {
5615 &format!("expected `;`, found {}", self.this_token_descr())
5617 "This was erroneously allowed and will become a hard error in a future release"
5621 fn err_dotdotdot_syntax(&self, span: Span) {
5622 self.diagnostic().struct_span_err(span, {
5623 "unexpected token: `...`"
5625 span, "use `..` for an exclusive range", "..".to_owned(),
5626 Applicability::MaybeIncorrect
5628 span, "or `..=` for an inclusive range", "..=".to_owned(),
5629 Applicability::MaybeIncorrect
5633 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5636 /// BOUND = TY_BOUND | LT_BOUND
5637 /// LT_BOUND = LIFETIME (e.g., `'a`)
5638 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5639 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5641 fn parse_generic_bounds_common(&mut self,
5643 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5644 let mut bounds = Vec::new();
5645 let mut negative_bounds = Vec::new();
5646 let mut last_plus_span = None;
5647 let mut was_negative = false;
5649 // This needs to be synchronized with `Token::can_begin_bound`.
5650 let is_bound_start = self.check_path() || self.check_lifetime() ||
5651 self.check(&token::Not) || // used for error reporting only
5652 self.check(&token::Question) ||
5653 self.check_keyword(keywords::For) ||
5654 self.check(&token::OpenDelim(token::Paren));
5657 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5658 let inner_lo = self.span;
5659 let is_negative = self.eat(&token::Not);
5660 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5661 if self.token.is_lifetime() {
5662 if let Some(question_span) = question {
5663 self.span_err(question_span,
5664 "`?` may only modify trait bounds, not lifetime bounds");
5666 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5668 let inner_span = inner_lo.to(self.prev_span);
5669 self.expect(&token::CloseDelim(token::Paren))?;
5670 let mut err = self.struct_span_err(
5671 lo.to(self.prev_span),
5672 "parenthesized lifetime bounds are not supported"
5674 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5675 err.span_suggestion_short(
5676 lo.to(self.prev_span),
5677 "remove the parentheses",
5679 Applicability::MachineApplicable
5685 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5686 let path = self.parse_path(PathStyle::Type)?;
5688 self.expect(&token::CloseDelim(token::Paren))?;
5690 let poly_span = lo.to(self.prev_span);
5692 was_negative = true;
5693 if let Some(sp) = last_plus_span.or(colon_span) {
5694 negative_bounds.push(sp.to(poly_span));
5697 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5698 let modifier = if question.is_some() {
5699 TraitBoundModifier::Maybe
5701 TraitBoundModifier::None
5703 bounds.push(GenericBound::Trait(poly_trait, modifier));
5710 if !allow_plus || !self.eat_plus() {
5713 last_plus_span = Some(self.prev_span);
5717 if !negative_bounds.is_empty() || was_negative {
5718 let plural = negative_bounds.len() > 1;
5719 let last_span = negative_bounds.last().map(|sp| *sp);
5720 let mut err = self.struct_span_err(
5722 "negative trait bounds are not supported",
5724 if let Some(sp) = last_span {
5725 err.span_label(sp, "negative trait bounds are not supported");
5727 if let Some(bound_list) = colon_span {
5728 let bound_list = bound_list.to(self.prev_span);
5729 let mut new_bound_list = String::new();
5730 if !bounds.is_empty() {
5731 let mut snippets = bounds.iter().map(|bound| bound.span())
5732 .map(|span| self.sess.source_map().span_to_snippet(span));
5733 while let Some(Ok(snippet)) = snippets.next() {
5734 new_bound_list.push_str(" + ");
5735 new_bound_list.push_str(&snippet);
5737 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5739 err.span_suggestion_hidden(
5741 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5743 Applicability::MachineApplicable,
5752 crate fn parse_generic_bounds(&mut self,
5753 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5754 self.parse_generic_bounds_common(true, colon_span)
5757 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5760 /// BOUND = LT_BOUND (e.g., `'a`)
5762 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5763 let mut lifetimes = Vec::new();
5764 while self.check_lifetime() {
5765 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5767 if !self.eat_plus() {
5774 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5775 fn parse_ty_param(&mut self,
5776 preceding_attrs: Vec<Attribute>)
5777 -> PResult<'a, GenericParam> {
5778 let ident = self.parse_ident()?;
5780 // Parse optional colon and param bounds.
5781 let bounds = if self.eat(&token::Colon) {
5782 self.parse_generic_bounds(Some(self.prev_span))?
5787 let default = if self.eat(&token::Eq) {
5788 Some(self.parse_ty()?)
5795 id: ast::DUMMY_NODE_ID,
5796 attrs: preceding_attrs.into(),
5798 kind: GenericParamKind::Type {
5804 /// Parses the following grammar:
5806 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5807 fn parse_trait_item_assoc_ty(&mut self)
5808 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5809 let ident = self.parse_ident()?;
5810 let mut generics = self.parse_generics()?;
5812 // Parse optional colon and param bounds.
5813 let bounds = if self.eat(&token::Colon) {
5814 self.parse_generic_bounds(None)?
5818 generics.where_clause = self.parse_where_clause()?;
5820 let default = if self.eat(&token::Eq) {
5821 Some(self.parse_ty()?)
5825 self.expect(&token::Semi)?;
5827 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5830 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5831 self.expect_keyword(keywords::Const)?;
5832 let ident = self.parse_ident()?;
5833 self.expect(&token::Colon)?;
5834 let ty = self.parse_ty()?;
5838 id: ast::DUMMY_NODE_ID,
5839 attrs: preceding_attrs.into(),
5841 kind: GenericParamKind::Const {
5847 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5848 /// a trailing comma and erroneous trailing attributes.
5849 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5850 let mut params = Vec::new();
5852 let attrs = self.parse_outer_attributes()?;
5853 if self.check_lifetime() {
5854 let lifetime = self.expect_lifetime();
5855 // Parse lifetime parameter.
5856 let bounds = if self.eat(&token::Colon) {
5857 self.parse_lt_param_bounds()
5861 params.push(ast::GenericParam {
5862 ident: lifetime.ident,
5864 attrs: attrs.into(),
5866 kind: ast::GenericParamKind::Lifetime,
5868 } else if self.check_keyword(keywords::Const) {
5869 // Parse const parameter.
5870 params.push(self.parse_const_param(attrs)?);
5871 } else if self.check_ident() {
5872 // Parse type parameter.
5873 params.push(self.parse_ty_param(attrs)?);
5875 // Check for trailing attributes and stop parsing.
5876 if !attrs.is_empty() {
5877 if !params.is_empty() {
5878 self.struct_span_err(
5880 &format!("trailing attribute after generic parameter"),
5882 .span_label(attrs[0].span, "attributes must go before parameters")
5885 self.struct_span_err(
5887 &format!("attribute without generic parameters"),
5891 "attributes are only permitted when preceding parameters",
5899 if !self.eat(&token::Comma) {
5906 /// Parses a set of optional generic type parameter declarations. Where
5907 /// clauses are not parsed here, and must be added later via
5908 /// `parse_where_clause()`.
5910 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5911 /// | ( < lifetimes , typaramseq ( , )? > )
5912 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5913 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5914 let span_lo = self.span;
5916 let params = self.parse_generic_params()?;
5920 where_clause: WhereClause {
5921 id: ast::DUMMY_NODE_ID,
5922 predicates: Vec::new(),
5923 span: syntax_pos::DUMMY_SP,
5925 span: span_lo.to(self.prev_span),
5928 Ok(ast::Generics::default())
5932 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5933 /// For the purposes of understanding the parsing logic of generic arguments, this function
5934 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5935 /// had the correct amount of leading angle brackets.
5937 /// ```ignore (diagnostics)
5938 /// bar::<<<<T as Foo>::Output>();
5939 /// ^^ help: remove extra angle brackets
5941 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5945 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5946 // We need to detect whether there are extra leading left angle brackets and produce an
5947 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5948 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5949 // then there won't be matching `>` tokens to find.
5951 // To explain how this detection works, consider the following example:
5953 // ```ignore (diagnostics)
5954 // bar::<<<<T as Foo>::Output>();
5955 // ^^ help: remove extra angle brackets
5958 // Parsing of the left angle brackets starts in this function. We start by parsing the
5959 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5962 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5963 // *Unmatched count:* 1
5964 // *`parse_path_segment` calls deep:* 0
5966 // This has the effect of recursing as this function is called if a `<` character
5967 // is found within the expected generic arguments:
5969 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5970 // *Unmatched count:* 2
5971 // *`parse_path_segment` calls deep:* 1
5973 // Eventually we will have recursed until having consumed all of the `<` tokens and
5974 // this will be reflected in the count:
5976 // *Upcoming tokens:* `T as Foo>::Output>;`
5977 // *Unmatched count:* 4
5978 // `parse_path_segment` calls deep:* 3
5980 // The parser will continue until reaching the first `>` - this will decrement the
5981 // unmatched angle bracket count and return to the parent invocation of this function
5982 // having succeeded in parsing:
5984 // *Upcoming tokens:* `::Output>;`
5985 // *Unmatched count:* 3
5986 // *`parse_path_segment` calls deep:* 2
5988 // This will continue until the next `>` character which will also return successfully
5989 // to the parent invocation of this function and decrement the count:
5991 // *Upcoming tokens:* `;`
5992 // *Unmatched count:* 2
5993 // *`parse_path_segment` calls deep:* 1
5995 // At this point, this function will expect to find another matching `>` character but
5996 // won't be able to and will return an error. This will continue all the way up the
5997 // call stack until the first invocation:
5999 // *Upcoming tokens:* `;`
6000 // *Unmatched count:* 2
6001 // *`parse_path_segment` calls deep:* 0
6003 // In doing this, we have managed to work out how many unmatched leading left angle
6004 // brackets there are, but we cannot recover as the unmatched angle brackets have
6005 // already been consumed. To remedy this, we keep a snapshot of the parser state
6006 // before we do the above. We can then inspect whether we ended up with a parsing error
6007 // and unmatched left angle brackets and if so, restore the parser state before we
6008 // consumed any `<` characters to emit an error and consume the erroneous tokens to
6009 // recover by attempting to parse again.
6011 // In practice, the recursion of this function is indirect and there will be other
6012 // locations that consume some `<` characters - as long as we update the count when
6013 // this happens, it isn't an issue.
6015 let is_first_invocation = style == PathStyle::Expr;
6016 // Take a snapshot before attempting to parse - we can restore this later.
6017 let snapshot = if is_first_invocation {
6023 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
6024 match self.parse_generic_args() {
6025 Ok(value) => Ok(value),
6026 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
6027 // Cancel error from being unable to find `>`. We know the error
6028 // must have been this due to a non-zero unmatched angle bracket
6032 // Swap `self` with our backup of the parser state before attempting to parse
6033 // generic arguments.
6034 let snapshot = mem::replace(self, snapshot.unwrap());
6037 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
6038 snapshot.count={:?}",
6039 snapshot.unmatched_angle_bracket_count,
6042 // Eat the unmatched angle brackets.
6043 for _ in 0..snapshot.unmatched_angle_bracket_count {
6047 // Make a span over ${unmatched angle bracket count} characters.
6048 let span = lo.with_hi(
6049 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
6051 let plural = snapshot.unmatched_angle_bracket_count > 1;
6056 "unmatched angle bracket{}",
6057 if plural { "s" } else { "" }
6063 "remove extra angle bracket{}",
6064 if plural { "s" } else { "" }
6067 Applicability::MachineApplicable,
6071 // Try again without unmatched angle bracket characters.
6072 self.parse_generic_args()
6078 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
6079 /// possibly including trailing comma.
6080 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6081 let mut args = Vec::new();
6082 let mut bindings = Vec::new();
6083 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
6084 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
6086 let args_lo = self.span;
6089 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6090 // Parse lifetime argument.
6091 args.push(GenericArg::Lifetime(self.expect_lifetime()));
6092 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6093 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
6094 // Parse associated type binding.
6096 let ident = self.parse_ident()?;
6098 let ty = self.parse_ty()?;
6099 let span = lo.to(self.prev_span);
6100 bindings.push(TypeBinding {
6101 id: ast::DUMMY_NODE_ID,
6106 assoc_ty_bindings.push(span);
6107 } else if self.check_const_arg() {
6108 // Parse const argument.
6109 let expr = if let token::OpenDelim(token::Brace) = self.token {
6110 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
6111 } else if self.token.is_ident() {
6112 // FIXME(const_generics): to distinguish between idents for types and consts,
6113 // we should introduce a GenericArg::Ident in the AST and distinguish when
6114 // lowering to the HIR. For now, idents for const args are not permitted.
6116 self.fatal("identifiers may currently not be used for const generics")
6119 self.parse_literal_maybe_minus()?
6121 let value = AnonConst {
6122 id: ast::DUMMY_NODE_ID,
6125 args.push(GenericArg::Const(value));
6126 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6127 } else if self.check_type() {
6128 // Parse type argument.
6129 args.push(GenericArg::Type(self.parse_ty()?));
6130 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6135 if !self.eat(&token::Comma) {
6140 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6141 // preserve ordering of generic parameters with respect to associated type binding, so we
6142 // lose that information after parsing.
6143 if misplaced_assoc_ty_bindings.len() > 0 {
6144 let mut err = self.struct_span_err(
6145 args_lo.to(self.prev_span),
6146 "associated type bindings must be declared after generic parameters",
6148 for span in misplaced_assoc_ty_bindings {
6151 "this associated type binding should be moved after the generic parameters",
6157 Ok((args, bindings))
6160 /// Parses an optional where-clause and places it in `generics`.
6162 /// ```ignore (only-for-syntax-highlight)
6163 /// where T : Trait<U, V> + 'b, 'a : 'b
6165 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6166 let mut where_clause = WhereClause {
6167 id: ast::DUMMY_NODE_ID,
6168 predicates: Vec::new(),
6169 span: syntax_pos::DUMMY_SP,
6172 if !self.eat_keyword(keywords::Where) {
6173 return Ok(where_clause);
6175 let lo = self.prev_span;
6177 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6178 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6179 // change we parse those generics now, but report an error.
6180 if self.choose_generics_over_qpath() {
6181 let generics = self.parse_generics()?;
6182 self.struct_span_err(
6184 "generic parameters on `where` clauses are reserved for future use",
6186 .span_label(generics.span, "currently unsupported")
6192 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6193 let lifetime = self.expect_lifetime();
6194 // Bounds starting with a colon are mandatory, but possibly empty.
6195 self.expect(&token::Colon)?;
6196 let bounds = self.parse_lt_param_bounds();
6197 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6198 ast::WhereRegionPredicate {
6199 span: lo.to(self.prev_span),
6204 } else if self.check_type() {
6205 // Parse optional `for<'a, 'b>`.
6206 // This `for` is parsed greedily and applies to the whole predicate,
6207 // the bounded type can have its own `for` applying only to it.
6208 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6209 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6210 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6211 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6213 // Parse type with mandatory colon and (possibly empty) bounds,
6214 // or with mandatory equality sign and the second type.
6215 let ty = self.parse_ty()?;
6216 if self.eat(&token::Colon) {
6217 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6218 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6219 ast::WhereBoundPredicate {
6220 span: lo.to(self.prev_span),
6221 bound_generic_params: lifetime_defs,
6226 // FIXME: Decide what should be used here, `=` or `==`.
6227 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6228 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6229 let rhs_ty = self.parse_ty()?;
6230 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6231 ast::WhereEqPredicate {
6232 span: lo.to(self.prev_span),
6235 id: ast::DUMMY_NODE_ID,
6239 return self.unexpected();
6245 if !self.eat(&token::Comma) {
6250 where_clause.span = lo.to(self.prev_span);
6254 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6255 -> PResult<'a, (Vec<Arg> , bool)> {
6256 self.expect(&token::OpenDelim(token::Paren))?;
6259 let mut c_variadic = false;
6260 let (args, recovered): (Vec<Option<Arg>>, bool) =
6261 self.parse_seq_to_before_end(
6262 &token::CloseDelim(token::Paren),
6263 SeqSep::trailing_allowed(token::Comma),
6265 // If the argument is a C-variadic argument we should not
6266 // enforce named arguments.
6267 let enforce_named_args = if p.token == token::DotDotDot {
6272 match p.parse_arg_general(enforce_named_args, false,
6275 if let TyKind::CVarArgs = arg.ty.node {
6277 if p.token != token::CloseDelim(token::Paren) {
6280 "`...` must be the last argument of a C-variadic function");
6291 let lo = p.prev_span;
6292 // Skip every token until next possible arg or end.
6293 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6294 // Create a placeholder argument for proper arg count (issue #34264).
6295 let span = lo.to(p.prev_span);
6296 Ok(Some(dummy_arg(span)))
6303 self.eat(&token::CloseDelim(token::Paren));
6306 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6308 if c_variadic && args.is_empty() {
6310 "C-variadic function must be declared with at least one named argument");
6313 Ok((args, c_variadic))
6316 /// Parses the argument list and result type of a function declaration.
6317 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6319 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6320 let ret_ty = self.parse_ret_ty(true)?;
6329 /// Returns the parsed optional self argument and whether a self shortcut was used.
6330 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6331 let expect_ident = |this: &mut Self| match this.token {
6332 // Preserve hygienic context.
6333 token::Ident(ident, _) =>
6334 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6337 let isolated_self = |this: &mut Self, n| {
6338 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6339 this.look_ahead(n + 1, |t| t != &token::ModSep)
6342 // Parse optional self parameter of a method.
6343 // Only a limited set of initial token sequences is considered self parameters, anything
6344 // else is parsed as a normal function parameter list, so some lookahead is required.
6345 let eself_lo = self.span;
6346 let (eself, eself_ident, eself_hi) = match self.token {
6347 token::BinOp(token::And) => {
6353 (if isolated_self(self, 1) {
6355 SelfKind::Region(None, Mutability::Immutable)
6356 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6357 isolated_self(self, 2) {
6360 SelfKind::Region(None, Mutability::Mutable)
6361 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6362 isolated_self(self, 2) {
6364 let lt = self.expect_lifetime();
6365 SelfKind::Region(Some(lt), Mutability::Immutable)
6366 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6367 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6368 isolated_self(self, 3) {
6370 let lt = self.expect_lifetime();
6372 SelfKind::Region(Some(lt), Mutability::Mutable)
6375 }, expect_ident(self), self.prev_span)
6377 token::BinOp(token::Star) => {
6382 // Emit special error for `self` cases.
6383 let msg = "cannot pass `self` by raw pointer";
6384 (if isolated_self(self, 1) {
6386 self.struct_span_err(self.span, msg)
6387 .span_label(self.span, msg)
6389 SelfKind::Value(Mutability::Immutable)
6390 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6391 isolated_self(self, 2) {
6394 self.struct_span_err(self.span, msg)
6395 .span_label(self.span, msg)
6397 SelfKind::Value(Mutability::Immutable)
6400 }, expect_ident(self), self.prev_span)
6402 token::Ident(..) => {
6403 if isolated_self(self, 0) {
6406 let eself_ident = expect_ident(self);
6407 let eself_hi = self.prev_span;
6408 (if self.eat(&token::Colon) {
6409 let ty = self.parse_ty()?;
6410 SelfKind::Explicit(ty, Mutability::Immutable)
6412 SelfKind::Value(Mutability::Immutable)
6413 }, eself_ident, eself_hi)
6414 } else if self.token.is_keyword(keywords::Mut) &&
6415 isolated_self(self, 1) {
6419 let eself_ident = expect_ident(self);
6420 let eself_hi = self.prev_span;
6421 (if self.eat(&token::Colon) {
6422 let ty = self.parse_ty()?;
6423 SelfKind::Explicit(ty, Mutability::Mutable)
6425 SelfKind::Value(Mutability::Mutable)
6426 }, eself_ident, eself_hi)
6431 _ => return Ok(None),
6434 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6435 Ok(Some(Arg::from_self(eself, eself_ident)))
6438 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6439 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6440 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6442 self.expect(&token::OpenDelim(token::Paren))?;
6444 // Parse optional self argument
6445 let self_arg = self.parse_self_arg()?;
6447 // Parse the rest of the function parameter list.
6448 let sep = SeqSep::trailing_allowed(token::Comma);
6449 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6450 if self.check(&token::CloseDelim(token::Paren)) {
6451 (vec![self_arg], false)
6452 } else if self.eat(&token::Comma) {
6453 let mut fn_inputs = vec![self_arg];
6454 let (mut input, recovered) = self.parse_seq_to_before_end(
6455 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6456 fn_inputs.append(&mut input);
6457 (fn_inputs, recovered)
6459 match self.expect_one_of(&[], &[]) {
6460 Err(err) => return Err(err),
6461 Ok(recovered) => (vec![self_arg], recovered),
6465 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6469 // Parse closing paren and return type.
6470 self.expect(&token::CloseDelim(token::Paren))?;
6474 output: self.parse_ret_ty(true)?,
6479 /// Parses the `|arg, arg|` header of a closure.
6480 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6481 let inputs_captures = {
6482 if self.eat(&token::OrOr) {
6485 self.expect(&token::BinOp(token::Or))?;
6486 let args = self.parse_seq_to_before_tokens(
6487 &[&token::BinOp(token::Or), &token::OrOr],
6488 SeqSep::trailing_allowed(token::Comma),
6489 TokenExpectType::NoExpect,
6490 |p| p.parse_fn_block_arg()
6496 let output = self.parse_ret_ty(true)?;
6499 inputs: inputs_captures,
6505 /// Parses the name and optional generic types of a function header.
6506 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6507 let id = self.parse_ident()?;
6508 let generics = self.parse_generics()?;
6512 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6513 attrs: Vec<Attribute>) -> P<Item> {
6517 id: ast::DUMMY_NODE_ID,
6525 /// Parses an item-position function declaration.
6526 fn parse_item_fn(&mut self,
6528 mut asyncness: Spanned<IsAsync>,
6529 constness: Spanned<Constness>,
6531 -> PResult<'a, ItemInfo> {
6532 let (ident, mut generics) = self.parse_fn_header()?;
6533 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6534 let mut decl = self.parse_fn_decl(allow_c_variadic)?;
6535 generics.where_clause = self.parse_where_clause()?;
6536 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6537 self.construct_async_arguments(&mut asyncness, &mut decl);
6538 let header = FnHeader { unsafety, asyncness, constness, abi };
6539 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6542 /// Returns `true` if we are looking at `const ID`
6543 /// (returns `false` for things like `const fn`, etc.).
6544 fn is_const_item(&mut self) -> bool {
6545 self.token.is_keyword(keywords::Const) &&
6546 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6547 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6550 /// Parses all the "front matter" for a `fn` declaration, up to
6551 /// and including the `fn` keyword:
6555 /// - `const unsafe fn`
6558 fn parse_fn_front_matter(&mut self)
6566 let is_const_fn = self.eat_keyword(keywords::Const);
6567 let const_span = self.prev_span;
6568 let unsafety = self.parse_unsafety();
6569 let asyncness = self.parse_asyncness();
6570 let asyncness = respan(self.prev_span, asyncness);
6571 let (constness, unsafety, abi) = if is_const_fn {
6572 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6574 let abi = if self.eat_keyword(keywords::Extern) {
6575 self.parse_opt_abi()?.unwrap_or(Abi::C)
6579 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6581 if !self.eat_keyword(keywords::Fn) {
6582 // It is possible for `expect_one_of` to recover given the contents of
6583 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6584 // account for this.
6585 if !self.expect_one_of(&[], &[])? { unreachable!() }
6587 Ok((constness, unsafety, asyncness, abi))
6590 /// Parses an impl item.
6591 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6592 maybe_whole!(self, NtImplItem, |x| x);
6593 let attrs = self.parse_outer_attributes()?;
6594 let mut unclosed_delims = vec![];
6595 let (mut item, tokens) = self.collect_tokens(|this| {
6596 let item = this.parse_impl_item_(at_end, attrs);
6597 unclosed_delims.append(&mut this.unclosed_delims);
6600 self.unclosed_delims.append(&mut unclosed_delims);
6602 // See `parse_item` for why this clause is here.
6603 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6604 item.tokens = Some(tokens);
6609 fn parse_impl_item_(&mut self,
6611 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6613 let vis = self.parse_visibility(false)?;
6614 let defaultness = self.parse_defaultness();
6615 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6616 let (name, alias, generics) = type_?;
6617 let kind = match alias {
6618 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6619 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6621 (name, kind, generics)
6622 } else if self.is_const_item() {
6623 // This parses the grammar:
6624 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6625 self.expect_keyword(keywords::Const)?;
6626 let name = self.parse_ident()?;
6627 self.expect(&token::Colon)?;
6628 let typ = self.parse_ty()?;
6629 self.expect(&token::Eq)?;
6630 let expr = self.parse_expr()?;
6631 self.expect(&token::Semi)?;
6632 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6634 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6635 attrs.extend(inner_attrs);
6636 (name, node, generics)
6640 id: ast::DUMMY_NODE_ID,
6641 span: lo.to(self.prev_span),
6652 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6654 VisibilityKind::Inherited => {}
6656 let is_macro_rules: bool = match self.token {
6657 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6660 let mut err = if is_macro_rules {
6661 let mut err = self.diagnostic()
6662 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6663 err.span_suggestion(
6665 "try exporting the macro",
6666 "#[macro_export]".to_owned(),
6667 Applicability::MaybeIncorrect // speculative
6671 let mut err = self.diagnostic()
6672 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6673 err.help("try adjusting the macro to put `pub` inside the invocation");
6681 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6682 -> DiagnosticBuilder<'a>
6684 let expected_kinds = if item_type == "extern" {
6685 "missing `fn`, `type`, or `static`"
6687 "missing `fn`, `type`, or `const`"
6690 // Given this code `path(`, it seems like this is not
6691 // setting the visibility of a macro invocation, but rather
6692 // a mistyped method declaration.
6693 // Create a diagnostic pointing out that `fn` is missing.
6695 // x | pub path(&self) {
6696 // | ^ missing `fn`, `type`, or `const`
6698 // ^^ `sp` below will point to this
6699 let sp = prev_span.between(self.prev_span);
6700 let mut err = self.diagnostic().struct_span_err(
6702 &format!("{} for {}-item declaration",
6703 expected_kinds, item_type));
6704 err.span_label(sp, expected_kinds);
6708 /// Parse a method or a macro invocation in a trait impl.
6709 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6710 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6711 ast::ImplItemKind)> {
6712 // code copied from parse_macro_use_or_failure... abstraction!
6713 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6715 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6716 ast::ImplItemKind::Macro(mac)))
6718 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6719 let ident = self.parse_ident()?;
6720 let mut generics = self.parse_generics()?;
6721 let mut decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6722 generics.where_clause = self.parse_where_clause()?;
6723 self.construct_async_arguments(&mut asyncness, &mut decl);
6725 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6726 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6727 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6728 ast::MethodSig { header, decl },
6734 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6735 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6736 let ident = self.parse_ident()?;
6737 let mut tps = self.parse_generics()?;
6739 // Parse optional colon and supertrait bounds.
6740 let bounds = if self.eat(&token::Colon) {
6741 self.parse_generic_bounds(Some(self.prev_span))?
6746 if self.eat(&token::Eq) {
6747 // it's a trait alias
6748 let bounds = self.parse_generic_bounds(None)?;
6749 tps.where_clause = self.parse_where_clause()?;
6750 self.expect(&token::Semi)?;
6751 if is_auto == IsAuto::Yes {
6752 let msg = "trait aliases cannot be `auto`";
6753 self.struct_span_err(self.prev_span, msg)
6754 .span_label(self.prev_span, msg)
6757 if unsafety != Unsafety::Normal {
6758 let msg = "trait aliases cannot be `unsafe`";
6759 self.struct_span_err(self.prev_span, msg)
6760 .span_label(self.prev_span, msg)
6763 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6765 // it's a normal trait
6766 tps.where_clause = self.parse_where_clause()?;
6767 self.expect(&token::OpenDelim(token::Brace))?;
6768 let mut trait_items = vec![];
6769 while !self.eat(&token::CloseDelim(token::Brace)) {
6770 if let token::DocComment(_) = self.token {
6771 if self.look_ahead(1,
6772 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6773 let mut err = self.diagnostic().struct_span_err_with_code(
6775 "found a documentation comment that doesn't document anything",
6776 DiagnosticId::Error("E0584".into()),
6778 err.help("doc comments must come before what they document, maybe a \
6779 comment was intended with `//`?",
6786 let mut at_end = false;
6787 match self.parse_trait_item(&mut at_end) {
6788 Ok(item) => trait_items.push(item),
6792 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6797 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6801 fn choose_generics_over_qpath(&self) -> bool {
6802 // There's an ambiguity between generic parameters and qualified paths in impls.
6803 // If we see `<` it may start both, so we have to inspect some following tokens.
6804 // The following combinations can only start generics,
6805 // but not qualified paths (with one exception):
6806 // `<` `>` - empty generic parameters
6807 // `<` `#` - generic parameters with attributes
6808 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6809 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6810 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6811 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6812 // `<` const - generic const parameter
6813 // The only truly ambiguous case is
6814 // `<` IDENT `>` `::` IDENT ...
6815 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6816 // because this is what almost always expected in practice, qualified paths in impls
6817 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6818 self.token == token::Lt &&
6819 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6820 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6821 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6822 t == &token::Colon || t == &token::Eq) ||
6823 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6826 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6827 self.expect(&token::OpenDelim(token::Brace))?;
6828 let attrs = self.parse_inner_attributes()?;
6830 let mut impl_items = Vec::new();
6831 while !self.eat(&token::CloseDelim(token::Brace)) {
6832 let mut at_end = false;
6833 match self.parse_impl_item(&mut at_end) {
6834 Ok(impl_item) => impl_items.push(impl_item),
6838 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6843 Ok((impl_items, attrs))
6846 /// Parses an implementation item, `impl` keyword is already parsed.
6848 /// impl<'a, T> TYPE { /* impl items */ }
6849 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6850 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6852 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6853 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6854 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6855 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6856 -> PResult<'a, ItemInfo> {
6857 // First, parse generic parameters if necessary.
6858 let mut generics = if self.choose_generics_over_qpath() {
6859 self.parse_generics()?
6861 ast::Generics::default()
6864 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6865 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6867 ast::ImplPolarity::Negative
6869 ast::ImplPolarity::Positive
6872 // Parse both types and traits as a type, then reinterpret if necessary.
6873 let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6874 let ty_first = if self.token.is_keyword(keywords::For) &&
6875 self.look_ahead(1, |t| t != &token::Lt) {
6876 let span = self.prev_span.between(self.span);
6877 self.struct_span_err(span, "missing trait in a trait impl").emit();
6878 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6883 // If `for` is missing we try to recover.
6884 let has_for = self.eat_keyword(keywords::For);
6885 let missing_for_span = self.prev_span.between(self.span);
6887 let ty_second = if self.token == token::DotDot {
6888 // We need to report this error after `cfg` expansion for compatibility reasons
6889 self.bump(); // `..`, do not add it to expected tokens
6890 Some(DummyResult::raw_ty(self.prev_span, true))
6891 } else if has_for || self.token.can_begin_type() {
6892 Some(self.parse_ty()?)
6897 generics.where_clause = self.parse_where_clause()?;
6899 let (impl_items, attrs) = self.parse_impl_body()?;
6901 let item_kind = match ty_second {
6902 Some(ty_second) => {
6903 // impl Trait for Type
6905 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6906 .span_suggestion_short(
6909 " for ".to_string(),
6910 Applicability::MachineApplicable,
6914 let ty_first = ty_first.into_inner();
6915 let path = match ty_first.node {
6916 // This notably includes paths passed through `ty` macro fragments (#46438).
6917 TyKind::Path(None, path) => path,
6919 self.span_err(ty_first.span, "expected a trait, found type");
6920 err_path(ty_first.span)
6923 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6925 ItemKind::Impl(unsafety, polarity, defaultness,
6926 generics, Some(trait_ref), ty_second, impl_items)
6930 ItemKind::Impl(unsafety, polarity, defaultness,
6931 generics, None, ty_first, impl_items)
6935 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6938 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6939 if self.eat_keyword(keywords::For) {
6941 let params = self.parse_generic_params()?;
6943 // We rely on AST validation to rule out invalid cases: There must not be type
6944 // parameters, and the lifetime parameters must not have bounds.
6951 /// Parses `struct Foo { ... }`.
6952 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6953 let class_name = self.parse_ident()?;
6955 let mut generics = self.parse_generics()?;
6957 // There is a special case worth noting here, as reported in issue #17904.
6958 // If we are parsing a tuple struct it is the case that the where clause
6959 // should follow the field list. Like so:
6961 // struct Foo<T>(T) where T: Copy;
6963 // If we are parsing a normal record-style struct it is the case
6964 // that the where clause comes before the body, and after the generics.
6965 // So if we look ahead and see a brace or a where-clause we begin
6966 // parsing a record style struct.
6968 // Otherwise if we look ahead and see a paren we parse a tuple-style
6971 let vdata = if self.token.is_keyword(keywords::Where) {
6972 generics.where_clause = self.parse_where_clause()?;
6973 if self.eat(&token::Semi) {
6974 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6975 VariantData::Unit(ast::DUMMY_NODE_ID)
6977 // If we see: `struct Foo<T> where T: Copy { ... }`
6978 let (fields, recovered) = self.parse_record_struct_body()?;
6979 VariantData::Struct(fields, recovered)
6981 // No `where` so: `struct Foo<T>;`
6982 } else if self.eat(&token::Semi) {
6983 VariantData::Unit(ast::DUMMY_NODE_ID)
6984 // Record-style struct definition
6985 } else if self.token == token::OpenDelim(token::Brace) {
6986 let (fields, recovered) = self.parse_record_struct_body()?;
6987 VariantData::Struct(fields, recovered)
6988 // Tuple-style struct definition with optional where-clause.
6989 } else if self.token == token::OpenDelim(token::Paren) {
6990 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6991 generics.where_clause = self.parse_where_clause()?;
6992 self.expect(&token::Semi)?;
6995 let token_str = self.this_token_descr();
6996 let mut err = self.fatal(&format!(
6997 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
7000 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
7004 Ok((class_name, ItemKind::Struct(vdata, generics), None))
7007 /// Parses `union Foo { ... }`.
7008 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
7009 let class_name = self.parse_ident()?;
7011 let mut generics = self.parse_generics()?;
7013 let vdata = if self.token.is_keyword(keywords::Where) {
7014 generics.where_clause = self.parse_where_clause()?;
7015 let (fields, recovered) = self.parse_record_struct_body()?;
7016 VariantData::Struct(fields, recovered)
7017 } else if self.token == token::OpenDelim(token::Brace) {
7018 let (fields, recovered) = self.parse_record_struct_body()?;
7019 VariantData::Struct(fields, recovered)
7021 let token_str = self.this_token_descr();
7022 let mut err = self.fatal(&format!(
7023 "expected `where` or `{{` after union name, found {}", token_str));
7024 err.span_label(self.span, "expected `where` or `{` after union name");
7028 Ok((class_name, ItemKind::Union(vdata, generics), None))
7031 fn consume_block(&mut self, delim: token::DelimToken) {
7032 let mut brace_depth = 0;
7034 if self.eat(&token::OpenDelim(delim)) {
7036 } else if self.eat(&token::CloseDelim(delim)) {
7037 if brace_depth == 0 {
7043 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
7051 fn parse_record_struct_body(
7053 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
7054 let mut fields = Vec::new();
7055 let mut recovered = false;
7056 if self.eat(&token::OpenDelim(token::Brace)) {
7057 while self.token != token::CloseDelim(token::Brace) {
7058 let field = self.parse_struct_decl_field().map_err(|e| {
7059 self.recover_stmt();
7064 Ok(field) => fields.push(field),
7070 self.eat(&token::CloseDelim(token::Brace));
7072 let token_str = self.this_token_descr();
7073 let mut err = self.fatal(&format!(
7074 "expected `where`, or `{{` after struct name, found {}", token_str));
7075 err.span_label(self.span, "expected `where`, or `{` after struct name");
7079 Ok((fields, recovered))
7082 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
7083 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
7084 // Unit like structs are handled in parse_item_struct function
7085 let fields = self.parse_unspanned_seq(
7086 &token::OpenDelim(token::Paren),
7087 &token::CloseDelim(token::Paren),
7088 SeqSep::trailing_allowed(token::Comma),
7090 let attrs = p.parse_outer_attributes()?;
7092 let vis = p.parse_visibility(true)?;
7093 let ty = p.parse_ty()?;
7095 span: lo.to(ty.span),
7098 id: ast::DUMMY_NODE_ID,
7107 /// Parses a structure field declaration.
7108 fn parse_single_struct_field(&mut self,
7111 attrs: Vec<Attribute> )
7112 -> PResult<'a, StructField> {
7113 let mut seen_comma: bool = false;
7114 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
7115 if self.token == token::Comma {
7122 token::CloseDelim(token::Brace) => {}
7123 token::DocComment(_) => {
7124 let previous_span = self.prev_span;
7125 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
7126 self.bump(); // consume the doc comment
7127 let comma_after_doc_seen = self.eat(&token::Comma);
7128 // `seen_comma` is always false, because we are inside doc block
7129 // condition is here to make code more readable
7130 if seen_comma == false && comma_after_doc_seen == true {
7133 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7136 if seen_comma == false {
7137 let sp = self.sess.source_map().next_point(previous_span);
7138 err.span_suggestion(
7140 "missing comma here",
7142 Applicability::MachineApplicable
7149 let sp = self.sess.source_map().next_point(self.prev_span);
7150 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7151 self.this_token_descr()));
7152 if self.token.is_ident() {
7153 // This is likely another field; emit the diagnostic and keep going
7154 err.span_suggestion(
7156 "try adding a comma",
7158 Applicability::MachineApplicable,
7169 /// Parses an element of a struct declaration.
7170 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7171 let attrs = self.parse_outer_attributes()?;
7173 let vis = self.parse_visibility(false)?;
7174 self.parse_single_struct_field(lo, vis, attrs)
7177 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7178 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7179 /// If the following element can't be a tuple (i.e., it's a function definition), then
7180 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7181 /// so emit a proper diagnostic.
7182 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7183 maybe_whole!(self, NtVis, |x| x);
7185 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7186 if self.is_crate_vis() {
7187 self.bump(); // `crate`
7188 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7191 if !self.eat_keyword(keywords::Pub) {
7192 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7193 // keyword to grab a span from for inherited visibility; an empty span at the
7194 // beginning of the current token would seem to be the "Schelling span".
7195 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7197 let lo = self.prev_span;
7199 if self.check(&token::OpenDelim(token::Paren)) {
7200 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7201 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7202 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7203 // by the following tokens.
7204 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) &&
7205 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
7209 self.bump(); // `crate`
7210 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7212 lo.to(self.prev_span),
7213 VisibilityKind::Crate(CrateSugar::PubCrate),
7216 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7219 self.bump(); // `in`
7220 let path = self.parse_path(PathStyle::Mod)?; // `path`
7221 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7222 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7224 id: ast::DUMMY_NODE_ID,
7227 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7228 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7229 t.is_keyword(keywords::SelfLower))
7231 // `pub(self)` or `pub(super)`
7233 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7234 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7235 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7237 id: ast::DUMMY_NODE_ID,
7240 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7241 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7243 let msg = "incorrect visibility restriction";
7244 let suggestion = r##"some possible visibility restrictions are:
7245 `pub(crate)`: visible only on the current crate
7246 `pub(super)`: visible only in the current module's parent
7247 `pub(in path::to::module)`: visible only on the specified path"##;
7248 let path = self.parse_path(PathStyle::Mod)?;
7250 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7251 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7252 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7253 err.help(suggestion);
7254 err.span_suggestion(
7255 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7257 err.emit(); // emit diagnostic, but continue with public visibility
7261 Ok(respan(lo, VisibilityKind::Public))
7264 /// Parses defaultness (i.e., `default` or nothing).
7265 fn parse_defaultness(&mut self) -> Defaultness {
7266 // `pub` is included for better error messages
7267 if self.check_keyword(keywords::Default) &&
7268 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7269 t.is_keyword(keywords::Const) ||
7270 t.is_keyword(keywords::Fn) ||
7271 t.is_keyword(keywords::Unsafe) ||
7272 t.is_keyword(keywords::Extern) ||
7273 t.is_keyword(keywords::Type) ||
7274 t.is_keyword(keywords::Pub)) {
7275 self.bump(); // `default`
7276 Defaultness::Default
7282 /// Given a termination token, parses all of the items in a module.
7283 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7284 let mut items = vec![];
7285 while let Some(item) = self.parse_item()? {
7287 self.maybe_consume_incorrect_semicolon(&items);
7290 if !self.eat(term) {
7291 let token_str = self.this_token_descr();
7292 if !self.maybe_consume_incorrect_semicolon(&items) {
7293 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7294 err.span_label(self.span, "expected item");
7299 let hi = if self.span.is_dummy() {
7306 inner: inner_lo.to(hi),
7312 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7313 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7314 self.expect(&token::Colon)?;
7315 let ty = self.parse_ty()?;
7316 self.expect(&token::Eq)?;
7317 let e = self.parse_expr()?;
7318 self.expect(&token::Semi)?;
7319 let item = match m {
7320 Some(m) => ItemKind::Static(ty, m, e),
7321 None => ItemKind::Const(ty, e),
7323 Ok((id, item, None))
7326 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7327 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7328 let (in_cfg, outer_attrs) = {
7329 let mut strip_unconfigured = crate::config::StripUnconfigured {
7331 features: None, // don't perform gated feature checking
7333 let mut outer_attrs = outer_attrs.to_owned();
7334 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7335 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7338 let id_span = self.span;
7339 let id = self.parse_ident()?;
7340 if self.eat(&token::Semi) {
7341 if in_cfg && self.recurse_into_file_modules {
7342 // This mod is in an external file. Let's go get it!
7343 let ModulePathSuccess { path, directory_ownership, warn } =
7344 self.submod_path(id, &outer_attrs, id_span)?;
7345 let (module, mut attrs) =
7346 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7347 // Record that we fetched the mod from an external file
7349 let attr = Attribute {
7350 id: attr::mk_attr_id(),
7351 style: ast::AttrStyle::Outer,
7352 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7353 tokens: TokenStream::empty(),
7354 is_sugared_doc: false,
7355 span: syntax_pos::DUMMY_SP,
7357 attr::mark_known(&attr);
7360 Ok((id, ItemKind::Mod(module), Some(attrs)))
7362 let placeholder = ast::Mod {
7363 inner: syntax_pos::DUMMY_SP,
7367 Ok((id, ItemKind::Mod(placeholder), None))
7370 let old_directory = self.directory.clone();
7371 self.push_directory(id, &outer_attrs);
7373 self.expect(&token::OpenDelim(token::Brace))?;
7374 let mod_inner_lo = self.span;
7375 let attrs = self.parse_inner_attributes()?;
7376 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7378 self.directory = old_directory;
7379 Ok((id, ItemKind::Mod(module), Some(attrs)))
7383 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7384 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7385 self.directory.path.to_mut().push(&path.as_str());
7386 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7388 // We have to push on the current module name in the case of relative
7389 // paths in order to ensure that any additional module paths from inline
7390 // `mod x { ... }` come after the relative extension.
7392 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7393 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7394 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7395 if let Some(ident) = relative.take() { // remove the relative offset
7396 self.directory.path.to_mut().push(ident.as_str());
7399 self.directory.path.to_mut().push(&id.as_str());
7403 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7404 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7407 // On windows, the base path might have the form
7408 // `\\?\foo\bar` in which case it does not tolerate
7409 // mixed `/` and `\` separators, so canonicalize
7412 let s = s.replace("/", "\\");
7413 Some(dir_path.join(s))
7419 /// Returns a path to a module.
7420 pub fn default_submod_path(
7422 relative: Option<ast::Ident>,
7424 source_map: &SourceMap) -> ModulePath
7426 // If we're in a foo.rs file instead of a mod.rs file,
7427 // we need to look for submodules in
7428 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7429 // `./<id>.rs` and `./<id>/mod.rs`.
7430 let relative_prefix_string;
7431 let relative_prefix = if let Some(ident) = relative {
7432 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7433 &relative_prefix_string
7438 let mod_name = id.to_string();
7439 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7440 let secondary_path_str = format!("{}{}{}mod.rs",
7441 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7442 let default_path = dir_path.join(&default_path_str);
7443 let secondary_path = dir_path.join(&secondary_path_str);
7444 let default_exists = source_map.file_exists(&default_path);
7445 let secondary_exists = source_map.file_exists(&secondary_path);
7447 let result = match (default_exists, secondary_exists) {
7448 (true, false) => Ok(ModulePathSuccess {
7450 directory_ownership: DirectoryOwnership::Owned {
7455 (false, true) => Ok(ModulePathSuccess {
7456 path: secondary_path,
7457 directory_ownership: DirectoryOwnership::Owned {
7462 (false, false) => Err(Error::FileNotFoundForModule {
7463 mod_name: mod_name.clone(),
7464 default_path: default_path_str,
7465 secondary_path: secondary_path_str,
7466 dir_path: dir_path.display().to_string(),
7468 (true, true) => Err(Error::DuplicatePaths {
7469 mod_name: mod_name.clone(),
7470 default_path: default_path_str,
7471 secondary_path: secondary_path_str,
7477 path_exists: default_exists || secondary_exists,
7482 fn submod_path(&mut self,
7484 outer_attrs: &[Attribute],
7486 -> PResult<'a, ModulePathSuccess> {
7487 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7488 return Ok(ModulePathSuccess {
7489 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7490 // All `#[path]` files are treated as though they are a `mod.rs` file.
7491 // This means that `mod foo;` declarations inside `#[path]`-included
7492 // files are siblings,
7494 // Note that this will produce weirdness when a file named `foo.rs` is
7495 // `#[path]` included and contains a `mod foo;` declaration.
7496 // If you encounter this, it's your own darn fault :P
7497 Some(_) => DirectoryOwnership::Owned { relative: None },
7498 _ => DirectoryOwnership::UnownedViaMod(true),
7505 let relative = match self.directory.ownership {
7506 DirectoryOwnership::Owned { relative } => relative,
7507 DirectoryOwnership::UnownedViaBlock |
7508 DirectoryOwnership::UnownedViaMod(_) => None,
7510 let paths = Parser::default_submod_path(
7511 id, relative, &self.directory.path, self.sess.source_map());
7513 match self.directory.ownership {
7514 DirectoryOwnership::Owned { .. } => {
7515 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7517 DirectoryOwnership::UnownedViaBlock => {
7519 "Cannot declare a non-inline module inside a block \
7520 unless it has a path attribute";
7521 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7522 if paths.path_exists {
7523 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7525 err.span_note(id_sp, &msg);
7529 DirectoryOwnership::UnownedViaMod(warn) => {
7531 if let Ok(result) = paths.result {
7532 return Ok(ModulePathSuccess { warn: true, ..result });
7535 let mut err = self.diagnostic().struct_span_err(id_sp,
7536 "cannot declare a new module at this location");
7537 if !id_sp.is_dummy() {
7538 let src_path = self.sess.source_map().span_to_filename(id_sp);
7539 if let FileName::Real(src_path) = src_path {
7540 if let Some(stem) = src_path.file_stem() {
7541 let mut dest_path = src_path.clone();
7542 dest_path.set_file_name(stem);
7543 dest_path.push("mod.rs");
7544 err.span_note(id_sp,
7545 &format!("maybe move this module `{}` to its own \
7546 directory via `{}`", src_path.display(),
7547 dest_path.display()));
7551 if paths.path_exists {
7552 err.span_note(id_sp,
7553 &format!("... or maybe `use` the module `{}` instead \
7554 of possibly redeclaring it",
7562 /// Reads a module from a source file.
7563 fn eval_src_mod(&mut self,
7565 directory_ownership: DirectoryOwnership,
7568 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7569 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7570 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7571 let mut err = String::from("circular modules: ");
7572 let len = included_mod_stack.len();
7573 for p in &included_mod_stack[i.. len] {
7574 err.push_str(&p.to_string_lossy());
7575 err.push_str(" -> ");
7577 err.push_str(&path.to_string_lossy());
7578 return Err(self.span_fatal(id_sp, &err[..]));
7580 included_mod_stack.push(path.clone());
7581 drop(included_mod_stack);
7584 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7585 p0.cfg_mods = self.cfg_mods;
7586 let mod_inner_lo = p0.span;
7587 let mod_attrs = p0.parse_inner_attributes()?;
7588 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7590 self.sess.included_mod_stack.borrow_mut().pop();
7594 /// Parses a function declaration from a foreign module.
7595 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7596 -> PResult<'a, ForeignItem> {
7597 self.expect_keyword(keywords::Fn)?;
7599 let (ident, mut generics) = self.parse_fn_header()?;
7600 let decl = self.parse_fn_decl(true)?;
7601 generics.where_clause = self.parse_where_clause()?;
7603 self.expect(&token::Semi)?;
7604 Ok(ast::ForeignItem {
7607 node: ForeignItemKind::Fn(decl, generics),
7608 id: ast::DUMMY_NODE_ID,
7614 /// Parses a static item from a foreign module.
7615 /// Assumes that the `static` keyword is already parsed.
7616 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7617 -> PResult<'a, ForeignItem> {
7618 let mutbl = self.parse_mutability();
7619 let ident = self.parse_ident()?;
7620 self.expect(&token::Colon)?;
7621 let ty = self.parse_ty()?;
7623 self.expect(&token::Semi)?;
7627 node: ForeignItemKind::Static(ty, mutbl),
7628 id: ast::DUMMY_NODE_ID,
7634 /// Parses a type from a foreign module.
7635 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7636 -> PResult<'a, ForeignItem> {
7637 self.expect_keyword(keywords::Type)?;
7639 let ident = self.parse_ident()?;
7641 self.expect(&token::Semi)?;
7642 Ok(ast::ForeignItem {
7645 node: ForeignItemKind::Ty,
7646 id: ast::DUMMY_NODE_ID,
7652 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7653 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7654 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7656 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7657 self.parse_path_segment_ident()
7661 let mut idents = vec![];
7662 let mut replacement = vec![];
7663 let mut fixed_crate_name = false;
7664 // Accept `extern crate name-like-this` for better diagnostics
7665 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7666 if self.token == dash { // Do not include `-` as part of the expected tokens list
7667 while self.eat(&dash) {
7668 fixed_crate_name = true;
7669 replacement.push((self.prev_span, "_".to_string()));
7670 idents.push(self.parse_ident()?);
7673 if fixed_crate_name {
7674 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7675 let mut fixed_name = format!("{}", ident.name);
7676 for part in idents {
7677 fixed_name.push_str(&format!("_{}", part.name));
7679 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7681 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7682 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7683 err.multipart_suggestion(
7686 Applicability::MachineApplicable,
7693 /// Parses `extern crate` links.
7698 /// extern crate foo;
7699 /// extern crate bar as foo;
7701 fn parse_item_extern_crate(&mut self,
7703 visibility: Visibility,
7704 attrs: Vec<Attribute>)
7705 -> PResult<'a, P<Item>> {
7706 // Accept `extern crate name-like-this` for better diagnostics
7707 let orig_name = self.parse_crate_name_with_dashes()?;
7708 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7709 (rename, Some(orig_name.name))
7713 self.expect(&token::Semi)?;
7715 let span = lo.to(self.prev_span);
7716 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7719 /// Parses `extern` for foreign ABIs modules.
7721 /// `extern` is expected to have been
7722 /// consumed before calling this method.
7726 /// ```ignore (only-for-syntax-highlight)
7730 fn parse_item_foreign_mod(&mut self,
7732 opt_abi: Option<Abi>,
7733 visibility: Visibility,
7734 mut attrs: Vec<Attribute>)
7735 -> PResult<'a, P<Item>> {
7736 self.expect(&token::OpenDelim(token::Brace))?;
7738 let abi = opt_abi.unwrap_or(Abi::C);
7740 attrs.extend(self.parse_inner_attributes()?);
7742 let mut foreign_items = vec![];
7743 while !self.eat(&token::CloseDelim(token::Brace)) {
7744 foreign_items.push(self.parse_foreign_item()?);
7747 let prev_span = self.prev_span;
7748 let m = ast::ForeignMod {
7750 items: foreign_items
7752 let invalid = keywords::Invalid.ident();
7753 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7756 /// Parses `type Foo = Bar;`
7758 /// `existential type Foo: Bar;`
7761 /// without modifying the parser state.
7762 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7763 // This parses the grammar:
7764 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7765 if self.check_keyword(keywords::Type) ||
7766 self.check_keyword(keywords::Existential) &&
7767 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7768 let existential = self.eat_keyword(keywords::Existential);
7769 assert!(self.eat_keyword(keywords::Type));
7770 Some(self.parse_existential_or_alias(existential))
7776 /// Parses a type alias or existential type.
7777 fn parse_existential_or_alias(
7780 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7781 let ident = self.parse_ident()?;
7782 let mut tps = self.parse_generics()?;
7783 tps.where_clause = self.parse_where_clause()?;
7784 let alias = if existential {
7785 self.expect(&token::Colon)?;
7786 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7787 AliasKind::Existential(bounds)
7789 self.expect(&token::Eq)?;
7790 let ty = self.parse_ty()?;
7793 self.expect(&token::Semi)?;
7794 Ok((ident, alias, tps))
7797 /// Parses the part of an enum declaration following the `{`.
7798 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7799 let mut variants = Vec::new();
7800 let mut all_nullary = true;
7801 let mut any_disr = vec![];
7802 while self.token != token::CloseDelim(token::Brace) {
7803 let variant_attrs = self.parse_outer_attributes()?;
7804 let vlo = self.span;
7807 let mut disr_expr = None;
7809 let ident = self.parse_ident()?;
7810 if self.check(&token::OpenDelim(token::Brace)) {
7811 // Parse a struct variant.
7812 all_nullary = false;
7813 let (fields, recovered) = self.parse_record_struct_body()?;
7814 struct_def = VariantData::Struct(fields, recovered);
7815 } else if self.check(&token::OpenDelim(token::Paren)) {
7816 all_nullary = false;
7817 struct_def = VariantData::Tuple(
7818 self.parse_tuple_struct_body()?,
7821 } else if self.eat(&token::Eq) {
7822 disr_expr = Some(AnonConst {
7823 id: ast::DUMMY_NODE_ID,
7824 value: self.parse_expr()?,
7826 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7829 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7831 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7834 let vr = ast::Variant_ {
7836 id: ast::DUMMY_NODE_ID,
7837 attrs: variant_attrs,
7841 variants.push(respan(vlo.to(self.prev_span), vr));
7843 if !self.eat(&token::Comma) {
7844 if self.token.is_ident() && !self.token.is_reserved_ident() {
7845 let sp = self.sess.source_map().next_point(self.prev_span);
7846 let mut err = self.struct_span_err(sp, "missing comma");
7847 err.span_suggestion_short(
7851 Applicability::MaybeIncorrect,
7859 self.expect(&token::CloseDelim(token::Brace))?;
7860 if !any_disr.is_empty() && !all_nullary {
7861 let mut err = self.struct_span_err(
7863 "discriminator values can only be used with a field-less enum",
7865 for sp in any_disr {
7866 err.span_label(sp, "only valid in field-less enums");
7871 Ok(ast::EnumDef { variants })
7874 /// Parses an enum declaration.
7875 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7876 let id = self.parse_ident()?;
7877 let mut generics = self.parse_generics()?;
7878 generics.where_clause = self.parse_where_clause()?;
7879 self.expect(&token::OpenDelim(token::Brace))?;
7881 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7882 self.recover_stmt();
7883 self.eat(&token::CloseDelim(token::Brace));
7886 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7889 /// Parses a string as an ABI spec on an extern type or module. Consumes
7890 /// the `extern` keyword, if one is found.
7891 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7893 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7895 self.expect_no_suffix(sp, "an ABI spec", suf);
7897 match abi::lookup(&s.as_str()) {
7898 Some(abi) => Ok(Some(abi)),
7900 let prev_span = self.prev_span;
7901 let mut err = struct_span_err!(
7902 self.sess.span_diagnostic,
7905 "invalid ABI: found `{}`",
7907 err.span_label(prev_span, "invalid ABI");
7908 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7919 fn is_static_global(&mut self) -> bool {
7920 if self.check_keyword(keywords::Static) {
7921 // Check if this could be a closure
7922 !self.look_ahead(1, |token| {
7923 if token.is_keyword(keywords::Move) {
7927 token::BinOp(token::Or) | token::OrOr => true,
7938 attrs: Vec<Attribute>,
7939 macros_allowed: bool,
7940 attributes_allowed: bool,
7941 ) -> PResult<'a, Option<P<Item>>> {
7942 let mut unclosed_delims = vec![];
7943 let (ret, tokens) = self.collect_tokens(|this| {
7944 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7945 unclosed_delims.append(&mut this.unclosed_delims);
7948 self.unclosed_delims.append(&mut unclosed_delims);
7950 // Once we've parsed an item and recorded the tokens we got while
7951 // parsing we may want to store `tokens` into the item we're about to
7952 // return. Note, though, that we specifically didn't capture tokens
7953 // related to outer attributes. The `tokens` field here may later be
7954 // used with procedural macros to convert this item back into a token
7955 // stream, but during expansion we may be removing attributes as we go
7958 // If we've got inner attributes then the `tokens` we've got above holds
7959 // these inner attributes. If an inner attribute is expanded we won't
7960 // actually remove it from the token stream, so we'll just keep yielding
7961 // it (bad!). To work around this case for now we just avoid recording
7962 // `tokens` if we detect any inner attributes. This should help keep
7963 // expansion correct, but we should fix this bug one day!
7966 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7967 i.tokens = Some(tokens);
7974 /// Parses one of the items allowed by the flags.
7975 fn parse_item_implementation(
7977 attrs: Vec<Attribute>,
7978 macros_allowed: bool,
7979 attributes_allowed: bool,
7980 ) -> PResult<'a, Option<P<Item>>> {
7981 maybe_whole!(self, NtItem, |item| {
7982 let mut item = item.into_inner();
7983 let mut attrs = attrs;
7984 mem::swap(&mut item.attrs, &mut attrs);
7985 item.attrs.extend(attrs);
7991 let visibility = self.parse_visibility(false)?;
7993 if self.eat_keyword(keywords::Use) {
7995 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7996 self.expect(&token::Semi)?;
7998 let span = lo.to(self.prev_span);
7999 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
8000 return Ok(Some(item));
8003 if self.eat_keyword(keywords::Extern) {
8004 if self.eat_keyword(keywords::Crate) {
8005 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
8008 let opt_abi = self.parse_opt_abi()?;
8010 if self.eat_keyword(keywords::Fn) {
8011 // EXTERN FUNCTION ITEM
8012 let fn_span = self.prev_span;
8013 let abi = opt_abi.unwrap_or(Abi::C);
8014 let (ident, item_, extra_attrs) =
8015 self.parse_item_fn(Unsafety::Normal,
8016 respan(fn_span, IsAsync::NotAsync),
8017 respan(fn_span, Constness::NotConst),
8019 let prev_span = self.prev_span;
8020 let item = self.mk_item(lo.to(prev_span),
8024 maybe_append(attrs, extra_attrs));
8025 return Ok(Some(item));
8026 } else if self.check(&token::OpenDelim(token::Brace)) {
8027 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
8033 if self.is_static_global() {
8036 let m = if self.eat_keyword(keywords::Mut) {
8039 Mutability::Immutable
8041 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
8042 let prev_span = self.prev_span;
8043 let item = self.mk_item(lo.to(prev_span),
8047 maybe_append(attrs, extra_attrs));
8048 return Ok(Some(item));
8050 if self.eat_keyword(keywords::Const) {
8051 let const_span = self.prev_span;
8052 if self.check_keyword(keywords::Fn)
8053 || (self.check_keyword(keywords::Unsafe)
8054 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
8055 // CONST FUNCTION ITEM
8056 let unsafety = self.parse_unsafety();
8058 let (ident, item_, extra_attrs) =
8059 self.parse_item_fn(unsafety,
8060 respan(const_span, IsAsync::NotAsync),
8061 respan(const_span, Constness::Const),
8063 let prev_span = self.prev_span;
8064 let item = self.mk_item(lo.to(prev_span),
8068 maybe_append(attrs, extra_attrs));
8069 return Ok(Some(item));
8073 if self.eat_keyword(keywords::Mut) {
8074 let prev_span = self.prev_span;
8075 let mut err = self.diagnostic()
8076 .struct_span_err(prev_span, "const globals cannot be mutable");
8077 err.span_label(prev_span, "cannot be mutable");
8078 err.span_suggestion(
8080 "you might want to declare a static instead",
8081 "static".to_owned(),
8082 Applicability::MaybeIncorrect,
8086 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
8087 let prev_span = self.prev_span;
8088 let item = self.mk_item(lo.to(prev_span),
8092 maybe_append(attrs, extra_attrs));
8093 return Ok(Some(item));
8096 // `unsafe async fn` or `async fn`
8098 self.check_keyword(keywords::Unsafe) &&
8099 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
8101 self.check_keyword(keywords::Async) &&
8102 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
8105 // ASYNC FUNCTION ITEM
8106 let unsafety = self.parse_unsafety();
8107 self.expect_keyword(keywords::Async)?;
8108 let async_span = self.prev_span;
8109 self.expect_keyword(keywords::Fn)?;
8110 let fn_span = self.prev_span;
8111 let (ident, item_, extra_attrs) =
8112 self.parse_item_fn(unsafety,
8113 respan(async_span, IsAsync::Async {
8114 closure_id: ast::DUMMY_NODE_ID,
8115 return_impl_trait_id: ast::DUMMY_NODE_ID,
8116 arguments: Vec::new(),
8118 respan(fn_span, Constness::NotConst),
8120 let prev_span = self.prev_span;
8121 let item = self.mk_item(lo.to(prev_span),
8125 maybe_append(attrs, extra_attrs));
8126 if self.span.rust_2015() {
8127 self.diagnostic().struct_span_err_with_code(
8129 "`async fn` is not permitted in the 2015 edition",
8130 DiagnosticId::Error("E0670".into())
8133 return Ok(Some(item));
8135 if self.check_keyword(keywords::Unsafe) &&
8136 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8137 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8139 // UNSAFE TRAIT ITEM
8140 self.bump(); // `unsafe`
8141 let is_auto = if self.eat_keyword(keywords::Trait) {
8144 self.expect_keyword(keywords::Auto)?;
8145 self.expect_keyword(keywords::Trait)?;
8148 let (ident, item_, extra_attrs) =
8149 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8150 let prev_span = self.prev_span;
8151 let item = self.mk_item(lo.to(prev_span),
8155 maybe_append(attrs, extra_attrs));
8156 return Ok(Some(item));
8158 if self.check_keyword(keywords::Impl) ||
8159 self.check_keyword(keywords::Unsafe) &&
8160 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8161 self.check_keyword(keywords::Default) &&
8162 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8163 self.check_keyword(keywords::Default) &&
8164 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8166 let defaultness = self.parse_defaultness();
8167 let unsafety = self.parse_unsafety();
8168 self.expect_keyword(keywords::Impl)?;
8169 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8170 let span = lo.to(self.prev_span);
8171 return Ok(Some(self.mk_item(span, ident, item, visibility,
8172 maybe_append(attrs, extra_attrs))));
8174 if self.check_keyword(keywords::Fn) {
8177 let fn_span = self.prev_span;
8178 let (ident, item_, extra_attrs) =
8179 self.parse_item_fn(Unsafety::Normal,
8180 respan(fn_span, IsAsync::NotAsync),
8181 respan(fn_span, Constness::NotConst),
8183 let prev_span = self.prev_span;
8184 let item = self.mk_item(lo.to(prev_span),
8188 maybe_append(attrs, extra_attrs));
8189 return Ok(Some(item));
8191 if self.check_keyword(keywords::Unsafe)
8192 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8193 // UNSAFE FUNCTION ITEM
8194 self.bump(); // `unsafe`
8195 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8196 self.check(&token::OpenDelim(token::Brace));
8197 let abi = if self.eat_keyword(keywords::Extern) {
8198 self.parse_opt_abi()?.unwrap_or(Abi::C)
8202 self.expect_keyword(keywords::Fn)?;
8203 let fn_span = self.prev_span;
8204 let (ident, item_, extra_attrs) =
8205 self.parse_item_fn(Unsafety::Unsafe,
8206 respan(fn_span, IsAsync::NotAsync),
8207 respan(fn_span, Constness::NotConst),
8209 let prev_span = self.prev_span;
8210 let item = self.mk_item(lo.to(prev_span),
8214 maybe_append(attrs, extra_attrs));
8215 return Ok(Some(item));
8217 if self.eat_keyword(keywords::Mod) {
8219 let (ident, item_, extra_attrs) =
8220 self.parse_item_mod(&attrs[..])?;
8221 let prev_span = self.prev_span;
8222 let item = self.mk_item(lo.to(prev_span),
8226 maybe_append(attrs, extra_attrs));
8227 return Ok(Some(item));
8229 if let Some(type_) = self.eat_type() {
8230 let (ident, alias, generics) = type_?;
8232 let item_ = match alias {
8233 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8234 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8236 let prev_span = self.prev_span;
8237 let item = self.mk_item(lo.to(prev_span),
8242 return Ok(Some(item));
8244 if self.eat_keyword(keywords::Enum) {
8246 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8247 let prev_span = self.prev_span;
8248 let item = self.mk_item(lo.to(prev_span),
8252 maybe_append(attrs, extra_attrs));
8253 return Ok(Some(item));
8255 if self.check_keyword(keywords::Trait)
8256 || (self.check_keyword(keywords::Auto)
8257 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8259 let is_auto = if self.eat_keyword(keywords::Trait) {
8262 self.expect_keyword(keywords::Auto)?;
8263 self.expect_keyword(keywords::Trait)?;
8267 let (ident, item_, extra_attrs) =
8268 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8269 let prev_span = self.prev_span;
8270 let item = self.mk_item(lo.to(prev_span),
8274 maybe_append(attrs, extra_attrs));
8275 return Ok(Some(item));
8277 if self.eat_keyword(keywords::Struct) {
8279 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8280 let prev_span = self.prev_span;
8281 let item = self.mk_item(lo.to(prev_span),
8285 maybe_append(attrs, extra_attrs));
8286 return Ok(Some(item));
8288 if self.is_union_item() {
8291 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8292 let prev_span = self.prev_span;
8293 let item = self.mk_item(lo.to(prev_span),
8297 maybe_append(attrs, extra_attrs));
8298 return Ok(Some(item));
8300 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8301 return Ok(Some(macro_def));
8304 // Verify whether we have encountered a struct or method definition where the user forgot to
8305 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8306 if visibility.node.is_pub() &&
8307 self.check_ident() &&
8308 self.look_ahead(1, |t| *t != token::Not)
8310 // Space between `pub` keyword and the identifier
8313 // ^^^ `sp` points here
8314 let sp = self.prev_span.between(self.span);
8315 let full_sp = self.prev_span.to(self.span);
8316 let ident_sp = self.span;
8317 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8318 // possible public struct definition where `struct` was forgotten
8319 let ident = self.parse_ident().unwrap();
8320 let msg = format!("add `struct` here to parse `{}` as a public struct",
8322 let mut err = self.diagnostic()
8323 .struct_span_err(sp, "missing `struct` for struct definition");
8324 err.span_suggestion_short(
8325 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8328 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8329 let ident = self.parse_ident().unwrap();
8331 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8336 self.consume_block(token::Paren);
8337 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8338 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8340 ("fn", kw_name, false)
8341 } else if self.check(&token::OpenDelim(token::Brace)) {
8343 ("fn", kw_name, false)
8344 } else if self.check(&token::Colon) {
8348 ("fn` or `struct", "function or struct", true)
8351 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8352 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8354 self.consume_block(token::Brace);
8355 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8359 err.span_suggestion_short(
8360 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8363 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8364 err.span_suggestion(
8366 "if you meant to call a macro, try",
8367 format!("{}!", snippet),
8368 // this is the `ambiguous` conditional branch
8369 Applicability::MaybeIncorrect
8372 err.help("if you meant to call a macro, remove the `pub` \
8373 and add a trailing `!` after the identifier");
8377 } else if self.look_ahead(1, |t| *t == token::Lt) {
8378 let ident = self.parse_ident().unwrap();
8379 self.eat_to_tokens(&[&token::Gt]);
8381 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8382 if let Ok(Some(_)) = self.parse_self_arg() {
8383 ("fn", "method", false)
8385 ("fn", "function", false)
8387 } else if self.check(&token::OpenDelim(token::Brace)) {
8388 ("struct", "struct", false)
8390 ("fn` or `struct", "function or struct", true)
8392 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8393 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8395 err.span_suggestion_short(
8397 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8398 format!(" {} ", kw),
8399 Applicability::MachineApplicable,
8405 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8408 /// Parses a foreign item.
8409 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8410 maybe_whole!(self, NtForeignItem, |ni| ni);
8412 let attrs = self.parse_outer_attributes()?;
8414 let visibility = self.parse_visibility(false)?;
8416 // FOREIGN STATIC ITEM
8417 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8418 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8419 if self.token.is_keyword(keywords::Const) {
8421 .struct_span_err(self.span, "extern items cannot be `const`")
8424 "try using a static value",
8425 "static".to_owned(),
8426 Applicability::MachineApplicable
8429 self.bump(); // `static` or `const`
8430 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8432 // FOREIGN FUNCTION ITEM
8433 if self.check_keyword(keywords::Fn) {
8434 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8436 // FOREIGN TYPE ITEM
8437 if self.check_keyword(keywords::Type) {
8438 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8441 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8445 ident: keywords::Invalid.ident(),
8446 span: lo.to(self.prev_span),
8447 id: ast::DUMMY_NODE_ID,
8450 node: ForeignItemKind::Macro(mac),
8455 if !attrs.is_empty() {
8456 self.expected_item_err(&attrs)?;
8464 /// This is the fall-through for parsing items.
8465 fn parse_macro_use_or_failure(
8467 attrs: Vec<Attribute> ,
8468 macros_allowed: bool,
8469 attributes_allowed: bool,
8471 visibility: Visibility
8472 ) -> PResult<'a, Option<P<Item>>> {
8473 if macros_allowed && self.token.is_path_start() &&
8474 !(self.is_async_fn() && self.span.rust_2015()) {
8475 // MACRO INVOCATION ITEM
8477 let prev_span = self.prev_span;
8478 self.complain_if_pub_macro(&visibility.node, prev_span);
8480 let mac_lo = self.span;
8483 let pth = self.parse_path(PathStyle::Mod)?;
8484 self.expect(&token::Not)?;
8486 // a 'special' identifier (like what `macro_rules!` uses)
8487 // is optional. We should eventually unify invoc syntax
8489 let id = if self.token.is_ident() {
8492 keywords::Invalid.ident() // no special identifier
8494 // eat a matched-delimiter token tree:
8495 let (delim, tts) = self.expect_delimited_token_tree()?;
8496 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8497 self.report_invalid_macro_expansion_item();
8500 let hi = self.prev_span;
8501 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8502 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8503 return Ok(Some(item));
8506 // FAILURE TO PARSE ITEM
8507 match visibility.node {
8508 VisibilityKind::Inherited => {}
8510 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8514 if !attributes_allowed && !attrs.is_empty() {
8515 self.expected_item_err(&attrs)?;
8520 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8521 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8522 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8524 if self.token.is_path_start() &&
8525 !(self.is_async_fn() && self.span.rust_2015()) {
8526 let prev_span = self.prev_span;
8528 let pth = self.parse_path(PathStyle::Mod)?;
8530 if pth.segments.len() == 1 {
8531 if !self.eat(&token::Not) {
8532 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8535 self.expect(&token::Not)?;
8538 if let Some(vis) = vis {
8539 self.complain_if_pub_macro(&vis.node, prev_span);
8544 // eat a matched-delimiter token tree:
8545 let (delim, tts) = self.expect_delimited_token_tree()?;
8546 if delim != MacDelimiter::Brace {
8547 self.expect(&token::Semi)?;
8550 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8556 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8557 where F: FnOnce(&mut Self) -> PResult<'a, R>
8559 // Record all tokens we parse when parsing this item.
8560 let mut tokens = Vec::new();
8561 let prev_collecting = match self.token_cursor.frame.last_token {
8562 LastToken::Collecting(ref mut list) => {
8563 Some(mem::replace(list, Vec::new()))
8565 LastToken::Was(ref mut last) => {
8566 tokens.extend(last.take());
8570 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8571 let prev = self.token_cursor.stack.len();
8573 let last_token = if self.token_cursor.stack.len() == prev {
8574 &mut self.token_cursor.frame.last_token
8576 &mut self.token_cursor.stack[prev].last_token
8579 // Pull out the tokens that we've collected from the call to `f` above.
8580 let mut collected_tokens = match *last_token {
8581 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8582 LastToken::Was(_) => panic!("our vector went away?"),
8585 // If we're not at EOF our current token wasn't actually consumed by
8586 // `f`, but it'll still be in our list that we pulled out. In that case
8588 let extra_token = if self.token != token::Eof {
8589 collected_tokens.pop()
8594 // If we were previously collecting tokens, then this was a recursive
8595 // call. In that case we need to record all the tokens we collected in
8596 // our parent list as well. To do that we push a clone of our stream
8597 // onto the previous list.
8598 match prev_collecting {
8600 list.extend(collected_tokens.iter().cloned());
8601 list.extend(extra_token);
8602 *last_token = LastToken::Collecting(list);
8605 *last_token = LastToken::Was(extra_token);
8609 Ok((ret?, TokenStream::new(collected_tokens)))
8612 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8613 let attrs = self.parse_outer_attributes()?;
8614 self.parse_item_(attrs, true, false)
8618 fn is_import_coupler(&mut self) -> bool {
8619 self.check(&token::ModSep) &&
8620 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8621 *t == token::BinOp(token::Star))
8624 /// Parses a `UseTree`.
8627 /// USE_TREE = [`::`] `*` |
8628 /// [`::`] `{` USE_TREE_LIST `}` |
8630 /// PATH `::` `{` USE_TREE_LIST `}` |
8631 /// PATH [`as` IDENT]
8633 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8636 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8637 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8638 self.check(&token::BinOp(token::Star)) ||
8639 self.is_import_coupler() {
8640 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8641 let mod_sep_ctxt = self.span.ctxt();
8642 if self.eat(&token::ModSep) {
8643 prefix.segments.push(
8644 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8648 if self.eat(&token::BinOp(token::Star)) {
8651 UseTreeKind::Nested(self.parse_use_tree_list()?)
8654 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8655 prefix = self.parse_path(PathStyle::Mod)?;
8657 if self.eat(&token::ModSep) {
8658 if self.eat(&token::BinOp(token::Star)) {
8661 UseTreeKind::Nested(self.parse_use_tree_list()?)
8664 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8668 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8671 /// Parses a `UseTreeKind::Nested(list)`.
8674 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8676 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8677 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8678 &token::CloseDelim(token::Brace),
8679 SeqSep::trailing_allowed(token::Comma), |this| {
8680 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8684 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8685 if self.eat_keyword(keywords::As) {
8686 self.parse_ident_or_underscore().map(Some)
8692 /// Parses a source module as a crate. This is the main entry point for the parser.
8693 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8695 let krate = Ok(ast::Crate {
8696 attrs: self.parse_inner_attributes()?,
8697 module: self.parse_mod_items(&token::Eof, lo)?,
8698 span: lo.to(self.span),
8703 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8704 let ret = match self.token {
8705 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8706 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8713 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8714 match self.parse_optional_str() {
8715 Some((s, style, suf)) => {
8716 let sp = self.prev_span;
8717 self.expect_no_suffix(sp, "a string literal", suf);
8721 let msg = "expected string literal";
8722 let mut err = self.fatal(msg);
8723 err.span_label(self.span, msg);
8729 fn report_invalid_macro_expansion_item(&self) {
8730 self.struct_span_err(
8732 "macros that expand to items must be delimited with braces or followed by a semicolon",
8733 ).multipart_suggestion(
8734 "change the delimiters to curly braces",
8736 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8737 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8739 Applicability::MaybeIncorrect,
8741 self.sess.source_map.next_point(self.prev_span),
8744 Applicability::MaybeIncorrect,
8748 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8749 fn eat_bad_pub(&mut self) {
8750 if self.token.is_keyword(keywords::Pub) {
8751 match self.parse_visibility(false) {
8753 let mut err = self.diagnostic()
8754 .struct_span_err(vis.span, "unnecessary visibility qualifier");
8755 err.span_label(vis.span, "`pub` not permitted here");
8758 Err(mut err) => err.emit(),
8763 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8764 /// into the generated closure so that they are dropped when the future is polled and not when
8767 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8768 /// this function and the statements created here are inserted at the top of the closure body.
8769 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &mut FnDecl) {
8770 // FIXME(davidtwco): This function should really live in the HIR lowering but because
8771 // the types constructed here need to be used in parts of resolve so that the correct
8772 // locals are considered upvars, it is currently easier for it to live here in the parser,
8773 // where it can be constructed once.
8774 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8775 for (index, input) in decl.inputs.iter_mut().enumerate() {
8776 let id = ast::DUMMY_NODE_ID;
8777 let span = input.pat.span;
8779 // Construct a name for our temporary argument.
8780 let name = format!("__arg{}", index);
8781 let ident = Ident::from_str(&name).gensym();
8783 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
8784 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
8786 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
8787 PatKind::Ident(binding_mode @ BindingMode::ByValue(_), ident, _) => {
8788 // Simple patterns like this don't have a generated argument, but they are
8789 // moved into the closure with a statement, so any `mut` bindings on the
8790 // argument will be unused. This binding mode can't be removed, because
8791 // this would affect the input to procedural macros, but they can have
8792 // their span marked as being the result of a compiler desugaring so
8793 // that they aren't linted against.
8794 input.pat.span = self.sess.source_map().mark_span_with_reason(
8795 CompilerDesugaringKind::Async, span, None);
8797 (binding_mode, ident, true)
8799 _ => (BindingMode::ByValue(Mutability::Mutable), ident, false),
8802 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8803 // async function if it isn't a simple pattern.
8804 let arg = if is_simple_pattern {
8808 ty: input.ty.clone(),
8812 node: PatKind::Ident(
8813 BindingMode::ByValue(Mutability::Immutable), ident, None,
8817 source: ArgSource::AsyncFn(input.pat.clone()),
8821 // Construct a `let __argN = __argN;` statement to insert at the top of the
8822 // async closure. This makes sure that the argument is captured by the closure and
8823 // that the drop order is correct.
8824 let move_local = Local {
8827 node: PatKind::Ident(binding_mode, ident, None),
8830 // We explicitly do not specify the type for this statement. When the user's
8831 // argument type is `impl Trait` then this would require the
8832 // `impl_trait_in_bindings` feature to also be present for that same type to
8833 // be valid in this binding. At the time of writing (13 Mar 19),
8834 // `impl_trait_in_bindings` is not stable.
8838 node: ExprKind::Path(None, ast::Path {
8840 segments: vec![PathSegment { ident, id, args: None }],
8843 attrs: ThinVec::new(),
8847 attrs: ThinVec::new(),
8848 source: LocalSource::AsyncFn,
8851 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8852 // async closure if this isn't a simple pattern.
8853 let pat_stmt = if is_simple_pattern {
8858 node: StmtKind::Local(P(Local {
8859 pat: input.pat.clone(),
8860 ..move_local.clone()
8866 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
8867 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
8873 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8874 for unmatched in unclosed_delims.iter() {
8875 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8876 "incorrect close delimiter: `{}`",
8877 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8879 err.span_label(unmatched.found_span, "incorrect close delimiter");
8880 if let Some(sp) = unmatched.candidate_span {
8881 err.span_label(sp, "close delimiter possibly meant for this");
8883 if let Some(sp) = unmatched.unclosed_span {
8884 err.span_label(sp, "un-closed delimiter");
8888 unclosed_delims.clear();