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(&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 maybe_whole!(self, NtArg, |x| x);
1930 if let Ok(Some(_)) = self.parse_self_arg() {
1931 let mut err = self.struct_span_err(self.prev_span,
1932 "unexpected `self` argument in function");
1933 err.span_label(self.prev_span,
1934 "`self` is only valid as the first argument of an associated function");
1938 let (pat, ty) = if require_name || self.is_named_argument() {
1939 debug!("parse_arg_general parse_pat (require_name:{})",
1941 self.eat_incorrect_doc_comment("method arguments");
1942 let pat = self.parse_pat(Some("argument name"))?;
1944 if let Err(mut err) = self.expect(&token::Colon) {
1945 // If we find a pattern followed by an identifier, it could be an (incorrect)
1946 // C-style parameter declaration.
1947 if self.check_ident() && self.look_ahead(1, |t| {
1948 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1950 let ident = self.parse_ident().unwrap();
1951 let span = pat.span.with_hi(ident.span.hi());
1953 err.span_suggestion(
1955 "declare the type after the parameter binding",
1956 String::from("<identifier>: <type>"),
1957 Applicability::HasPlaceholders,
1959 } else if require_name && is_trait_item {
1960 if let PatKind::Ident(_, ident, _) = pat.node {
1961 err.span_suggestion(
1963 "explicitly ignore parameter",
1964 format!("_: {}", ident),
1965 Applicability::MachineApplicable,
1969 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1975 self.eat_incorrect_doc_comment("a method argument's type");
1976 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1978 debug!("parse_arg_general ident_to_pat");
1979 let parser_snapshot_before_ty = self.clone();
1980 self.eat_incorrect_doc_comment("a method argument's type");
1981 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1982 if ty.is_ok() && self.token != token::Comma &&
1983 self.token != token::CloseDelim(token::Paren) {
1984 // This wasn't actually a type, but a pattern looking like a type,
1985 // so we are going to rollback and re-parse for recovery.
1986 ty = self.unexpected();
1990 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1992 id: ast::DUMMY_NODE_ID,
1993 node: PatKind::Ident(
1994 BindingMode::ByValue(Mutability::Immutable), ident, None),
2000 // If this is a C-variadic argument and we hit an error, return the
2002 if self.token == token::DotDotDot {
2005 // Recover from attempting to parse the argument as a type without pattern.
2007 mem::replace(self, parser_snapshot_before_ty);
2008 let pat = self.parse_pat(Some("argument name"))?;
2009 self.expect(&token::Colon)?;
2010 let ty = self.parse_ty()?;
2012 let mut err = self.diagnostic().struct_span_err_with_code(
2014 "patterns aren't allowed in methods without bodies",
2015 DiagnosticId::Error("E0642".into()),
2017 err.span_suggestion_short(
2019 "give this argument a name or use an underscore to ignore it",
2021 Applicability::MachineApplicable,
2025 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2027 node: PatKind::Wild,
2029 id: ast::DUMMY_NODE_ID
2036 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
2039 /// Parses a single function argument.
2040 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2041 self.parse_arg_general(true, false, false)
2044 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2045 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2046 let pat = self.parse_pat(Some("argument name"))?;
2047 let t = if self.eat(&token::Colon) {
2051 id: ast::DUMMY_NODE_ID,
2052 node: TyKind::Infer,
2053 span: self.prev_span,
2059 id: ast::DUMMY_NODE_ID,
2060 source: ast::ArgSource::Normal,
2064 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2065 if self.eat(&token::Semi) {
2066 Ok(Some(self.parse_expr()?))
2072 /// Matches `token_lit = LIT_INTEGER | ...`.
2073 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2074 let out = match self.token {
2075 token::Interpolated(ref nt) => match **nt {
2076 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2077 ExprKind::Lit(ref lit) => { lit.node.clone() }
2078 _ => { return self.unexpected_last(&self.token); }
2080 _ => { return self.unexpected_last(&self.token); }
2082 token::Literal(lit, suf) => {
2083 let diag = Some((self.span, &self.sess.span_diagnostic));
2084 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2088 self.expect_no_suffix(sp, &format!("a {}", lit.literal_name()), suf)
2093 token::Dot if self.look_ahead(1, |t| match t {
2094 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2096 }) => { // recover from `let x = .4;`
2099 if let token::Literal(
2100 parse::token::Lit::Integer(val),
2103 let suffix = suffix.and_then(|s| {
2107 } else if s == "f64" {
2114 let sp = lo.to(self.prev_span);
2115 let mut err = self.diagnostic()
2116 .struct_span_err(sp, "float literals must have an integer part");
2117 err.span_suggestion(
2119 "must have an integer part",
2120 format!("0.{}{}", val, suffix),
2121 Applicability::MachineApplicable,
2124 return Ok(match suffix {
2125 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2126 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2127 _ => ast::LitKind::FloatUnsuffixed(val),
2133 _ => { return self.unexpected_last(&self.token); }
2140 /// Matches `lit = true | false | token_lit`.
2141 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2143 let lit = if self.eat_keyword(keywords::True) {
2145 } else if self.eat_keyword(keywords::False) {
2146 LitKind::Bool(false)
2148 let lit = self.parse_lit_token()?;
2151 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2154 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2155 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2156 maybe_whole_expr!(self);
2158 let minus_lo = self.span;
2159 let minus_present = self.eat(&token::BinOp(token::Minus));
2161 let literal = self.parse_lit()?;
2162 let hi = self.prev_span;
2163 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2166 let minus_hi = self.prev_span;
2167 let unary = self.mk_unary(UnOp::Neg, expr);
2168 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2174 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2176 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2177 let span = self.span;
2179 Ok(Ident::new(ident.name, span))
2181 _ => self.parse_ident(),
2185 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2187 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2188 let span = self.span;
2190 Ok(Ident::new(ident.name, span))
2192 _ => self.parse_ident(),
2196 /// Parses a qualified path.
2197 /// Assumes that the leading `<` has been parsed already.
2199 /// `qualified_path = <type [as trait_ref]>::path`
2204 /// `<T as U>::F::a<S>` (without disambiguator)
2205 /// `<T as U>::F::a::<S>` (with disambiguator)
2206 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2207 let lo = self.prev_span;
2208 let ty = self.parse_ty()?;
2210 // `path` will contain the prefix of the path up to the `>`,
2211 // if any (e.g., `U` in the `<T as U>::*` examples
2212 // above). `path_span` has the span of that path, or an empty
2213 // span in the case of something like `<T>::Bar`.
2214 let (mut path, path_span);
2215 if self.eat_keyword(keywords::As) {
2216 let path_lo = self.span;
2217 path = self.parse_path(PathStyle::Type)?;
2218 path_span = path_lo.to(self.prev_span);
2220 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2221 path_span = self.span.to(self.span);
2224 // See doc comment for `unmatched_angle_bracket_count`.
2225 self.expect(&token::Gt)?;
2226 if self.unmatched_angle_bracket_count > 0 {
2227 self.unmatched_angle_bracket_count -= 1;
2228 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2231 self.expect(&token::ModSep)?;
2233 let qself = QSelf { ty, path_span, position: path.segments.len() };
2234 self.parse_path_segments(&mut path.segments, style)?;
2236 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2239 /// Parses simple paths.
2241 /// `path = [::] segment+`
2242 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2245 /// `a::b::C<D>` (without disambiguator)
2246 /// `a::b::C::<D>` (with disambiguator)
2247 /// `Fn(Args)` (without disambiguator)
2248 /// `Fn::(Args)` (with disambiguator)
2249 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2250 maybe_whole!(self, NtPath, |path| {
2251 if style == PathStyle::Mod &&
2252 path.segments.iter().any(|segment| segment.args.is_some()) {
2253 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2258 let lo = self.meta_var_span.unwrap_or(self.span);
2259 let mut segments = Vec::new();
2260 let mod_sep_ctxt = self.span.ctxt();
2261 if self.eat(&token::ModSep) {
2262 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2264 self.parse_path_segments(&mut segments, style)?;
2266 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2269 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2270 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2272 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2273 let meta_ident = match self.token {
2274 token::Interpolated(ref nt) => match **nt {
2275 token::NtMeta(ref meta) => match meta.node {
2276 ast::MetaItemKind::Word => Some(meta.path.clone()),
2283 if let Some(path) = meta_ident {
2287 self.parse_path(style)
2290 crate fn parse_path_segments(&mut self,
2291 segments: &mut Vec<PathSegment>,
2293 -> PResult<'a, ()> {
2295 let segment = self.parse_path_segment(style)?;
2296 if style == PathStyle::Expr {
2297 // In order to check for trailing angle brackets, we must have finished
2298 // recursing (`parse_path_segment` can indirectly call this function),
2299 // that is, the next token must be the highlighted part of the below example:
2301 // `Foo::<Bar as Baz<T>>::Qux`
2304 // As opposed to the below highlight (if we had only finished the first
2307 // `Foo::<Bar as Baz<T>>::Qux`
2310 // `PathStyle::Expr` is only provided at the root invocation and never in
2311 // `parse_path_segment` to recurse and therefore can be checked to maintain
2313 self.check_trailing_angle_brackets(&segment, token::ModSep);
2315 segments.push(segment);
2317 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2323 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2324 let ident = self.parse_path_segment_ident()?;
2326 let is_args_start = |token: &token::Token| match *token {
2327 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
2328 | token::LArrow => true,
2331 let check_args_start = |this: &mut Self| {
2332 this.expected_tokens.extend_from_slice(
2333 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2335 is_args_start(&this.token)
2338 Ok(if style == PathStyle::Type && check_args_start(self) ||
2339 style != PathStyle::Mod && self.check(&token::ModSep)
2340 && self.look_ahead(1, |t| is_args_start(t)) {
2341 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2342 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2343 // parsing a new path.
2344 if style == PathStyle::Expr {
2345 self.unmatched_angle_bracket_count = 0;
2346 self.max_angle_bracket_count = 0;
2349 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2350 self.eat(&token::ModSep);
2352 let args = if self.eat_lt() {
2354 let (args, bindings) =
2355 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2357 let span = lo.to(self.prev_span);
2358 AngleBracketedArgs { args, bindings, span }.into()
2362 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2363 &[&token::CloseDelim(token::Paren)],
2364 SeqSep::trailing_allowed(token::Comma),
2365 TokenExpectType::Expect,
2370 let span = lo.to(self.prev_span);
2371 let output = if self.eat(&token::RArrow) {
2372 Some(self.parse_ty_common(false, false, false)?)
2376 ParenthesizedArgs { inputs, output, span }.into()
2379 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2381 // Generic arguments are not found.
2382 PathSegment::from_ident(ident)
2386 crate fn check_lifetime(&mut self) -> bool {
2387 self.expected_tokens.push(TokenType::Lifetime);
2388 self.token.is_lifetime()
2391 /// Parses a single lifetime `'a` or panics.
2392 crate fn expect_lifetime(&mut self) -> Lifetime {
2393 if let Some(ident) = self.token.lifetime() {
2394 let span = self.span;
2396 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2398 self.span_bug(self.span, "not a lifetime")
2402 fn eat_label(&mut self) -> Option<Label> {
2403 if let Some(ident) = self.token.lifetime() {
2404 let span = self.span;
2406 Some(Label { ident: Ident::new(ident.name, span) })
2412 /// Parses mutability (`mut` or nothing).
2413 fn parse_mutability(&mut self) -> Mutability {
2414 if self.eat_keyword(keywords::Mut) {
2417 Mutability::Immutable
2421 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2422 if let token::Literal(token::Integer(name), suffix) = self.token {
2423 self.expect_no_suffix(self.span, "a tuple index", suffix);
2425 Ok(Ident::new(name, self.prev_span))
2427 self.parse_ident_common(false)
2431 /// Parse ident (COLON expr)?
2432 fn parse_field(&mut self) -> PResult<'a, Field> {
2433 let attrs = self.parse_outer_attributes()?;
2436 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2437 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2438 t == &token::Colon || t == &token::Eq
2440 let fieldname = self.parse_field_name()?;
2442 // Check for an equals token. This means the source incorrectly attempts to
2443 // initialize a field with an eq rather than a colon.
2444 if self.token == token::Eq {
2446 .struct_span_err(self.span, "expected `:`, found `=`")
2448 fieldname.span.shrink_to_hi().to(self.span),
2449 "replace equals symbol with a colon",
2451 Applicability::MachineApplicable,
2456 (fieldname, self.parse_expr()?, false)
2458 let fieldname = self.parse_ident_common(false)?;
2460 // Mimic `x: x` for the `x` field shorthand.
2461 let path = ast::Path::from_ident(fieldname);
2462 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2463 (fieldname, expr, true)
2467 span: lo.to(expr.span),
2470 attrs: attrs.into(),
2474 fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2475 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2478 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2479 ExprKind::Unary(unop, expr)
2482 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2483 ExprKind::Binary(binop, lhs, rhs)
2486 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2487 ExprKind::Call(f, args)
2490 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2491 ExprKind::Index(expr, idx)
2495 start: Option<P<Expr>>,
2496 end: Option<P<Expr>>,
2497 limits: RangeLimits)
2498 -> PResult<'a, ast::ExprKind> {
2499 if end.is_none() && limits == RangeLimits::Closed {
2500 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2502 Ok(ExprKind::Range(start, end, limits))
2506 fn mk_assign_op(&self, binop: ast::BinOp,
2507 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2508 ExprKind::AssignOp(binop, lhs, rhs)
2511 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2512 let delim = match self.token {
2513 token::OpenDelim(delim) => delim,
2515 let msg = "expected open delimiter";
2516 let mut err = self.fatal(msg);
2517 err.span_label(self.span, msg);
2521 let tts = match self.parse_token_tree() {
2522 TokenTree::Delimited(_, _, tts) => tts,
2523 _ => unreachable!(),
2525 let delim = match delim {
2526 token::Paren => MacDelimiter::Parenthesis,
2527 token::Bracket => MacDelimiter::Bracket,
2528 token::Brace => MacDelimiter::Brace,
2529 token::NoDelim => self.bug("unexpected no delimiter"),
2531 Ok((delim, tts.into()))
2534 /// At the bottom (top?) of the precedence hierarchy,
2535 /// Parses things like parenthesized exprs, macros, `return`, etc.
2537 /// N.B., this does not parse outer attributes, and is private because it only works
2538 /// correctly if called from `parse_dot_or_call_expr()`.
2539 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2540 maybe_recover_from_interpolated_ty_qpath!(self, true);
2541 maybe_whole_expr!(self);
2543 // Outer attributes are already parsed and will be
2544 // added to the return value after the fact.
2546 // Therefore, prevent sub-parser from parsing
2547 // attributes by giving them a empty "already parsed" list.
2548 let mut attrs = ThinVec::new();
2551 let mut hi = self.span;
2555 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2557 token::OpenDelim(token::Paren) => {
2560 attrs.extend(self.parse_inner_attributes()?);
2562 // (e) is parenthesized e
2563 // (e,) is a tuple with only one field, e
2564 let mut es = vec![];
2565 let mut trailing_comma = false;
2566 let mut recovered = false;
2567 while self.token != token::CloseDelim(token::Paren) {
2568 es.push(match self.parse_expr() {
2571 // recover from parse error in tuple list
2572 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2575 recovered = self.expect_one_of(
2577 &[token::Comma, token::CloseDelim(token::Paren)],
2579 if self.eat(&token::Comma) {
2580 trailing_comma = true;
2582 trailing_comma = false;
2590 hi = self.prev_span;
2591 ex = if es.len() == 1 && !trailing_comma {
2592 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2597 token::OpenDelim(token::Brace) => {
2598 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2600 token::BinOp(token::Or) | token::OrOr => {
2601 return self.parse_lambda_expr(attrs);
2603 token::OpenDelim(token::Bracket) => {
2606 attrs.extend(self.parse_inner_attributes()?);
2608 if self.eat(&token::CloseDelim(token::Bracket)) {
2610 ex = ExprKind::Array(Vec::new());
2613 let first_expr = self.parse_expr()?;
2614 if self.eat(&token::Semi) {
2615 // Repeating array syntax: [ 0; 512 ]
2616 let count = AnonConst {
2617 id: ast::DUMMY_NODE_ID,
2618 value: self.parse_expr()?,
2620 self.expect(&token::CloseDelim(token::Bracket))?;
2621 ex = ExprKind::Repeat(first_expr, count);
2622 } else if self.eat(&token::Comma) {
2623 // Vector with two or more elements.
2624 let remaining_exprs = self.parse_seq_to_end(
2625 &token::CloseDelim(token::Bracket),
2626 SeqSep::trailing_allowed(token::Comma),
2627 |p| Ok(p.parse_expr()?)
2629 let mut exprs = vec![first_expr];
2630 exprs.extend(remaining_exprs);
2631 ex = ExprKind::Array(exprs);
2633 // Vector with one element.
2634 self.expect(&token::CloseDelim(token::Bracket))?;
2635 ex = ExprKind::Array(vec![first_expr]);
2638 hi = self.prev_span;
2642 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2644 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2646 if self.span.rust_2018() && self.check_keyword(keywords::Async) {
2647 return if self.is_async_block() { // check for `async {` and `async move {`
2648 self.parse_async_block(attrs)
2650 self.parse_lambda_expr(attrs)
2653 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2654 return self.parse_lambda_expr(attrs);
2656 if self.eat_keyword(keywords::If) {
2657 return self.parse_if_expr(attrs);
2659 if self.eat_keyword(keywords::For) {
2660 let lo = self.prev_span;
2661 return self.parse_for_expr(None, lo, attrs);
2663 if self.eat_keyword(keywords::While) {
2664 let lo = self.prev_span;
2665 return self.parse_while_expr(None, lo, attrs);
2667 if let Some(label) = self.eat_label() {
2668 let lo = label.ident.span;
2669 self.expect(&token::Colon)?;
2670 if self.eat_keyword(keywords::While) {
2671 return self.parse_while_expr(Some(label), lo, attrs)
2673 if self.eat_keyword(keywords::For) {
2674 return self.parse_for_expr(Some(label), lo, attrs)
2676 if self.eat_keyword(keywords::Loop) {
2677 return self.parse_loop_expr(Some(label), lo, attrs)
2679 if self.token == token::OpenDelim(token::Brace) {
2680 return self.parse_block_expr(Some(label),
2682 BlockCheckMode::Default,
2685 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2686 let mut err = self.fatal(msg);
2687 err.span_label(self.span, msg);
2690 if self.eat_keyword(keywords::Loop) {
2691 let lo = self.prev_span;
2692 return self.parse_loop_expr(None, lo, attrs);
2694 if self.eat_keyword(keywords::Continue) {
2695 let label = self.eat_label();
2696 let ex = ExprKind::Continue(label);
2697 let hi = self.prev_span;
2698 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2700 if self.eat_keyword(keywords::Match) {
2701 let match_sp = self.prev_span;
2702 return self.parse_match_expr(attrs).map_err(|mut err| {
2703 err.span_label(match_sp, "while parsing this match expression");
2707 if self.eat_keyword(keywords::Unsafe) {
2708 return self.parse_block_expr(
2711 BlockCheckMode::Unsafe(ast::UserProvided),
2714 if self.is_do_catch_block() {
2715 let mut db = self.fatal("found removed `do catch` syntax");
2716 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2719 if self.is_try_block() {
2721 assert!(self.eat_keyword(keywords::Try));
2722 return self.parse_try_block(lo, attrs);
2724 if self.eat_keyword(keywords::Return) {
2725 if self.token.can_begin_expr() {
2726 let e = self.parse_expr()?;
2728 ex = ExprKind::Ret(Some(e));
2730 ex = ExprKind::Ret(None);
2732 } else if self.eat_keyword(keywords::Break) {
2733 let label = self.eat_label();
2734 let e = if self.token.can_begin_expr()
2735 && !(self.token == token::OpenDelim(token::Brace)
2736 && self.restrictions.contains(
2737 Restrictions::NO_STRUCT_LITERAL)) {
2738 Some(self.parse_expr()?)
2742 ex = ExprKind::Break(label, e);
2743 hi = self.prev_span;
2744 } else if self.eat_keyword(keywords::Yield) {
2745 if self.token.can_begin_expr() {
2746 let e = self.parse_expr()?;
2748 ex = ExprKind::Yield(Some(e));
2750 ex = ExprKind::Yield(None);
2752 } else if self.token.is_keyword(keywords::Let) {
2753 // Catch this syntax error here, instead of in `parse_ident`, so
2754 // that we can explicitly mention that let is not to be used as an expression
2755 let mut db = self.fatal("expected expression, found statement (`let`)");
2756 db.span_label(self.span, "expected expression");
2757 db.note("variable declaration using `let` is a statement");
2759 } else if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
2760 // FIXME: remove this branch when `await!` is no longer supported
2761 // https://github.com/rust-lang/rust/issues/60610
2762 self.expect(&token::Not)?;
2763 self.expect(&token::OpenDelim(token::Paren))?;
2764 let expr = self.parse_expr()?;
2765 self.expect(&token::CloseDelim(token::Paren))?;
2766 ex = ExprKind::Await(ast::AwaitOrigin::MacroLike, expr);
2767 } else if self.token.is_path_start() {
2768 let path = self.parse_path(PathStyle::Expr)?;
2770 // `!`, as an operator, is prefix, so we know this isn't that
2771 if self.eat(&token::Not) {
2772 // MACRO INVOCATION expression
2773 let (delim, tts) = self.expect_delimited_token_tree()?;
2774 hi = self.prev_span;
2775 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2776 } else if self.check(&token::OpenDelim(token::Brace)) {
2777 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2781 ex = ExprKind::Path(None, path);
2785 ex = ExprKind::Path(None, path);
2788 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2789 // Don't complain about bare semicolons after unclosed braces
2790 // recovery in order to keep the error count down. Fixing the
2791 // delimiters will possibly also fix the bare semicolon found in
2792 // expression context. For example, silence the following error:
2794 // error: expected expression, found `;`
2798 // | ^ expected expression
2801 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2803 match self.parse_literal_maybe_minus() {
2806 ex = expr.node.clone();
2809 self.cancel(&mut err);
2810 let msg = format!("expected expression, found {}",
2811 self.this_token_descr());
2812 let mut err = self.fatal(&msg);
2813 let sp = self.sess.source_map().start_point(self.span);
2814 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow()
2817 self.sess.expr_parentheses_needed(&mut err, *sp, None);
2819 err.span_label(self.span, "expected expression");
2827 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2828 self.maybe_recover_from_bad_qpath(expr, true)
2831 fn maybe_parse_struct_expr(
2835 attrs: &ThinVec<Attribute>,
2836 ) -> Option<PResult<'a, P<Expr>>> {
2837 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2838 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2839 // `{ ident, ` cannot start a block
2840 self.look_ahead(2, |t| t == &token::Comma) ||
2841 self.look_ahead(2, |t| t == &token::Colon) && (
2842 // `{ ident: token, ` cannot start a block
2843 self.look_ahead(4, |t| t == &token::Comma) ||
2844 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2845 self.look_ahead(3, |t| !t.can_begin_type())
2849 if struct_allowed || certainly_not_a_block() {
2850 // This is a struct literal, but we don't can't accept them here
2851 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2852 if let (Ok(expr), false) = (&expr, struct_allowed) {
2853 let mut err = self.diagnostic().struct_span_err(
2855 "struct literals are not allowed here",
2857 err.multipart_suggestion(
2858 "surround the struct literal with parentheses",
2860 (lo.shrink_to_lo(), "(".to_string()),
2861 (expr.span.shrink_to_hi(), ")".to_string()),
2863 Applicability::MachineApplicable,
2872 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2873 -> PResult<'a, P<Expr>> {
2874 let struct_sp = lo.to(self.prev_span);
2876 let mut fields = Vec::new();
2877 let mut base = None;
2879 attrs.extend(self.parse_inner_attributes()?);
2881 while self.token != token::CloseDelim(token::Brace) {
2882 if self.eat(&token::DotDot) {
2883 let exp_span = self.prev_span;
2884 match self.parse_expr() {
2890 self.recover_stmt();
2893 if self.token == token::Comma {
2894 let mut err = self.sess.span_diagnostic.mut_span_err(
2895 exp_span.to(self.prev_span),
2896 "cannot use a comma after the base struct",
2898 err.span_suggestion_short(
2900 "remove this comma",
2902 Applicability::MachineApplicable
2904 err.note("the base struct must always be the last field");
2906 self.recover_stmt();
2911 let mut recovery_field = None;
2912 if let token::Ident(ident, _) = self.token {
2913 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2914 // Use in case of error after field-looking code: `S { foo: () with a }`
2915 let mut ident = ident.clone();
2916 ident.span = self.span;
2917 recovery_field = Some(ast::Field {
2920 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2921 is_shorthand: false,
2922 attrs: ThinVec::new(),
2926 let mut parsed_field = None;
2927 match self.parse_field() {
2928 Ok(f) => parsed_field = Some(f),
2930 e.span_label(struct_sp, "while parsing this struct");
2933 // If the next token is a comma, then try to parse
2934 // what comes next as additional fields, rather than
2935 // bailing out until next `}`.
2936 if self.token != token::Comma {
2937 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2938 if self.token != token::Comma {
2945 match self.expect_one_of(&[token::Comma],
2946 &[token::CloseDelim(token::Brace)]) {
2947 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2948 // only include the field if there's no parse error for the field name
2952 if let Some(f) = recovery_field {
2955 e.span_label(struct_sp, "while parsing this struct");
2957 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2958 self.eat(&token::Comma);
2963 let span = lo.to(self.span);
2964 self.expect(&token::CloseDelim(token::Brace))?;
2965 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2968 fn parse_or_use_outer_attributes(&mut self,
2969 already_parsed_attrs: Option<ThinVec<Attribute>>)
2970 -> PResult<'a, ThinVec<Attribute>> {
2971 if let Some(attrs) = already_parsed_attrs {
2974 self.parse_outer_attributes().map(|a| a.into())
2978 /// Parses a block or unsafe block.
2979 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2980 lo: Span, blk_mode: BlockCheckMode,
2981 outer_attrs: ThinVec<Attribute>)
2982 -> PResult<'a, P<Expr>> {
2983 self.expect(&token::OpenDelim(token::Brace))?;
2985 let mut attrs = outer_attrs;
2986 attrs.extend(self.parse_inner_attributes()?);
2988 let blk = self.parse_block_tail(lo, blk_mode)?;
2989 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2992 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2993 fn parse_dot_or_call_expr(&mut self,
2994 already_parsed_attrs: Option<ThinVec<Attribute>>)
2995 -> PResult<'a, P<Expr>> {
2996 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2998 let b = self.parse_bottom_expr();
2999 let (span, b) = self.interpolated_or_expr_span(b)?;
3000 self.parse_dot_or_call_expr_with(b, span, attrs)
3003 fn parse_dot_or_call_expr_with(&mut self,
3006 mut attrs: ThinVec<Attribute>)
3007 -> PResult<'a, P<Expr>> {
3008 // Stitch the list of outer attributes onto the return value.
3009 // A little bit ugly, but the best way given the current code
3011 self.parse_dot_or_call_expr_with_(e0, lo)
3013 expr.map(|mut expr| {
3014 attrs.extend::<Vec<_>>(expr.attrs.into());
3017 ExprKind::If(..) | ExprKind::IfLet(..) => {
3018 if !expr.attrs.is_empty() {
3019 // Just point to the first attribute in there...
3020 let span = expr.attrs[0].span;
3023 "attributes are not yet allowed on `if` \
3034 // Assuming we have just parsed `.`, continue parsing into an expression.
3035 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3036 if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
3037 let span = lo.to(self.prev_span);
3038 let await_expr = self.mk_expr(
3040 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
3043 return Ok(await_expr);
3045 let segment = self.parse_path_segment(PathStyle::Expr)?;
3046 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3048 Ok(match self.token {
3049 token::OpenDelim(token::Paren) => {
3050 // Method call `expr.f()`
3051 let mut args = self.parse_unspanned_seq(
3052 &token::OpenDelim(token::Paren),
3053 &token::CloseDelim(token::Paren),
3054 SeqSep::trailing_allowed(token::Comma),
3055 |p| Ok(p.parse_expr()?)
3057 args.insert(0, self_arg);
3059 let span = lo.to(self.prev_span);
3060 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3063 // Field access `expr.f`
3064 if let Some(args) = segment.args {
3065 self.span_err(args.span(),
3066 "field expressions may not have generic arguments");
3069 let span = lo.to(self.prev_span);
3070 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3075 /// This function checks if there are trailing angle brackets and produces
3076 /// a diagnostic to suggest removing them.
3078 /// ```ignore (diagnostic)
3079 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3080 /// ^^ help: remove extra angle brackets
3082 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3083 // This function is intended to be invoked after parsing a path segment where there are two
3086 // 1. A specific token is expected after the path segment.
3087 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3088 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3089 // 2. No specific token is expected after the path segment.
3090 // eg. `x.foo` (field access)
3092 // This function is called after parsing `.foo` and before parsing the token `end` (if
3093 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3096 // We only care about trailing angle brackets if we previously parsed angle bracket
3097 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3098 // removed in this case:
3100 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3102 // This case is particularly tricky as we won't notice it just looking at the tokens -
3103 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3104 // have already been parsed):
3106 // `x.foo::<u32>>>(3)`
3107 let parsed_angle_bracket_args = segment.args
3109 .map(|args| args.is_angle_bracketed())
3113 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3114 parsed_angle_bracket_args,
3116 if !parsed_angle_bracket_args {
3120 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3124 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3125 // (since we might have the field access case and the characters we're eating are
3126 // actual operators and not trailing characters - ie `x.foo >> 3`).
3127 let mut position = 0;
3129 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3130 // many of each (so we can correctly pluralize our error messages) and continue to
3132 let mut number_of_shr = 0;
3133 let mut number_of_gt = 0;
3134 while self.look_ahead(position, |t| {
3135 trace!("check_trailing_angle_brackets: t={:?}", t);
3136 if *t == token::BinOp(token::BinOpToken::Shr) {
3139 } else if *t == token::Gt {
3149 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3151 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3152 number_of_gt, number_of_shr,
3154 if number_of_gt < 1 && number_of_shr < 1 {
3158 // Finally, double check that we have our end token as otherwise this is the
3160 if self.look_ahead(position, |t| {
3161 trace!("check_trailing_angle_brackets: t={:?}", t);
3164 // Eat from where we started until the end token so that parsing can continue
3165 // as if we didn't have those extra angle brackets.
3166 self.eat_to_tokens(&[&end]);
3167 let span = lo.until(self.span);
3169 let plural = number_of_gt > 1 || number_of_shr >= 1;
3173 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3177 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3179 Applicability::MachineApplicable,
3185 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3190 while self.eat(&token::Question) {
3191 let hi = self.prev_span;
3192 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3196 if self.eat(&token::Dot) {
3198 token::Ident(..) => {
3199 e = self.parse_dot_suffix(e, lo)?;
3201 token::Literal(token::Integer(name), suffix) => {
3202 let span = self.span;
3204 let field = ExprKind::Field(e, Ident::new(name, span));
3205 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3207 self.expect_no_suffix(span, "a tuple index", suffix);
3209 token::Literal(token::Float(n), _suf) => {
3211 let fstr = n.as_str();
3212 let mut err = self.diagnostic()
3213 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3214 err.span_label(self.prev_span, "unexpected token");
3215 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3216 let float = match fstr.parse::<f64>().ok() {
3220 let sugg = pprust::to_string(|s| {
3221 use crate::print::pprust::PrintState;
3225 s.print_usize(float.trunc() as usize)?;
3228 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3230 err.span_suggestion(
3231 lo.to(self.prev_span),
3232 "try parenthesizing the first index",
3234 Applicability::MachineApplicable
3241 // FIXME Could factor this out into non_fatal_unexpected or something.
3242 let actual = self.this_token_to_string();
3243 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3248 if self.expr_is_complete(&e) { break; }
3251 token::OpenDelim(token::Paren) => {
3252 let seq = self.parse_unspanned_seq(
3253 &token::OpenDelim(token::Paren),
3254 &token::CloseDelim(token::Paren),
3255 SeqSep::trailing_allowed(token::Comma),
3256 |p| Ok(p.parse_expr()?)
3258 let nd = self.mk_call(e, es);
3259 let hi = self.prev_span;
3260 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3262 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3266 // Could be either an index expression or a slicing expression.
3267 token::OpenDelim(token::Bracket) => {
3269 let ix = self.parse_expr()?;
3271 self.expect(&token::CloseDelim(token::Bracket))?;
3272 let index = self.mk_index(e, ix);
3273 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3281 fn recover_seq_parse_error(
3283 delim: token::DelimToken,
3285 result: PResult<'a, P<Expr>>,
3291 // recover from parse error
3292 self.consume_block(delim);
3293 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
3298 crate fn process_potential_macro_variable(&mut self) {
3299 let (token, span) = match self.token {
3300 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3301 self.look_ahead(1, |t| t.is_ident()) => {
3303 let name = match self.token {
3304 token::Ident(ident, _) => ident,
3307 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3308 err.span_label(self.span, "unknown macro variable");
3313 token::Interpolated(ref nt) => {
3314 self.meta_var_span = Some(self.span);
3315 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3316 // and lifetime tokens, so the former are never encountered during normal parsing.
3318 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3319 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3329 /// Parses a single token tree from the input.
3330 crate fn parse_token_tree(&mut self) -> TokenTree {
3332 token::OpenDelim(..) => {
3333 let frame = mem::replace(&mut self.token_cursor.frame,
3334 self.token_cursor.stack.pop().unwrap());
3335 self.span = frame.span.entire();
3337 TokenTree::Delimited(
3340 frame.tree_cursor.stream.into(),
3343 token::CloseDelim(_) | token::Eof => unreachable!(),
3345 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3347 TokenTree::Token(span, token)
3352 // parse a stream of tokens into a list of TokenTree's,
3354 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3355 let mut tts = Vec::new();
3356 while self.token != token::Eof {
3357 tts.push(self.parse_token_tree());
3362 pub fn parse_tokens(&mut self) -> TokenStream {
3363 let mut result = Vec::new();
3366 token::Eof | token::CloseDelim(..) => break,
3367 _ => result.push(self.parse_token_tree().into()),
3370 TokenStream::new(result)
3373 /// Parse a prefix-unary-operator expr
3374 fn parse_prefix_expr(&mut self,
3375 already_parsed_attrs: Option<ThinVec<Attribute>>)
3376 -> PResult<'a, P<Expr>> {
3377 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3379 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3380 let (hi, ex) = match self.token {
3383 let e = self.parse_prefix_expr(None);
3384 let (span, e) = self.interpolated_or_expr_span(e)?;
3385 (lo.to(span), self.mk_unary(UnOp::Not, e))
3387 // Suggest `!` for bitwise negation when encountering a `~`
3390 let e = self.parse_prefix_expr(None);
3391 let (span, e) = self.interpolated_or_expr_span(e)?;
3392 let span_of_tilde = lo;
3393 let mut err = self.diagnostic()
3394 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3395 err.span_suggestion_short(
3397 "use `!` to perform bitwise negation",
3399 Applicability::MachineApplicable
3402 (lo.to(span), self.mk_unary(UnOp::Not, e))
3404 token::BinOp(token::Minus) => {
3406 let e = self.parse_prefix_expr(None);
3407 let (span, e) = self.interpolated_or_expr_span(e)?;
3408 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3410 token::BinOp(token::Star) => {
3412 let e = self.parse_prefix_expr(None);
3413 let (span, e) = self.interpolated_or_expr_span(e)?;
3414 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3416 token::BinOp(token::And) | token::AndAnd => {
3418 let m = self.parse_mutability();
3419 let e = self.parse_prefix_expr(None);
3420 let (span, e) = self.interpolated_or_expr_span(e)?;
3421 (lo.to(span), ExprKind::AddrOf(m, e))
3423 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3425 let place = self.parse_expr_res(
3426 Restrictions::NO_STRUCT_LITERAL,
3429 let blk = self.parse_block()?;
3430 let span = blk.span;
3431 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3432 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3434 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3436 let e = self.parse_prefix_expr(None);
3437 let (span, e) = self.interpolated_or_expr_span(e)?;
3438 (lo.to(span), ExprKind::Box(e))
3440 token::Ident(..) if self.token.is_ident_named("not") => {
3441 // `not` is just an ordinary identifier in Rust-the-language,
3442 // but as `rustc`-the-compiler, we can issue clever diagnostics
3443 // for confused users who really want to say `!`
3444 let token_cannot_continue_expr = |t: &token::Token| match *t {
3445 // These tokens can start an expression after `!`, but
3446 // can't continue an expression after an ident
3447 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3448 token::Literal(..) | token::Pound => true,
3449 token::Interpolated(ref nt) => match **nt {
3450 token::NtIdent(..) | token::NtExpr(..) |
3451 token::NtBlock(..) | token::NtPath(..) => true,
3456 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3457 if cannot_continue_expr {
3459 // Emit the error ...
3460 let mut err = self.diagnostic()
3461 .struct_span_err(self.span,
3462 &format!("unexpected {} after identifier",
3463 self.this_token_descr()));
3464 // span the `not` plus trailing whitespace to avoid
3465 // trailing whitespace after the `!` in our suggestion
3466 let to_replace = self.sess.source_map()
3467 .span_until_non_whitespace(lo.to(self.span));
3468 err.span_suggestion_short(
3470 "use `!` to perform logical negation",
3472 Applicability::MachineApplicable
3475 // —and recover! (just as if we were in the block
3476 // for the `token::Not` arm)
3477 let e = self.parse_prefix_expr(None);
3478 let (span, e) = self.interpolated_or_expr_span(e)?;
3479 (lo.to(span), self.mk_unary(UnOp::Not, e))
3481 return self.parse_dot_or_call_expr(Some(attrs));
3484 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3486 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3489 /// Parses an associative expression.
3491 /// This parses an expression accounting for associativity and precedence of the operators in
3494 fn parse_assoc_expr(&mut self,
3495 already_parsed_attrs: Option<ThinVec<Attribute>>)
3496 -> PResult<'a, P<Expr>> {
3497 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3500 /// Parses an associative expression with operators of at least `min_prec` precedence.
3501 fn parse_assoc_expr_with(&mut self,
3504 -> PResult<'a, P<Expr>> {
3505 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3508 let attrs = match lhs {
3509 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3512 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3513 return self.parse_prefix_range_expr(attrs);
3515 self.parse_prefix_expr(attrs)?
3519 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
3521 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3524 (false, _) => {} // continue parsing the expression
3525 // An exhaustive check is done in the following block, but these are checked first
3526 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
3527 // want to keep their span info to improve diagnostics in these cases in a later stage.
3528 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
3529 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
3530 (true, Some(AssocOp::Add)) => { // `{ 42 } + 42
3531 // These cases are ambiguous and can't be identified in the parser alone
3532 let sp = self.sess.source_map().start_point(self.span);
3533 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
3536 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
3539 (true, Some(_)) => {
3540 // We've found an expression that would be parsed as a statement, but the next
3541 // token implies this should be parsed as an expression.
3542 // For example: `if let Some(x) = x { x } else { 0 } / 2`
3543 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
3544 "expected expression, found `{}`",
3545 pprust::token_to_string(&self.token),
3547 err.span_label(self.span, "expected expression");
3548 self.sess.expr_parentheses_needed(
3551 Some(pprust::expr_to_string(&lhs),
3556 self.expected_tokens.push(TokenType::Operator);
3557 while let Some(op) = AssocOp::from_token(&self.token) {
3559 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3560 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3561 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3562 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3563 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3564 (PrevTokenKind::Interpolated, _) => self.prev_span,
3565 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3566 if path.segments.len() == 1 => self.prev_span,
3570 let cur_op_span = self.span;
3571 let restrictions = if op.is_assign_like() {
3572 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3576 let prec = op.precedence();
3577 if prec < min_prec {
3580 // Check for deprecated `...` syntax
3581 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3582 self.err_dotdotdot_syntax(self.span);
3586 if op.is_comparison() {
3587 self.check_no_chained_comparison(&lhs, &op);
3590 if op == AssocOp::As {
3591 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3593 } else if op == AssocOp::Colon {
3594 let maybe_path = self.could_ascription_be_path(&lhs.node);
3595 let next_sp = self.span;
3597 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3600 self.bad_type_ascription(
3611 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3612 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3613 // generalise it to the Fixity::None code.
3615 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3616 // two variants are handled with `parse_prefix_range_expr` call above.
3617 let rhs = if self.is_at_start_of_range_notation_rhs() {
3618 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
3622 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3627 let limits = if op == AssocOp::DotDot {
3628 RangeLimits::HalfOpen
3633 let r = self.mk_range(Some(lhs), rhs, limits)?;
3634 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3638 let fixity = op.fixity();
3639 let prec_adjustment = match fixity {
3642 // We currently have no non-associative operators that are not handled above by
3643 // the special cases. The code is here only for future convenience.
3646 let rhs = self.with_res(
3647 restrictions - Restrictions::STMT_EXPR,
3648 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
3651 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3652 // including the attributes.
3656 .filter(|a| a.style == AttrStyle::Outer)
3658 .map_or(lhs_span, |a| a.span);
3659 let span = lhs_span.to(rhs.span);
3661 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3662 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3663 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3664 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3665 AssocOp::Greater | AssocOp::GreaterEqual => {
3666 let ast_op = op.to_ast_binop().unwrap();
3667 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3668 self.mk_expr(span, binary, ThinVec::new())
3671 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3672 AssocOp::ObsoleteInPlace =>
3673 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3674 AssocOp::AssignOp(k) => {
3676 token::Plus => BinOpKind::Add,
3677 token::Minus => BinOpKind::Sub,
3678 token::Star => BinOpKind::Mul,
3679 token::Slash => BinOpKind::Div,
3680 token::Percent => BinOpKind::Rem,
3681 token::Caret => BinOpKind::BitXor,
3682 token::And => BinOpKind::BitAnd,
3683 token::Or => BinOpKind::BitOr,
3684 token::Shl => BinOpKind::Shl,
3685 token::Shr => BinOpKind::Shr,
3687 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3688 self.mk_expr(span, aopexpr, ThinVec::new())
3690 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3691 self.bug("AssocOp should have been handled by special case")
3695 if let Fixity::None = fixity { break }
3700 fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
3701 self.token.is_ident() &&
3702 if let ast::ExprKind::Path(..) = node { true } else { false } &&
3703 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
3704 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
3705 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
3706 self.look_ahead(2, |t| t.is_ident()) ||
3707 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
3708 self.look_ahead(2, |t| t.is_ident()) ||
3709 self.look_ahead(1, |t| t == &token::ModSep) && // `foo:bar::baz`
3710 self.look_ahead(2, |t| t.is_ident())
3713 fn bad_type_ascription(
3715 err: &mut DiagnosticBuilder<'a>,
3721 err.span_label(self.span, "expecting a type here because of type ascription");
3722 let cm = self.sess.source_map();
3723 let next_pos = cm.lookup_char_pos(next_sp.lo());
3724 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3725 if op_pos.line != next_pos.line {
3726 err.span_suggestion(
3728 "try using a semicolon",
3730 Applicability::MaybeIncorrect,
3734 err.span_suggestion(
3736 "maybe you meant to write a path separator here",
3738 Applicability::MaybeIncorrect,
3741 err.note("type ascription is a nightly-only feature that lets \
3742 you annotate an expression with a type: `<expr>: <type>`");
3745 "this expression expects an ascribed type after the colon",
3747 err.help("this might be indicative of a syntax error elsewhere");
3752 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3753 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3754 -> PResult<'a, P<Expr>> {
3755 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3756 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3759 // Save the state of the parser before parsing type normally, in case there is a
3760 // LessThan comparison after this cast.
3761 let parser_snapshot_before_type = self.clone();
3762 match self.parse_ty_no_plus() {
3764 Ok(mk_expr(self, rhs))
3766 Err(mut type_err) => {
3767 // Rewind to before attempting to parse the type with generics, to recover
3768 // from situations like `x as usize < y` in which we first tried to parse
3769 // `usize < y` as a type with generic arguments.
3770 let parser_snapshot_after_type = self.clone();
3771 mem::replace(self, parser_snapshot_before_type);
3773 match self.parse_path(PathStyle::Expr) {
3775 let (op_noun, op_verb) = match self.token {
3776 token::Lt => ("comparison", "comparing"),
3777 token::BinOp(token::Shl) => ("shift", "shifting"),
3779 // We can end up here even without `<` being the next token, for
3780 // example because `parse_ty_no_plus` returns `Err` on keywords,
3781 // but `parse_path` returns `Ok` on them due to error recovery.
3782 // Return original error and parser state.
3783 mem::replace(self, parser_snapshot_after_type);
3784 return Err(type_err);
3788 // Successfully parsed the type path leaving a `<` yet to parse.
3791 // Report non-fatal diagnostics, keep `x as usize` as an expression
3792 // in AST and continue parsing.
3793 let msg = format!("`<` is interpreted as a start of generic \
3794 arguments for `{}`, not a {}", path, op_noun);
3795 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3796 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3797 "interpreted as generic arguments");
3798 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3800 let expr = mk_expr(self, P(Ty {
3802 node: TyKind::Path(None, path),
3803 id: ast::DUMMY_NODE_ID
3806 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3807 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3808 err.span_suggestion(
3810 &format!("try {} the cast value", op_verb),
3811 format!("({})", expr_str),
3812 Applicability::MachineApplicable
3818 Err(mut path_err) => {
3819 // Couldn't parse as a path, return original error and parser state.
3821 mem::replace(self, parser_snapshot_after_type);
3829 /// Produce an error if comparison operators are chained (RFC #558).
3830 /// We only need to check lhs, not rhs, because all comparison ops
3831 /// have same precedence and are left-associative
3832 fn check_no_chained_comparison(&self, lhs: &Expr, outer_op: &AssocOp) {
3833 debug_assert!(outer_op.is_comparison(),
3834 "check_no_chained_comparison: {:?} is not comparison",
3837 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3838 // respan to include both operators
3839 let op_span = op.span.to(self.span);
3840 let mut err = self.diagnostic().struct_span_err(op_span,
3841 "chained comparison operators require parentheses");
3842 if op.node == BinOpKind::Lt &&
3843 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3844 *outer_op == AssocOp::Greater // even in a case like the following:
3845 { // Foo<Bar<Baz<Qux, ()>>>
3847 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3848 err.help("or use `(...)` if you meant to specify fn arguments");
3856 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3857 fn parse_prefix_range_expr(&mut self,
3858 already_parsed_attrs: Option<ThinVec<Attribute>>)
3859 -> PResult<'a, P<Expr>> {
3860 // Check for deprecated `...` syntax
3861 if self.token == token::DotDotDot {
3862 self.err_dotdotdot_syntax(self.span);
3865 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3866 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3868 let tok = self.token.clone();
3869 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3871 let mut hi = self.span;
3873 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3874 // RHS must be parsed with more associativity than the dots.
3875 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3876 Some(self.parse_assoc_expr_with(next_prec,
3877 LhsExpr::NotYetParsed)
3885 let limits = if tok == token::DotDot {
3886 RangeLimits::HalfOpen
3891 let r = self.mk_range(None, opt_end, limits)?;
3892 Ok(self.mk_expr(lo.to(hi), r, attrs))
3895 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3896 if self.token.can_begin_expr() {
3897 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3898 if self.token == token::OpenDelim(token::Brace) {
3899 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3907 /// Parses an `if` or `if let` expression (`if` token already eaten).
3908 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3909 if self.check_keyword(keywords::Let) {
3910 return self.parse_if_let_expr(attrs);
3912 let lo = self.prev_span;
3913 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3915 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3916 // verify that the last statement is either an implicit return (no `;`) or an explicit
3917 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3918 // the dead code lint.
3919 if self.eat_keyword(keywords::Else) || !cond.returns() {
3920 let sp = self.sess.source_map().next_point(lo);
3921 let mut err = self.diagnostic()
3922 .struct_span_err(sp, "missing condition for `if` statemement");
3923 err.span_label(sp, "expected if condition here");
3926 let not_block = self.token != token::OpenDelim(token::Brace);
3927 let thn = self.parse_block().map_err(|mut err| {
3929 err.span_label(lo, "this `if` statement has a condition, but no block");
3933 let mut els: Option<P<Expr>> = None;
3934 let mut hi = thn.span;
3935 if self.eat_keyword(keywords::Else) {
3936 let elexpr = self.parse_else_expr()?;
3940 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3943 /// Parses an `if let` expression (`if` token already eaten).
3944 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3945 -> PResult<'a, P<Expr>> {
3946 let lo = self.prev_span;
3947 self.expect_keyword(keywords::Let)?;
3948 let pats = self.parse_pats()?;
3949 self.expect(&token::Eq)?;
3950 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3951 let thn = self.parse_block()?;
3952 let (hi, els) = if self.eat_keyword(keywords::Else) {
3953 let expr = self.parse_else_expr()?;
3954 (expr.span, Some(expr))
3958 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3961 /// Parses `move |args| expr`.
3962 fn parse_lambda_expr(&mut self,
3963 attrs: ThinVec<Attribute>)
3964 -> PResult<'a, P<Expr>>
3967 let movability = if self.eat_keyword(keywords::Static) {
3972 let asyncness = if self.span.rust_2018() {
3973 self.parse_asyncness()
3977 let capture_clause = if self.eat_keyword(keywords::Move) {
3982 let decl = self.parse_fn_block_decl()?;
3983 let decl_hi = self.prev_span;
3984 let body = match decl.output {
3985 FunctionRetTy::Default(_) => {
3986 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3987 self.parse_expr_res(restrictions, None)?
3990 // If an explicit return type is given, require a
3991 // block to appear (RFC 968).
3992 let body_lo = self.span;
3993 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3999 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
4003 // `else` token already eaten
4004 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
4005 if self.eat_keyword(keywords::If) {
4006 return self.parse_if_expr(ThinVec::new());
4008 let blk = self.parse_block()?;
4009 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
4013 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
4014 fn parse_for_expr(&mut self, opt_label: Option<Label>,
4016 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4017 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
4019 let pat = self.parse_top_level_pat()?;
4020 if !self.eat_keyword(keywords::In) {
4021 let in_span = self.prev_span.between(self.span);
4022 let mut err = self.sess.span_diagnostic
4023 .struct_span_err(in_span, "missing `in` in `for` loop");
4024 err.span_suggestion_short(
4025 in_span, "try adding `in` here", " in ".into(),
4026 // has been misleading, at least in the past (closed Issue #48492)
4027 Applicability::MaybeIncorrect
4031 let in_span = self.prev_span;
4032 if self.eat_keyword(keywords::In) {
4033 // a common typo: `for _ in in bar {}`
4034 let mut err = self.sess.span_diagnostic.struct_span_err(
4036 "expected iterable, found keyword `in`",
4038 err.span_suggestion_short(
4039 in_span.until(self.prev_span),
4040 "remove the duplicated `in`",
4042 Applicability::MachineApplicable,
4044 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
4045 err.note("for more information on the status of emplacement syntax, see <\
4046 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
4049 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4050 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
4051 attrs.extend(iattrs);
4053 let hi = self.prev_span;
4054 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
4057 /// Parses a `while` or `while let` expression (`while` token already eaten).
4058 fn parse_while_expr(&mut self, opt_label: Option<Label>,
4060 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4061 if self.token.is_keyword(keywords::Let) {
4062 return self.parse_while_let_expr(opt_label, span_lo, attrs);
4064 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4065 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4066 attrs.extend(iattrs);
4067 let span = span_lo.to(body.span);
4068 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
4071 /// Parses a `while let` expression (`while` token already eaten).
4072 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
4074 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4075 self.expect_keyword(keywords::Let)?;
4076 let pats = self.parse_pats()?;
4077 self.expect(&token::Eq)?;
4078 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4079 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4080 attrs.extend(iattrs);
4081 let span = span_lo.to(body.span);
4082 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
4085 // parse `loop {...}`, `loop` token already eaten
4086 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
4088 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4089 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4090 attrs.extend(iattrs);
4091 let span = span_lo.to(body.span);
4092 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
4095 /// Parses an `async move {...}` expression.
4096 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4097 -> PResult<'a, P<Expr>>
4099 let span_lo = self.span;
4100 self.expect_keyword(keywords::Async)?;
4101 let capture_clause = if self.eat_keyword(keywords::Move) {
4106 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4107 attrs.extend(iattrs);
4109 span_lo.to(body.span),
4110 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4113 /// Parses a `try {...}` expression (`try` token already eaten).
4114 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4115 -> PResult<'a, P<Expr>>
4117 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4118 attrs.extend(iattrs);
4119 if self.eat_keyword(keywords::Catch) {
4120 let mut error = self.struct_span_err(self.prev_span,
4121 "keyword `catch` cannot follow a `try` block");
4122 error.help("try using `match` on the result of the `try` block instead");
4126 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4130 // `match` token already eaten
4131 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4132 let match_span = self.prev_span;
4133 let lo = self.prev_span;
4134 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4136 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4137 if self.token == token::Token::Semi {
4138 e.span_suggestion_short(
4140 "try removing this `match`",
4142 Applicability::MaybeIncorrect // speculative
4147 attrs.extend(self.parse_inner_attributes()?);
4149 let mut arms: Vec<Arm> = Vec::new();
4150 while self.token != token::CloseDelim(token::Brace) {
4151 match self.parse_arm() {
4152 Ok(arm) => arms.push(arm),
4154 // Recover by skipping to the end of the block.
4156 self.recover_stmt();
4157 let span = lo.to(self.span);
4158 if self.token == token::CloseDelim(token::Brace) {
4161 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4167 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4170 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4171 maybe_whole!(self, NtArm, |x| x);
4173 let attrs = self.parse_outer_attributes()?;
4174 let pats = self.parse_pats()?;
4175 let guard = if self.eat_keyword(keywords::If) {
4176 Some(Guard::If(self.parse_expr()?))
4180 let arrow_span = self.span;
4181 self.expect(&token::FatArrow)?;
4182 let arm_start_span = self.span;
4184 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4185 .map_err(|mut err| {
4186 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4190 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4191 && self.token != token::CloseDelim(token::Brace);
4194 let cm = self.sess.source_map();
4195 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4196 .map_err(|mut err| {
4197 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4198 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4199 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4200 && expr_lines.lines.len() == 2
4201 && self.token == token::FatArrow => {
4202 // We check whether there's any trailing code in the parse span,
4203 // if there isn't, we very likely have the following:
4206 // | -- - missing comma
4212 // | parsed until here as `"y" & X`
4213 err.span_suggestion_short(
4214 cm.next_point(arm_start_span),
4215 "missing a comma here to end this `match` arm",
4217 Applicability::MachineApplicable
4221 err.span_label(arrow_span,
4222 "while parsing the `match` arm starting here");
4228 self.eat(&token::Comma);
4239 /// Parses an expression.
4241 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4242 self.parse_expr_res(Restrictions::empty(), None)
4245 /// Evaluates the closure with restrictions in place.
4247 /// Afters the closure is evaluated, restrictions are reset.
4248 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4249 where F: FnOnce(&mut Self) -> T
4251 let old = self.restrictions;
4252 self.restrictions = r;
4254 self.restrictions = old;
4259 /// Parses an expression, subject to the given restrictions.
4261 fn parse_expr_res(&mut self, r: Restrictions,
4262 already_parsed_attrs: Option<ThinVec<Attribute>>)
4263 -> PResult<'a, P<Expr>> {
4264 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4267 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4268 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4269 if self.eat(&token::Eq) {
4270 Ok(Some(self.parse_expr()?))
4272 Ok(Some(self.parse_expr()?))
4278 /// Parses patterns, separated by '|' s.
4279 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4280 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4281 self.eat(&token::BinOp(token::Or));
4283 let mut pats = Vec::new();
4285 pats.push(self.parse_top_level_pat()?);
4287 if self.token == token::OrOr {
4288 let mut err = self.struct_span_err(self.span,
4289 "unexpected token `||` after pattern");
4290 err.span_suggestion(
4292 "use a single `|` to specify multiple patterns",
4294 Applicability::MachineApplicable
4298 } else if self.eat(&token::BinOp(token::Or)) {
4299 // This is a No-op. Continue the loop to parse the next
4307 // Parses a parenthesized list of patterns like
4308 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4309 // - a vector of the patterns that were parsed
4310 // - an option indicating the index of the `..` element
4311 // - a boolean indicating whether a trailing comma was present.
4312 // Trailing commas are significant because (p) and (p,) are different patterns.
4313 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4314 self.expect(&token::OpenDelim(token::Paren))?;
4315 let result = match self.parse_pat_list() {
4316 Ok(result) => result,
4317 Err(mut err) => { // recover from parse error in tuple pattern list
4319 self.consume_block(token::Paren);
4320 return Ok((vec![], Some(0), false));
4323 self.expect(&token::CloseDelim(token::Paren))?;
4327 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4328 let mut fields = Vec::new();
4329 let mut ddpos = None;
4330 let mut prev_dd_sp = None;
4331 let mut trailing_comma = false;
4333 if self.eat(&token::DotDot) {
4334 if ddpos.is_none() {
4335 ddpos = Some(fields.len());
4336 prev_dd_sp = Some(self.prev_span);
4338 // Emit a friendly error, ignore `..` and continue parsing
4339 let mut err = self.struct_span_err(
4341 "`..` can only be used once per tuple or tuple struct pattern",
4343 err.span_label(self.prev_span, "can only be used once per pattern");
4344 if let Some(sp) = prev_dd_sp {
4345 err.span_label(sp, "previously present here");
4349 } else if !self.check(&token::CloseDelim(token::Paren)) {
4350 fields.push(self.parse_pat(None)?);
4355 trailing_comma = self.eat(&token::Comma);
4356 if !trailing_comma {
4361 if ddpos == Some(fields.len()) && trailing_comma {
4362 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4363 let msg = "trailing comma is not permitted after `..`";
4364 self.struct_span_err(self.prev_span, msg)
4365 .span_label(self.prev_span, msg)
4369 Ok((fields, ddpos, trailing_comma))
4372 fn parse_pat_vec_elements(
4374 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4375 let mut before = Vec::new();
4376 let mut slice = None;
4377 let mut after = Vec::new();
4378 let mut first = true;
4379 let mut before_slice = true;
4381 while self.token != token::CloseDelim(token::Bracket) {
4385 self.expect(&token::Comma)?;
4387 if self.token == token::CloseDelim(token::Bracket)
4388 && (before_slice || !after.is_empty()) {
4394 if self.eat(&token::DotDot) {
4396 if self.check(&token::Comma) ||
4397 self.check(&token::CloseDelim(token::Bracket)) {
4398 slice = Some(P(Pat {
4399 id: ast::DUMMY_NODE_ID,
4400 node: PatKind::Wild,
4401 span: self.prev_span,
4403 before_slice = false;
4409 let subpat = self.parse_pat(None)?;
4410 if before_slice && self.eat(&token::DotDot) {
4411 slice = Some(subpat);
4412 before_slice = false;
4413 } else if before_slice {
4414 before.push(subpat);
4420 Ok((before, slice, after))
4426 attrs: Vec<Attribute>
4427 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4428 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4430 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4431 // Parsing a pattern of the form "fieldname: pat"
4432 let fieldname = self.parse_field_name()?;
4434 let pat = self.parse_pat(None)?;
4436 (pat, fieldname, false)
4438 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4439 let is_box = self.eat_keyword(keywords::Box);
4440 let boxed_span = self.span;
4441 let is_ref = self.eat_keyword(keywords::Ref);
4442 let is_mut = self.eat_keyword(keywords::Mut);
4443 let fieldname = self.parse_ident()?;
4444 hi = self.prev_span;
4446 let bind_type = match (is_ref, is_mut) {
4447 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4448 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4449 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4450 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4452 let fieldpat = P(Pat {
4453 id: ast::DUMMY_NODE_ID,
4454 node: PatKind::Ident(bind_type, fieldname, None),
4455 span: boxed_span.to(hi),
4458 let subpat = if is_box {
4460 id: ast::DUMMY_NODE_ID,
4461 node: PatKind::Box(fieldpat),
4467 (subpat, fieldname, true)
4470 Ok(source_map::Spanned {
4472 node: ast::FieldPat {
4476 attrs: attrs.into(),
4481 /// Parses the fields of a struct-like pattern.
4482 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4483 let mut fields = Vec::new();
4484 let mut etc = false;
4485 let mut ate_comma = true;
4486 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4487 let mut etc_span = None;
4489 while self.token != token::CloseDelim(token::Brace) {
4490 let attrs = self.parse_outer_attributes()?;
4493 // check that a comma comes after every field
4495 let err = self.struct_span_err(self.prev_span, "expected `,`");
4496 if let Some(mut delayed) = delayed_err {
4503 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4505 let mut etc_sp = self.span;
4507 if self.token == token::DotDotDot { // Issue #46718
4508 // Accept `...` as if it were `..` to avoid further errors
4509 let mut err = self.struct_span_err(self.span,
4510 "expected field pattern, found `...`");
4511 err.span_suggestion(
4513 "to omit remaining fields, use one fewer `.`",
4515 Applicability::MachineApplicable
4519 self.bump(); // `..` || `...`
4521 if self.token == token::CloseDelim(token::Brace) {
4522 etc_span = Some(etc_sp);
4525 let token_str = self.this_token_descr();
4526 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4528 err.span_label(self.span, "expected `}`");
4529 let mut comma_sp = None;
4530 if self.token == token::Comma { // Issue #49257
4531 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4532 err.span_label(etc_sp,
4533 "`..` must be at the end and cannot have a trailing comma");
4534 comma_sp = Some(self.span);
4539 etc_span = Some(etc_sp.until(self.span));
4540 if self.token == token::CloseDelim(token::Brace) {
4541 // If the struct looks otherwise well formed, recover and continue.
4542 if let Some(sp) = comma_sp {
4543 err.span_suggestion_short(
4545 "remove this comma",
4547 Applicability::MachineApplicable,
4552 } else if self.token.is_ident() && ate_comma {
4553 // Accept fields coming after `..,`.
4554 // This way we avoid "pattern missing fields" errors afterwards.
4555 // We delay this error until the end in order to have a span for a
4557 if let Some(mut delayed_err) = delayed_err {
4561 delayed_err = Some(err);
4564 if let Some(mut err) = delayed_err {
4571 fields.push(match self.parse_pat_field(lo, attrs) {
4574 if let Some(mut delayed_err) = delayed_err {
4580 ate_comma = self.eat(&token::Comma);
4583 if let Some(mut err) = delayed_err {
4584 if let Some(etc_span) = etc_span {
4585 err.multipart_suggestion(
4586 "move the `..` to the end of the field list",
4588 (etc_span, String::new()),
4589 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4591 Applicability::MachineApplicable,
4596 return Ok((fields, etc));
4599 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4600 if self.token.is_path_start() {
4602 let (qself, path) = if self.eat_lt() {
4603 // Parse a qualified path
4604 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4607 // Parse an unqualified path
4608 (None, self.parse_path(PathStyle::Expr)?)
4610 let hi = self.prev_span;
4611 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4613 self.parse_literal_maybe_minus()
4617 // helper function to decide whether to parse as ident binding or to try to do
4618 // something more complex like range patterns
4619 fn parse_as_ident(&mut self) -> bool {
4620 self.look_ahead(1, |t| match *t {
4621 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4622 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4623 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4624 // range pattern branch
4625 token::DotDot => None,
4627 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4628 token::Comma | token::CloseDelim(token::Bracket) => true,
4633 /// A wrapper around `parse_pat` with some special error handling for the
4634 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4635 /// to subpatterns within such).
4636 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4637 let pat = self.parse_pat(None)?;
4638 if self.token == token::Comma {
4639 // An unexpected comma after a top-level pattern is a clue that the
4640 // user (perhaps more accustomed to some other language) forgot the
4641 // parentheses in what should have been a tuple pattern; return a
4642 // suggestion-enhanced error here rather than choking on the comma
4644 let comma_span = self.span;
4646 if let Err(mut err) = self.parse_pat_list() {
4647 // We didn't expect this to work anyway; we just wanted
4648 // to advance to the end of the comma-sequence so we know
4649 // the span to suggest parenthesizing
4652 let seq_span = pat.span.to(self.prev_span);
4653 let mut err = self.struct_span_err(comma_span,
4654 "unexpected `,` in pattern");
4655 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4656 err.span_suggestion(
4658 "try adding parentheses to match on a tuple..",
4659 format!("({})", seq_snippet),
4660 Applicability::MachineApplicable
4663 "..or a vertical bar to match on multiple alternatives",
4664 format!("{}", seq_snippet.replace(",", " |")),
4665 Applicability::MachineApplicable
4673 /// Parses a pattern.
4674 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4675 self.parse_pat_with_range_pat(true, expected)
4678 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4680 fn parse_pat_with_range_pat(
4682 allow_range_pat: bool,
4683 expected: Option<&'static str>,
4684 ) -> PResult<'a, P<Pat>> {
4685 maybe_recover_from_interpolated_ty_qpath!(self, true);
4686 maybe_whole!(self, NtPat, |x| x);
4691 token::BinOp(token::And) | token::AndAnd => {
4692 // Parse &pat / &mut pat
4694 let mutbl = self.parse_mutability();
4695 if let token::Lifetime(ident) = self.token {
4696 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4698 err.span_label(self.span, "unexpected lifetime");
4701 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4702 pat = PatKind::Ref(subpat, mutbl);
4704 token::OpenDelim(token::Paren) => {
4705 // Parse (pat,pat,pat,...) as tuple pattern
4706 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4707 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4708 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4710 PatKind::Tuple(fields, ddpos)
4713 token::OpenDelim(token::Bracket) => {
4714 // Parse [pat,pat,...] as slice pattern
4716 let (before, slice, after) = self.parse_pat_vec_elements()?;
4717 self.expect(&token::CloseDelim(token::Bracket))?;
4718 pat = PatKind::Slice(before, slice, after);
4720 // At this point, token != &, &&, (, [
4721 _ => if self.eat_keyword(keywords::Underscore) {
4723 pat = PatKind::Wild;
4724 } else if self.eat_keyword(keywords::Mut) {
4725 // Parse mut ident @ pat / mut ref ident @ pat
4726 let mutref_span = self.prev_span.to(self.span);
4727 let binding_mode = if self.eat_keyword(keywords::Ref) {
4729 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4732 "try switching the order",
4734 Applicability::MachineApplicable
4736 BindingMode::ByRef(Mutability::Mutable)
4738 BindingMode::ByValue(Mutability::Mutable)
4740 pat = self.parse_pat_ident(binding_mode)?;
4741 } else if self.eat_keyword(keywords::Ref) {
4742 // Parse ref ident @ pat / ref mut ident @ pat
4743 let mutbl = self.parse_mutability();
4744 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4745 } else if self.eat_keyword(keywords::Box) {
4747 let subpat = self.parse_pat_with_range_pat(false, None)?;
4748 pat = PatKind::Box(subpat);
4749 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4750 self.parse_as_ident() {
4751 // Parse ident @ pat
4752 // This can give false positives and parse nullary enums,
4753 // they are dealt with later in resolve
4754 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4755 pat = self.parse_pat_ident(binding_mode)?;
4756 } else if self.token.is_path_start() {
4757 // Parse pattern starting with a path
4758 let (qself, path) = if self.eat_lt() {
4759 // Parse a qualified path
4760 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4763 // Parse an unqualified path
4764 (None, self.parse_path(PathStyle::Expr)?)
4767 token::Not if qself.is_none() => {
4768 // Parse macro invocation
4770 let (delim, tts) = self.expect_delimited_token_tree()?;
4771 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4772 pat = PatKind::Mac(mac);
4774 token::DotDotDot | token::DotDotEq | token::DotDot => {
4775 let end_kind = match self.token {
4776 token::DotDot => RangeEnd::Excluded,
4777 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4778 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4779 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4782 let op_span = self.span;
4784 let span = lo.to(self.prev_span);
4785 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4787 let end = self.parse_pat_range_end()?;
4788 let op = Spanned { span: op_span, node: end_kind };
4789 pat = PatKind::Range(begin, end, op);
4791 token::OpenDelim(token::Brace) => {
4792 if qself.is_some() {
4793 let msg = "unexpected `{` after qualified path";
4794 let mut err = self.fatal(msg);
4795 err.span_label(self.span, msg);
4798 // Parse struct pattern
4800 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4802 self.recover_stmt();
4806 pat = PatKind::Struct(path, fields, etc);
4808 token::OpenDelim(token::Paren) => {
4809 if qself.is_some() {
4810 let msg = "unexpected `(` after qualified path";
4811 let mut err = self.fatal(msg);
4812 err.span_label(self.span, msg);
4815 // Parse tuple struct or enum pattern
4816 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4817 pat = PatKind::TupleStruct(path, fields, ddpos)
4819 _ => pat = PatKind::Path(qself, path),
4822 // Try to parse everything else as literal with optional minus
4823 match self.parse_literal_maybe_minus() {
4825 let op_span = self.span;
4826 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4827 self.check(&token::DotDotDot) {
4828 let end_kind = if self.eat(&token::DotDotDot) {
4829 RangeEnd::Included(RangeSyntax::DotDotDot)
4830 } else if self.eat(&token::DotDotEq) {
4831 RangeEnd::Included(RangeSyntax::DotDotEq)
4832 } else if self.eat(&token::DotDot) {
4835 panic!("impossible case: we already matched \
4836 on a range-operator token")
4838 let end = self.parse_pat_range_end()?;
4839 let op = Spanned { span: op_span, node: end_kind };
4840 pat = PatKind::Range(begin, end, op);
4842 pat = PatKind::Lit(begin);
4846 self.cancel(&mut err);
4847 let expected = expected.unwrap_or("pattern");
4849 "expected {}, found {}",
4851 self.this_token_descr(),
4853 let mut err = self.fatal(&msg);
4854 err.span_label(self.span, format!("expected {}", expected));
4855 let sp = self.sess.source_map().start_point(self.span);
4856 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4857 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4865 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4866 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4868 if !allow_range_pat {
4871 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4873 PatKind::Range(..) => {
4874 let mut err = self.struct_span_err(
4876 "the range pattern here has ambiguous interpretation",
4878 err.span_suggestion(
4880 "add parentheses to clarify the precedence",
4881 format!("({})", pprust::pat_to_string(&pat)),
4882 // "ambiguous interpretation" implies that we have to be guessing
4883 Applicability::MaybeIncorrect
4894 /// Parses `ident` or `ident @ pat`.
4895 /// used by the copy foo and ref foo patterns to give a good
4896 /// error message when parsing mistakes like `ref foo(a, b)`.
4897 fn parse_pat_ident(&mut self,
4898 binding_mode: ast::BindingMode)
4899 -> PResult<'a, PatKind> {
4900 let ident = self.parse_ident()?;
4901 let sub = if self.eat(&token::At) {
4902 Some(self.parse_pat(Some("binding pattern"))?)
4907 // just to be friendly, if they write something like
4909 // we end up here with ( as the current token. This shortly
4910 // leads to a parse error. Note that if there is no explicit
4911 // binding mode then we do not end up here, because the lookahead
4912 // will direct us over to parse_enum_variant()
4913 if self.token == token::OpenDelim(token::Paren) {
4914 return Err(self.span_fatal(
4916 "expected identifier, found enum pattern"))
4919 Ok(PatKind::Ident(binding_mode, ident, sub))
4922 /// Parses a local variable declaration.
4923 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4924 let lo = self.prev_span;
4925 let pat = self.parse_top_level_pat()?;
4927 let (err, ty) = if self.eat(&token::Colon) {
4928 // Save the state of the parser before parsing type normally, in case there is a `:`
4929 // instead of an `=` typo.
4930 let parser_snapshot_before_type = self.clone();
4931 let colon_sp = self.prev_span;
4932 match self.parse_ty() {
4933 Ok(ty) => (None, Some(ty)),
4935 // Rewind to before attempting to parse the type and continue parsing
4936 let parser_snapshot_after_type = self.clone();
4937 mem::replace(self, parser_snapshot_before_type);
4939 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4940 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4941 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4947 let init = match (self.parse_initializer(err.is_some()), err) {
4948 (Ok(init), None) => { // init parsed, ty parsed
4951 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4952 // Could parse the type as if it were the initializer, it is likely there was a
4953 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4954 err.span_suggestion_short(
4956 "use `=` if you meant to assign",
4958 Applicability::MachineApplicable
4961 // As this was parsed successfully, continue as if the code has been fixed for the
4962 // rest of the file. It will still fail due to the emitted error, but we avoid
4966 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4968 // Couldn't parse the type nor the initializer, only raise the type error and
4969 // return to the parser state before parsing the type as the initializer.
4970 // let x: <parse_error>;
4971 mem::replace(self, snapshot);
4974 (Err(err), None) => { // init error, ty parsed
4975 // Couldn't parse the initializer and we're not attempting to recover a failed
4976 // parse of the type, return the error.
4980 let hi = if self.token == token::Semi {
4989 id: ast::DUMMY_NODE_ID,
4992 source: LocalSource::Normal,
4996 /// Parses a structure field.
4997 fn parse_name_and_ty(&mut self,
5000 attrs: Vec<Attribute>)
5001 -> PResult<'a, StructField> {
5002 let name = self.parse_ident()?;
5003 self.expect(&token::Colon)?;
5004 let ty = self.parse_ty()?;
5006 span: lo.to(self.prev_span),
5009 id: ast::DUMMY_NODE_ID,
5015 /// Emits an expected-item-after-attributes error.
5016 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
5017 let message = match attrs.last() {
5018 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
5019 _ => "expected item after attributes",
5022 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
5023 if attrs.last().unwrap().is_sugared_doc {
5024 err.span_label(self.prev_span, "this doc comment doesn't document anything");
5029 /// Parse a statement. This stops just before trailing semicolons on everything but items.
5030 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
5031 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
5032 Ok(self.parse_stmt_(true))
5035 // Eat tokens until we can be relatively sure we reached the end of the
5036 // statement. This is something of a best-effort heuristic.
5038 // We terminate when we find an unmatched `}` (without consuming it).
5039 fn recover_stmt(&mut self) {
5040 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
5043 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
5044 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
5045 // approximate - it can mean we break too early due to macros, but that
5046 // should only lead to sub-optimal recovery, not inaccurate parsing).
5048 // If `break_on_block` is `Break`, then we will stop consuming tokens
5049 // after finding (and consuming) a brace-delimited block.
5050 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
5051 let mut brace_depth = 0;
5052 let mut bracket_depth = 0;
5053 let mut in_block = false;
5054 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
5055 break_on_semi, break_on_block);
5057 debug!("recover_stmt_ loop {:?}", self.token);
5059 token::OpenDelim(token::DelimToken::Brace) => {
5062 if break_on_block == BlockMode::Break &&
5064 bracket_depth == 0 {
5068 token::OpenDelim(token::DelimToken::Bracket) => {
5072 token::CloseDelim(token::DelimToken::Brace) => {
5073 if brace_depth == 0 {
5074 debug!("recover_stmt_ return - close delim {:?}", self.token);
5079 if in_block && bracket_depth == 0 && brace_depth == 0 {
5080 debug!("recover_stmt_ return - block end {:?}", self.token);
5084 token::CloseDelim(token::DelimToken::Bracket) => {
5086 if bracket_depth < 0 {
5092 debug!("recover_stmt_ return - Eof");
5097 if break_on_semi == SemiColonMode::Break &&
5099 bracket_depth == 0 {
5100 debug!("recover_stmt_ return - Semi");
5105 if break_on_semi == SemiColonMode::Comma &&
5107 bracket_depth == 0 {
5108 debug!("recover_stmt_ return - Semi");
5121 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5122 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5124 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5129 fn is_async_block(&self) -> bool {
5130 self.token.is_keyword(keywords::Async) &&
5133 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5134 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5136 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5141 fn is_async_fn(&self) -> bool {
5142 self.token.is_keyword(keywords::Async) &&
5143 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5146 fn is_do_catch_block(&self) -> bool {
5147 self.token.is_keyword(keywords::Do) &&
5148 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5149 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5150 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5153 fn is_try_block(&self) -> bool {
5154 self.token.is_keyword(keywords::Try) &&
5155 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5156 self.span.rust_2018() &&
5157 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5158 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5161 fn is_union_item(&self) -> bool {
5162 self.token.is_keyword(keywords::Union) &&
5163 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5166 fn is_crate_vis(&self) -> bool {
5167 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5170 fn is_existential_type_decl(&self) -> bool {
5171 self.token.is_keyword(keywords::Existential) &&
5172 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5175 fn is_auto_trait_item(&self) -> bool {
5177 (self.token.is_keyword(keywords::Auto)
5178 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5179 || // unsafe auto trait
5180 (self.token.is_keyword(keywords::Unsafe) &&
5181 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5182 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5185 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5186 -> PResult<'a, Option<P<Item>>> {
5187 let token_lo = self.span;
5188 let (ident, def) = match self.token {
5189 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5191 let ident = self.parse_ident()?;
5192 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5193 match self.parse_token_tree() {
5194 TokenTree::Delimited(_, _, tts) => tts,
5195 _ => unreachable!(),
5197 } else if self.check(&token::OpenDelim(token::Paren)) {
5198 let args = self.parse_token_tree();
5199 let body = if self.check(&token::OpenDelim(token::Brace)) {
5200 self.parse_token_tree()
5205 TokenStream::new(vec![
5207 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5215 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5217 token::Ident(ident, _) if ident.name == "macro_rules" &&
5218 self.look_ahead(1, |t| *t == token::Not) => {
5219 let prev_span = self.prev_span;
5220 self.complain_if_pub_macro(&vis.node, prev_span);
5224 let ident = self.parse_ident()?;
5225 let (delim, tokens) = self.expect_delimited_token_tree()?;
5226 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5227 self.report_invalid_macro_expansion_item();
5230 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5232 _ => return Ok(None),
5235 let span = lo.to(self.prev_span);
5236 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5239 fn parse_stmt_without_recovery(&mut self,
5240 macro_legacy_warnings: bool)
5241 -> PResult<'a, Option<Stmt>> {
5242 maybe_whole!(self, NtStmt, |x| Some(x));
5244 let attrs = self.parse_outer_attributes()?;
5247 Ok(Some(if self.eat_keyword(keywords::Let) {
5249 id: ast::DUMMY_NODE_ID,
5250 node: StmtKind::Local(self.parse_local(attrs.into())?),
5251 span: lo.to(self.prev_span),
5253 } else if let Some(macro_def) = self.eat_macro_def(
5255 &source_map::respan(lo, VisibilityKind::Inherited),
5259 id: ast::DUMMY_NODE_ID,
5260 node: StmtKind::Item(macro_def),
5261 span: lo.to(self.prev_span),
5263 // Starts like a simple path, being careful to avoid contextual keywords
5264 // such as a union items, item with `crate` visibility or auto trait items.
5265 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5266 // like a path (1 token), but it fact not a path.
5267 // `union::b::c` - path, `union U { ... }` - not a path.
5268 // `crate::b::c` - path, `crate struct S;` - not a path.
5269 } else if self.token.is_path_start() &&
5270 !self.token.is_qpath_start() &&
5271 !self.is_union_item() &&
5272 !self.is_crate_vis() &&
5273 !self.is_existential_type_decl() &&
5274 !self.is_auto_trait_item() &&
5275 !self.is_async_fn() {
5276 let pth = self.parse_path(PathStyle::Expr)?;
5278 if !self.eat(&token::Not) {
5279 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5280 self.parse_struct_expr(lo, pth, ThinVec::new())?
5282 let hi = self.prev_span;
5283 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5286 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5287 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5288 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5291 return Ok(Some(Stmt {
5292 id: ast::DUMMY_NODE_ID,
5293 node: StmtKind::Expr(expr),
5294 span: lo.to(self.prev_span),
5298 // it's a macro invocation
5299 let id = match self.token {
5300 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5301 _ => self.parse_ident()?,
5304 // check that we're pointing at delimiters (need to check
5305 // again after the `if`, because of `parse_ident`
5306 // consuming more tokens).
5308 token::OpenDelim(_) => {}
5310 // we only expect an ident if we didn't parse one
5312 let ident_str = if id.name == keywords::Invalid.name() {
5317 let tok_str = self.this_token_descr();
5318 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5321 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5326 let (delim, tts) = self.expect_delimited_token_tree()?;
5327 let hi = self.prev_span;
5329 let style = if delim == MacDelimiter::Brace {
5330 MacStmtStyle::Braces
5332 MacStmtStyle::NoBraces
5335 if id.name == keywords::Invalid.name() {
5336 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5337 let node = if delim == MacDelimiter::Brace ||
5338 self.token == token::Semi || self.token == token::Eof {
5339 StmtKind::Mac(P((mac, style, attrs.into())))
5341 // We used to incorrectly stop parsing macro-expanded statements here.
5342 // If the next token will be an error anyway but could have parsed with the
5343 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5344 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5345 // These can continue an expression, so we can't stop parsing and warn.
5346 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5347 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5348 token::BinOp(token::And) | token::BinOp(token::Or) |
5349 token::AndAnd | token::OrOr |
5350 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5353 self.warn_missing_semicolon();
5354 StmtKind::Mac(P((mac, style, attrs.into())))
5356 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5357 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5358 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5359 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5363 id: ast::DUMMY_NODE_ID,
5368 // if it has a special ident, it's definitely an item
5370 // Require a semicolon or braces.
5371 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5372 self.report_invalid_macro_expansion_item();
5374 let span = lo.to(hi);
5376 id: ast::DUMMY_NODE_ID,
5378 node: StmtKind::Item({
5380 span, id /*id is good here*/,
5381 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5382 respan(lo, VisibilityKind::Inherited),
5388 // FIXME: Bad copy of attrs
5389 let old_directory_ownership =
5390 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5391 let item = self.parse_item_(attrs.clone(), false, true)?;
5392 self.directory.ownership = old_directory_ownership;
5396 id: ast::DUMMY_NODE_ID,
5397 span: lo.to(i.span),
5398 node: StmtKind::Item(i),
5401 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5402 if !attrs.is_empty() {
5403 if s.prev_token_kind == PrevTokenKind::DocComment {
5404 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5405 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5406 s.span_err(s.span, "expected statement after outer attribute");
5411 // Do not attempt to parse an expression if we're done here.
5412 if self.token == token::Semi {
5413 unused_attrs(&attrs, self);
5418 if self.token == token::CloseDelim(token::Brace) {
5419 unused_attrs(&attrs, self);
5423 // Remainder are line-expr stmts.
5424 let e = self.parse_expr_res(
5425 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5427 id: ast::DUMMY_NODE_ID,
5428 span: lo.to(e.span),
5429 node: StmtKind::Expr(e),
5436 /// Checks if this expression is a successfully parsed statement.
5437 fn expr_is_complete(&self, e: &Expr) -> bool {
5438 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5439 !classify::expr_requires_semi_to_be_stmt(e)
5442 /// Parses a block. No inner attributes are allowed.
5443 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5444 maybe_whole!(self, NtBlock, |x| x);
5448 if !self.eat(&token::OpenDelim(token::Brace)) {
5450 let tok = self.this_token_descr();
5451 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5452 let do_not_suggest_help =
5453 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5455 if self.token.is_ident_named("and") {
5456 e.span_suggestion_short(
5458 "use `&&` instead of `and` for the boolean operator",
5460 Applicability::MaybeIncorrect,
5463 if self.token.is_ident_named("or") {
5464 e.span_suggestion_short(
5466 "use `||` instead of `or` for the boolean operator",
5468 Applicability::MaybeIncorrect,
5472 // Check to see if the user has written something like
5477 // Which is valid in other languages, but not Rust.
5478 match self.parse_stmt_without_recovery(false) {
5480 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5481 || do_not_suggest_help {
5482 // if the next token is an open brace (e.g., `if a b {`), the place-
5483 // inside-a-block suggestion would be more likely wrong than right
5484 e.span_label(sp, "expected `{`");
5487 let mut stmt_span = stmt.span;
5488 // expand the span to include the semicolon, if it exists
5489 if self.eat(&token::Semi) {
5490 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5492 let sugg = pprust::to_string(|s| {
5493 use crate::print::pprust::{PrintState, INDENT_UNIT};
5494 s.ibox(INDENT_UNIT)?;
5496 s.print_stmt(&stmt)?;
5497 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5501 "try placing this code inside a block",
5503 // speculative, has been misleading in the past (closed Issue #46836)
5504 Applicability::MaybeIncorrect
5508 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5509 self.cancel(&mut e);
5513 e.span_label(sp, "expected `{`");
5517 self.parse_block_tail(lo, BlockCheckMode::Default)
5520 /// Parses a block. Inner attributes are allowed.
5521 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5522 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5525 self.expect(&token::OpenDelim(token::Brace))?;
5526 Ok((self.parse_inner_attributes()?,
5527 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5530 /// Parses the rest of a block expression or function body.
5531 /// Precondition: already parsed the '{'.
5532 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5533 let mut stmts = vec![];
5534 while !self.eat(&token::CloseDelim(token::Brace)) {
5535 let stmt = match self.parse_full_stmt(false) {
5538 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5540 id: ast::DUMMY_NODE_ID,
5541 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5547 if let Some(stmt) = stmt {
5549 } else if self.token == token::Eof {
5552 // Found only `;` or `}`.
5558 id: ast::DUMMY_NODE_ID,
5560 span: lo.to(self.prev_span),
5564 /// Parses a statement, including the trailing semicolon.
5565 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5566 // skip looking for a trailing semicolon when we have an interpolated statement
5567 maybe_whole!(self, NtStmt, |x| Some(x));
5569 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5571 None => return Ok(None),
5575 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5576 // expression without semicolon
5577 if classify::expr_requires_semi_to_be_stmt(expr) {
5578 // Just check for errors and recover; do not eat semicolon yet.
5580 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5583 self.recover_stmt();
5587 StmtKind::Local(..) => {
5588 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5589 if macro_legacy_warnings && self.token != token::Semi {
5590 self.warn_missing_semicolon();
5592 self.expect_one_of(&[], &[token::Semi])?;
5598 if self.eat(&token::Semi) {
5599 stmt = stmt.add_trailing_semicolon();
5602 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5606 fn warn_missing_semicolon(&self) {
5607 self.diagnostic().struct_span_warn(self.span, {
5608 &format!("expected `;`, found {}", self.this_token_descr())
5610 "This was erroneously allowed and will become a hard error in a future release"
5614 fn err_dotdotdot_syntax(&self, span: Span) {
5615 self.diagnostic().struct_span_err(span, {
5616 "unexpected token: `...`"
5618 span, "use `..` for an exclusive range", "..".to_owned(),
5619 Applicability::MaybeIncorrect
5621 span, "or `..=` for an inclusive range", "..=".to_owned(),
5622 Applicability::MaybeIncorrect
5626 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5629 /// BOUND = TY_BOUND | LT_BOUND
5630 /// LT_BOUND = LIFETIME (e.g., `'a`)
5631 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5632 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5634 fn parse_generic_bounds_common(&mut self,
5636 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5637 let mut bounds = Vec::new();
5638 let mut negative_bounds = Vec::new();
5639 let mut last_plus_span = None;
5640 let mut was_negative = false;
5642 // This needs to be synchronized with `Token::can_begin_bound`.
5643 let is_bound_start = self.check_path() || self.check_lifetime() ||
5644 self.check(&token::Not) || // used for error reporting only
5645 self.check(&token::Question) ||
5646 self.check_keyword(keywords::For) ||
5647 self.check(&token::OpenDelim(token::Paren));
5650 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5651 let inner_lo = self.span;
5652 let is_negative = self.eat(&token::Not);
5653 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5654 if self.token.is_lifetime() {
5655 if let Some(question_span) = question {
5656 self.span_err(question_span,
5657 "`?` may only modify trait bounds, not lifetime bounds");
5659 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5661 let inner_span = inner_lo.to(self.prev_span);
5662 self.expect(&token::CloseDelim(token::Paren))?;
5663 let mut err = self.struct_span_err(
5664 lo.to(self.prev_span),
5665 "parenthesized lifetime bounds are not supported"
5667 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5668 err.span_suggestion_short(
5669 lo.to(self.prev_span),
5670 "remove the parentheses",
5672 Applicability::MachineApplicable
5678 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5679 let path = self.parse_path(PathStyle::Type)?;
5681 self.expect(&token::CloseDelim(token::Paren))?;
5683 let poly_span = lo.to(self.prev_span);
5685 was_negative = true;
5686 if let Some(sp) = last_plus_span.or(colon_span) {
5687 negative_bounds.push(sp.to(poly_span));
5690 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5691 let modifier = if question.is_some() {
5692 TraitBoundModifier::Maybe
5694 TraitBoundModifier::None
5696 bounds.push(GenericBound::Trait(poly_trait, modifier));
5703 if !allow_plus || !self.eat_plus() {
5706 last_plus_span = Some(self.prev_span);
5710 if !negative_bounds.is_empty() || was_negative {
5711 let plural = negative_bounds.len() > 1;
5712 let last_span = negative_bounds.last().map(|sp| *sp);
5713 let mut err = self.struct_span_err(
5715 "negative trait bounds are not supported",
5717 if let Some(sp) = last_span {
5718 err.span_label(sp, "negative trait bounds are not supported");
5720 if let Some(bound_list) = colon_span {
5721 let bound_list = bound_list.to(self.prev_span);
5722 let mut new_bound_list = String::new();
5723 if !bounds.is_empty() {
5724 let mut snippets = bounds.iter().map(|bound| bound.span())
5725 .map(|span| self.sess.source_map().span_to_snippet(span));
5726 while let Some(Ok(snippet)) = snippets.next() {
5727 new_bound_list.push_str(" + ");
5728 new_bound_list.push_str(&snippet);
5730 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5732 err.span_suggestion_hidden(
5734 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5736 Applicability::MachineApplicable,
5745 crate fn parse_generic_bounds(&mut self,
5746 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5747 self.parse_generic_bounds_common(true, colon_span)
5750 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5753 /// BOUND = LT_BOUND (e.g., `'a`)
5755 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5756 let mut lifetimes = Vec::new();
5757 while self.check_lifetime() {
5758 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5760 if !self.eat_plus() {
5767 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5768 fn parse_ty_param(&mut self,
5769 preceding_attrs: Vec<Attribute>)
5770 -> PResult<'a, GenericParam> {
5771 let ident = self.parse_ident()?;
5773 // Parse optional colon and param bounds.
5774 let bounds = if self.eat(&token::Colon) {
5775 self.parse_generic_bounds(Some(self.prev_span))?
5780 let default = if self.eat(&token::Eq) {
5781 Some(self.parse_ty()?)
5788 id: ast::DUMMY_NODE_ID,
5789 attrs: preceding_attrs.into(),
5791 kind: GenericParamKind::Type {
5797 /// Parses the following grammar:
5799 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5800 fn parse_trait_item_assoc_ty(&mut self)
5801 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5802 let ident = self.parse_ident()?;
5803 let mut generics = self.parse_generics()?;
5805 // Parse optional colon and param bounds.
5806 let bounds = if self.eat(&token::Colon) {
5807 self.parse_generic_bounds(None)?
5811 generics.where_clause = self.parse_where_clause()?;
5813 let default = if self.eat(&token::Eq) {
5814 Some(self.parse_ty()?)
5818 self.expect(&token::Semi)?;
5820 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5823 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5824 self.expect_keyword(keywords::Const)?;
5825 let ident = self.parse_ident()?;
5826 self.expect(&token::Colon)?;
5827 let ty = self.parse_ty()?;
5831 id: ast::DUMMY_NODE_ID,
5832 attrs: preceding_attrs.into(),
5834 kind: GenericParamKind::Const {
5840 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5841 /// a trailing comma and erroneous trailing attributes.
5842 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5843 let mut params = Vec::new();
5845 let attrs = self.parse_outer_attributes()?;
5846 if self.check_lifetime() {
5847 let lifetime = self.expect_lifetime();
5848 // Parse lifetime parameter.
5849 let bounds = if self.eat(&token::Colon) {
5850 self.parse_lt_param_bounds()
5854 params.push(ast::GenericParam {
5855 ident: lifetime.ident,
5857 attrs: attrs.into(),
5859 kind: ast::GenericParamKind::Lifetime,
5861 } else if self.check_keyword(keywords::Const) {
5862 // Parse const parameter.
5863 params.push(self.parse_const_param(attrs)?);
5864 } else if self.check_ident() {
5865 // Parse type parameter.
5866 params.push(self.parse_ty_param(attrs)?);
5868 // Check for trailing attributes and stop parsing.
5869 if !attrs.is_empty() {
5870 if !params.is_empty() {
5871 self.struct_span_err(
5873 &format!("trailing attribute after generic parameter"),
5875 .span_label(attrs[0].span, "attributes must go before parameters")
5878 self.struct_span_err(
5880 &format!("attribute without generic parameters"),
5884 "attributes are only permitted when preceding parameters",
5892 if !self.eat(&token::Comma) {
5899 /// Parses a set of optional generic type parameter declarations. Where
5900 /// clauses are not parsed here, and must be added later via
5901 /// `parse_where_clause()`.
5903 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5904 /// | ( < lifetimes , typaramseq ( , )? > )
5905 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5906 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5907 maybe_whole!(self, NtGenerics, |x| x);
5909 let span_lo = self.span;
5911 let params = self.parse_generic_params()?;
5915 where_clause: WhereClause {
5916 id: ast::DUMMY_NODE_ID,
5917 predicates: Vec::new(),
5918 span: syntax_pos::DUMMY_SP,
5920 span: span_lo.to(self.prev_span),
5923 Ok(ast::Generics::default())
5927 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5928 /// For the purposes of understanding the parsing logic of generic arguments, this function
5929 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5930 /// had the correct amount of leading angle brackets.
5932 /// ```ignore (diagnostics)
5933 /// bar::<<<<T as Foo>::Output>();
5934 /// ^^ help: remove extra angle brackets
5936 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5940 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5941 // We need to detect whether there are extra leading left angle brackets and produce an
5942 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5943 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5944 // then there won't be matching `>` tokens to find.
5946 // To explain how this detection works, consider the following example:
5948 // ```ignore (diagnostics)
5949 // bar::<<<<T as Foo>::Output>();
5950 // ^^ help: remove extra angle brackets
5953 // Parsing of the left angle brackets starts in this function. We start by parsing the
5954 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5957 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5958 // *Unmatched count:* 1
5959 // *`parse_path_segment` calls deep:* 0
5961 // This has the effect of recursing as this function is called if a `<` character
5962 // is found within the expected generic arguments:
5964 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5965 // *Unmatched count:* 2
5966 // *`parse_path_segment` calls deep:* 1
5968 // Eventually we will have recursed until having consumed all of the `<` tokens and
5969 // this will be reflected in the count:
5971 // *Upcoming tokens:* `T as Foo>::Output>;`
5972 // *Unmatched count:* 4
5973 // `parse_path_segment` calls deep:* 3
5975 // The parser will continue until reaching the first `>` - this will decrement the
5976 // unmatched angle bracket count and return to the parent invocation of this function
5977 // having succeeded in parsing:
5979 // *Upcoming tokens:* `::Output>;`
5980 // *Unmatched count:* 3
5981 // *`parse_path_segment` calls deep:* 2
5983 // This will continue until the next `>` character which will also return successfully
5984 // to the parent invocation of this function and decrement the count:
5986 // *Upcoming tokens:* `;`
5987 // *Unmatched count:* 2
5988 // *`parse_path_segment` calls deep:* 1
5990 // At this point, this function will expect to find another matching `>` character but
5991 // won't be able to and will return an error. This will continue all the way up the
5992 // call stack until the first invocation:
5994 // *Upcoming tokens:* `;`
5995 // *Unmatched count:* 2
5996 // *`parse_path_segment` calls deep:* 0
5998 // In doing this, we have managed to work out how many unmatched leading left angle
5999 // brackets there are, but we cannot recover as the unmatched angle brackets have
6000 // already been consumed. To remedy this, we keep a snapshot of the parser state
6001 // before we do the above. We can then inspect whether we ended up with a parsing error
6002 // and unmatched left angle brackets and if so, restore the parser state before we
6003 // consumed any `<` characters to emit an error and consume the erroneous tokens to
6004 // recover by attempting to parse again.
6006 // In practice, the recursion of this function is indirect and there will be other
6007 // locations that consume some `<` characters - as long as we update the count when
6008 // this happens, it isn't an issue.
6010 let is_first_invocation = style == PathStyle::Expr;
6011 // Take a snapshot before attempting to parse - we can restore this later.
6012 let snapshot = if is_first_invocation {
6018 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
6019 match self.parse_generic_args() {
6020 Ok(value) => Ok(value),
6021 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
6022 // Cancel error from being unable to find `>`. We know the error
6023 // must have been this due to a non-zero unmatched angle bracket
6027 // Swap `self` with our backup of the parser state before attempting to parse
6028 // generic arguments.
6029 let snapshot = mem::replace(self, snapshot.unwrap());
6032 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
6033 snapshot.count={:?}",
6034 snapshot.unmatched_angle_bracket_count,
6037 // Eat the unmatched angle brackets.
6038 for _ in 0..snapshot.unmatched_angle_bracket_count {
6042 // Make a span over ${unmatched angle bracket count} characters.
6043 let span = lo.with_hi(
6044 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
6046 let plural = snapshot.unmatched_angle_bracket_count > 1;
6051 "unmatched angle bracket{}",
6052 if plural { "s" } else { "" }
6058 "remove extra angle bracket{}",
6059 if plural { "s" } else { "" }
6062 Applicability::MachineApplicable,
6066 // Try again without unmatched angle bracket characters.
6067 self.parse_generic_args()
6073 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
6074 /// possibly including trailing comma.
6075 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6076 let mut args = Vec::new();
6077 let mut bindings = Vec::new();
6078 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
6079 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
6081 let args_lo = self.span;
6084 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6085 // Parse lifetime argument.
6086 args.push(GenericArg::Lifetime(self.expect_lifetime()));
6087 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6088 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
6089 // Parse associated type binding.
6091 let ident = self.parse_ident()?;
6093 let ty = self.parse_ty()?;
6094 let span = lo.to(self.prev_span);
6095 bindings.push(TypeBinding {
6096 id: ast::DUMMY_NODE_ID,
6101 assoc_ty_bindings.push(span);
6102 } else if self.check_const_arg() {
6103 // Parse const argument.
6104 let expr = if let token::OpenDelim(token::Brace) = self.token {
6105 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
6106 } else if self.token.is_ident() {
6107 // FIXME(const_generics): to distinguish between idents for types and consts,
6108 // we should introduce a GenericArg::Ident in the AST and distinguish when
6109 // lowering to the HIR. For now, idents for const args are not permitted.
6111 self.fatal("identifiers may currently not be used for const generics")
6114 self.parse_literal_maybe_minus()?
6116 let value = AnonConst {
6117 id: ast::DUMMY_NODE_ID,
6120 args.push(GenericArg::Const(value));
6121 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6122 } else if self.check_type() {
6123 // Parse type argument.
6124 args.push(GenericArg::Type(self.parse_ty()?));
6125 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6130 if !self.eat(&token::Comma) {
6135 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6136 // preserve ordering of generic parameters with respect to associated type binding, so we
6137 // lose that information after parsing.
6138 if misplaced_assoc_ty_bindings.len() > 0 {
6139 let mut err = self.struct_span_err(
6140 args_lo.to(self.prev_span),
6141 "associated type bindings must be declared after generic parameters",
6143 for span in misplaced_assoc_ty_bindings {
6146 "this associated type binding should be moved after the generic parameters",
6152 Ok((args, bindings))
6155 /// Parses an optional where-clause and places it in `generics`.
6157 /// ```ignore (only-for-syntax-highlight)
6158 /// where T : Trait<U, V> + 'b, 'a : 'b
6160 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6161 maybe_whole!(self, NtWhereClause, |x| x);
6163 let mut where_clause = WhereClause {
6164 id: ast::DUMMY_NODE_ID,
6165 predicates: Vec::new(),
6166 span: syntax_pos::DUMMY_SP,
6169 if !self.eat_keyword(keywords::Where) {
6170 return Ok(where_clause);
6172 let lo = self.prev_span;
6174 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6175 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6176 // change we parse those generics now, but report an error.
6177 if self.choose_generics_over_qpath() {
6178 let generics = self.parse_generics()?;
6179 self.struct_span_err(
6181 "generic parameters on `where` clauses are reserved for future use",
6183 .span_label(generics.span, "currently unsupported")
6189 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6190 let lifetime = self.expect_lifetime();
6191 // Bounds starting with a colon are mandatory, but possibly empty.
6192 self.expect(&token::Colon)?;
6193 let bounds = self.parse_lt_param_bounds();
6194 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6195 ast::WhereRegionPredicate {
6196 span: lo.to(self.prev_span),
6201 } else if self.check_type() {
6202 // Parse optional `for<'a, 'b>`.
6203 // This `for` is parsed greedily and applies to the whole predicate,
6204 // the bounded type can have its own `for` applying only to it.
6205 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6206 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6207 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6208 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6210 // Parse type with mandatory colon and (possibly empty) bounds,
6211 // or with mandatory equality sign and the second type.
6212 let ty = self.parse_ty()?;
6213 if self.eat(&token::Colon) {
6214 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6215 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6216 ast::WhereBoundPredicate {
6217 span: lo.to(self.prev_span),
6218 bound_generic_params: lifetime_defs,
6223 // FIXME: Decide what should be used here, `=` or `==`.
6224 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6225 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6226 let rhs_ty = self.parse_ty()?;
6227 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6228 ast::WhereEqPredicate {
6229 span: lo.to(self.prev_span),
6232 id: ast::DUMMY_NODE_ID,
6236 return self.unexpected();
6242 if !self.eat(&token::Comma) {
6247 where_clause.span = lo.to(self.prev_span);
6251 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6252 -> PResult<'a, (Vec<Arg> , bool)> {
6253 self.expect(&token::OpenDelim(token::Paren))?;
6256 let mut c_variadic = false;
6257 let (args, recovered): (Vec<Option<Arg>>, bool) =
6258 self.parse_seq_to_before_end(
6259 &token::CloseDelim(token::Paren),
6260 SeqSep::trailing_allowed(token::Comma),
6262 // If the argument is a C-variadic argument we should not
6263 // enforce named arguments.
6264 let enforce_named_args = if p.token == token::DotDotDot {
6269 match p.parse_arg_general(enforce_named_args, false,
6272 if let TyKind::CVarArgs = arg.ty.node {
6274 if p.token != token::CloseDelim(token::Paren) {
6277 "`...` must be the last argument of a C-variadic function");
6288 let lo = p.prev_span;
6289 // Skip every token until next possible arg or end.
6290 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6291 // Create a placeholder argument for proper arg count (issue #34264).
6292 let span = lo.to(p.prev_span);
6293 Ok(Some(dummy_arg(span)))
6300 self.eat(&token::CloseDelim(token::Paren));
6303 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6305 if c_variadic && args.is_empty() {
6307 "C-variadic function must be declared with at least one named argument");
6310 Ok((args, c_variadic))
6313 /// Parses the argument list and result type of a function declaration.
6314 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6316 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6317 let ret_ty = self.parse_ret_ty(true)?;
6326 /// Returns the parsed optional self argument and whether a self shortcut was used.
6327 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6328 let expect_ident = |this: &mut Self| match this.token {
6329 // Preserve hygienic context.
6330 token::Ident(ident, _) =>
6331 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6334 let isolated_self = |this: &mut Self, n| {
6335 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6336 this.look_ahead(n + 1, |t| t != &token::ModSep)
6339 // Parse optional self parameter of a method.
6340 // Only a limited set of initial token sequences is considered self parameters, anything
6341 // else is parsed as a normal function parameter list, so some lookahead is required.
6342 let eself_lo = self.span;
6343 let (eself, eself_ident, eself_hi) = match self.token {
6344 token::BinOp(token::And) => {
6350 (if isolated_self(self, 1) {
6352 SelfKind::Region(None, Mutability::Immutable)
6353 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6354 isolated_self(self, 2) {
6357 SelfKind::Region(None, Mutability::Mutable)
6358 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6359 isolated_self(self, 2) {
6361 let lt = self.expect_lifetime();
6362 SelfKind::Region(Some(lt), Mutability::Immutable)
6363 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6364 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6365 isolated_self(self, 3) {
6367 let lt = self.expect_lifetime();
6369 SelfKind::Region(Some(lt), Mutability::Mutable)
6372 }, expect_ident(self), self.prev_span)
6374 token::BinOp(token::Star) => {
6379 // Emit special error for `self` cases.
6380 let msg = "cannot pass `self` by raw pointer";
6381 (if isolated_self(self, 1) {
6383 self.struct_span_err(self.span, msg)
6384 .span_label(self.span, msg)
6386 SelfKind::Value(Mutability::Immutable)
6387 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6388 isolated_self(self, 2) {
6391 self.struct_span_err(self.span, msg)
6392 .span_label(self.span, msg)
6394 SelfKind::Value(Mutability::Immutable)
6397 }, expect_ident(self), self.prev_span)
6399 token::Ident(..) => {
6400 if isolated_self(self, 0) {
6403 let eself_ident = expect_ident(self);
6404 let eself_hi = self.prev_span;
6405 (if self.eat(&token::Colon) {
6406 let ty = self.parse_ty()?;
6407 SelfKind::Explicit(ty, Mutability::Immutable)
6409 SelfKind::Value(Mutability::Immutable)
6410 }, eself_ident, eself_hi)
6411 } else if self.token.is_keyword(keywords::Mut) &&
6412 isolated_self(self, 1) {
6416 let eself_ident = expect_ident(self);
6417 let eself_hi = self.prev_span;
6418 (if self.eat(&token::Colon) {
6419 let ty = self.parse_ty()?;
6420 SelfKind::Explicit(ty, Mutability::Mutable)
6422 SelfKind::Value(Mutability::Mutable)
6423 }, eself_ident, eself_hi)
6428 _ => return Ok(None),
6431 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6432 Ok(Some(Arg::from_self(eself, eself_ident)))
6435 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6436 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6437 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6439 self.expect(&token::OpenDelim(token::Paren))?;
6441 // Parse optional self argument
6442 let self_arg = self.parse_self_arg()?;
6444 // Parse the rest of the function parameter list.
6445 let sep = SeqSep::trailing_allowed(token::Comma);
6446 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6447 if self.check(&token::CloseDelim(token::Paren)) {
6448 (vec![self_arg], false)
6449 } else if self.eat(&token::Comma) {
6450 let mut fn_inputs = vec![self_arg];
6451 let (mut input, recovered) = self.parse_seq_to_before_end(
6452 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6453 fn_inputs.append(&mut input);
6454 (fn_inputs, recovered)
6456 match self.expect_one_of(&[], &[]) {
6457 Err(err) => return Err(err),
6458 Ok(recovered) => (vec![self_arg], recovered),
6462 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6466 // Parse closing paren and return type.
6467 self.expect(&token::CloseDelim(token::Paren))?;
6471 output: self.parse_ret_ty(true)?,
6476 /// Parses the `|arg, arg|` header of a closure.
6477 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6478 let inputs_captures = {
6479 if self.eat(&token::OrOr) {
6482 self.expect(&token::BinOp(token::Or))?;
6483 let args = self.parse_seq_to_before_tokens(
6484 &[&token::BinOp(token::Or), &token::OrOr],
6485 SeqSep::trailing_allowed(token::Comma),
6486 TokenExpectType::NoExpect,
6487 |p| p.parse_fn_block_arg()
6493 let output = self.parse_ret_ty(true)?;
6496 inputs: inputs_captures,
6502 /// Parses the name and optional generic types of a function header.
6503 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6504 let id = self.parse_ident()?;
6505 let generics = self.parse_generics()?;
6509 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6510 attrs: Vec<Attribute>) -> P<Item> {
6514 id: ast::DUMMY_NODE_ID,
6522 /// Parses an item-position function declaration.
6523 fn parse_item_fn(&mut self,
6525 mut asyncness: Spanned<IsAsync>,
6526 constness: Spanned<Constness>,
6528 -> PResult<'a, ItemInfo> {
6529 let (ident, mut generics) = self.parse_fn_header()?;
6530 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6531 let mut decl = self.parse_fn_decl(allow_c_variadic)?;
6532 generics.where_clause = self.parse_where_clause()?;
6533 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6534 self.construct_async_arguments(&mut asyncness, &mut decl);
6535 let header = FnHeader { unsafety, asyncness, constness, abi };
6536 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6539 /// Returns `true` if we are looking at `const ID`
6540 /// (returns `false` for things like `const fn`, etc.).
6541 fn is_const_item(&self) -> bool {
6542 self.token.is_keyword(keywords::Const) &&
6543 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6544 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6547 /// Parses all the "front matter" for a `fn` declaration, up to
6548 /// and including the `fn` keyword:
6552 /// - `const unsafe fn`
6555 fn parse_fn_front_matter(&mut self)
6563 let is_const_fn = self.eat_keyword(keywords::Const);
6564 let const_span = self.prev_span;
6565 let unsafety = self.parse_unsafety();
6566 let asyncness = self.parse_asyncness();
6567 let asyncness = respan(self.prev_span, asyncness);
6568 let (constness, unsafety, abi) = if is_const_fn {
6569 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6571 let abi = if self.eat_keyword(keywords::Extern) {
6572 self.parse_opt_abi()?.unwrap_or(Abi::C)
6576 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6578 if !self.eat_keyword(keywords::Fn) {
6579 // It is possible for `expect_one_of` to recover given the contents of
6580 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6581 // account for this.
6582 if !self.expect_one_of(&[], &[])? { unreachable!() }
6584 Ok((constness, unsafety, asyncness, abi))
6587 /// Parses an impl item.
6588 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6589 maybe_whole!(self, NtImplItem, |x| x);
6590 let attrs = self.parse_outer_attributes()?;
6591 let mut unclosed_delims = vec![];
6592 let (mut item, tokens) = self.collect_tokens(|this| {
6593 let item = this.parse_impl_item_(at_end, attrs);
6594 unclosed_delims.append(&mut this.unclosed_delims);
6597 self.unclosed_delims.append(&mut unclosed_delims);
6599 // See `parse_item` for why this clause is here.
6600 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6601 item.tokens = Some(tokens);
6606 fn parse_impl_item_(&mut self,
6608 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6610 let vis = self.parse_visibility(false)?;
6611 let defaultness = self.parse_defaultness();
6612 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6613 let (name, alias, generics) = type_?;
6614 let kind = match alias {
6615 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6616 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6618 (name, kind, generics)
6619 } else if self.is_const_item() {
6620 // This parses the grammar:
6621 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6622 self.expect_keyword(keywords::Const)?;
6623 let name = self.parse_ident()?;
6624 self.expect(&token::Colon)?;
6625 let typ = self.parse_ty()?;
6626 self.expect(&token::Eq)?;
6627 let expr = self.parse_expr()?;
6628 self.expect(&token::Semi)?;
6629 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6631 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6632 attrs.extend(inner_attrs);
6633 (name, node, generics)
6637 id: ast::DUMMY_NODE_ID,
6638 span: lo.to(self.prev_span),
6649 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
6651 VisibilityKind::Inherited => {}
6653 let is_macro_rules: bool = match self.token {
6654 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6657 let mut err = if is_macro_rules {
6658 let mut err = self.diagnostic()
6659 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6660 err.span_suggestion(
6662 "try exporting the macro",
6663 "#[macro_export]".to_owned(),
6664 Applicability::MaybeIncorrect // speculative
6668 let mut err = self.diagnostic()
6669 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6670 err.help("try adjusting the macro to put `pub` inside the invocation");
6678 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
6679 -> DiagnosticBuilder<'a>
6681 let expected_kinds = if item_type == "extern" {
6682 "missing `fn`, `type`, or `static`"
6684 "missing `fn`, `type`, or `const`"
6687 // Given this code `path(`, it seems like this is not
6688 // setting the visibility of a macro invocation, but rather
6689 // a mistyped method declaration.
6690 // Create a diagnostic pointing out that `fn` is missing.
6692 // x | pub path(&self) {
6693 // | ^ missing `fn`, `type`, or `const`
6695 // ^^ `sp` below will point to this
6696 let sp = prev_span.between(self.prev_span);
6697 let mut err = self.diagnostic().struct_span_err(
6699 &format!("{} for {}-item declaration",
6700 expected_kinds, item_type));
6701 err.span_label(sp, expected_kinds);
6705 /// Parse a method or a macro invocation in a trait impl.
6706 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6707 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6708 ast::ImplItemKind)> {
6709 // code copied from parse_macro_use_or_failure... abstraction!
6710 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6712 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6713 ast::ImplItemKind::Macro(mac)))
6715 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6716 let ident = self.parse_ident()?;
6717 let mut generics = self.parse_generics()?;
6718 let mut decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6719 generics.where_clause = self.parse_where_clause()?;
6720 self.construct_async_arguments(&mut asyncness, &mut decl);
6722 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6723 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6724 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6725 ast::MethodSig { header, decl },
6731 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6732 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6733 let ident = self.parse_ident()?;
6734 let mut tps = self.parse_generics()?;
6736 // Parse optional colon and supertrait bounds.
6737 let bounds = if self.eat(&token::Colon) {
6738 self.parse_generic_bounds(Some(self.prev_span))?
6743 if self.eat(&token::Eq) {
6744 // it's a trait alias
6745 let bounds = self.parse_generic_bounds(None)?;
6746 tps.where_clause = self.parse_where_clause()?;
6747 self.expect(&token::Semi)?;
6748 if is_auto == IsAuto::Yes {
6749 let msg = "trait aliases cannot be `auto`";
6750 self.struct_span_err(self.prev_span, msg)
6751 .span_label(self.prev_span, msg)
6754 if unsafety != Unsafety::Normal {
6755 let msg = "trait aliases cannot be `unsafe`";
6756 self.struct_span_err(self.prev_span, msg)
6757 .span_label(self.prev_span, msg)
6760 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6762 // it's a normal trait
6763 tps.where_clause = self.parse_where_clause()?;
6764 self.expect(&token::OpenDelim(token::Brace))?;
6765 let mut trait_items = vec![];
6766 while !self.eat(&token::CloseDelim(token::Brace)) {
6767 if let token::DocComment(_) = self.token {
6768 if self.look_ahead(1,
6769 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6770 let mut err = self.diagnostic().struct_span_err_with_code(
6772 "found a documentation comment that doesn't document anything",
6773 DiagnosticId::Error("E0584".into()),
6775 err.help("doc comments must come before what they document, maybe a \
6776 comment was intended with `//`?",
6783 let mut at_end = false;
6784 match self.parse_trait_item(&mut at_end) {
6785 Ok(item) => trait_items.push(item),
6789 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6794 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6798 fn choose_generics_over_qpath(&self) -> bool {
6799 // There's an ambiguity between generic parameters and qualified paths in impls.
6800 // If we see `<` it may start both, so we have to inspect some following tokens.
6801 // The following combinations can only start generics,
6802 // but not qualified paths (with one exception):
6803 // `<` `>` - empty generic parameters
6804 // `<` `#` - generic parameters with attributes
6805 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6806 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6807 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6808 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6809 // `<` const - generic const parameter
6810 // The only truly ambiguous case is
6811 // `<` IDENT `>` `::` IDENT ...
6812 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6813 // because this is what almost always expected in practice, qualified paths in impls
6814 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6815 self.token == token::Lt &&
6816 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6817 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6818 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6819 t == &token::Colon || t == &token::Eq) ||
6820 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6823 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6824 self.expect(&token::OpenDelim(token::Brace))?;
6825 let attrs = self.parse_inner_attributes()?;
6827 let mut impl_items = Vec::new();
6828 while !self.eat(&token::CloseDelim(token::Brace)) {
6829 let mut at_end = false;
6830 match self.parse_impl_item(&mut at_end) {
6831 Ok(impl_item) => impl_items.push(impl_item),
6835 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6840 Ok((impl_items, attrs))
6843 /// Parses an implementation item, `impl` keyword is already parsed.
6845 /// impl<'a, T> TYPE { /* impl items */ }
6846 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6847 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6849 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6850 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6851 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6852 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6853 -> PResult<'a, ItemInfo> {
6854 // First, parse generic parameters if necessary.
6855 let mut generics = if self.choose_generics_over_qpath() {
6856 self.parse_generics()?
6858 ast::Generics::default()
6861 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6862 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6864 ast::ImplPolarity::Negative
6866 ast::ImplPolarity::Positive
6869 // Parse both types and traits as a type, then reinterpret if necessary.
6870 let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6871 let ty_first = if self.token.is_keyword(keywords::For) &&
6872 self.look_ahead(1, |t| t != &token::Lt) {
6873 let span = self.prev_span.between(self.span);
6874 self.struct_span_err(span, "missing trait in a trait impl").emit();
6875 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6880 // If `for` is missing we try to recover.
6881 let has_for = self.eat_keyword(keywords::For);
6882 let missing_for_span = self.prev_span.between(self.span);
6884 let ty_second = if self.token == token::DotDot {
6885 // We need to report this error after `cfg` expansion for compatibility reasons
6886 self.bump(); // `..`, do not add it to expected tokens
6887 Some(DummyResult::raw_ty(self.prev_span, true))
6888 } else if has_for || self.token.can_begin_type() {
6889 Some(self.parse_ty()?)
6894 generics.where_clause = self.parse_where_clause()?;
6896 let (impl_items, attrs) = self.parse_impl_body()?;
6898 let item_kind = match ty_second {
6899 Some(ty_second) => {
6900 // impl Trait for Type
6902 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6903 .span_suggestion_short(
6906 " for ".to_string(),
6907 Applicability::MachineApplicable,
6911 let ty_first = ty_first.into_inner();
6912 let path = match ty_first.node {
6913 // This notably includes paths passed through `ty` macro fragments (#46438).
6914 TyKind::Path(None, path) => path,
6916 self.span_err(ty_first.span, "expected a trait, found type");
6917 err_path(ty_first.span)
6920 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6922 ItemKind::Impl(unsafety, polarity, defaultness,
6923 generics, Some(trait_ref), ty_second, impl_items)
6927 ItemKind::Impl(unsafety, polarity, defaultness,
6928 generics, None, ty_first, impl_items)
6932 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6935 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6936 if self.eat_keyword(keywords::For) {
6938 let params = self.parse_generic_params()?;
6940 // We rely on AST validation to rule out invalid cases: There must not be type
6941 // parameters, and the lifetime parameters must not have bounds.
6948 /// Parses `struct Foo { ... }`.
6949 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6950 let class_name = self.parse_ident()?;
6952 let mut generics = self.parse_generics()?;
6954 // There is a special case worth noting here, as reported in issue #17904.
6955 // If we are parsing a tuple struct it is the case that the where clause
6956 // should follow the field list. Like so:
6958 // struct Foo<T>(T) where T: Copy;
6960 // If we are parsing a normal record-style struct it is the case
6961 // that the where clause comes before the body, and after the generics.
6962 // So if we look ahead and see a brace or a where-clause we begin
6963 // parsing a record style struct.
6965 // Otherwise if we look ahead and see a paren we parse a tuple-style
6968 let vdata = if self.token.is_keyword(keywords::Where) {
6969 generics.where_clause = self.parse_where_clause()?;
6970 if self.eat(&token::Semi) {
6971 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6972 VariantData::Unit(ast::DUMMY_NODE_ID)
6974 // If we see: `struct Foo<T> where T: Copy { ... }`
6975 let (fields, recovered) = self.parse_record_struct_body()?;
6976 VariantData::Struct(fields, recovered)
6978 // No `where` so: `struct Foo<T>;`
6979 } else if self.eat(&token::Semi) {
6980 VariantData::Unit(ast::DUMMY_NODE_ID)
6981 // Record-style struct definition
6982 } else if self.token == token::OpenDelim(token::Brace) {
6983 let (fields, recovered) = self.parse_record_struct_body()?;
6984 VariantData::Struct(fields, recovered)
6985 // Tuple-style struct definition with optional where-clause.
6986 } else if self.token == token::OpenDelim(token::Paren) {
6987 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6988 generics.where_clause = self.parse_where_clause()?;
6989 self.expect(&token::Semi)?;
6992 let token_str = self.this_token_descr();
6993 let mut err = self.fatal(&format!(
6994 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6997 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
7001 Ok((class_name, ItemKind::Struct(vdata, generics), None))
7004 /// Parses `union Foo { ... }`.
7005 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
7006 let class_name = self.parse_ident()?;
7008 let mut generics = self.parse_generics()?;
7010 let vdata = if self.token.is_keyword(keywords::Where) {
7011 generics.where_clause = self.parse_where_clause()?;
7012 let (fields, recovered) = self.parse_record_struct_body()?;
7013 VariantData::Struct(fields, recovered)
7014 } else if self.token == token::OpenDelim(token::Brace) {
7015 let (fields, recovered) = self.parse_record_struct_body()?;
7016 VariantData::Struct(fields, recovered)
7018 let token_str = self.this_token_descr();
7019 let mut err = self.fatal(&format!(
7020 "expected `where` or `{{` after union name, found {}", token_str));
7021 err.span_label(self.span, "expected `where` or `{` after union name");
7025 Ok((class_name, ItemKind::Union(vdata, generics), None))
7028 fn consume_block(&mut self, delim: token::DelimToken) {
7029 let mut brace_depth = 0;
7031 if self.eat(&token::OpenDelim(delim)) {
7033 } else if self.eat(&token::CloseDelim(delim)) {
7034 if brace_depth == 0 {
7040 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
7048 fn parse_record_struct_body(
7050 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
7051 let mut fields = Vec::new();
7052 let mut recovered = false;
7053 if self.eat(&token::OpenDelim(token::Brace)) {
7054 while self.token != token::CloseDelim(token::Brace) {
7055 let field = self.parse_struct_decl_field().map_err(|e| {
7056 self.recover_stmt();
7061 Ok(field) => fields.push(field),
7067 self.eat(&token::CloseDelim(token::Brace));
7069 let token_str = self.this_token_descr();
7070 let mut err = self.fatal(&format!(
7071 "expected `where`, or `{{` after struct name, found {}", token_str));
7072 err.span_label(self.span, "expected `where`, or `{` after struct name");
7076 Ok((fields, recovered))
7079 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
7080 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
7081 // Unit like structs are handled in parse_item_struct function
7082 let fields = self.parse_unspanned_seq(
7083 &token::OpenDelim(token::Paren),
7084 &token::CloseDelim(token::Paren),
7085 SeqSep::trailing_allowed(token::Comma),
7087 let attrs = p.parse_outer_attributes()?;
7089 let vis = p.parse_visibility(true)?;
7090 let ty = p.parse_ty()?;
7092 span: lo.to(ty.span),
7095 id: ast::DUMMY_NODE_ID,
7104 /// Parses a structure field declaration.
7105 fn parse_single_struct_field(&mut self,
7108 attrs: Vec<Attribute> )
7109 -> PResult<'a, StructField> {
7110 let mut seen_comma: bool = false;
7111 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
7112 if self.token == token::Comma {
7119 token::CloseDelim(token::Brace) => {}
7120 token::DocComment(_) => {
7121 let previous_span = self.prev_span;
7122 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
7123 self.bump(); // consume the doc comment
7124 let comma_after_doc_seen = self.eat(&token::Comma);
7125 // `seen_comma` is always false, because we are inside doc block
7126 // condition is here to make code more readable
7127 if seen_comma == false && comma_after_doc_seen == true {
7130 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7133 if seen_comma == false {
7134 let sp = self.sess.source_map().next_point(previous_span);
7135 err.span_suggestion(
7137 "missing comma here",
7139 Applicability::MachineApplicable
7146 let sp = self.sess.source_map().next_point(self.prev_span);
7147 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7148 self.this_token_descr()));
7149 if self.token.is_ident() {
7150 // This is likely another field; emit the diagnostic and keep going
7151 err.span_suggestion(
7153 "try adding a comma",
7155 Applicability::MachineApplicable,
7166 /// Parses an element of a struct declaration.
7167 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7168 let attrs = self.parse_outer_attributes()?;
7170 let vis = self.parse_visibility(false)?;
7171 self.parse_single_struct_field(lo, vis, attrs)
7174 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7175 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7176 /// If the following element can't be a tuple (i.e., it's a function definition), then
7177 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7178 /// so emit a proper diagnostic.
7179 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7180 maybe_whole!(self, NtVis, |x| x);
7182 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7183 if self.is_crate_vis() {
7184 self.bump(); // `crate`
7185 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7188 if !self.eat_keyword(keywords::Pub) {
7189 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7190 // keyword to grab a span from for inherited visibility; an empty span at the
7191 // beginning of the current token would seem to be the "Schelling span".
7192 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7194 let lo = self.prev_span;
7196 if self.check(&token::OpenDelim(token::Paren)) {
7197 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7198 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7199 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7200 // by the following tokens.
7201 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) &&
7202 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
7206 self.bump(); // `crate`
7207 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7209 lo.to(self.prev_span),
7210 VisibilityKind::Crate(CrateSugar::PubCrate),
7213 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7216 self.bump(); // `in`
7217 let path = self.parse_path(PathStyle::Mod)?; // `path`
7218 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7219 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7221 id: ast::DUMMY_NODE_ID,
7224 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7225 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7226 t.is_keyword(keywords::SelfLower))
7228 // `pub(self)` or `pub(super)`
7230 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7231 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7232 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7234 id: ast::DUMMY_NODE_ID,
7237 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7238 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7240 let msg = "incorrect visibility restriction";
7241 let suggestion = r##"some possible visibility restrictions are:
7242 `pub(crate)`: visible only on the current crate
7243 `pub(super)`: visible only in the current module's parent
7244 `pub(in path::to::module)`: visible only on the specified path"##;
7245 let path = self.parse_path(PathStyle::Mod)?;
7247 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7248 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7249 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7250 err.help(suggestion);
7251 err.span_suggestion(
7252 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7254 err.emit(); // emit diagnostic, but continue with public visibility
7258 Ok(respan(lo, VisibilityKind::Public))
7261 /// Parses defaultness (i.e., `default` or nothing).
7262 fn parse_defaultness(&mut self) -> Defaultness {
7263 // `pub` is included for better error messages
7264 if self.check_keyword(keywords::Default) &&
7265 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7266 t.is_keyword(keywords::Const) ||
7267 t.is_keyword(keywords::Fn) ||
7268 t.is_keyword(keywords::Unsafe) ||
7269 t.is_keyword(keywords::Extern) ||
7270 t.is_keyword(keywords::Type) ||
7271 t.is_keyword(keywords::Pub)) {
7272 self.bump(); // `default`
7273 Defaultness::Default
7279 /// Given a termination token, parses all of the items in a module.
7280 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7281 let mut items = vec![];
7282 while let Some(item) = self.parse_item()? {
7284 self.maybe_consume_incorrect_semicolon(&items);
7287 if !self.eat(term) {
7288 let token_str = self.this_token_descr();
7289 if !self.maybe_consume_incorrect_semicolon(&items) {
7290 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7291 err.span_label(self.span, "expected item");
7296 let hi = if self.span.is_dummy() {
7303 inner: inner_lo.to(hi),
7309 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7310 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7311 self.expect(&token::Colon)?;
7312 let ty = self.parse_ty()?;
7313 self.expect(&token::Eq)?;
7314 let e = self.parse_expr()?;
7315 self.expect(&token::Semi)?;
7316 let item = match m {
7317 Some(m) => ItemKind::Static(ty, m, e),
7318 None => ItemKind::Const(ty, e),
7320 Ok((id, item, None))
7323 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7324 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7325 let (in_cfg, outer_attrs) = {
7326 let mut strip_unconfigured = crate::config::StripUnconfigured {
7328 features: None, // don't perform gated feature checking
7330 let mut outer_attrs = outer_attrs.to_owned();
7331 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7332 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7335 let id_span = self.span;
7336 let id = self.parse_ident()?;
7337 if self.eat(&token::Semi) {
7338 if in_cfg && self.recurse_into_file_modules {
7339 // This mod is in an external file. Let's go get it!
7340 let ModulePathSuccess { path, directory_ownership, warn } =
7341 self.submod_path(id, &outer_attrs, id_span)?;
7342 let (module, mut attrs) =
7343 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7344 // Record that we fetched the mod from an external file
7346 let attr = Attribute {
7347 id: attr::mk_attr_id(),
7348 style: ast::AttrStyle::Outer,
7349 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7350 tokens: TokenStream::empty(),
7351 is_sugared_doc: false,
7352 span: syntax_pos::DUMMY_SP,
7354 attr::mark_known(&attr);
7357 Ok((id, ItemKind::Mod(module), Some(attrs)))
7359 let placeholder = ast::Mod {
7360 inner: syntax_pos::DUMMY_SP,
7364 Ok((id, ItemKind::Mod(placeholder), None))
7367 let old_directory = self.directory.clone();
7368 self.push_directory(id, &outer_attrs);
7370 self.expect(&token::OpenDelim(token::Brace))?;
7371 let mod_inner_lo = self.span;
7372 let attrs = self.parse_inner_attributes()?;
7373 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7375 self.directory = old_directory;
7376 Ok((id, ItemKind::Mod(module), Some(attrs)))
7380 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7381 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7382 self.directory.path.to_mut().push(&path.as_str());
7383 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7385 // We have to push on the current module name in the case of relative
7386 // paths in order to ensure that any additional module paths from inline
7387 // `mod x { ... }` come after the relative extension.
7389 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7390 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7391 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7392 if let Some(ident) = relative.take() { // remove the relative offset
7393 self.directory.path.to_mut().push(ident.as_str());
7396 self.directory.path.to_mut().push(&id.as_str());
7400 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7401 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7404 // On windows, the base path might have the form
7405 // `\\?\foo\bar` in which case it does not tolerate
7406 // mixed `/` and `\` separators, so canonicalize
7409 let s = s.replace("/", "\\");
7410 Some(dir_path.join(s))
7416 /// Returns a path to a module.
7417 pub fn default_submod_path(
7419 relative: Option<ast::Ident>,
7421 source_map: &SourceMap) -> ModulePath
7423 // If we're in a foo.rs file instead of a mod.rs file,
7424 // we need to look for submodules in
7425 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7426 // `./<id>.rs` and `./<id>/mod.rs`.
7427 let relative_prefix_string;
7428 let relative_prefix = if let Some(ident) = relative {
7429 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7430 &relative_prefix_string
7435 let mod_name = id.to_string();
7436 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7437 let secondary_path_str = format!("{}{}{}mod.rs",
7438 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7439 let default_path = dir_path.join(&default_path_str);
7440 let secondary_path = dir_path.join(&secondary_path_str);
7441 let default_exists = source_map.file_exists(&default_path);
7442 let secondary_exists = source_map.file_exists(&secondary_path);
7444 let result = match (default_exists, secondary_exists) {
7445 (true, false) => Ok(ModulePathSuccess {
7447 directory_ownership: DirectoryOwnership::Owned {
7452 (false, true) => Ok(ModulePathSuccess {
7453 path: secondary_path,
7454 directory_ownership: DirectoryOwnership::Owned {
7459 (false, false) => Err(Error::FileNotFoundForModule {
7460 mod_name: mod_name.clone(),
7461 default_path: default_path_str,
7462 secondary_path: secondary_path_str,
7463 dir_path: dir_path.display().to_string(),
7465 (true, true) => Err(Error::DuplicatePaths {
7466 mod_name: mod_name.clone(),
7467 default_path: default_path_str,
7468 secondary_path: secondary_path_str,
7474 path_exists: default_exists || secondary_exists,
7479 fn submod_path(&mut self,
7481 outer_attrs: &[Attribute],
7483 -> PResult<'a, ModulePathSuccess> {
7484 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7485 return Ok(ModulePathSuccess {
7486 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7487 // All `#[path]` files are treated as though they are a `mod.rs` file.
7488 // This means that `mod foo;` declarations inside `#[path]`-included
7489 // files are siblings,
7491 // Note that this will produce weirdness when a file named `foo.rs` is
7492 // `#[path]` included and contains a `mod foo;` declaration.
7493 // If you encounter this, it's your own darn fault :P
7494 Some(_) => DirectoryOwnership::Owned { relative: None },
7495 _ => DirectoryOwnership::UnownedViaMod(true),
7502 let relative = match self.directory.ownership {
7503 DirectoryOwnership::Owned { relative } => relative,
7504 DirectoryOwnership::UnownedViaBlock |
7505 DirectoryOwnership::UnownedViaMod(_) => None,
7507 let paths = Parser::default_submod_path(
7508 id, relative, &self.directory.path, self.sess.source_map());
7510 match self.directory.ownership {
7511 DirectoryOwnership::Owned { .. } => {
7512 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7514 DirectoryOwnership::UnownedViaBlock => {
7516 "Cannot declare a non-inline module inside a block \
7517 unless it has a path attribute";
7518 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7519 if paths.path_exists {
7520 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7522 err.span_note(id_sp, &msg);
7526 DirectoryOwnership::UnownedViaMod(warn) => {
7528 if let Ok(result) = paths.result {
7529 return Ok(ModulePathSuccess { warn: true, ..result });
7532 let mut err = self.diagnostic().struct_span_err(id_sp,
7533 "cannot declare a new module at this location");
7534 if !id_sp.is_dummy() {
7535 let src_path = self.sess.source_map().span_to_filename(id_sp);
7536 if let FileName::Real(src_path) = src_path {
7537 if let Some(stem) = src_path.file_stem() {
7538 let mut dest_path = src_path.clone();
7539 dest_path.set_file_name(stem);
7540 dest_path.push("mod.rs");
7541 err.span_note(id_sp,
7542 &format!("maybe move this module `{}` to its own \
7543 directory via `{}`", src_path.display(),
7544 dest_path.display()));
7548 if paths.path_exists {
7549 err.span_note(id_sp,
7550 &format!("... or maybe `use` the module `{}` instead \
7551 of possibly redeclaring it",
7559 /// Reads a module from a source file.
7560 fn eval_src_mod(&mut self,
7562 directory_ownership: DirectoryOwnership,
7565 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7566 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7567 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7568 let mut err = String::from("circular modules: ");
7569 let len = included_mod_stack.len();
7570 for p in &included_mod_stack[i.. len] {
7571 err.push_str(&p.to_string_lossy());
7572 err.push_str(" -> ");
7574 err.push_str(&path.to_string_lossy());
7575 return Err(self.span_fatal(id_sp, &err[..]));
7577 included_mod_stack.push(path.clone());
7578 drop(included_mod_stack);
7581 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7582 p0.cfg_mods = self.cfg_mods;
7583 let mod_inner_lo = p0.span;
7584 let mod_attrs = p0.parse_inner_attributes()?;
7585 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7587 self.sess.included_mod_stack.borrow_mut().pop();
7591 /// Parses a function declaration from a foreign module.
7592 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7593 -> PResult<'a, ForeignItem> {
7594 self.expect_keyword(keywords::Fn)?;
7596 let (ident, mut generics) = self.parse_fn_header()?;
7597 let decl = self.parse_fn_decl(true)?;
7598 generics.where_clause = self.parse_where_clause()?;
7600 self.expect(&token::Semi)?;
7601 Ok(ast::ForeignItem {
7604 node: ForeignItemKind::Fn(decl, generics),
7605 id: ast::DUMMY_NODE_ID,
7611 /// Parses a static item from a foreign module.
7612 /// Assumes that the `static` keyword is already parsed.
7613 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7614 -> PResult<'a, ForeignItem> {
7615 let mutbl = self.parse_mutability();
7616 let ident = self.parse_ident()?;
7617 self.expect(&token::Colon)?;
7618 let ty = self.parse_ty()?;
7620 self.expect(&token::Semi)?;
7624 node: ForeignItemKind::Static(ty, mutbl),
7625 id: ast::DUMMY_NODE_ID,
7631 /// Parses a type from a foreign module.
7632 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7633 -> PResult<'a, ForeignItem> {
7634 self.expect_keyword(keywords::Type)?;
7636 let ident = self.parse_ident()?;
7638 self.expect(&token::Semi)?;
7639 Ok(ast::ForeignItem {
7642 node: ForeignItemKind::Ty,
7643 id: ast::DUMMY_NODE_ID,
7649 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7650 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7651 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7653 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7654 self.parse_path_segment_ident()
7658 let mut idents = vec![];
7659 let mut replacement = vec![];
7660 let mut fixed_crate_name = false;
7661 // Accept `extern crate name-like-this` for better diagnostics
7662 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7663 if self.token == dash { // Do not include `-` as part of the expected tokens list
7664 while self.eat(&dash) {
7665 fixed_crate_name = true;
7666 replacement.push((self.prev_span, "_".to_string()));
7667 idents.push(self.parse_ident()?);
7670 if fixed_crate_name {
7671 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7672 let mut fixed_name = format!("{}", ident.name);
7673 for part in idents {
7674 fixed_name.push_str(&format!("_{}", part.name));
7676 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7678 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7679 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7680 err.multipart_suggestion(
7683 Applicability::MachineApplicable,
7690 /// Parses `extern crate` links.
7695 /// extern crate foo;
7696 /// extern crate bar as foo;
7698 fn parse_item_extern_crate(&mut self,
7700 visibility: Visibility,
7701 attrs: Vec<Attribute>)
7702 -> PResult<'a, P<Item>> {
7703 // Accept `extern crate name-like-this` for better diagnostics
7704 let orig_name = self.parse_crate_name_with_dashes()?;
7705 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7706 (rename, Some(orig_name.name))
7710 self.expect(&token::Semi)?;
7712 let span = lo.to(self.prev_span);
7713 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7716 /// Parses `extern` for foreign ABIs modules.
7718 /// `extern` is expected to have been
7719 /// consumed before calling this method.
7723 /// ```ignore (only-for-syntax-highlight)
7727 fn parse_item_foreign_mod(&mut self,
7729 opt_abi: Option<Abi>,
7730 visibility: Visibility,
7731 mut attrs: Vec<Attribute>)
7732 -> PResult<'a, P<Item>> {
7733 self.expect(&token::OpenDelim(token::Brace))?;
7735 let abi = opt_abi.unwrap_or(Abi::C);
7737 attrs.extend(self.parse_inner_attributes()?);
7739 let mut foreign_items = vec![];
7740 while !self.eat(&token::CloseDelim(token::Brace)) {
7741 foreign_items.push(self.parse_foreign_item()?);
7744 let prev_span = self.prev_span;
7745 let m = ast::ForeignMod {
7747 items: foreign_items
7749 let invalid = keywords::Invalid.ident();
7750 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7753 /// Parses `type Foo = Bar;`
7755 /// `existential type Foo: Bar;`
7758 /// without modifying the parser state.
7759 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7760 // This parses the grammar:
7761 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7762 if self.check_keyword(keywords::Type) ||
7763 self.check_keyword(keywords::Existential) &&
7764 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7765 let existential = self.eat_keyword(keywords::Existential);
7766 assert!(self.eat_keyword(keywords::Type));
7767 Some(self.parse_existential_or_alias(existential))
7773 /// Parses a type alias or existential type.
7774 fn parse_existential_or_alias(
7777 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7778 let ident = self.parse_ident()?;
7779 let mut tps = self.parse_generics()?;
7780 tps.where_clause = self.parse_where_clause()?;
7781 let alias = if existential {
7782 self.expect(&token::Colon)?;
7783 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7784 AliasKind::Existential(bounds)
7786 self.expect(&token::Eq)?;
7787 let ty = self.parse_ty()?;
7790 self.expect(&token::Semi)?;
7791 Ok((ident, alias, tps))
7794 /// Parses the part of an enum declaration following the `{`.
7795 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7796 let mut variants = Vec::new();
7797 let mut all_nullary = true;
7798 let mut any_disr = vec![];
7799 while self.token != token::CloseDelim(token::Brace) {
7800 let variant_attrs = self.parse_outer_attributes()?;
7801 let vlo = self.span;
7804 let mut disr_expr = None;
7806 let ident = self.parse_ident()?;
7807 if self.check(&token::OpenDelim(token::Brace)) {
7808 // Parse a struct variant.
7809 all_nullary = false;
7810 let (fields, recovered) = self.parse_record_struct_body()?;
7811 struct_def = VariantData::Struct(fields, recovered);
7812 } else if self.check(&token::OpenDelim(token::Paren)) {
7813 all_nullary = false;
7814 struct_def = VariantData::Tuple(
7815 self.parse_tuple_struct_body()?,
7818 } else if self.eat(&token::Eq) {
7819 disr_expr = Some(AnonConst {
7820 id: ast::DUMMY_NODE_ID,
7821 value: self.parse_expr()?,
7823 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7826 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7828 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7831 let vr = ast::Variant_ {
7833 id: ast::DUMMY_NODE_ID,
7834 attrs: variant_attrs,
7838 variants.push(respan(vlo.to(self.prev_span), vr));
7840 if !self.eat(&token::Comma) {
7841 if self.token.is_ident() && !self.token.is_reserved_ident() {
7842 let sp = self.sess.source_map().next_point(self.prev_span);
7843 let mut err = self.struct_span_err(sp, "missing comma");
7844 err.span_suggestion_short(
7848 Applicability::MaybeIncorrect,
7856 self.expect(&token::CloseDelim(token::Brace))?;
7857 if !any_disr.is_empty() && !all_nullary {
7858 let mut err = self.struct_span_err(
7860 "discriminator values can only be used with a field-less enum",
7862 for sp in any_disr {
7863 err.span_label(sp, "only valid in field-less enums");
7868 Ok(ast::EnumDef { variants })
7871 /// Parses an enum declaration.
7872 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7873 let id = self.parse_ident()?;
7874 let mut generics = self.parse_generics()?;
7875 generics.where_clause = self.parse_where_clause()?;
7876 self.expect(&token::OpenDelim(token::Brace))?;
7878 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7879 self.recover_stmt();
7880 self.eat(&token::CloseDelim(token::Brace));
7883 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7886 /// Parses a string as an ABI spec on an extern type or module. Consumes
7887 /// the `extern` keyword, if one is found.
7888 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7890 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7892 self.expect_no_suffix(sp, "an ABI spec", suf);
7894 match abi::lookup(&s.as_str()) {
7895 Some(abi) => Ok(Some(abi)),
7897 let prev_span = self.prev_span;
7898 let mut err = struct_span_err!(
7899 self.sess.span_diagnostic,
7902 "invalid ABI: found `{}`",
7904 err.span_label(prev_span, "invalid ABI");
7905 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7916 fn is_static_global(&mut self) -> bool {
7917 if self.check_keyword(keywords::Static) {
7918 // Check if this could be a closure
7919 !self.look_ahead(1, |token| {
7920 if token.is_keyword(keywords::Move) {
7924 token::BinOp(token::Or) | token::OrOr => true,
7935 attrs: Vec<Attribute>,
7936 macros_allowed: bool,
7937 attributes_allowed: bool,
7938 ) -> PResult<'a, Option<P<Item>>> {
7939 let mut unclosed_delims = vec![];
7940 let (ret, tokens) = self.collect_tokens(|this| {
7941 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7942 unclosed_delims.append(&mut this.unclosed_delims);
7945 self.unclosed_delims.append(&mut unclosed_delims);
7947 // Once we've parsed an item and recorded the tokens we got while
7948 // parsing we may want to store `tokens` into the item we're about to
7949 // return. Note, though, that we specifically didn't capture tokens
7950 // related to outer attributes. The `tokens` field here may later be
7951 // used with procedural macros to convert this item back into a token
7952 // stream, but during expansion we may be removing attributes as we go
7955 // If we've got inner attributes then the `tokens` we've got above holds
7956 // these inner attributes. If an inner attribute is expanded we won't
7957 // actually remove it from the token stream, so we'll just keep yielding
7958 // it (bad!). To work around this case for now we just avoid recording
7959 // `tokens` if we detect any inner attributes. This should help keep
7960 // expansion correct, but we should fix this bug one day!
7963 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7964 i.tokens = Some(tokens);
7971 /// Parses one of the items allowed by the flags.
7972 fn parse_item_implementation(
7974 attrs: Vec<Attribute>,
7975 macros_allowed: bool,
7976 attributes_allowed: bool,
7977 ) -> PResult<'a, Option<P<Item>>> {
7978 maybe_whole!(self, NtItem, |item| {
7979 let mut item = item.into_inner();
7980 let mut attrs = attrs;
7981 mem::swap(&mut item.attrs, &mut attrs);
7982 item.attrs.extend(attrs);
7988 let visibility = self.parse_visibility(false)?;
7990 if self.eat_keyword(keywords::Use) {
7992 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7993 self.expect(&token::Semi)?;
7995 let span = lo.to(self.prev_span);
7996 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7997 return Ok(Some(item));
8000 if self.eat_keyword(keywords::Extern) {
8001 if self.eat_keyword(keywords::Crate) {
8002 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
8005 let opt_abi = self.parse_opt_abi()?;
8007 if self.eat_keyword(keywords::Fn) {
8008 // EXTERN FUNCTION ITEM
8009 let fn_span = self.prev_span;
8010 let abi = opt_abi.unwrap_or(Abi::C);
8011 let (ident, item_, extra_attrs) =
8012 self.parse_item_fn(Unsafety::Normal,
8013 respan(fn_span, IsAsync::NotAsync),
8014 respan(fn_span, Constness::NotConst),
8016 let prev_span = self.prev_span;
8017 let item = self.mk_item(lo.to(prev_span),
8021 maybe_append(attrs, extra_attrs));
8022 return Ok(Some(item));
8023 } else if self.check(&token::OpenDelim(token::Brace)) {
8024 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
8030 if self.is_static_global() {
8033 let m = if self.eat_keyword(keywords::Mut) {
8036 Mutability::Immutable
8038 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
8039 let prev_span = self.prev_span;
8040 let item = self.mk_item(lo.to(prev_span),
8044 maybe_append(attrs, extra_attrs));
8045 return Ok(Some(item));
8047 if self.eat_keyword(keywords::Const) {
8048 let const_span = self.prev_span;
8049 if self.check_keyword(keywords::Fn)
8050 || (self.check_keyword(keywords::Unsafe)
8051 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
8052 // CONST FUNCTION ITEM
8053 let unsafety = self.parse_unsafety();
8055 let (ident, item_, extra_attrs) =
8056 self.parse_item_fn(unsafety,
8057 respan(const_span, IsAsync::NotAsync),
8058 respan(const_span, Constness::Const),
8060 let prev_span = self.prev_span;
8061 let item = self.mk_item(lo.to(prev_span),
8065 maybe_append(attrs, extra_attrs));
8066 return Ok(Some(item));
8070 if self.eat_keyword(keywords::Mut) {
8071 let prev_span = self.prev_span;
8072 let mut err = self.diagnostic()
8073 .struct_span_err(prev_span, "const globals cannot be mutable");
8074 err.span_label(prev_span, "cannot be mutable");
8075 err.span_suggestion(
8077 "you might want to declare a static instead",
8078 "static".to_owned(),
8079 Applicability::MaybeIncorrect,
8083 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
8084 let prev_span = self.prev_span;
8085 let item = self.mk_item(lo.to(prev_span),
8089 maybe_append(attrs, extra_attrs));
8090 return Ok(Some(item));
8093 // `unsafe async fn` or `async fn`
8095 self.check_keyword(keywords::Unsafe) &&
8096 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
8098 self.check_keyword(keywords::Async) &&
8099 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
8102 // ASYNC FUNCTION ITEM
8103 let unsafety = self.parse_unsafety();
8104 self.expect_keyword(keywords::Async)?;
8105 let async_span = self.prev_span;
8106 self.expect_keyword(keywords::Fn)?;
8107 let fn_span = self.prev_span;
8108 let (ident, item_, extra_attrs) =
8109 self.parse_item_fn(unsafety,
8110 respan(async_span, IsAsync::Async {
8111 closure_id: ast::DUMMY_NODE_ID,
8112 return_impl_trait_id: ast::DUMMY_NODE_ID,
8113 arguments: Vec::new(),
8115 respan(fn_span, Constness::NotConst),
8117 let prev_span = self.prev_span;
8118 let item = self.mk_item(lo.to(prev_span),
8122 maybe_append(attrs, extra_attrs));
8123 if self.span.rust_2015() {
8124 self.diagnostic().struct_span_err_with_code(
8126 "`async fn` is not permitted in the 2015 edition",
8127 DiagnosticId::Error("E0670".into())
8130 return Ok(Some(item));
8132 if self.check_keyword(keywords::Unsafe) &&
8133 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8134 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8136 // UNSAFE TRAIT ITEM
8137 self.bump(); // `unsafe`
8138 let is_auto = if self.eat_keyword(keywords::Trait) {
8141 self.expect_keyword(keywords::Auto)?;
8142 self.expect_keyword(keywords::Trait)?;
8145 let (ident, item_, extra_attrs) =
8146 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8147 let prev_span = self.prev_span;
8148 let item = self.mk_item(lo.to(prev_span),
8152 maybe_append(attrs, extra_attrs));
8153 return Ok(Some(item));
8155 if self.check_keyword(keywords::Impl) ||
8156 self.check_keyword(keywords::Unsafe) &&
8157 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8158 self.check_keyword(keywords::Default) &&
8159 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8160 self.check_keyword(keywords::Default) &&
8161 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8163 let defaultness = self.parse_defaultness();
8164 let unsafety = self.parse_unsafety();
8165 self.expect_keyword(keywords::Impl)?;
8166 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8167 let span = lo.to(self.prev_span);
8168 return Ok(Some(self.mk_item(span, ident, item, visibility,
8169 maybe_append(attrs, extra_attrs))));
8171 if self.check_keyword(keywords::Fn) {
8174 let fn_span = self.prev_span;
8175 let (ident, item_, extra_attrs) =
8176 self.parse_item_fn(Unsafety::Normal,
8177 respan(fn_span, IsAsync::NotAsync),
8178 respan(fn_span, Constness::NotConst),
8180 let prev_span = self.prev_span;
8181 let item = self.mk_item(lo.to(prev_span),
8185 maybe_append(attrs, extra_attrs));
8186 return Ok(Some(item));
8188 if self.check_keyword(keywords::Unsafe)
8189 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8190 // UNSAFE FUNCTION ITEM
8191 self.bump(); // `unsafe`
8192 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8193 self.check(&token::OpenDelim(token::Brace));
8194 let abi = if self.eat_keyword(keywords::Extern) {
8195 self.parse_opt_abi()?.unwrap_or(Abi::C)
8199 self.expect_keyword(keywords::Fn)?;
8200 let fn_span = self.prev_span;
8201 let (ident, item_, extra_attrs) =
8202 self.parse_item_fn(Unsafety::Unsafe,
8203 respan(fn_span, IsAsync::NotAsync),
8204 respan(fn_span, Constness::NotConst),
8206 let prev_span = self.prev_span;
8207 let item = self.mk_item(lo.to(prev_span),
8211 maybe_append(attrs, extra_attrs));
8212 return Ok(Some(item));
8214 if self.eat_keyword(keywords::Mod) {
8216 let (ident, item_, extra_attrs) =
8217 self.parse_item_mod(&attrs[..])?;
8218 let prev_span = self.prev_span;
8219 let item = self.mk_item(lo.to(prev_span),
8223 maybe_append(attrs, extra_attrs));
8224 return Ok(Some(item));
8226 if let Some(type_) = self.eat_type() {
8227 let (ident, alias, generics) = type_?;
8229 let item_ = match alias {
8230 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8231 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8233 let prev_span = self.prev_span;
8234 let item = self.mk_item(lo.to(prev_span),
8239 return Ok(Some(item));
8241 if self.eat_keyword(keywords::Enum) {
8243 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8244 let prev_span = self.prev_span;
8245 let item = self.mk_item(lo.to(prev_span),
8249 maybe_append(attrs, extra_attrs));
8250 return Ok(Some(item));
8252 if self.check_keyword(keywords::Trait)
8253 || (self.check_keyword(keywords::Auto)
8254 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8256 let is_auto = if self.eat_keyword(keywords::Trait) {
8259 self.expect_keyword(keywords::Auto)?;
8260 self.expect_keyword(keywords::Trait)?;
8264 let (ident, item_, extra_attrs) =
8265 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8266 let prev_span = self.prev_span;
8267 let item = self.mk_item(lo.to(prev_span),
8271 maybe_append(attrs, extra_attrs));
8272 return Ok(Some(item));
8274 if self.eat_keyword(keywords::Struct) {
8276 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8277 let prev_span = self.prev_span;
8278 let item = self.mk_item(lo.to(prev_span),
8282 maybe_append(attrs, extra_attrs));
8283 return Ok(Some(item));
8285 if self.is_union_item() {
8288 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8289 let prev_span = self.prev_span;
8290 let item = self.mk_item(lo.to(prev_span),
8294 maybe_append(attrs, extra_attrs));
8295 return Ok(Some(item));
8297 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8298 return Ok(Some(macro_def));
8301 // Verify whether we have encountered a struct or method definition where the user forgot to
8302 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8303 if visibility.node.is_pub() &&
8304 self.check_ident() &&
8305 self.look_ahead(1, |t| *t != token::Not)
8307 // Space between `pub` keyword and the identifier
8310 // ^^^ `sp` points here
8311 let sp = self.prev_span.between(self.span);
8312 let full_sp = self.prev_span.to(self.span);
8313 let ident_sp = self.span;
8314 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8315 // possible public struct definition where `struct` was forgotten
8316 let ident = self.parse_ident().unwrap();
8317 let msg = format!("add `struct` here to parse `{}` as a public struct",
8319 let mut err = self.diagnostic()
8320 .struct_span_err(sp, "missing `struct` for struct definition");
8321 err.span_suggestion_short(
8322 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8325 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8326 let ident = self.parse_ident().unwrap();
8328 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8333 self.consume_block(token::Paren);
8334 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8335 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8337 ("fn", kw_name, false)
8338 } else if self.check(&token::OpenDelim(token::Brace)) {
8340 ("fn", kw_name, false)
8341 } else if self.check(&token::Colon) {
8345 ("fn` or `struct", "function or struct", true)
8348 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8349 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8351 self.consume_block(token::Brace);
8352 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8356 err.span_suggestion_short(
8357 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8360 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8361 err.span_suggestion(
8363 "if you meant to call a macro, try",
8364 format!("{}!", snippet),
8365 // this is the `ambiguous` conditional branch
8366 Applicability::MaybeIncorrect
8369 err.help("if you meant to call a macro, remove the `pub` \
8370 and add a trailing `!` after the identifier");
8374 } else if self.look_ahead(1, |t| *t == token::Lt) {
8375 let ident = self.parse_ident().unwrap();
8376 self.eat_to_tokens(&[&token::Gt]);
8378 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8379 if let Ok(Some(_)) = self.parse_self_arg() {
8380 ("fn", "method", false)
8382 ("fn", "function", false)
8384 } else if self.check(&token::OpenDelim(token::Brace)) {
8385 ("struct", "struct", false)
8387 ("fn` or `struct", "function or struct", true)
8389 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8390 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8392 err.span_suggestion_short(
8394 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8395 format!(" {} ", kw),
8396 Applicability::MachineApplicable,
8402 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8405 /// Parses a foreign item.
8406 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8407 maybe_whole!(self, NtForeignItem, |ni| ni);
8409 let attrs = self.parse_outer_attributes()?;
8411 let visibility = self.parse_visibility(false)?;
8413 // FOREIGN STATIC ITEM
8414 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8415 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8416 if self.token.is_keyword(keywords::Const) {
8418 .struct_span_err(self.span, "extern items cannot be `const`")
8421 "try using a static value",
8422 "static".to_owned(),
8423 Applicability::MachineApplicable
8426 self.bump(); // `static` or `const`
8427 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8429 // FOREIGN FUNCTION ITEM
8430 if self.check_keyword(keywords::Fn) {
8431 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8433 // FOREIGN TYPE ITEM
8434 if self.check_keyword(keywords::Type) {
8435 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8438 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8442 ident: keywords::Invalid.ident(),
8443 span: lo.to(self.prev_span),
8444 id: ast::DUMMY_NODE_ID,
8447 node: ForeignItemKind::Macro(mac),
8452 if !attrs.is_empty() {
8453 self.expected_item_err(&attrs)?;
8461 /// This is the fall-through for parsing items.
8462 fn parse_macro_use_or_failure(
8464 attrs: Vec<Attribute> ,
8465 macros_allowed: bool,
8466 attributes_allowed: bool,
8468 visibility: Visibility
8469 ) -> PResult<'a, Option<P<Item>>> {
8470 if macros_allowed && self.token.is_path_start() &&
8471 !(self.is_async_fn() && self.span.rust_2015()) {
8472 // MACRO INVOCATION ITEM
8474 let prev_span = self.prev_span;
8475 self.complain_if_pub_macro(&visibility.node, prev_span);
8477 let mac_lo = self.span;
8480 let pth = self.parse_path(PathStyle::Mod)?;
8481 self.expect(&token::Not)?;
8483 // a 'special' identifier (like what `macro_rules!` uses)
8484 // is optional. We should eventually unify invoc syntax
8486 let id = if self.token.is_ident() {
8489 keywords::Invalid.ident() // no special identifier
8491 // eat a matched-delimiter token tree:
8492 let (delim, tts) = self.expect_delimited_token_tree()?;
8493 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8494 self.report_invalid_macro_expansion_item();
8497 let hi = self.prev_span;
8498 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8499 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8500 return Ok(Some(item));
8503 // FAILURE TO PARSE ITEM
8504 match visibility.node {
8505 VisibilityKind::Inherited => {}
8507 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8511 if !attributes_allowed && !attrs.is_empty() {
8512 self.expected_item_err(&attrs)?;
8517 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8518 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8519 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8521 if self.token.is_path_start() &&
8522 !(self.is_async_fn() && self.span.rust_2015()) {
8523 let prev_span = self.prev_span;
8525 let pth = self.parse_path(PathStyle::Mod)?;
8527 if pth.segments.len() == 1 {
8528 if !self.eat(&token::Not) {
8529 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8532 self.expect(&token::Not)?;
8535 if let Some(vis) = vis {
8536 self.complain_if_pub_macro(&vis.node, prev_span);
8541 // eat a matched-delimiter token tree:
8542 let (delim, tts) = self.expect_delimited_token_tree()?;
8543 if delim != MacDelimiter::Brace {
8544 self.expect(&token::Semi)?;
8547 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8553 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8554 where F: FnOnce(&mut Self) -> PResult<'a, R>
8556 // Record all tokens we parse when parsing this item.
8557 let mut tokens = Vec::new();
8558 let prev_collecting = match self.token_cursor.frame.last_token {
8559 LastToken::Collecting(ref mut list) => {
8560 Some(mem::replace(list, Vec::new()))
8562 LastToken::Was(ref mut last) => {
8563 tokens.extend(last.take());
8567 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8568 let prev = self.token_cursor.stack.len();
8570 let last_token = if self.token_cursor.stack.len() == prev {
8571 &mut self.token_cursor.frame.last_token
8573 &mut self.token_cursor.stack[prev].last_token
8576 // Pull out the tokens that we've collected from the call to `f` above.
8577 let mut collected_tokens = match *last_token {
8578 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8579 LastToken::Was(_) => panic!("our vector went away?"),
8582 // If we're not at EOF our current token wasn't actually consumed by
8583 // `f`, but it'll still be in our list that we pulled out. In that case
8585 let extra_token = if self.token != token::Eof {
8586 collected_tokens.pop()
8591 // If we were previously collecting tokens, then this was a recursive
8592 // call. In that case we need to record all the tokens we collected in
8593 // our parent list as well. To do that we push a clone of our stream
8594 // onto the previous list.
8595 match prev_collecting {
8597 list.extend(collected_tokens.iter().cloned());
8598 list.extend(extra_token);
8599 *last_token = LastToken::Collecting(list);
8602 *last_token = LastToken::Was(extra_token);
8606 Ok((ret?, TokenStream::new(collected_tokens)))
8609 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8610 let attrs = self.parse_outer_attributes()?;
8611 self.parse_item_(attrs, true, false)
8615 fn is_import_coupler(&mut self) -> bool {
8616 self.check(&token::ModSep) &&
8617 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8618 *t == token::BinOp(token::Star))
8621 /// Parses a `UseTree`.
8624 /// USE_TREE = [`::`] `*` |
8625 /// [`::`] `{` USE_TREE_LIST `}` |
8627 /// PATH `::` `{` USE_TREE_LIST `}` |
8628 /// PATH [`as` IDENT]
8630 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8633 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8634 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8635 self.check(&token::BinOp(token::Star)) ||
8636 self.is_import_coupler() {
8637 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8638 let mod_sep_ctxt = self.span.ctxt();
8639 if self.eat(&token::ModSep) {
8640 prefix.segments.push(
8641 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8645 if self.eat(&token::BinOp(token::Star)) {
8648 UseTreeKind::Nested(self.parse_use_tree_list()?)
8651 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8652 prefix = self.parse_path(PathStyle::Mod)?;
8654 if self.eat(&token::ModSep) {
8655 if self.eat(&token::BinOp(token::Star)) {
8658 UseTreeKind::Nested(self.parse_use_tree_list()?)
8661 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8665 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8668 /// Parses a `UseTreeKind::Nested(list)`.
8671 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8673 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8674 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8675 &token::CloseDelim(token::Brace),
8676 SeqSep::trailing_allowed(token::Comma), |this| {
8677 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8681 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8682 if self.eat_keyword(keywords::As) {
8683 self.parse_ident_or_underscore().map(Some)
8689 /// Parses a source module as a crate. This is the main entry point for the parser.
8690 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8692 let krate = Ok(ast::Crate {
8693 attrs: self.parse_inner_attributes()?,
8694 module: self.parse_mod_items(&token::Eof, lo)?,
8695 span: lo.to(self.span),
8700 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8701 let ret = match self.token {
8702 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8703 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8710 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8711 match self.parse_optional_str() {
8712 Some((s, style, suf)) => {
8713 let sp = self.prev_span;
8714 self.expect_no_suffix(sp, "a string literal", suf);
8718 let msg = "expected string literal";
8719 let mut err = self.fatal(msg);
8720 err.span_label(self.span, msg);
8726 fn report_invalid_macro_expansion_item(&self) {
8727 self.struct_span_err(
8729 "macros that expand to items must be delimited with braces or followed by a semicolon",
8730 ).multipart_suggestion(
8731 "change the delimiters to curly braces",
8733 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8734 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8736 Applicability::MaybeIncorrect,
8738 self.sess.source_map.next_point(self.prev_span),
8741 Applicability::MaybeIncorrect,
8745 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8746 fn eat_bad_pub(&mut self) {
8747 if self.token.is_keyword(keywords::Pub) {
8748 match self.parse_visibility(false) {
8750 let mut err = self.diagnostic()
8751 .struct_span_err(vis.span, "unnecessary visibility qualifier");
8752 err.span_label(vis.span, "`pub` not permitted here");
8755 Err(mut err) => err.emit(),
8760 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8761 /// into the generated closure so that they are dropped when the future is polled and not when
8764 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8765 /// this function and the statements created here are inserted at the top of the closure body.
8766 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &mut FnDecl) {
8767 // FIXME(davidtwco): This function should really live in the HIR lowering but because
8768 // the types constructed here need to be used in parts of resolve so that the correct
8769 // locals are considered upvars, it is currently easier for it to live here in the parser,
8770 // where it can be constructed once.
8771 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8772 for (index, input) in decl.inputs.iter_mut().enumerate() {
8773 let id = ast::DUMMY_NODE_ID;
8774 let span = input.pat.span;
8776 // Construct a name for our temporary argument.
8777 let name = format!("__arg{}", index);
8778 let ident = Ident::from_str(&name).gensym();
8780 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
8781 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
8783 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
8784 PatKind::Ident(binding_mode @ BindingMode::ByValue(_), ident, _) => {
8785 // Simple patterns like this don't have a generated argument, but they are
8786 // moved into the closure with a statement, so any `mut` bindings on the
8787 // argument will be unused. This binding mode can't be removed, because
8788 // this would affect the input to procedural macros, but they can have
8789 // their span marked as being the result of a compiler desugaring so
8790 // that they aren't linted against.
8791 input.pat.span = self.sess.source_map().mark_span_with_reason(
8792 CompilerDesugaringKind::Async, span, None);
8794 (binding_mode, ident, true)
8796 _ => (BindingMode::ByValue(Mutability::Mutable), ident, false),
8799 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8800 // async function if it isn't a simple pattern.
8801 let arg = if is_simple_pattern {
8805 ty: input.ty.clone(),
8809 node: PatKind::Ident(
8810 BindingMode::ByValue(Mutability::Immutable), ident, None,
8814 source: ArgSource::AsyncFn(input.pat.clone()),
8818 // Construct a `let __argN = __argN;` statement to insert at the top of the
8819 // async closure. This makes sure that the argument is captured by the closure and
8820 // that the drop order is correct.
8821 let move_local = Local {
8824 node: PatKind::Ident(binding_mode, ident, None),
8827 // We explicitly do not specify the type for this statement. When the user's
8828 // argument type is `impl Trait` then this would require the
8829 // `impl_trait_in_bindings` feature to also be present for that same type to
8830 // be valid in this binding. At the time of writing (13 Mar 19),
8831 // `impl_trait_in_bindings` is not stable.
8835 node: ExprKind::Path(None, ast::Path {
8837 segments: vec![PathSegment { ident, id, args: None }],
8840 attrs: ThinVec::new(),
8844 attrs: ThinVec::new(),
8845 source: LocalSource::AsyncFn,
8848 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8849 // async closure if this isn't a simple pattern.
8850 let pat_stmt = if is_simple_pattern {
8855 node: StmtKind::Local(P(Local {
8856 pat: input.pat.clone(),
8857 ..move_local.clone()
8863 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
8864 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
8870 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8871 for unmatched in unclosed_delims.iter() {
8872 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8873 "incorrect close delimiter: `{}`",
8874 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8876 err.span_label(unmatched.found_span, "incorrect close delimiter");
8877 if let Some(sp) = unmatched.candidate_span {
8878 err.span_label(sp, "close delimiter possibly meant for this");
8880 if let Some(sp) = unmatched.unclosed_span {
8881 err.span_label(sp, "un-closed delimiter");
8885 unclosed_delims.clear();