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 if let Ok(Some(_)) = self.parse_self_arg() {
1929 let mut err = self.struct_span_err(self.prev_span,
1930 "unexpected `self` argument in function");
1931 err.span_label(self.prev_span,
1932 "`self` is only valid as the first argument of an associated function");
1936 let (pat, ty) = if require_name || self.is_named_argument() {
1937 debug!("parse_arg_general parse_pat (require_name:{})",
1939 self.eat_incorrect_doc_comment("method arguments");
1940 let pat = self.parse_pat(Some("argument name"))?;
1942 if let Err(mut err) = self.expect(&token::Colon) {
1943 // If we find a pattern followed by an identifier, it could be an (incorrect)
1944 // C-style parameter declaration.
1945 if self.check_ident() && self.look_ahead(1, |t| {
1946 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1948 let ident = self.parse_ident().unwrap();
1949 let span = pat.span.with_hi(ident.span.hi());
1951 err.span_suggestion(
1953 "declare the type after the parameter binding",
1954 String::from("<identifier>: <type>"),
1955 Applicability::HasPlaceholders,
1957 } else if require_name && is_trait_item {
1958 if let PatKind::Ident(_, ident, _) = pat.node {
1959 err.span_suggestion(
1961 "explicitly ignore parameter",
1962 format!("_: {}", ident),
1963 Applicability::MachineApplicable,
1967 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1973 self.eat_incorrect_doc_comment("a method argument's type");
1974 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1976 debug!("parse_arg_general ident_to_pat");
1977 let parser_snapshot_before_ty = self.clone();
1978 self.eat_incorrect_doc_comment("a method argument's type");
1979 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1980 if ty.is_ok() && self.token != token::Comma &&
1981 self.token != token::CloseDelim(token::Paren) {
1982 // This wasn't actually a type, but a pattern looking like a type,
1983 // so we are going to rollback and re-parse for recovery.
1984 ty = self.unexpected();
1988 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1990 id: ast::DUMMY_NODE_ID,
1991 node: PatKind::Ident(
1992 BindingMode::ByValue(Mutability::Immutable), ident, None),
1998 // If this is a C-variadic argument and we hit an error, return the
2000 if self.token == token::DotDotDot {
2003 // Recover from attempting to parse the argument as a type without pattern.
2005 mem::replace(self, parser_snapshot_before_ty);
2006 let pat = self.parse_pat(Some("argument name"))?;
2007 self.expect(&token::Colon)?;
2008 let ty = self.parse_ty()?;
2010 let mut err = self.diagnostic().struct_span_err_with_code(
2012 "patterns aren't allowed in methods without bodies",
2013 DiagnosticId::Error("E0642".into()),
2015 err.span_suggestion_short(
2017 "give this argument a name or use an underscore to ignore it",
2019 Applicability::MachineApplicable,
2023 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2025 node: PatKind::Wild,
2027 id: ast::DUMMY_NODE_ID
2034 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
2037 /// Parses a single function argument.
2038 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2039 self.parse_arg_general(true, false, false)
2042 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2043 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2044 let pat = self.parse_pat(Some("argument name"))?;
2045 let t = if self.eat(&token::Colon) {
2049 id: ast::DUMMY_NODE_ID,
2050 node: TyKind::Infer,
2051 span: self.prev_span,
2057 id: ast::DUMMY_NODE_ID,
2058 source: ast::ArgSource::Normal,
2062 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2063 if self.eat(&token::Semi) {
2064 Ok(Some(self.parse_expr()?))
2070 /// Matches `token_lit = LIT_INTEGER | ...`.
2071 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2072 let out = match self.token {
2073 token::Interpolated(ref nt) => match **nt {
2074 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2075 ExprKind::Lit(ref lit) => { lit.node.clone() }
2076 _ => { return self.unexpected_last(&self.token); }
2078 _ => { return self.unexpected_last(&self.token); }
2080 token::Literal(lit, suf) => {
2081 let diag = Some((self.span, &self.sess.span_diagnostic));
2082 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2086 self.expect_no_suffix(sp, &format!("a {}", lit.literal_name()), suf)
2091 token::Dot if self.look_ahead(1, |t| match t {
2092 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2094 }) => { // recover from `let x = .4;`
2097 if let token::Literal(
2098 parse::token::Lit::Integer(val),
2101 let suffix = suffix.and_then(|s| {
2105 } else if s == "f64" {
2112 let sp = lo.to(self.prev_span);
2113 let mut err = self.diagnostic()
2114 .struct_span_err(sp, "float literals must have an integer part");
2115 err.span_suggestion(
2117 "must have an integer part",
2118 format!("0.{}{}", val, suffix),
2119 Applicability::MachineApplicable,
2122 return Ok(match suffix {
2123 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2124 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2125 _ => ast::LitKind::FloatUnsuffixed(val),
2131 _ => { return self.unexpected_last(&self.token); }
2138 /// Matches `lit = true | false | token_lit`.
2139 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2141 let lit = if self.eat_keyword(keywords::True) {
2143 } else if self.eat_keyword(keywords::False) {
2144 LitKind::Bool(false)
2146 let lit = self.parse_lit_token()?;
2149 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2152 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2153 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2154 maybe_whole_expr!(self);
2156 let minus_lo = self.span;
2157 let minus_present = self.eat(&token::BinOp(token::Minus));
2159 let literal = self.parse_lit()?;
2160 let hi = self.prev_span;
2161 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2164 let minus_hi = self.prev_span;
2165 let unary = self.mk_unary(UnOp::Neg, expr);
2166 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2172 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2174 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2175 let span = self.span;
2177 Ok(Ident::new(ident.name, span))
2179 _ => self.parse_ident(),
2183 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2185 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2186 let span = self.span;
2188 Ok(Ident::new(ident.name, span))
2190 _ => self.parse_ident(),
2194 /// Parses a qualified path.
2195 /// Assumes that the leading `<` has been parsed already.
2197 /// `qualified_path = <type [as trait_ref]>::path`
2202 /// `<T as U>::F::a<S>` (without disambiguator)
2203 /// `<T as U>::F::a::<S>` (with disambiguator)
2204 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2205 let lo = self.prev_span;
2206 let ty = self.parse_ty()?;
2208 // `path` will contain the prefix of the path up to the `>`,
2209 // if any (e.g., `U` in the `<T as U>::*` examples
2210 // above). `path_span` has the span of that path, or an empty
2211 // span in the case of something like `<T>::Bar`.
2212 let (mut path, path_span);
2213 if self.eat_keyword(keywords::As) {
2214 let path_lo = self.span;
2215 path = self.parse_path(PathStyle::Type)?;
2216 path_span = path_lo.to(self.prev_span);
2218 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2219 path_span = self.span.to(self.span);
2222 // See doc comment for `unmatched_angle_bracket_count`.
2223 self.expect(&token::Gt)?;
2224 if self.unmatched_angle_bracket_count > 0 {
2225 self.unmatched_angle_bracket_count -= 1;
2226 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2229 self.expect(&token::ModSep)?;
2231 let qself = QSelf { ty, path_span, position: path.segments.len() };
2232 self.parse_path_segments(&mut path.segments, style)?;
2234 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2237 /// Parses simple paths.
2239 /// `path = [::] segment+`
2240 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2243 /// `a::b::C<D>` (without disambiguator)
2244 /// `a::b::C::<D>` (with disambiguator)
2245 /// `Fn(Args)` (without disambiguator)
2246 /// `Fn::(Args)` (with disambiguator)
2247 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2248 maybe_whole!(self, NtPath, |path| {
2249 if style == PathStyle::Mod &&
2250 path.segments.iter().any(|segment| segment.args.is_some()) {
2251 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2256 let lo = self.meta_var_span.unwrap_or(self.span);
2257 let mut segments = Vec::new();
2258 let mod_sep_ctxt = self.span.ctxt();
2259 if self.eat(&token::ModSep) {
2260 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2262 self.parse_path_segments(&mut segments, style)?;
2264 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2267 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2268 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2270 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2271 let meta_ident = match self.token {
2272 token::Interpolated(ref nt) => match **nt {
2273 token::NtMeta(ref meta) => match meta.node {
2274 ast::MetaItemKind::Word => Some(meta.path.clone()),
2281 if let Some(path) = meta_ident {
2285 self.parse_path(style)
2288 crate fn parse_path_segments(&mut self,
2289 segments: &mut Vec<PathSegment>,
2291 -> PResult<'a, ()> {
2293 let segment = self.parse_path_segment(style)?;
2294 if style == PathStyle::Expr {
2295 // In order to check for trailing angle brackets, we must have finished
2296 // recursing (`parse_path_segment` can indirectly call this function),
2297 // that is, the next token must be the highlighted part of the below example:
2299 // `Foo::<Bar as Baz<T>>::Qux`
2302 // As opposed to the below highlight (if we had only finished the first
2305 // `Foo::<Bar as Baz<T>>::Qux`
2308 // `PathStyle::Expr` is only provided at the root invocation and never in
2309 // `parse_path_segment` to recurse and therefore can be checked to maintain
2311 self.check_trailing_angle_brackets(&segment, token::ModSep);
2313 segments.push(segment);
2315 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2321 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2322 let ident = self.parse_path_segment_ident()?;
2324 let is_args_start = |token: &token::Token| match *token {
2325 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
2326 | token::LArrow => true,
2329 let check_args_start = |this: &mut Self| {
2330 this.expected_tokens.extend_from_slice(
2331 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2333 is_args_start(&this.token)
2336 Ok(if style == PathStyle::Type && check_args_start(self) ||
2337 style != PathStyle::Mod && self.check(&token::ModSep)
2338 && self.look_ahead(1, |t| is_args_start(t)) {
2339 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2340 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2341 // parsing a new path.
2342 if style == PathStyle::Expr {
2343 self.unmatched_angle_bracket_count = 0;
2344 self.max_angle_bracket_count = 0;
2347 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2348 self.eat(&token::ModSep);
2350 let args = if self.eat_lt() {
2352 let (args, bindings) =
2353 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2355 let span = lo.to(self.prev_span);
2356 AngleBracketedArgs { args, bindings, span }.into()
2360 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2361 &[&token::CloseDelim(token::Paren)],
2362 SeqSep::trailing_allowed(token::Comma),
2363 TokenExpectType::Expect,
2368 let span = lo.to(self.prev_span);
2369 let output = if self.eat(&token::RArrow) {
2370 Some(self.parse_ty_common(false, false, false)?)
2374 ParenthesizedArgs { inputs, output, span }.into()
2377 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2379 // Generic arguments are not found.
2380 PathSegment::from_ident(ident)
2384 crate fn check_lifetime(&mut self) -> bool {
2385 self.expected_tokens.push(TokenType::Lifetime);
2386 self.token.is_lifetime()
2389 /// Parses a single lifetime `'a` or panics.
2390 crate fn expect_lifetime(&mut self) -> Lifetime {
2391 if let Some(ident) = self.token.lifetime() {
2392 let span = self.span;
2394 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2396 self.span_bug(self.span, "not a lifetime")
2400 fn eat_label(&mut self) -> Option<Label> {
2401 if let Some(ident) = self.token.lifetime() {
2402 let span = self.span;
2404 Some(Label { ident: Ident::new(ident.name, span) })
2410 /// Parses mutability (`mut` or nothing).
2411 fn parse_mutability(&mut self) -> Mutability {
2412 if self.eat_keyword(keywords::Mut) {
2415 Mutability::Immutable
2419 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2420 if let token::Literal(token::Integer(name), suffix) = self.token {
2421 self.expect_no_suffix(self.span, "a tuple index", suffix);
2423 Ok(Ident::new(name, self.prev_span))
2425 self.parse_ident_common(false)
2429 /// Parse ident (COLON expr)?
2430 fn parse_field(&mut self) -> PResult<'a, Field> {
2431 let attrs = self.parse_outer_attributes()?;
2434 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2435 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2436 t == &token::Colon || t == &token::Eq
2438 let fieldname = self.parse_field_name()?;
2440 // Check for an equals token. This means the source incorrectly attempts to
2441 // initialize a field with an eq rather than a colon.
2442 if self.token == token::Eq {
2444 .struct_span_err(self.span, "expected `:`, found `=`")
2446 fieldname.span.shrink_to_hi().to(self.span),
2447 "replace equals symbol with a colon",
2449 Applicability::MachineApplicable,
2454 (fieldname, self.parse_expr()?, false)
2456 let fieldname = self.parse_ident_common(false)?;
2458 // Mimic `x: x` for the `x` field shorthand.
2459 let path = ast::Path::from_ident(fieldname);
2460 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2461 (fieldname, expr, true)
2465 span: lo.to(expr.span),
2468 attrs: attrs.into(),
2472 fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2473 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2476 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2477 ExprKind::Unary(unop, expr)
2480 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2481 ExprKind::Binary(binop, lhs, rhs)
2484 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2485 ExprKind::Call(f, args)
2488 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2489 ExprKind::Index(expr, idx)
2493 start: Option<P<Expr>>,
2494 end: Option<P<Expr>>,
2495 limits: RangeLimits)
2496 -> PResult<'a, ast::ExprKind> {
2497 if end.is_none() && limits == RangeLimits::Closed {
2498 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2500 Ok(ExprKind::Range(start, end, limits))
2504 fn mk_assign_op(&self, binop: ast::BinOp,
2505 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2506 ExprKind::AssignOp(binop, lhs, rhs)
2509 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2510 let delim = match self.token {
2511 token::OpenDelim(delim) => delim,
2513 let msg = "expected open delimiter";
2514 let mut err = self.fatal(msg);
2515 err.span_label(self.span, msg);
2519 let tts = match self.parse_token_tree() {
2520 TokenTree::Delimited(_, _, tts) => tts,
2521 _ => unreachable!(),
2523 let delim = match delim {
2524 token::Paren => MacDelimiter::Parenthesis,
2525 token::Bracket => MacDelimiter::Bracket,
2526 token::Brace => MacDelimiter::Brace,
2527 token::NoDelim => self.bug("unexpected no delimiter"),
2529 Ok((delim, tts.into()))
2532 /// At the bottom (top?) of the precedence hierarchy,
2533 /// Parses things like parenthesized exprs, macros, `return`, etc.
2535 /// N.B., this does not parse outer attributes, and is private because it only works
2536 /// correctly if called from `parse_dot_or_call_expr()`.
2537 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2538 maybe_recover_from_interpolated_ty_qpath!(self, true);
2539 maybe_whole_expr!(self);
2541 // Outer attributes are already parsed and will be
2542 // added to the return value after the fact.
2544 // Therefore, prevent sub-parser from parsing
2545 // attributes by giving them a empty "already parsed" list.
2546 let mut attrs = ThinVec::new();
2549 let mut hi = self.span;
2553 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2555 token::OpenDelim(token::Paren) => {
2558 attrs.extend(self.parse_inner_attributes()?);
2560 // (e) is parenthesized e
2561 // (e,) is a tuple with only one field, e
2562 let mut es = vec![];
2563 let mut trailing_comma = false;
2564 let mut recovered = false;
2565 while self.token != token::CloseDelim(token::Paren) {
2566 es.push(match self.parse_expr() {
2569 // recover from parse error in tuple list
2570 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2573 recovered = self.expect_one_of(
2575 &[token::Comma, token::CloseDelim(token::Paren)],
2577 if self.eat(&token::Comma) {
2578 trailing_comma = true;
2580 trailing_comma = false;
2588 hi = self.prev_span;
2589 ex = if es.len() == 1 && !trailing_comma {
2590 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2595 token::OpenDelim(token::Brace) => {
2596 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2598 token::BinOp(token::Or) | token::OrOr => {
2599 return self.parse_lambda_expr(attrs);
2601 token::OpenDelim(token::Bracket) => {
2604 attrs.extend(self.parse_inner_attributes()?);
2606 if self.eat(&token::CloseDelim(token::Bracket)) {
2608 ex = ExprKind::Array(Vec::new());
2611 let first_expr = self.parse_expr()?;
2612 if self.eat(&token::Semi) {
2613 // Repeating array syntax: [ 0; 512 ]
2614 let count = AnonConst {
2615 id: ast::DUMMY_NODE_ID,
2616 value: self.parse_expr()?,
2618 self.expect(&token::CloseDelim(token::Bracket))?;
2619 ex = ExprKind::Repeat(first_expr, count);
2620 } else if self.eat(&token::Comma) {
2621 // Vector with two or more elements.
2622 let remaining_exprs = self.parse_seq_to_end(
2623 &token::CloseDelim(token::Bracket),
2624 SeqSep::trailing_allowed(token::Comma),
2625 |p| Ok(p.parse_expr()?)
2627 let mut exprs = vec![first_expr];
2628 exprs.extend(remaining_exprs);
2629 ex = ExprKind::Array(exprs);
2631 // Vector with one element.
2632 self.expect(&token::CloseDelim(token::Bracket))?;
2633 ex = ExprKind::Array(vec![first_expr]);
2636 hi = self.prev_span;
2640 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2642 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2644 if self.span.rust_2018() && self.check_keyword(keywords::Async) {
2645 return if self.is_async_block() { // check for `async {` and `async move {`
2646 self.parse_async_block(attrs)
2648 self.parse_lambda_expr(attrs)
2651 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2652 return self.parse_lambda_expr(attrs);
2654 if self.eat_keyword(keywords::If) {
2655 return self.parse_if_expr(attrs);
2657 if self.eat_keyword(keywords::For) {
2658 let lo = self.prev_span;
2659 return self.parse_for_expr(None, lo, attrs);
2661 if self.eat_keyword(keywords::While) {
2662 let lo = self.prev_span;
2663 return self.parse_while_expr(None, lo, attrs);
2665 if let Some(label) = self.eat_label() {
2666 let lo = label.ident.span;
2667 self.expect(&token::Colon)?;
2668 if self.eat_keyword(keywords::While) {
2669 return self.parse_while_expr(Some(label), lo, attrs)
2671 if self.eat_keyword(keywords::For) {
2672 return self.parse_for_expr(Some(label), lo, attrs)
2674 if self.eat_keyword(keywords::Loop) {
2675 return self.parse_loop_expr(Some(label), lo, attrs)
2677 if self.token == token::OpenDelim(token::Brace) {
2678 return self.parse_block_expr(Some(label),
2680 BlockCheckMode::Default,
2683 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2684 let mut err = self.fatal(msg);
2685 err.span_label(self.span, msg);
2688 if self.eat_keyword(keywords::Loop) {
2689 let lo = self.prev_span;
2690 return self.parse_loop_expr(None, lo, attrs);
2692 if self.eat_keyword(keywords::Continue) {
2693 let label = self.eat_label();
2694 let ex = ExprKind::Continue(label);
2695 let hi = self.prev_span;
2696 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2698 if self.eat_keyword(keywords::Match) {
2699 let match_sp = self.prev_span;
2700 return self.parse_match_expr(attrs).map_err(|mut err| {
2701 err.span_label(match_sp, "while parsing this match expression");
2705 if self.eat_keyword(keywords::Unsafe) {
2706 return self.parse_block_expr(
2709 BlockCheckMode::Unsafe(ast::UserProvided),
2712 if self.is_do_catch_block() {
2713 let mut db = self.fatal("found removed `do catch` syntax");
2714 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2717 if self.is_try_block() {
2719 assert!(self.eat_keyword(keywords::Try));
2720 return self.parse_try_block(lo, attrs);
2722 if self.eat_keyword(keywords::Return) {
2723 if self.token.can_begin_expr() {
2724 let e = self.parse_expr()?;
2726 ex = ExprKind::Ret(Some(e));
2728 ex = ExprKind::Ret(None);
2730 } else if self.eat_keyword(keywords::Break) {
2731 let label = self.eat_label();
2732 let e = if self.token.can_begin_expr()
2733 && !(self.token == token::OpenDelim(token::Brace)
2734 && self.restrictions.contains(
2735 Restrictions::NO_STRUCT_LITERAL)) {
2736 Some(self.parse_expr()?)
2740 ex = ExprKind::Break(label, e);
2741 hi = self.prev_span;
2742 } else if self.eat_keyword(keywords::Yield) {
2743 if self.token.can_begin_expr() {
2744 let e = self.parse_expr()?;
2746 ex = ExprKind::Yield(Some(e));
2748 ex = ExprKind::Yield(None);
2750 } else if self.token.is_keyword(keywords::Let) {
2751 // Catch this syntax error here, instead of in `parse_ident`, so
2752 // that we can explicitly mention that let is not to be used as an expression
2753 let mut db = self.fatal("expected expression, found statement (`let`)");
2754 db.span_label(self.span, "expected expression");
2755 db.note("variable declaration using `let` is a statement");
2757 } else if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
2758 // FIXME: remove this branch when `await!` is no longer supported
2759 // https://github.com/rust-lang/rust/issues/60610
2760 self.expect(&token::Not)?;
2761 self.expect(&token::OpenDelim(token::Paren))?;
2762 let expr = self.parse_expr()?;
2763 self.expect(&token::CloseDelim(token::Paren))?;
2764 ex = ExprKind::Await(ast::AwaitOrigin::MacroLike, expr);
2765 } else if self.token.is_path_start() {
2766 let path = self.parse_path(PathStyle::Expr)?;
2768 // `!`, as an operator, is prefix, so we know this isn't that
2769 if self.eat(&token::Not) {
2770 // MACRO INVOCATION expression
2771 let (delim, tts) = self.expect_delimited_token_tree()?;
2772 hi = self.prev_span;
2773 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2774 } else if self.check(&token::OpenDelim(token::Brace)) {
2775 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2779 ex = ExprKind::Path(None, path);
2783 ex = ExprKind::Path(None, path);
2786 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2787 // Don't complain about bare semicolons after unclosed braces
2788 // recovery in order to keep the error count down. Fixing the
2789 // delimiters will possibly also fix the bare semicolon found in
2790 // expression context. For example, silence the following error:
2792 // error: expected expression, found `;`
2796 // | ^ expected expression
2799 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2801 match self.parse_literal_maybe_minus() {
2804 ex = expr.node.clone();
2807 self.cancel(&mut err);
2808 let msg = format!("expected expression, found {}",
2809 self.this_token_descr());
2810 let mut err = self.fatal(&msg);
2811 let sp = self.sess.source_map().start_point(self.span);
2812 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow()
2815 self.sess.expr_parentheses_needed(&mut err, *sp, None);
2817 err.span_label(self.span, "expected expression");
2825 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2826 self.maybe_recover_from_bad_qpath(expr, true)
2829 fn maybe_parse_struct_expr(
2833 attrs: &ThinVec<Attribute>,
2834 ) -> Option<PResult<'a, P<Expr>>> {
2835 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2836 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2837 // `{ ident, ` cannot start a block
2838 self.look_ahead(2, |t| t == &token::Comma) ||
2839 self.look_ahead(2, |t| t == &token::Colon) && (
2840 // `{ ident: token, ` cannot start a block
2841 self.look_ahead(4, |t| t == &token::Comma) ||
2842 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2843 self.look_ahead(3, |t| !t.can_begin_type())
2847 if struct_allowed || certainly_not_a_block() {
2848 // This is a struct literal, but we don't can't accept them here
2849 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2850 if let (Ok(expr), false) = (&expr, struct_allowed) {
2851 let mut err = self.diagnostic().struct_span_err(
2853 "struct literals are not allowed here",
2855 err.multipart_suggestion(
2856 "surround the struct literal with parentheses",
2858 (lo.shrink_to_lo(), "(".to_string()),
2859 (expr.span.shrink_to_hi(), ")".to_string()),
2861 Applicability::MachineApplicable,
2870 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2871 -> PResult<'a, P<Expr>> {
2872 let struct_sp = lo.to(self.prev_span);
2874 let mut fields = Vec::new();
2875 let mut base = None;
2877 attrs.extend(self.parse_inner_attributes()?);
2879 while self.token != token::CloseDelim(token::Brace) {
2880 if self.eat(&token::DotDot) {
2881 let exp_span = self.prev_span;
2882 match self.parse_expr() {
2888 self.recover_stmt();
2891 if self.token == token::Comma {
2892 let mut err = self.sess.span_diagnostic.mut_span_err(
2893 exp_span.to(self.prev_span),
2894 "cannot use a comma after the base struct",
2896 err.span_suggestion_short(
2898 "remove this comma",
2900 Applicability::MachineApplicable
2902 err.note("the base struct must always be the last field");
2904 self.recover_stmt();
2909 let mut recovery_field = None;
2910 if let token::Ident(ident, _) = self.token {
2911 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2912 // Use in case of error after field-looking code: `S { foo: () with a }`
2913 let mut ident = ident.clone();
2914 ident.span = self.span;
2915 recovery_field = Some(ast::Field {
2918 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2919 is_shorthand: false,
2920 attrs: ThinVec::new(),
2924 let mut parsed_field = None;
2925 match self.parse_field() {
2926 Ok(f) => parsed_field = Some(f),
2928 e.span_label(struct_sp, "while parsing this struct");
2931 // If the next token is a comma, then try to parse
2932 // what comes next as additional fields, rather than
2933 // bailing out until next `}`.
2934 if self.token != token::Comma {
2935 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2936 if self.token != token::Comma {
2943 match self.expect_one_of(&[token::Comma],
2944 &[token::CloseDelim(token::Brace)]) {
2945 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2946 // only include the field if there's no parse error for the field name
2950 if let Some(f) = recovery_field {
2953 e.span_label(struct_sp, "while parsing this struct");
2955 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2956 self.eat(&token::Comma);
2961 let span = lo.to(self.span);
2962 self.expect(&token::CloseDelim(token::Brace))?;
2963 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2966 fn parse_or_use_outer_attributes(&mut self,
2967 already_parsed_attrs: Option<ThinVec<Attribute>>)
2968 -> PResult<'a, ThinVec<Attribute>> {
2969 if let Some(attrs) = already_parsed_attrs {
2972 self.parse_outer_attributes().map(|a| a.into())
2976 /// Parses a block or unsafe block.
2977 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2978 lo: Span, blk_mode: BlockCheckMode,
2979 outer_attrs: ThinVec<Attribute>)
2980 -> PResult<'a, P<Expr>> {
2981 self.expect(&token::OpenDelim(token::Brace))?;
2983 let mut attrs = outer_attrs;
2984 attrs.extend(self.parse_inner_attributes()?);
2986 let blk = self.parse_block_tail(lo, blk_mode)?;
2987 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2990 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2991 fn parse_dot_or_call_expr(&mut self,
2992 already_parsed_attrs: Option<ThinVec<Attribute>>)
2993 -> PResult<'a, P<Expr>> {
2994 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2996 let b = self.parse_bottom_expr();
2997 let (span, b) = self.interpolated_or_expr_span(b)?;
2998 self.parse_dot_or_call_expr_with(b, span, attrs)
3001 fn parse_dot_or_call_expr_with(&mut self,
3004 mut attrs: ThinVec<Attribute>)
3005 -> PResult<'a, P<Expr>> {
3006 // Stitch the list of outer attributes onto the return value.
3007 // A little bit ugly, but the best way given the current code
3009 self.parse_dot_or_call_expr_with_(e0, lo)
3011 expr.map(|mut expr| {
3012 attrs.extend::<Vec<_>>(expr.attrs.into());
3015 ExprKind::If(..) | ExprKind::IfLet(..) => {
3016 if !expr.attrs.is_empty() {
3017 // Just point to the first attribute in there...
3018 let span = expr.attrs[0].span;
3021 "attributes are not yet allowed on `if` \
3032 // Assuming we have just parsed `.`, continue parsing into an expression.
3033 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3034 if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
3035 let span = lo.to(self.prev_span);
3036 let await_expr = self.mk_expr(
3038 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
3041 return Ok(await_expr);
3043 let segment = self.parse_path_segment(PathStyle::Expr)?;
3044 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3046 Ok(match self.token {
3047 token::OpenDelim(token::Paren) => {
3048 // Method call `expr.f()`
3049 let mut args = self.parse_unspanned_seq(
3050 &token::OpenDelim(token::Paren),
3051 &token::CloseDelim(token::Paren),
3052 SeqSep::trailing_allowed(token::Comma),
3053 |p| Ok(p.parse_expr()?)
3055 args.insert(0, self_arg);
3057 let span = lo.to(self.prev_span);
3058 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3061 // Field access `expr.f`
3062 if let Some(args) = segment.args {
3063 self.span_err(args.span(),
3064 "field expressions may not have generic arguments");
3067 let span = lo.to(self.prev_span);
3068 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3073 /// This function checks if there are trailing angle brackets and produces
3074 /// a diagnostic to suggest removing them.
3076 /// ```ignore (diagnostic)
3077 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3078 /// ^^ help: remove extra angle brackets
3080 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3081 // This function is intended to be invoked after parsing a path segment where there are two
3084 // 1. A specific token is expected after the path segment.
3085 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3086 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3087 // 2. No specific token is expected after the path segment.
3088 // eg. `x.foo` (field access)
3090 // This function is called after parsing `.foo` and before parsing the token `end` (if
3091 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3094 // We only care about trailing angle brackets if we previously parsed angle bracket
3095 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3096 // removed in this case:
3098 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3100 // This case is particularly tricky as we won't notice it just looking at the tokens -
3101 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3102 // have already been parsed):
3104 // `x.foo::<u32>>>(3)`
3105 let parsed_angle_bracket_args = segment.args
3107 .map(|args| args.is_angle_bracketed())
3111 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3112 parsed_angle_bracket_args,
3114 if !parsed_angle_bracket_args {
3118 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3122 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3123 // (since we might have the field access case and the characters we're eating are
3124 // actual operators and not trailing characters - ie `x.foo >> 3`).
3125 let mut position = 0;
3127 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3128 // many of each (so we can correctly pluralize our error messages) and continue to
3130 let mut number_of_shr = 0;
3131 let mut number_of_gt = 0;
3132 while self.look_ahead(position, |t| {
3133 trace!("check_trailing_angle_brackets: t={:?}", t);
3134 if *t == token::BinOp(token::BinOpToken::Shr) {
3137 } else if *t == token::Gt {
3147 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3149 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3150 number_of_gt, number_of_shr,
3152 if number_of_gt < 1 && number_of_shr < 1 {
3156 // Finally, double check that we have our end token as otherwise this is the
3158 if self.look_ahead(position, |t| {
3159 trace!("check_trailing_angle_brackets: t={:?}", t);
3162 // Eat from where we started until the end token so that parsing can continue
3163 // as if we didn't have those extra angle brackets.
3164 self.eat_to_tokens(&[&end]);
3165 let span = lo.until(self.span);
3167 let plural = number_of_gt > 1 || number_of_shr >= 1;
3171 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3175 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3177 Applicability::MachineApplicable,
3183 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3188 while self.eat(&token::Question) {
3189 let hi = self.prev_span;
3190 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3194 if self.eat(&token::Dot) {
3196 token::Ident(..) => {
3197 e = self.parse_dot_suffix(e, lo)?;
3199 token::Literal(token::Integer(name), suffix) => {
3200 let span = self.span;
3202 let field = ExprKind::Field(e, Ident::new(name, span));
3203 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3205 self.expect_no_suffix(span, "a tuple index", suffix);
3207 token::Literal(token::Float(n), _suf) => {
3209 let fstr = n.as_str();
3210 let mut err = self.diagnostic()
3211 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3212 err.span_label(self.prev_span, "unexpected token");
3213 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3214 let float = match fstr.parse::<f64>().ok() {
3218 let sugg = pprust::to_string(|s| {
3219 use crate::print::pprust::PrintState;
3223 s.print_usize(float.trunc() as usize)?;
3226 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3228 err.span_suggestion(
3229 lo.to(self.prev_span),
3230 "try parenthesizing the first index",
3232 Applicability::MachineApplicable
3239 // FIXME Could factor this out into non_fatal_unexpected or something.
3240 let actual = self.this_token_to_string();
3241 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3246 if self.expr_is_complete(&e) { break; }
3249 token::OpenDelim(token::Paren) => {
3250 let seq = self.parse_unspanned_seq(
3251 &token::OpenDelim(token::Paren),
3252 &token::CloseDelim(token::Paren),
3253 SeqSep::trailing_allowed(token::Comma),
3254 |p| Ok(p.parse_expr()?)
3256 let nd = self.mk_call(e, es);
3257 let hi = self.prev_span;
3258 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3260 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3264 // Could be either an index expression or a slicing expression.
3265 token::OpenDelim(token::Bracket) => {
3267 let ix = self.parse_expr()?;
3269 self.expect(&token::CloseDelim(token::Bracket))?;
3270 let index = self.mk_index(e, ix);
3271 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3279 fn recover_seq_parse_error(
3281 delim: token::DelimToken,
3283 result: PResult<'a, P<Expr>>,
3289 // recover from parse error
3290 self.consume_block(delim);
3291 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
3296 crate fn process_potential_macro_variable(&mut self) {
3297 let (token, span) = match self.token {
3298 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3299 self.look_ahead(1, |t| t.is_ident()) => {
3301 let name = match self.token {
3302 token::Ident(ident, _) => ident,
3305 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3306 err.span_label(self.span, "unknown macro variable");
3311 token::Interpolated(ref nt) => {
3312 self.meta_var_span = Some(self.span);
3313 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3314 // and lifetime tokens, so the former are never encountered during normal parsing.
3316 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3317 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3327 /// Parses a single token tree from the input.
3328 crate fn parse_token_tree(&mut self) -> TokenTree {
3330 token::OpenDelim(..) => {
3331 let frame = mem::replace(&mut self.token_cursor.frame,
3332 self.token_cursor.stack.pop().unwrap());
3333 self.span = frame.span.entire();
3335 TokenTree::Delimited(
3338 frame.tree_cursor.stream.into(),
3341 token::CloseDelim(_) | token::Eof => unreachable!(),
3343 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3345 TokenTree::Token(span, token)
3350 // parse a stream of tokens into a list of TokenTree's,
3352 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3353 let mut tts = Vec::new();
3354 while self.token != token::Eof {
3355 tts.push(self.parse_token_tree());
3360 pub fn parse_tokens(&mut self) -> TokenStream {
3361 let mut result = Vec::new();
3364 token::Eof | token::CloseDelim(..) => break,
3365 _ => result.push(self.parse_token_tree().into()),
3368 TokenStream::new(result)
3371 /// Parse a prefix-unary-operator expr
3372 fn parse_prefix_expr(&mut self,
3373 already_parsed_attrs: Option<ThinVec<Attribute>>)
3374 -> PResult<'a, P<Expr>> {
3375 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3377 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3378 let (hi, ex) = match self.token {
3381 let e = self.parse_prefix_expr(None);
3382 let (span, e) = self.interpolated_or_expr_span(e)?;
3383 (lo.to(span), self.mk_unary(UnOp::Not, e))
3385 // Suggest `!` for bitwise negation when encountering a `~`
3388 let e = self.parse_prefix_expr(None);
3389 let (span, e) = self.interpolated_or_expr_span(e)?;
3390 let span_of_tilde = lo;
3391 let mut err = self.diagnostic()
3392 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3393 err.span_suggestion_short(
3395 "use `!` to perform bitwise negation",
3397 Applicability::MachineApplicable
3400 (lo.to(span), self.mk_unary(UnOp::Not, e))
3402 token::BinOp(token::Minus) => {
3404 let e = self.parse_prefix_expr(None);
3405 let (span, e) = self.interpolated_or_expr_span(e)?;
3406 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3408 token::BinOp(token::Star) => {
3410 let e = self.parse_prefix_expr(None);
3411 let (span, e) = self.interpolated_or_expr_span(e)?;
3412 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3414 token::BinOp(token::And) | token::AndAnd => {
3416 let m = self.parse_mutability();
3417 let e = self.parse_prefix_expr(None);
3418 let (span, e) = self.interpolated_or_expr_span(e)?;
3419 (lo.to(span), ExprKind::AddrOf(m, e))
3421 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3423 let place = self.parse_expr_res(
3424 Restrictions::NO_STRUCT_LITERAL,
3427 let blk = self.parse_block()?;
3428 let span = blk.span;
3429 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3430 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3432 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3434 let e = self.parse_prefix_expr(None);
3435 let (span, e) = self.interpolated_or_expr_span(e)?;
3436 (lo.to(span), ExprKind::Box(e))
3438 token::Ident(..) if self.token.is_ident_named("not") => {
3439 // `not` is just an ordinary identifier in Rust-the-language,
3440 // but as `rustc`-the-compiler, we can issue clever diagnostics
3441 // for confused users who really want to say `!`
3442 let token_cannot_continue_expr = |t: &token::Token| match *t {
3443 // These tokens can start an expression after `!`, but
3444 // can't continue an expression after an ident
3445 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3446 token::Literal(..) | token::Pound => true,
3447 token::Interpolated(ref nt) => match **nt {
3448 token::NtIdent(..) | token::NtExpr(..) |
3449 token::NtBlock(..) | token::NtPath(..) => true,
3454 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3455 if cannot_continue_expr {
3457 // Emit the error ...
3458 let mut err = self.diagnostic()
3459 .struct_span_err(self.span,
3460 &format!("unexpected {} after identifier",
3461 self.this_token_descr()));
3462 // span the `not` plus trailing whitespace to avoid
3463 // trailing whitespace after the `!` in our suggestion
3464 let to_replace = self.sess.source_map()
3465 .span_until_non_whitespace(lo.to(self.span));
3466 err.span_suggestion_short(
3468 "use `!` to perform logical negation",
3470 Applicability::MachineApplicable
3473 // —and recover! (just as if we were in the block
3474 // for the `token::Not` arm)
3475 let e = self.parse_prefix_expr(None);
3476 let (span, e) = self.interpolated_or_expr_span(e)?;
3477 (lo.to(span), self.mk_unary(UnOp::Not, e))
3479 return self.parse_dot_or_call_expr(Some(attrs));
3482 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3484 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3487 /// Parses an associative expression.
3489 /// This parses an expression accounting for associativity and precedence of the operators in
3492 fn parse_assoc_expr(&mut self,
3493 already_parsed_attrs: Option<ThinVec<Attribute>>)
3494 -> PResult<'a, P<Expr>> {
3495 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3498 /// Parses an associative expression with operators of at least `min_prec` precedence.
3499 fn parse_assoc_expr_with(&mut self,
3502 -> PResult<'a, P<Expr>> {
3503 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3506 let attrs = match lhs {
3507 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3510 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3511 return self.parse_prefix_range_expr(attrs);
3513 self.parse_prefix_expr(attrs)?
3517 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
3519 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3522 (false, _) => {} // continue parsing the expression
3523 // An exhaustive check is done in the following block, but these are checked first
3524 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
3525 // want to keep their span info to improve diagnostics in these cases in a later stage.
3526 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
3527 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
3528 (true, Some(AssocOp::Add)) => { // `{ 42 } + 42
3529 // These cases are ambiguous and can't be identified in the parser alone
3530 let sp = self.sess.source_map().start_point(self.span);
3531 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
3534 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
3537 (true, Some(_)) => {
3538 // We've found an expression that would be parsed as a statement, but the next
3539 // token implies this should be parsed as an expression.
3540 // For example: `if let Some(x) = x { x } else { 0 } / 2`
3541 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
3542 "expected expression, found `{}`",
3543 pprust::token_to_string(&self.token),
3545 err.span_label(self.span, "expected expression");
3546 self.sess.expr_parentheses_needed(
3549 Some(pprust::expr_to_string(&lhs),
3554 self.expected_tokens.push(TokenType::Operator);
3555 while let Some(op) = AssocOp::from_token(&self.token) {
3557 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3558 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3559 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3560 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3561 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3562 (PrevTokenKind::Interpolated, _) => self.prev_span,
3563 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3564 if path.segments.len() == 1 => self.prev_span,
3568 let cur_op_span = self.span;
3569 let restrictions = if op.is_assign_like() {
3570 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3574 let prec = op.precedence();
3575 if prec < min_prec {
3578 // Check for deprecated `...` syntax
3579 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3580 self.err_dotdotdot_syntax(self.span);
3584 if op.is_comparison() {
3585 self.check_no_chained_comparison(&lhs, &op);
3588 if op == AssocOp::As {
3589 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3591 } else if op == AssocOp::Colon {
3592 let maybe_path = self.could_ascription_be_path(&lhs.node);
3593 let next_sp = self.span;
3595 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3598 self.bad_type_ascription(
3609 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3610 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3611 // generalise it to the Fixity::None code.
3613 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3614 // two variants are handled with `parse_prefix_range_expr` call above.
3615 let rhs = if self.is_at_start_of_range_notation_rhs() {
3616 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
3620 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3625 let limits = if op == AssocOp::DotDot {
3626 RangeLimits::HalfOpen
3631 let r = self.mk_range(Some(lhs), rhs, limits)?;
3632 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3636 let fixity = op.fixity();
3637 let prec_adjustment = match fixity {
3640 // We currently have no non-associative operators that are not handled above by
3641 // the special cases. The code is here only for future convenience.
3644 let rhs = self.with_res(
3645 restrictions - Restrictions::STMT_EXPR,
3646 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
3649 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3650 // including the attributes.
3654 .filter(|a| a.style == AttrStyle::Outer)
3656 .map_or(lhs_span, |a| a.span);
3657 let span = lhs_span.to(rhs.span);
3659 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3660 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3661 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3662 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3663 AssocOp::Greater | AssocOp::GreaterEqual => {
3664 let ast_op = op.to_ast_binop().unwrap();
3665 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3666 self.mk_expr(span, binary, ThinVec::new())
3669 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3670 AssocOp::ObsoleteInPlace =>
3671 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3672 AssocOp::AssignOp(k) => {
3674 token::Plus => BinOpKind::Add,
3675 token::Minus => BinOpKind::Sub,
3676 token::Star => BinOpKind::Mul,
3677 token::Slash => BinOpKind::Div,
3678 token::Percent => BinOpKind::Rem,
3679 token::Caret => BinOpKind::BitXor,
3680 token::And => BinOpKind::BitAnd,
3681 token::Or => BinOpKind::BitOr,
3682 token::Shl => BinOpKind::Shl,
3683 token::Shr => BinOpKind::Shr,
3685 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3686 self.mk_expr(span, aopexpr, ThinVec::new())
3688 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3689 self.bug("AssocOp should have been handled by special case")
3693 if let Fixity::None = fixity { break }
3698 fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
3699 self.token.is_ident() &&
3700 if let ast::ExprKind::Path(..) = node { true } else { false } &&
3701 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
3702 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
3703 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
3704 self.look_ahead(2, |t| t.is_ident()) ||
3705 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
3706 self.look_ahead(2, |t| t.is_ident()) ||
3707 self.look_ahead(1, |t| t == &token::ModSep) && // `foo:bar::baz`
3708 self.look_ahead(2, |t| t.is_ident())
3711 fn bad_type_ascription(
3713 err: &mut DiagnosticBuilder<'a>,
3719 err.span_label(self.span, "expecting a type here because of type ascription");
3720 let cm = self.sess.source_map();
3721 let next_pos = cm.lookup_char_pos(next_sp.lo());
3722 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3723 if op_pos.line != next_pos.line {
3724 err.span_suggestion(
3726 "try using a semicolon",
3728 Applicability::MaybeIncorrect,
3732 err.span_suggestion(
3734 "maybe you meant to write a path separator here",
3736 Applicability::MaybeIncorrect,
3739 err.note("type ascription is a nightly-only feature that lets \
3740 you annotate an expression with a type: `<expr>: <type>`");
3743 "this expression expects an ascribed type after the colon",
3745 err.help("this might be indicative of a syntax error elsewhere");
3750 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3751 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3752 -> PResult<'a, P<Expr>> {
3753 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3754 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3757 // Save the state of the parser before parsing type normally, in case there is a
3758 // LessThan comparison after this cast.
3759 let parser_snapshot_before_type = self.clone();
3760 match self.parse_ty_no_plus() {
3762 Ok(mk_expr(self, rhs))
3764 Err(mut type_err) => {
3765 // Rewind to before attempting to parse the type with generics, to recover
3766 // from situations like `x as usize < y` in which we first tried to parse
3767 // `usize < y` as a type with generic arguments.
3768 let parser_snapshot_after_type = self.clone();
3769 mem::replace(self, parser_snapshot_before_type);
3771 match self.parse_path(PathStyle::Expr) {
3773 let (op_noun, op_verb) = match self.token {
3774 token::Lt => ("comparison", "comparing"),
3775 token::BinOp(token::Shl) => ("shift", "shifting"),
3777 // We can end up here even without `<` being the next token, for
3778 // example because `parse_ty_no_plus` returns `Err` on keywords,
3779 // but `parse_path` returns `Ok` on them due to error recovery.
3780 // Return original error and parser state.
3781 mem::replace(self, parser_snapshot_after_type);
3782 return Err(type_err);
3786 // Successfully parsed the type path leaving a `<` yet to parse.
3789 // Report non-fatal diagnostics, keep `x as usize` as an expression
3790 // in AST and continue parsing.
3791 let msg = format!("`<` is interpreted as a start of generic \
3792 arguments for `{}`, not a {}", path, op_noun);
3793 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3794 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3795 "interpreted as generic arguments");
3796 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3798 let expr = mk_expr(self, P(Ty {
3800 node: TyKind::Path(None, path),
3801 id: ast::DUMMY_NODE_ID
3804 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3805 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3806 err.span_suggestion(
3808 &format!("try {} the cast value", op_verb),
3809 format!("({})", expr_str),
3810 Applicability::MachineApplicable
3816 Err(mut path_err) => {
3817 // Couldn't parse as a path, return original error and parser state.
3819 mem::replace(self, parser_snapshot_after_type);
3827 /// Produce an error if comparison operators are chained (RFC #558).
3828 /// We only need to check lhs, not rhs, because all comparison ops
3829 /// have same precedence and are left-associative
3830 fn check_no_chained_comparison(&self, lhs: &Expr, outer_op: &AssocOp) {
3831 debug_assert!(outer_op.is_comparison(),
3832 "check_no_chained_comparison: {:?} is not comparison",
3835 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3836 // respan to include both operators
3837 let op_span = op.span.to(self.span);
3838 let mut err = self.diagnostic().struct_span_err(op_span,
3839 "chained comparison operators require parentheses");
3840 if op.node == BinOpKind::Lt &&
3841 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3842 *outer_op == AssocOp::Greater // even in a case like the following:
3843 { // Foo<Bar<Baz<Qux, ()>>>
3845 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3846 err.help("or use `(...)` if you meant to specify fn arguments");
3854 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3855 fn parse_prefix_range_expr(&mut self,
3856 already_parsed_attrs: Option<ThinVec<Attribute>>)
3857 -> PResult<'a, P<Expr>> {
3858 // Check for deprecated `...` syntax
3859 if self.token == token::DotDotDot {
3860 self.err_dotdotdot_syntax(self.span);
3863 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3864 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3866 let tok = self.token.clone();
3867 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3869 let mut hi = self.span;
3871 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3872 // RHS must be parsed with more associativity than the dots.
3873 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3874 Some(self.parse_assoc_expr_with(next_prec,
3875 LhsExpr::NotYetParsed)
3883 let limits = if tok == token::DotDot {
3884 RangeLimits::HalfOpen
3889 let r = self.mk_range(None, opt_end, limits)?;
3890 Ok(self.mk_expr(lo.to(hi), r, attrs))
3893 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3894 if self.token.can_begin_expr() {
3895 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3896 if self.token == token::OpenDelim(token::Brace) {
3897 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3905 /// Parses an `if` or `if let` expression (`if` token already eaten).
3906 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3907 if self.check_keyword(keywords::Let) {
3908 return self.parse_if_let_expr(attrs);
3910 let lo = self.prev_span;
3911 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3913 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3914 // verify that the last statement is either an implicit return (no `;`) or an explicit
3915 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3916 // the dead code lint.
3917 if self.eat_keyword(keywords::Else) || !cond.returns() {
3918 let sp = self.sess.source_map().next_point(lo);
3919 let mut err = self.diagnostic()
3920 .struct_span_err(sp, "missing condition for `if` statemement");
3921 err.span_label(sp, "expected if condition here");
3924 let not_block = self.token != token::OpenDelim(token::Brace);
3925 let thn = self.parse_block().map_err(|mut err| {
3927 err.span_label(lo, "this `if` statement has a condition, but no block");
3931 let mut els: Option<P<Expr>> = None;
3932 let mut hi = thn.span;
3933 if self.eat_keyword(keywords::Else) {
3934 let elexpr = self.parse_else_expr()?;
3938 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3941 /// Parses an `if let` expression (`if` token already eaten).
3942 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3943 -> PResult<'a, P<Expr>> {
3944 let lo = self.prev_span;
3945 self.expect_keyword(keywords::Let)?;
3946 let pats = self.parse_pats()?;
3947 self.expect(&token::Eq)?;
3948 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3949 let thn = self.parse_block()?;
3950 let (hi, els) = if self.eat_keyword(keywords::Else) {
3951 let expr = self.parse_else_expr()?;
3952 (expr.span, Some(expr))
3956 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3959 /// Parses `move |args| expr`.
3960 fn parse_lambda_expr(&mut self,
3961 attrs: ThinVec<Attribute>)
3962 -> PResult<'a, P<Expr>>
3965 let movability = if self.eat_keyword(keywords::Static) {
3970 let asyncness = if self.span.rust_2018() {
3971 self.parse_asyncness()
3975 let capture_clause = if self.eat_keyword(keywords::Move) {
3980 let decl = self.parse_fn_block_decl()?;
3981 let decl_hi = self.prev_span;
3982 let body = match decl.output {
3983 FunctionRetTy::Default(_) => {
3984 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3985 self.parse_expr_res(restrictions, None)?
3988 // If an explicit return type is given, require a
3989 // block to appear (RFC 968).
3990 let body_lo = self.span;
3991 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3997 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
4001 // `else` token already eaten
4002 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
4003 if self.eat_keyword(keywords::If) {
4004 return self.parse_if_expr(ThinVec::new());
4006 let blk = self.parse_block()?;
4007 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
4011 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
4012 fn parse_for_expr(&mut self, opt_label: Option<Label>,
4014 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4015 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
4017 let pat = self.parse_top_level_pat()?;
4018 if !self.eat_keyword(keywords::In) {
4019 let in_span = self.prev_span.between(self.span);
4020 let mut err = self.sess.span_diagnostic
4021 .struct_span_err(in_span, "missing `in` in `for` loop");
4022 err.span_suggestion_short(
4023 in_span, "try adding `in` here", " in ".into(),
4024 // has been misleading, at least in the past (closed Issue #48492)
4025 Applicability::MaybeIncorrect
4029 let in_span = self.prev_span;
4030 if self.eat_keyword(keywords::In) {
4031 // a common typo: `for _ in in bar {}`
4032 let mut err = self.sess.span_diagnostic.struct_span_err(
4034 "expected iterable, found keyword `in`",
4036 err.span_suggestion_short(
4037 in_span.until(self.prev_span),
4038 "remove the duplicated `in`",
4040 Applicability::MachineApplicable,
4042 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
4043 err.note("for more information on the status of emplacement syntax, see <\
4044 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
4047 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4048 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
4049 attrs.extend(iattrs);
4051 let hi = self.prev_span;
4052 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
4055 /// Parses a `while` or `while let` expression (`while` token already eaten).
4056 fn parse_while_expr(&mut self, opt_label: Option<Label>,
4058 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4059 if self.token.is_keyword(keywords::Let) {
4060 return self.parse_while_let_expr(opt_label, span_lo, attrs);
4062 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4063 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4064 attrs.extend(iattrs);
4065 let span = span_lo.to(body.span);
4066 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
4069 /// Parses a `while let` expression (`while` token already eaten).
4070 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
4072 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4073 self.expect_keyword(keywords::Let)?;
4074 let pats = self.parse_pats()?;
4075 self.expect(&token::Eq)?;
4076 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4077 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4078 attrs.extend(iattrs);
4079 let span = span_lo.to(body.span);
4080 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
4083 // parse `loop {...}`, `loop` token already eaten
4084 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
4086 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4087 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4088 attrs.extend(iattrs);
4089 let span = span_lo.to(body.span);
4090 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
4093 /// Parses an `async move {...}` expression.
4094 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4095 -> PResult<'a, P<Expr>>
4097 let span_lo = self.span;
4098 self.expect_keyword(keywords::Async)?;
4099 let capture_clause = if self.eat_keyword(keywords::Move) {
4104 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4105 attrs.extend(iattrs);
4107 span_lo.to(body.span),
4108 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4111 /// Parses a `try {...}` expression (`try` token already eaten).
4112 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4113 -> PResult<'a, P<Expr>>
4115 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4116 attrs.extend(iattrs);
4117 if self.eat_keyword(keywords::Catch) {
4118 let mut error = self.struct_span_err(self.prev_span,
4119 "keyword `catch` cannot follow a `try` block");
4120 error.help("try using `match` on the result of the `try` block instead");
4124 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4128 // `match` token already eaten
4129 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4130 let match_span = self.prev_span;
4131 let lo = self.prev_span;
4132 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4134 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4135 if self.token == token::Token::Semi {
4136 e.span_suggestion_short(
4138 "try removing this `match`",
4140 Applicability::MaybeIncorrect // speculative
4145 attrs.extend(self.parse_inner_attributes()?);
4147 let mut arms: Vec<Arm> = Vec::new();
4148 while self.token != token::CloseDelim(token::Brace) {
4149 match self.parse_arm() {
4150 Ok(arm) => arms.push(arm),
4152 // Recover by skipping to the end of the block.
4154 self.recover_stmt();
4155 let span = lo.to(self.span);
4156 if self.token == token::CloseDelim(token::Brace) {
4159 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4165 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4168 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4169 let attrs = self.parse_outer_attributes()?;
4170 let pats = self.parse_pats()?;
4171 let guard = if self.eat_keyword(keywords::If) {
4172 Some(Guard::If(self.parse_expr()?))
4176 let arrow_span = self.span;
4177 self.expect(&token::FatArrow)?;
4178 let arm_start_span = self.span;
4180 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4181 .map_err(|mut err| {
4182 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4186 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4187 && self.token != token::CloseDelim(token::Brace);
4190 let cm = self.sess.source_map();
4191 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4192 .map_err(|mut err| {
4193 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4194 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4195 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4196 && expr_lines.lines.len() == 2
4197 && self.token == token::FatArrow => {
4198 // We check whether there's any trailing code in the parse span,
4199 // if there isn't, we very likely have the following:
4202 // | -- - missing comma
4208 // | parsed until here as `"y" & X`
4209 err.span_suggestion_short(
4210 cm.next_point(arm_start_span),
4211 "missing a comma here to end this `match` arm",
4213 Applicability::MachineApplicable
4217 err.span_label(arrow_span,
4218 "while parsing the `match` arm starting here");
4224 self.eat(&token::Comma);
4235 /// Parses an expression.
4237 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4238 self.parse_expr_res(Restrictions::empty(), None)
4241 /// Evaluates the closure with restrictions in place.
4243 /// Afters the closure is evaluated, restrictions are reset.
4244 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4245 where F: FnOnce(&mut Self) -> T
4247 let old = self.restrictions;
4248 self.restrictions = r;
4250 self.restrictions = old;
4255 /// Parses an expression, subject to the given restrictions.
4257 fn parse_expr_res(&mut self, r: Restrictions,
4258 already_parsed_attrs: Option<ThinVec<Attribute>>)
4259 -> PResult<'a, P<Expr>> {
4260 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4263 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4264 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4265 if self.eat(&token::Eq) {
4266 Ok(Some(self.parse_expr()?))
4268 Ok(Some(self.parse_expr()?))
4274 /// Parses patterns, separated by '|' s.
4275 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4276 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4277 self.eat(&token::BinOp(token::Or));
4279 let mut pats = Vec::new();
4281 pats.push(self.parse_top_level_pat()?);
4283 if self.token == token::OrOr {
4284 let mut err = self.struct_span_err(self.span,
4285 "unexpected token `||` after pattern");
4286 err.span_suggestion(
4288 "use a single `|` to specify multiple patterns",
4290 Applicability::MachineApplicable
4294 } else if self.eat(&token::BinOp(token::Or)) {
4295 // This is a No-op. Continue the loop to parse the next
4303 // Parses a parenthesized list of patterns like
4304 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4305 // - a vector of the patterns that were parsed
4306 // - an option indicating the index of the `..` element
4307 // - a boolean indicating whether a trailing comma was present.
4308 // Trailing commas are significant because (p) and (p,) are different patterns.
4309 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4310 self.expect(&token::OpenDelim(token::Paren))?;
4311 let result = match self.parse_pat_list() {
4312 Ok(result) => result,
4313 Err(mut err) => { // recover from parse error in tuple pattern list
4315 self.consume_block(token::Paren);
4316 return Ok((vec![], Some(0), false));
4319 self.expect(&token::CloseDelim(token::Paren))?;
4323 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4324 let mut fields = Vec::new();
4325 let mut ddpos = None;
4326 let mut prev_dd_sp = None;
4327 let mut trailing_comma = false;
4329 if self.eat(&token::DotDot) {
4330 if ddpos.is_none() {
4331 ddpos = Some(fields.len());
4332 prev_dd_sp = Some(self.prev_span);
4334 // Emit a friendly error, ignore `..` and continue parsing
4335 let mut err = self.struct_span_err(
4337 "`..` can only be used once per tuple or tuple struct pattern",
4339 err.span_label(self.prev_span, "can only be used once per pattern");
4340 if let Some(sp) = prev_dd_sp {
4341 err.span_label(sp, "previously present here");
4345 } else if !self.check(&token::CloseDelim(token::Paren)) {
4346 fields.push(self.parse_pat(None)?);
4351 trailing_comma = self.eat(&token::Comma);
4352 if !trailing_comma {
4357 if ddpos == Some(fields.len()) && trailing_comma {
4358 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4359 let msg = "trailing comma is not permitted after `..`";
4360 self.struct_span_err(self.prev_span, msg)
4361 .span_label(self.prev_span, msg)
4365 Ok((fields, ddpos, trailing_comma))
4368 fn parse_pat_vec_elements(
4370 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4371 let mut before = Vec::new();
4372 let mut slice = None;
4373 let mut after = Vec::new();
4374 let mut first = true;
4375 let mut before_slice = true;
4377 while self.token != token::CloseDelim(token::Bracket) {
4381 self.expect(&token::Comma)?;
4383 if self.token == token::CloseDelim(token::Bracket)
4384 && (before_slice || !after.is_empty()) {
4390 if self.eat(&token::DotDot) {
4392 if self.check(&token::Comma) ||
4393 self.check(&token::CloseDelim(token::Bracket)) {
4394 slice = Some(P(Pat {
4395 id: ast::DUMMY_NODE_ID,
4396 node: PatKind::Wild,
4397 span: self.prev_span,
4399 before_slice = false;
4405 let subpat = self.parse_pat(None)?;
4406 if before_slice && self.eat(&token::DotDot) {
4407 slice = Some(subpat);
4408 before_slice = false;
4409 } else if before_slice {
4410 before.push(subpat);
4416 Ok((before, slice, after))
4422 attrs: Vec<Attribute>
4423 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4424 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4426 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4427 // Parsing a pattern of the form "fieldname: pat"
4428 let fieldname = self.parse_field_name()?;
4430 let pat = self.parse_pat(None)?;
4432 (pat, fieldname, false)
4434 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4435 let is_box = self.eat_keyword(keywords::Box);
4436 let boxed_span = self.span;
4437 let is_ref = self.eat_keyword(keywords::Ref);
4438 let is_mut = self.eat_keyword(keywords::Mut);
4439 let fieldname = self.parse_ident()?;
4440 hi = self.prev_span;
4442 let bind_type = match (is_ref, is_mut) {
4443 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4444 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4445 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4446 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4448 let fieldpat = P(Pat {
4449 id: ast::DUMMY_NODE_ID,
4450 node: PatKind::Ident(bind_type, fieldname, None),
4451 span: boxed_span.to(hi),
4454 let subpat = if is_box {
4456 id: ast::DUMMY_NODE_ID,
4457 node: PatKind::Box(fieldpat),
4463 (subpat, fieldname, true)
4466 Ok(source_map::Spanned {
4468 node: ast::FieldPat {
4472 attrs: attrs.into(),
4477 /// Parses the fields of a struct-like pattern.
4478 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4479 let mut fields = Vec::new();
4480 let mut etc = false;
4481 let mut ate_comma = true;
4482 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4483 let mut etc_span = None;
4485 while self.token != token::CloseDelim(token::Brace) {
4486 let attrs = self.parse_outer_attributes()?;
4489 // check that a comma comes after every field
4491 let err = self.struct_span_err(self.prev_span, "expected `,`");
4492 if let Some(mut delayed) = delayed_err {
4499 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4501 let mut etc_sp = self.span;
4503 if self.token == token::DotDotDot { // Issue #46718
4504 // Accept `...` as if it were `..` to avoid further errors
4505 let mut err = self.struct_span_err(self.span,
4506 "expected field pattern, found `...`");
4507 err.span_suggestion(
4509 "to omit remaining fields, use one fewer `.`",
4511 Applicability::MachineApplicable
4515 self.bump(); // `..` || `...`
4517 if self.token == token::CloseDelim(token::Brace) {
4518 etc_span = Some(etc_sp);
4521 let token_str = self.this_token_descr();
4522 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4524 err.span_label(self.span, "expected `}`");
4525 let mut comma_sp = None;
4526 if self.token == token::Comma { // Issue #49257
4527 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4528 err.span_label(etc_sp,
4529 "`..` must be at the end and cannot have a trailing comma");
4530 comma_sp = Some(self.span);
4535 etc_span = Some(etc_sp.until(self.span));
4536 if self.token == token::CloseDelim(token::Brace) {
4537 // If the struct looks otherwise well formed, recover and continue.
4538 if let Some(sp) = comma_sp {
4539 err.span_suggestion_short(
4541 "remove this comma",
4543 Applicability::MachineApplicable,
4548 } else if self.token.is_ident() && ate_comma {
4549 // Accept fields coming after `..,`.
4550 // This way we avoid "pattern missing fields" errors afterwards.
4551 // We delay this error until the end in order to have a span for a
4553 if let Some(mut delayed_err) = delayed_err {
4557 delayed_err = Some(err);
4560 if let Some(mut err) = delayed_err {
4567 fields.push(match self.parse_pat_field(lo, attrs) {
4570 if let Some(mut delayed_err) = delayed_err {
4576 ate_comma = self.eat(&token::Comma);
4579 if let Some(mut err) = delayed_err {
4580 if let Some(etc_span) = etc_span {
4581 err.multipart_suggestion(
4582 "move the `..` to the end of the field list",
4584 (etc_span, String::new()),
4585 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4587 Applicability::MachineApplicable,
4592 return Ok((fields, etc));
4595 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4596 if self.token.is_path_start() {
4598 let (qself, path) = if self.eat_lt() {
4599 // Parse a qualified path
4600 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4603 // Parse an unqualified path
4604 (None, self.parse_path(PathStyle::Expr)?)
4606 let hi = self.prev_span;
4607 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4609 self.parse_literal_maybe_minus()
4613 // helper function to decide whether to parse as ident binding or to try to do
4614 // something more complex like range patterns
4615 fn parse_as_ident(&mut self) -> bool {
4616 self.look_ahead(1, |t| match *t {
4617 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4618 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4619 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4620 // range pattern branch
4621 token::DotDot => None,
4623 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4624 token::Comma | token::CloseDelim(token::Bracket) => true,
4629 /// A wrapper around `parse_pat` with some special error handling for the
4630 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4631 /// to subpatterns within such).
4632 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4633 let pat = self.parse_pat(None)?;
4634 if self.token == token::Comma {
4635 // An unexpected comma after a top-level pattern is a clue that the
4636 // user (perhaps more accustomed to some other language) forgot the
4637 // parentheses in what should have been a tuple pattern; return a
4638 // suggestion-enhanced error here rather than choking on the comma
4640 let comma_span = self.span;
4642 if let Err(mut err) = self.parse_pat_list() {
4643 // We didn't expect this to work anyway; we just wanted
4644 // to advance to the end of the comma-sequence so we know
4645 // the span to suggest parenthesizing
4648 let seq_span = pat.span.to(self.prev_span);
4649 let mut err = self.struct_span_err(comma_span,
4650 "unexpected `,` in pattern");
4651 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4652 err.span_suggestion(
4654 "try adding parentheses to match on a tuple..",
4655 format!("({})", seq_snippet),
4656 Applicability::MachineApplicable
4659 "..or a vertical bar to match on multiple alternatives",
4660 format!("{}", seq_snippet.replace(",", " |")),
4661 Applicability::MachineApplicable
4669 /// Parses a pattern.
4670 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4671 self.parse_pat_with_range_pat(true, expected)
4674 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4676 fn parse_pat_with_range_pat(
4678 allow_range_pat: bool,
4679 expected: Option<&'static str>,
4680 ) -> PResult<'a, P<Pat>> {
4681 maybe_recover_from_interpolated_ty_qpath!(self, true);
4682 maybe_whole!(self, NtPat, |x| x);
4687 token::BinOp(token::And) | token::AndAnd => {
4688 // Parse &pat / &mut pat
4690 let mutbl = self.parse_mutability();
4691 if let token::Lifetime(ident) = self.token {
4692 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4694 err.span_label(self.span, "unexpected lifetime");
4697 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4698 pat = PatKind::Ref(subpat, mutbl);
4700 token::OpenDelim(token::Paren) => {
4701 // Parse (pat,pat,pat,...) as tuple pattern
4702 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4703 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4704 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4706 PatKind::Tuple(fields, ddpos)
4709 token::OpenDelim(token::Bracket) => {
4710 // Parse [pat,pat,...] as slice pattern
4712 let (before, slice, after) = self.parse_pat_vec_elements()?;
4713 self.expect(&token::CloseDelim(token::Bracket))?;
4714 pat = PatKind::Slice(before, slice, after);
4716 // At this point, token != &, &&, (, [
4717 _ => if self.eat_keyword(keywords::Underscore) {
4719 pat = PatKind::Wild;
4720 } else if self.eat_keyword(keywords::Mut) {
4721 // Parse mut ident @ pat / mut ref ident @ pat
4722 let mutref_span = self.prev_span.to(self.span);
4723 let binding_mode = if self.eat_keyword(keywords::Ref) {
4725 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4728 "try switching the order",
4730 Applicability::MachineApplicable
4732 BindingMode::ByRef(Mutability::Mutable)
4734 BindingMode::ByValue(Mutability::Mutable)
4736 pat = self.parse_pat_ident(binding_mode)?;
4737 } else if self.eat_keyword(keywords::Ref) {
4738 // Parse ref ident @ pat / ref mut ident @ pat
4739 let mutbl = self.parse_mutability();
4740 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4741 } else if self.eat_keyword(keywords::Box) {
4743 let subpat = self.parse_pat_with_range_pat(false, None)?;
4744 pat = PatKind::Box(subpat);
4745 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4746 self.parse_as_ident() {
4747 // Parse ident @ pat
4748 // This can give false positives and parse nullary enums,
4749 // they are dealt with later in resolve
4750 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4751 pat = self.parse_pat_ident(binding_mode)?;
4752 } else if self.token.is_path_start() {
4753 // Parse pattern starting with a path
4754 let (qself, path) = if self.eat_lt() {
4755 // Parse a qualified path
4756 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4759 // Parse an unqualified path
4760 (None, self.parse_path(PathStyle::Expr)?)
4763 token::Not if qself.is_none() => {
4764 // Parse macro invocation
4766 let (delim, tts) = self.expect_delimited_token_tree()?;
4767 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4768 pat = PatKind::Mac(mac);
4770 token::DotDotDot | token::DotDotEq | token::DotDot => {
4771 let end_kind = match self.token {
4772 token::DotDot => RangeEnd::Excluded,
4773 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4774 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4775 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4778 let op_span = self.span;
4780 let span = lo.to(self.prev_span);
4781 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4783 let end = self.parse_pat_range_end()?;
4784 let op = Spanned { span: op_span, node: end_kind };
4785 pat = PatKind::Range(begin, end, op);
4787 token::OpenDelim(token::Brace) => {
4788 if qself.is_some() {
4789 let msg = "unexpected `{` after qualified path";
4790 let mut err = self.fatal(msg);
4791 err.span_label(self.span, msg);
4794 // Parse struct pattern
4796 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4798 self.recover_stmt();
4802 pat = PatKind::Struct(path, fields, etc);
4804 token::OpenDelim(token::Paren) => {
4805 if qself.is_some() {
4806 let msg = "unexpected `(` after qualified path";
4807 let mut err = self.fatal(msg);
4808 err.span_label(self.span, msg);
4811 // Parse tuple struct or enum pattern
4812 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4813 pat = PatKind::TupleStruct(path, fields, ddpos)
4815 _ => pat = PatKind::Path(qself, path),
4818 // Try to parse everything else as literal with optional minus
4819 match self.parse_literal_maybe_minus() {
4821 let op_span = self.span;
4822 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4823 self.check(&token::DotDotDot) {
4824 let end_kind = if self.eat(&token::DotDotDot) {
4825 RangeEnd::Included(RangeSyntax::DotDotDot)
4826 } else if self.eat(&token::DotDotEq) {
4827 RangeEnd::Included(RangeSyntax::DotDotEq)
4828 } else if self.eat(&token::DotDot) {
4831 panic!("impossible case: we already matched \
4832 on a range-operator token")
4834 let end = self.parse_pat_range_end()?;
4835 let op = Spanned { span: op_span, node: end_kind };
4836 pat = PatKind::Range(begin, end, op);
4838 pat = PatKind::Lit(begin);
4842 self.cancel(&mut err);
4843 let expected = expected.unwrap_or("pattern");
4845 "expected {}, found {}",
4847 self.this_token_descr(),
4849 let mut err = self.fatal(&msg);
4850 err.span_label(self.span, format!("expected {}", expected));
4851 let sp = self.sess.source_map().start_point(self.span);
4852 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4853 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4861 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4862 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4864 if !allow_range_pat {
4867 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4869 PatKind::Range(..) => {
4870 let mut err = self.struct_span_err(
4872 "the range pattern here has ambiguous interpretation",
4874 err.span_suggestion(
4876 "add parentheses to clarify the precedence",
4877 format!("({})", pprust::pat_to_string(&pat)),
4878 // "ambiguous interpretation" implies that we have to be guessing
4879 Applicability::MaybeIncorrect
4890 /// Parses `ident` or `ident @ pat`.
4891 /// used by the copy foo and ref foo patterns to give a good
4892 /// error message when parsing mistakes like `ref foo(a, b)`.
4893 fn parse_pat_ident(&mut self,
4894 binding_mode: ast::BindingMode)
4895 -> PResult<'a, PatKind> {
4896 let ident = self.parse_ident()?;
4897 let sub = if self.eat(&token::At) {
4898 Some(self.parse_pat(Some("binding pattern"))?)
4903 // just to be friendly, if they write something like
4905 // we end up here with ( as the current token. This shortly
4906 // leads to a parse error. Note that if there is no explicit
4907 // binding mode then we do not end up here, because the lookahead
4908 // will direct us over to parse_enum_variant()
4909 if self.token == token::OpenDelim(token::Paren) {
4910 return Err(self.span_fatal(
4912 "expected identifier, found enum pattern"))
4915 Ok(PatKind::Ident(binding_mode, ident, sub))
4918 /// Parses a local variable declaration.
4919 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4920 let lo = self.prev_span;
4921 let pat = self.parse_top_level_pat()?;
4923 let (err, ty) = if self.eat(&token::Colon) {
4924 // Save the state of the parser before parsing type normally, in case there is a `:`
4925 // instead of an `=` typo.
4926 let parser_snapshot_before_type = self.clone();
4927 let colon_sp = self.prev_span;
4928 match self.parse_ty() {
4929 Ok(ty) => (None, Some(ty)),
4931 // Rewind to before attempting to parse the type and continue parsing
4932 let parser_snapshot_after_type = self.clone();
4933 mem::replace(self, parser_snapshot_before_type);
4935 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4936 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4937 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4943 let init = match (self.parse_initializer(err.is_some()), err) {
4944 (Ok(init), None) => { // init parsed, ty parsed
4947 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4948 // Could parse the type as if it were the initializer, it is likely there was a
4949 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4950 err.span_suggestion_short(
4952 "use `=` if you meant to assign",
4954 Applicability::MachineApplicable
4957 // As this was parsed successfully, continue as if the code has been fixed for the
4958 // rest of the file. It will still fail due to the emitted error, but we avoid
4962 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4964 // Couldn't parse the type nor the initializer, only raise the type error and
4965 // return to the parser state before parsing the type as the initializer.
4966 // let x: <parse_error>;
4967 mem::replace(self, snapshot);
4970 (Err(err), None) => { // init error, ty parsed
4971 // Couldn't parse the initializer and we're not attempting to recover a failed
4972 // parse of the type, return the error.
4976 let hi = if self.token == token::Semi {
4985 id: ast::DUMMY_NODE_ID,
4988 source: LocalSource::Normal,
4992 /// Parses a structure field.
4993 fn parse_name_and_ty(&mut self,
4996 attrs: Vec<Attribute>)
4997 -> PResult<'a, StructField> {
4998 let name = self.parse_ident()?;
4999 self.expect(&token::Colon)?;
5000 let ty = self.parse_ty()?;
5002 span: lo.to(self.prev_span),
5005 id: ast::DUMMY_NODE_ID,
5011 /// Emits an expected-item-after-attributes error.
5012 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
5013 let message = match attrs.last() {
5014 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
5015 _ => "expected item after attributes",
5018 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
5019 if attrs.last().unwrap().is_sugared_doc {
5020 err.span_label(self.prev_span, "this doc comment doesn't document anything");
5025 /// Parse a statement. This stops just before trailing semicolons on everything but items.
5026 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
5027 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
5028 Ok(self.parse_stmt_(true))
5031 // Eat tokens until we can be relatively sure we reached the end of the
5032 // statement. This is something of a best-effort heuristic.
5034 // We terminate when we find an unmatched `}` (without consuming it).
5035 fn recover_stmt(&mut self) {
5036 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
5039 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
5040 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
5041 // approximate - it can mean we break too early due to macros, but that
5042 // should only lead to sub-optimal recovery, not inaccurate parsing).
5044 // If `break_on_block` is `Break`, then we will stop consuming tokens
5045 // after finding (and consuming) a brace-delimited block.
5046 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
5047 let mut brace_depth = 0;
5048 let mut bracket_depth = 0;
5049 let mut in_block = false;
5050 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
5051 break_on_semi, break_on_block);
5053 debug!("recover_stmt_ loop {:?}", self.token);
5055 token::OpenDelim(token::DelimToken::Brace) => {
5058 if break_on_block == BlockMode::Break &&
5060 bracket_depth == 0 {
5064 token::OpenDelim(token::DelimToken::Bracket) => {
5068 token::CloseDelim(token::DelimToken::Brace) => {
5069 if brace_depth == 0 {
5070 debug!("recover_stmt_ return - close delim {:?}", self.token);
5075 if in_block && bracket_depth == 0 && brace_depth == 0 {
5076 debug!("recover_stmt_ return - block end {:?}", self.token);
5080 token::CloseDelim(token::DelimToken::Bracket) => {
5082 if bracket_depth < 0 {
5088 debug!("recover_stmt_ return - Eof");
5093 if break_on_semi == SemiColonMode::Break &&
5095 bracket_depth == 0 {
5096 debug!("recover_stmt_ return - Semi");
5101 if break_on_semi == SemiColonMode::Comma &&
5103 bracket_depth == 0 {
5104 debug!("recover_stmt_ return - Semi");
5117 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5118 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5120 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5125 fn is_async_block(&self) -> bool {
5126 self.token.is_keyword(keywords::Async) &&
5129 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5130 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5132 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5137 fn is_async_fn(&self) -> bool {
5138 self.token.is_keyword(keywords::Async) &&
5139 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5142 fn is_do_catch_block(&self) -> bool {
5143 self.token.is_keyword(keywords::Do) &&
5144 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5145 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5146 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5149 fn is_try_block(&self) -> bool {
5150 self.token.is_keyword(keywords::Try) &&
5151 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5152 self.span.rust_2018() &&
5153 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5154 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5157 fn is_union_item(&self) -> bool {
5158 self.token.is_keyword(keywords::Union) &&
5159 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5162 fn is_crate_vis(&self) -> bool {
5163 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5166 fn is_existential_type_decl(&self) -> bool {
5167 self.token.is_keyword(keywords::Existential) &&
5168 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5171 fn is_auto_trait_item(&self) -> bool {
5173 (self.token.is_keyword(keywords::Auto)
5174 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5175 || // unsafe auto trait
5176 (self.token.is_keyword(keywords::Unsafe) &&
5177 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5178 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5181 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5182 -> PResult<'a, Option<P<Item>>> {
5183 let token_lo = self.span;
5184 let (ident, def) = match self.token {
5185 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5187 let ident = self.parse_ident()?;
5188 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5189 match self.parse_token_tree() {
5190 TokenTree::Delimited(_, _, tts) => tts,
5191 _ => unreachable!(),
5193 } else if self.check(&token::OpenDelim(token::Paren)) {
5194 let args = self.parse_token_tree();
5195 let body = if self.check(&token::OpenDelim(token::Brace)) {
5196 self.parse_token_tree()
5201 TokenStream::new(vec![
5203 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5211 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5213 token::Ident(ident, _) if ident.name == "macro_rules" &&
5214 self.look_ahead(1, |t| *t == token::Not) => {
5215 let prev_span = self.prev_span;
5216 self.complain_if_pub_macro(&vis.node, prev_span);
5220 let ident = self.parse_ident()?;
5221 let (delim, tokens) = self.expect_delimited_token_tree()?;
5222 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5223 self.report_invalid_macro_expansion_item();
5226 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5228 _ => return Ok(None),
5231 let span = lo.to(self.prev_span);
5232 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5235 fn parse_stmt_without_recovery(&mut self,
5236 macro_legacy_warnings: bool)
5237 -> PResult<'a, Option<Stmt>> {
5238 maybe_whole!(self, NtStmt, |x| Some(x));
5240 let attrs = self.parse_outer_attributes()?;
5243 Ok(Some(if self.eat_keyword(keywords::Let) {
5245 id: ast::DUMMY_NODE_ID,
5246 node: StmtKind::Local(self.parse_local(attrs.into())?),
5247 span: lo.to(self.prev_span),
5249 } else if let Some(macro_def) = self.eat_macro_def(
5251 &source_map::respan(lo, VisibilityKind::Inherited),
5255 id: ast::DUMMY_NODE_ID,
5256 node: StmtKind::Item(macro_def),
5257 span: lo.to(self.prev_span),
5259 // Starts like a simple path, being careful to avoid contextual keywords
5260 // such as a union items, item with `crate` visibility or auto trait items.
5261 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5262 // like a path (1 token), but it fact not a path.
5263 // `union::b::c` - path, `union U { ... }` - not a path.
5264 // `crate::b::c` - path, `crate struct S;` - not a path.
5265 } else if self.token.is_path_start() &&
5266 !self.token.is_qpath_start() &&
5267 !self.is_union_item() &&
5268 !self.is_crate_vis() &&
5269 !self.is_existential_type_decl() &&
5270 !self.is_auto_trait_item() &&
5271 !self.is_async_fn() {
5272 let pth = self.parse_path(PathStyle::Expr)?;
5274 if !self.eat(&token::Not) {
5275 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5276 self.parse_struct_expr(lo, pth, ThinVec::new())?
5278 let hi = self.prev_span;
5279 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5282 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5283 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5284 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5287 return Ok(Some(Stmt {
5288 id: ast::DUMMY_NODE_ID,
5289 node: StmtKind::Expr(expr),
5290 span: lo.to(self.prev_span),
5294 // it's a macro invocation
5295 let id = match self.token {
5296 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5297 _ => self.parse_ident()?,
5300 // check that we're pointing at delimiters (need to check
5301 // again after the `if`, because of `parse_ident`
5302 // consuming more tokens).
5304 token::OpenDelim(_) => {}
5306 // we only expect an ident if we didn't parse one
5308 let ident_str = if id.name == keywords::Invalid.name() {
5313 let tok_str = self.this_token_descr();
5314 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5317 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5322 let (delim, tts) = self.expect_delimited_token_tree()?;
5323 let hi = self.prev_span;
5325 let style = if delim == MacDelimiter::Brace {
5326 MacStmtStyle::Braces
5328 MacStmtStyle::NoBraces
5331 if id.name == keywords::Invalid.name() {
5332 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5333 let node = if delim == MacDelimiter::Brace ||
5334 self.token == token::Semi || self.token == token::Eof {
5335 StmtKind::Mac(P((mac, style, attrs.into())))
5337 // We used to incorrectly stop parsing macro-expanded statements here.
5338 // If the next token will be an error anyway but could have parsed with the
5339 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5340 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5341 // These can continue an expression, so we can't stop parsing and warn.
5342 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5343 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5344 token::BinOp(token::And) | token::BinOp(token::Or) |
5345 token::AndAnd | token::OrOr |
5346 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5349 self.warn_missing_semicolon();
5350 StmtKind::Mac(P((mac, style, attrs.into())))
5352 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5353 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5354 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5355 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5359 id: ast::DUMMY_NODE_ID,
5364 // if it has a special ident, it's definitely an item
5366 // Require a semicolon or braces.
5367 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5368 self.report_invalid_macro_expansion_item();
5370 let span = lo.to(hi);
5372 id: ast::DUMMY_NODE_ID,
5374 node: StmtKind::Item({
5376 span, id /*id is good here*/,
5377 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5378 respan(lo, VisibilityKind::Inherited),
5384 // FIXME: Bad copy of attrs
5385 let old_directory_ownership =
5386 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5387 let item = self.parse_item_(attrs.clone(), false, true)?;
5388 self.directory.ownership = old_directory_ownership;
5392 id: ast::DUMMY_NODE_ID,
5393 span: lo.to(i.span),
5394 node: StmtKind::Item(i),
5397 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5398 if !attrs.is_empty() {
5399 if s.prev_token_kind == PrevTokenKind::DocComment {
5400 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5401 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5402 s.span_err(s.span, "expected statement after outer attribute");
5407 // Do not attempt to parse an expression if we're done here.
5408 if self.token == token::Semi {
5409 unused_attrs(&attrs, self);
5414 if self.token == token::CloseDelim(token::Brace) {
5415 unused_attrs(&attrs, self);
5419 // Remainder are line-expr stmts.
5420 let e = self.parse_expr_res(
5421 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5423 id: ast::DUMMY_NODE_ID,
5424 span: lo.to(e.span),
5425 node: StmtKind::Expr(e),
5432 /// Checks if this expression is a successfully parsed statement.
5433 fn expr_is_complete(&self, e: &Expr) -> bool {
5434 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5435 !classify::expr_requires_semi_to_be_stmt(e)
5438 /// Parses a block. No inner attributes are allowed.
5439 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5440 maybe_whole!(self, NtBlock, |x| x);
5444 if !self.eat(&token::OpenDelim(token::Brace)) {
5446 let tok = self.this_token_descr();
5447 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5448 let do_not_suggest_help =
5449 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5451 if self.token.is_ident_named("and") {
5452 e.span_suggestion_short(
5454 "use `&&` instead of `and` for the boolean operator",
5456 Applicability::MaybeIncorrect,
5459 if self.token.is_ident_named("or") {
5460 e.span_suggestion_short(
5462 "use `||` instead of `or` for the boolean operator",
5464 Applicability::MaybeIncorrect,
5468 // Check to see if the user has written something like
5473 // Which is valid in other languages, but not Rust.
5474 match self.parse_stmt_without_recovery(false) {
5476 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5477 || do_not_suggest_help {
5478 // if the next token is an open brace (e.g., `if a b {`), the place-
5479 // inside-a-block suggestion would be more likely wrong than right
5480 e.span_label(sp, "expected `{`");
5483 let mut stmt_span = stmt.span;
5484 // expand the span to include the semicolon, if it exists
5485 if self.eat(&token::Semi) {
5486 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5488 let sugg = pprust::to_string(|s| {
5489 use crate::print::pprust::{PrintState, INDENT_UNIT};
5490 s.ibox(INDENT_UNIT)?;
5492 s.print_stmt(&stmt)?;
5493 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5497 "try placing this code inside a block",
5499 // speculative, has been misleading in the past (closed Issue #46836)
5500 Applicability::MaybeIncorrect
5504 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5505 self.cancel(&mut e);
5509 e.span_label(sp, "expected `{`");
5513 self.parse_block_tail(lo, BlockCheckMode::Default)
5516 /// Parses a block. Inner attributes are allowed.
5517 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5518 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5521 self.expect(&token::OpenDelim(token::Brace))?;
5522 Ok((self.parse_inner_attributes()?,
5523 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5526 /// Parses the rest of a block expression or function body.
5527 /// Precondition: already parsed the '{'.
5528 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5529 let mut stmts = vec![];
5530 while !self.eat(&token::CloseDelim(token::Brace)) {
5531 let stmt = match self.parse_full_stmt(false) {
5534 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5536 id: ast::DUMMY_NODE_ID,
5537 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5543 if let Some(stmt) = stmt {
5545 } else if self.token == token::Eof {
5548 // Found only `;` or `}`.
5554 id: ast::DUMMY_NODE_ID,
5556 span: lo.to(self.prev_span),
5560 /// Parses a statement, including the trailing semicolon.
5561 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5562 // skip looking for a trailing semicolon when we have an interpolated statement
5563 maybe_whole!(self, NtStmt, |x| Some(x));
5565 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5567 None => return Ok(None),
5571 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5572 // expression without semicolon
5573 if classify::expr_requires_semi_to_be_stmt(expr) {
5574 // Just check for errors and recover; do not eat semicolon yet.
5576 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5579 self.recover_stmt();
5583 StmtKind::Local(..) => {
5584 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5585 if macro_legacy_warnings && self.token != token::Semi {
5586 self.warn_missing_semicolon();
5588 self.expect_one_of(&[], &[token::Semi])?;
5594 if self.eat(&token::Semi) {
5595 stmt = stmt.add_trailing_semicolon();
5598 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5602 fn warn_missing_semicolon(&self) {
5603 self.diagnostic().struct_span_warn(self.span, {
5604 &format!("expected `;`, found {}", self.this_token_descr())
5606 "This was erroneously allowed and will become a hard error in a future release"
5610 fn err_dotdotdot_syntax(&self, span: Span) {
5611 self.diagnostic().struct_span_err(span, {
5612 "unexpected token: `...`"
5614 span, "use `..` for an exclusive range", "..".to_owned(),
5615 Applicability::MaybeIncorrect
5617 span, "or `..=` for an inclusive range", "..=".to_owned(),
5618 Applicability::MaybeIncorrect
5622 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5625 /// BOUND = TY_BOUND | LT_BOUND
5626 /// LT_BOUND = LIFETIME (e.g., `'a`)
5627 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5628 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5630 fn parse_generic_bounds_common(&mut self,
5632 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5633 let mut bounds = Vec::new();
5634 let mut negative_bounds = Vec::new();
5635 let mut last_plus_span = None;
5636 let mut was_negative = false;
5638 // This needs to be synchronized with `Token::can_begin_bound`.
5639 let is_bound_start = self.check_path() || self.check_lifetime() ||
5640 self.check(&token::Not) || // used for error reporting only
5641 self.check(&token::Question) ||
5642 self.check_keyword(keywords::For) ||
5643 self.check(&token::OpenDelim(token::Paren));
5646 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5647 let inner_lo = self.span;
5648 let is_negative = self.eat(&token::Not);
5649 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5650 if self.token.is_lifetime() {
5651 if let Some(question_span) = question {
5652 self.span_err(question_span,
5653 "`?` may only modify trait bounds, not lifetime bounds");
5655 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5657 let inner_span = inner_lo.to(self.prev_span);
5658 self.expect(&token::CloseDelim(token::Paren))?;
5659 let mut err = self.struct_span_err(
5660 lo.to(self.prev_span),
5661 "parenthesized lifetime bounds are not supported"
5663 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5664 err.span_suggestion_short(
5665 lo.to(self.prev_span),
5666 "remove the parentheses",
5668 Applicability::MachineApplicable
5674 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5675 let path = self.parse_path(PathStyle::Type)?;
5677 self.expect(&token::CloseDelim(token::Paren))?;
5679 let poly_span = lo.to(self.prev_span);
5681 was_negative = true;
5682 if let Some(sp) = last_plus_span.or(colon_span) {
5683 negative_bounds.push(sp.to(poly_span));
5686 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5687 let modifier = if question.is_some() {
5688 TraitBoundModifier::Maybe
5690 TraitBoundModifier::None
5692 bounds.push(GenericBound::Trait(poly_trait, modifier));
5699 if !allow_plus || !self.eat_plus() {
5702 last_plus_span = Some(self.prev_span);
5706 if !negative_bounds.is_empty() || was_negative {
5707 let plural = negative_bounds.len() > 1;
5708 let last_span = negative_bounds.last().map(|sp| *sp);
5709 let mut err = self.struct_span_err(
5711 "negative trait bounds are not supported",
5713 if let Some(sp) = last_span {
5714 err.span_label(sp, "negative trait bounds are not supported");
5716 if let Some(bound_list) = colon_span {
5717 let bound_list = bound_list.to(self.prev_span);
5718 let mut new_bound_list = String::new();
5719 if !bounds.is_empty() {
5720 let mut snippets = bounds.iter().map(|bound| bound.span())
5721 .map(|span| self.sess.source_map().span_to_snippet(span));
5722 while let Some(Ok(snippet)) = snippets.next() {
5723 new_bound_list.push_str(" + ");
5724 new_bound_list.push_str(&snippet);
5726 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5728 err.span_suggestion_hidden(
5730 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5732 Applicability::MachineApplicable,
5741 crate fn parse_generic_bounds(&mut self,
5742 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5743 self.parse_generic_bounds_common(true, colon_span)
5746 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5749 /// BOUND = LT_BOUND (e.g., `'a`)
5751 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5752 let mut lifetimes = Vec::new();
5753 while self.check_lifetime() {
5754 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5756 if !self.eat_plus() {
5763 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5764 fn parse_ty_param(&mut self,
5765 preceding_attrs: Vec<Attribute>)
5766 -> PResult<'a, GenericParam> {
5767 let ident = self.parse_ident()?;
5769 // Parse optional colon and param bounds.
5770 let bounds = if self.eat(&token::Colon) {
5771 self.parse_generic_bounds(Some(self.prev_span))?
5776 let default = if self.eat(&token::Eq) {
5777 Some(self.parse_ty()?)
5784 id: ast::DUMMY_NODE_ID,
5785 attrs: preceding_attrs.into(),
5787 kind: GenericParamKind::Type {
5793 /// Parses the following grammar:
5795 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5796 fn parse_trait_item_assoc_ty(&mut self)
5797 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5798 let ident = self.parse_ident()?;
5799 let mut generics = self.parse_generics()?;
5801 // Parse optional colon and param bounds.
5802 let bounds = if self.eat(&token::Colon) {
5803 self.parse_generic_bounds(None)?
5807 generics.where_clause = self.parse_where_clause()?;
5809 let default = if self.eat(&token::Eq) {
5810 Some(self.parse_ty()?)
5814 self.expect(&token::Semi)?;
5816 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5819 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5820 self.expect_keyword(keywords::Const)?;
5821 let ident = self.parse_ident()?;
5822 self.expect(&token::Colon)?;
5823 let ty = self.parse_ty()?;
5827 id: ast::DUMMY_NODE_ID,
5828 attrs: preceding_attrs.into(),
5830 kind: GenericParamKind::Const {
5836 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5837 /// a trailing comma and erroneous trailing attributes.
5838 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5839 let mut params = Vec::new();
5841 let attrs = self.parse_outer_attributes()?;
5842 if self.check_lifetime() {
5843 let lifetime = self.expect_lifetime();
5844 // Parse lifetime parameter.
5845 let bounds = if self.eat(&token::Colon) {
5846 self.parse_lt_param_bounds()
5850 params.push(ast::GenericParam {
5851 ident: lifetime.ident,
5853 attrs: attrs.into(),
5855 kind: ast::GenericParamKind::Lifetime,
5857 } else if self.check_keyword(keywords::Const) {
5858 // Parse const parameter.
5859 params.push(self.parse_const_param(attrs)?);
5860 } else if self.check_ident() {
5861 // Parse type parameter.
5862 params.push(self.parse_ty_param(attrs)?);
5864 // Check for trailing attributes and stop parsing.
5865 if !attrs.is_empty() {
5866 if !params.is_empty() {
5867 self.struct_span_err(
5869 &format!("trailing attribute after generic parameter"),
5871 .span_label(attrs[0].span, "attributes must go before parameters")
5874 self.struct_span_err(
5876 &format!("attribute without generic parameters"),
5880 "attributes are only permitted when preceding parameters",
5888 if !self.eat(&token::Comma) {
5895 /// Parses a set of optional generic type parameter declarations. Where
5896 /// clauses are not parsed here, and must be added later via
5897 /// `parse_where_clause()`.
5899 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5900 /// | ( < lifetimes , typaramseq ( , )? > )
5901 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5902 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5903 let span_lo = self.span;
5905 let params = self.parse_generic_params()?;
5909 where_clause: WhereClause {
5910 id: ast::DUMMY_NODE_ID,
5911 predicates: Vec::new(),
5912 span: syntax_pos::DUMMY_SP,
5914 span: span_lo.to(self.prev_span),
5917 Ok(ast::Generics::default())
5921 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5922 /// For the purposes of understanding the parsing logic of generic arguments, this function
5923 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5924 /// had the correct amount of leading angle brackets.
5926 /// ```ignore (diagnostics)
5927 /// bar::<<<<T as Foo>::Output>();
5928 /// ^^ help: remove extra angle brackets
5930 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5934 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5935 // We need to detect whether there are extra leading left angle brackets and produce an
5936 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5937 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5938 // then there won't be matching `>` tokens to find.
5940 // To explain how this detection works, consider the following example:
5942 // ```ignore (diagnostics)
5943 // bar::<<<<T as Foo>::Output>();
5944 // ^^ help: remove extra angle brackets
5947 // Parsing of the left angle brackets starts in this function. We start by parsing the
5948 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5951 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5952 // *Unmatched count:* 1
5953 // *`parse_path_segment` calls deep:* 0
5955 // This has the effect of recursing as this function is called if a `<` character
5956 // is found within the expected generic arguments:
5958 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5959 // *Unmatched count:* 2
5960 // *`parse_path_segment` calls deep:* 1
5962 // Eventually we will have recursed until having consumed all of the `<` tokens and
5963 // this will be reflected in the count:
5965 // *Upcoming tokens:* `T as Foo>::Output>;`
5966 // *Unmatched count:* 4
5967 // `parse_path_segment` calls deep:* 3
5969 // The parser will continue until reaching the first `>` - this will decrement the
5970 // unmatched angle bracket count and return to the parent invocation of this function
5971 // having succeeded in parsing:
5973 // *Upcoming tokens:* `::Output>;`
5974 // *Unmatched count:* 3
5975 // *`parse_path_segment` calls deep:* 2
5977 // This will continue until the next `>` character which will also return successfully
5978 // to the parent invocation of this function and decrement the count:
5980 // *Upcoming tokens:* `;`
5981 // *Unmatched count:* 2
5982 // *`parse_path_segment` calls deep:* 1
5984 // At this point, this function will expect to find another matching `>` character but
5985 // won't be able to and will return an error. This will continue all the way up the
5986 // call stack until the first invocation:
5988 // *Upcoming tokens:* `;`
5989 // *Unmatched count:* 2
5990 // *`parse_path_segment` calls deep:* 0
5992 // In doing this, we have managed to work out how many unmatched leading left angle
5993 // brackets there are, but we cannot recover as the unmatched angle brackets have
5994 // already been consumed. To remedy this, we keep a snapshot of the parser state
5995 // before we do the above. We can then inspect whether we ended up with a parsing error
5996 // and unmatched left angle brackets and if so, restore the parser state before we
5997 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5998 // recover by attempting to parse again.
6000 // In practice, the recursion of this function is indirect and there will be other
6001 // locations that consume some `<` characters - as long as we update the count when
6002 // this happens, it isn't an issue.
6004 let is_first_invocation = style == PathStyle::Expr;
6005 // Take a snapshot before attempting to parse - we can restore this later.
6006 let snapshot = if is_first_invocation {
6012 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
6013 match self.parse_generic_args() {
6014 Ok(value) => Ok(value),
6015 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
6016 // Cancel error from being unable to find `>`. We know the error
6017 // must have been this due to a non-zero unmatched angle bracket
6021 // Swap `self` with our backup of the parser state before attempting to parse
6022 // generic arguments.
6023 let snapshot = mem::replace(self, snapshot.unwrap());
6026 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
6027 snapshot.count={:?}",
6028 snapshot.unmatched_angle_bracket_count,
6031 // Eat the unmatched angle brackets.
6032 for _ in 0..snapshot.unmatched_angle_bracket_count {
6036 // Make a span over ${unmatched angle bracket count} characters.
6037 let span = lo.with_hi(
6038 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
6040 let plural = snapshot.unmatched_angle_bracket_count > 1;
6045 "unmatched angle bracket{}",
6046 if plural { "s" } else { "" }
6052 "remove extra angle bracket{}",
6053 if plural { "s" } else { "" }
6056 Applicability::MachineApplicable,
6060 // Try again without unmatched angle bracket characters.
6061 self.parse_generic_args()
6067 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
6068 /// possibly including trailing comma.
6069 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6070 let mut args = Vec::new();
6071 let mut bindings = Vec::new();
6072 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
6073 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
6075 let args_lo = self.span;
6078 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6079 // Parse lifetime argument.
6080 args.push(GenericArg::Lifetime(self.expect_lifetime()));
6081 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6082 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
6083 // Parse associated type binding.
6085 let ident = self.parse_ident()?;
6087 let ty = self.parse_ty()?;
6088 let span = lo.to(self.prev_span);
6089 bindings.push(TypeBinding {
6090 id: ast::DUMMY_NODE_ID,
6095 assoc_ty_bindings.push(span);
6096 } else if self.check_const_arg() {
6097 // Parse const argument.
6098 let expr = if let token::OpenDelim(token::Brace) = self.token {
6099 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
6100 } else if self.token.is_ident() {
6101 // FIXME(const_generics): to distinguish between idents for types and consts,
6102 // we should introduce a GenericArg::Ident in the AST and distinguish when
6103 // lowering to the HIR. For now, idents for const args are not permitted.
6105 self.fatal("identifiers may currently not be used for const generics")
6108 self.parse_literal_maybe_minus()?
6110 let value = AnonConst {
6111 id: ast::DUMMY_NODE_ID,
6114 args.push(GenericArg::Const(value));
6115 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6116 } else if self.check_type() {
6117 // Parse type argument.
6118 args.push(GenericArg::Type(self.parse_ty()?));
6119 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6124 if !self.eat(&token::Comma) {
6129 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6130 // preserve ordering of generic parameters with respect to associated type binding, so we
6131 // lose that information after parsing.
6132 if misplaced_assoc_ty_bindings.len() > 0 {
6133 let mut err = self.struct_span_err(
6134 args_lo.to(self.prev_span),
6135 "associated type bindings must be declared after generic parameters",
6137 for span in misplaced_assoc_ty_bindings {
6140 "this associated type binding should be moved after the generic parameters",
6146 Ok((args, bindings))
6149 /// Parses an optional where-clause and places it in `generics`.
6151 /// ```ignore (only-for-syntax-highlight)
6152 /// where T : Trait<U, V> + 'b, 'a : 'b
6154 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6155 let mut where_clause = WhereClause {
6156 id: ast::DUMMY_NODE_ID,
6157 predicates: Vec::new(),
6158 span: syntax_pos::DUMMY_SP,
6161 if !self.eat_keyword(keywords::Where) {
6162 return Ok(where_clause);
6164 let lo = self.prev_span;
6166 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6167 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6168 // change we parse those generics now, but report an error.
6169 if self.choose_generics_over_qpath() {
6170 let generics = self.parse_generics()?;
6171 self.struct_span_err(
6173 "generic parameters on `where` clauses are reserved for future use",
6175 .span_label(generics.span, "currently unsupported")
6181 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6182 let lifetime = self.expect_lifetime();
6183 // Bounds starting with a colon are mandatory, but possibly empty.
6184 self.expect(&token::Colon)?;
6185 let bounds = self.parse_lt_param_bounds();
6186 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6187 ast::WhereRegionPredicate {
6188 span: lo.to(self.prev_span),
6193 } else if self.check_type() {
6194 // Parse optional `for<'a, 'b>`.
6195 // This `for` is parsed greedily and applies to the whole predicate,
6196 // the bounded type can have its own `for` applying only to it.
6197 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6198 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6199 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6200 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6202 // Parse type with mandatory colon and (possibly empty) bounds,
6203 // or with mandatory equality sign and the second type.
6204 let ty = self.parse_ty()?;
6205 if self.eat(&token::Colon) {
6206 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6207 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6208 ast::WhereBoundPredicate {
6209 span: lo.to(self.prev_span),
6210 bound_generic_params: lifetime_defs,
6215 // FIXME: Decide what should be used here, `=` or `==`.
6216 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6217 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6218 let rhs_ty = self.parse_ty()?;
6219 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6220 ast::WhereEqPredicate {
6221 span: lo.to(self.prev_span),
6224 id: ast::DUMMY_NODE_ID,
6228 return self.unexpected();
6234 if !self.eat(&token::Comma) {
6239 where_clause.span = lo.to(self.prev_span);
6243 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6244 -> PResult<'a, (Vec<Arg> , bool)> {
6245 self.expect(&token::OpenDelim(token::Paren))?;
6248 let mut c_variadic = false;
6249 let (args, recovered): (Vec<Option<Arg>>, bool) =
6250 self.parse_seq_to_before_end(
6251 &token::CloseDelim(token::Paren),
6252 SeqSep::trailing_allowed(token::Comma),
6254 // If the argument is a C-variadic argument we should not
6255 // enforce named arguments.
6256 let enforce_named_args = if p.token == token::DotDotDot {
6261 match p.parse_arg_general(enforce_named_args, false,
6264 if let TyKind::CVarArgs = arg.ty.node {
6266 if p.token != token::CloseDelim(token::Paren) {
6269 "`...` must be the last argument of a C-variadic function");
6280 let lo = p.prev_span;
6281 // Skip every token until next possible arg or end.
6282 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6283 // Create a placeholder argument for proper arg count (issue #34264).
6284 let span = lo.to(p.prev_span);
6285 Ok(Some(dummy_arg(span)))
6292 self.eat(&token::CloseDelim(token::Paren));
6295 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6297 if c_variadic && args.is_empty() {
6299 "C-variadic function must be declared with at least one named argument");
6302 Ok((args, c_variadic))
6305 /// Parses the argument list and result type of a function declaration.
6306 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6308 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6309 let ret_ty = self.parse_ret_ty(true)?;
6318 /// Returns the parsed optional self argument and whether a self shortcut was used.
6319 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6320 let expect_ident = |this: &mut Self| match this.token {
6321 // Preserve hygienic context.
6322 token::Ident(ident, _) =>
6323 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6326 let isolated_self = |this: &mut Self, n| {
6327 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6328 this.look_ahead(n + 1, |t| t != &token::ModSep)
6331 // Parse optional self parameter of a method.
6332 // Only a limited set of initial token sequences is considered self parameters, anything
6333 // else is parsed as a normal function parameter list, so some lookahead is required.
6334 let eself_lo = self.span;
6335 let (eself, eself_ident, eself_hi) = match self.token {
6336 token::BinOp(token::And) => {
6342 (if isolated_self(self, 1) {
6344 SelfKind::Region(None, Mutability::Immutable)
6345 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6346 isolated_self(self, 2) {
6349 SelfKind::Region(None, Mutability::Mutable)
6350 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6351 isolated_self(self, 2) {
6353 let lt = self.expect_lifetime();
6354 SelfKind::Region(Some(lt), Mutability::Immutable)
6355 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6356 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6357 isolated_self(self, 3) {
6359 let lt = self.expect_lifetime();
6361 SelfKind::Region(Some(lt), Mutability::Mutable)
6364 }, expect_ident(self), self.prev_span)
6366 token::BinOp(token::Star) => {
6371 // Emit special error for `self` cases.
6372 let msg = "cannot pass `self` by raw pointer";
6373 (if isolated_self(self, 1) {
6375 self.struct_span_err(self.span, msg)
6376 .span_label(self.span, msg)
6378 SelfKind::Value(Mutability::Immutable)
6379 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6380 isolated_self(self, 2) {
6383 self.struct_span_err(self.span, msg)
6384 .span_label(self.span, msg)
6386 SelfKind::Value(Mutability::Immutable)
6389 }, expect_ident(self), self.prev_span)
6391 token::Ident(..) => {
6392 if isolated_self(self, 0) {
6395 let eself_ident = expect_ident(self);
6396 let eself_hi = self.prev_span;
6397 (if self.eat(&token::Colon) {
6398 let ty = self.parse_ty()?;
6399 SelfKind::Explicit(ty, Mutability::Immutable)
6401 SelfKind::Value(Mutability::Immutable)
6402 }, eself_ident, eself_hi)
6403 } else if self.token.is_keyword(keywords::Mut) &&
6404 isolated_self(self, 1) {
6408 let eself_ident = expect_ident(self);
6409 let eself_hi = self.prev_span;
6410 (if self.eat(&token::Colon) {
6411 let ty = self.parse_ty()?;
6412 SelfKind::Explicit(ty, Mutability::Mutable)
6414 SelfKind::Value(Mutability::Mutable)
6415 }, eself_ident, eself_hi)
6420 _ => return Ok(None),
6423 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6424 Ok(Some(Arg::from_self(eself, eself_ident)))
6427 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6428 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6429 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6431 self.expect(&token::OpenDelim(token::Paren))?;
6433 // Parse optional self argument
6434 let self_arg = self.parse_self_arg()?;
6436 // Parse the rest of the function parameter list.
6437 let sep = SeqSep::trailing_allowed(token::Comma);
6438 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6439 if self.check(&token::CloseDelim(token::Paren)) {
6440 (vec![self_arg], false)
6441 } else if self.eat(&token::Comma) {
6442 let mut fn_inputs = vec![self_arg];
6443 let (mut input, recovered) = self.parse_seq_to_before_end(
6444 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6445 fn_inputs.append(&mut input);
6446 (fn_inputs, recovered)
6448 match self.expect_one_of(&[], &[]) {
6449 Err(err) => return Err(err),
6450 Ok(recovered) => (vec![self_arg], recovered),
6454 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6458 // Parse closing paren and return type.
6459 self.expect(&token::CloseDelim(token::Paren))?;
6463 output: self.parse_ret_ty(true)?,
6468 /// Parses the `|arg, arg|` header of a closure.
6469 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6470 let inputs_captures = {
6471 if self.eat(&token::OrOr) {
6474 self.expect(&token::BinOp(token::Or))?;
6475 let args = self.parse_seq_to_before_tokens(
6476 &[&token::BinOp(token::Or), &token::OrOr],
6477 SeqSep::trailing_allowed(token::Comma),
6478 TokenExpectType::NoExpect,
6479 |p| p.parse_fn_block_arg()
6485 let output = self.parse_ret_ty(true)?;
6488 inputs: inputs_captures,
6494 /// Parses the name and optional generic types of a function header.
6495 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6496 let id = self.parse_ident()?;
6497 let generics = self.parse_generics()?;
6501 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6502 attrs: Vec<Attribute>) -> P<Item> {
6506 id: ast::DUMMY_NODE_ID,
6514 /// Parses an item-position function declaration.
6515 fn parse_item_fn(&mut self,
6517 mut asyncness: Spanned<IsAsync>,
6518 constness: Spanned<Constness>,
6520 -> PResult<'a, ItemInfo> {
6521 let (ident, mut generics) = self.parse_fn_header()?;
6522 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6523 let mut decl = self.parse_fn_decl(allow_c_variadic)?;
6524 generics.where_clause = self.parse_where_clause()?;
6525 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6526 self.construct_async_arguments(&mut asyncness, &mut decl);
6527 let header = FnHeader { unsafety, asyncness, constness, abi };
6528 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6531 /// Returns `true` if we are looking at `const ID`
6532 /// (returns `false` for things like `const fn`, etc.).
6533 fn is_const_item(&self) -> bool {
6534 self.token.is_keyword(keywords::Const) &&
6535 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6536 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6539 /// Parses all the "front matter" for a `fn` declaration, up to
6540 /// and including the `fn` keyword:
6544 /// - `const unsafe fn`
6547 fn parse_fn_front_matter(&mut self)
6555 let is_const_fn = self.eat_keyword(keywords::Const);
6556 let const_span = self.prev_span;
6557 let unsafety = self.parse_unsafety();
6558 let asyncness = self.parse_asyncness();
6559 let asyncness = respan(self.prev_span, asyncness);
6560 let (constness, unsafety, abi) = if is_const_fn {
6561 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6563 let abi = if self.eat_keyword(keywords::Extern) {
6564 self.parse_opt_abi()?.unwrap_or(Abi::C)
6568 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6570 if !self.eat_keyword(keywords::Fn) {
6571 // It is possible for `expect_one_of` to recover given the contents of
6572 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6573 // account for this.
6574 if !self.expect_one_of(&[], &[])? { unreachable!() }
6576 Ok((constness, unsafety, asyncness, abi))
6579 /// Parses an impl item.
6580 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6581 maybe_whole!(self, NtImplItem, |x| x);
6582 let attrs = self.parse_outer_attributes()?;
6583 let mut unclosed_delims = vec![];
6584 let (mut item, tokens) = self.collect_tokens(|this| {
6585 let item = this.parse_impl_item_(at_end, attrs);
6586 unclosed_delims.append(&mut this.unclosed_delims);
6589 self.unclosed_delims.append(&mut unclosed_delims);
6591 // See `parse_item` for why this clause is here.
6592 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6593 item.tokens = Some(tokens);
6598 fn parse_impl_item_(&mut self,
6600 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6602 let vis = self.parse_visibility(false)?;
6603 let defaultness = self.parse_defaultness();
6604 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6605 let (name, alias, generics) = type_?;
6606 let kind = match alias {
6607 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6608 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6610 (name, kind, generics)
6611 } else if self.is_const_item() {
6612 // This parses the grammar:
6613 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6614 self.expect_keyword(keywords::Const)?;
6615 let name = self.parse_ident()?;
6616 self.expect(&token::Colon)?;
6617 let typ = self.parse_ty()?;
6618 self.expect(&token::Eq)?;
6619 let expr = self.parse_expr()?;
6620 self.expect(&token::Semi)?;
6621 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6623 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6624 attrs.extend(inner_attrs);
6625 (name, node, generics)
6629 id: ast::DUMMY_NODE_ID,
6630 span: lo.to(self.prev_span),
6641 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
6643 VisibilityKind::Inherited => {}
6645 let is_macro_rules: bool = match self.token {
6646 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6649 let mut err = if is_macro_rules {
6650 let mut err = self.diagnostic()
6651 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6652 err.span_suggestion(
6654 "try exporting the macro",
6655 "#[macro_export]".to_owned(),
6656 Applicability::MaybeIncorrect // speculative
6660 let mut err = self.diagnostic()
6661 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6662 err.help("try adjusting the macro to put `pub` inside the invocation");
6670 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
6671 -> DiagnosticBuilder<'a>
6673 let expected_kinds = if item_type == "extern" {
6674 "missing `fn`, `type`, or `static`"
6676 "missing `fn`, `type`, or `const`"
6679 // Given this code `path(`, it seems like this is not
6680 // setting the visibility of a macro invocation, but rather
6681 // a mistyped method declaration.
6682 // Create a diagnostic pointing out that `fn` is missing.
6684 // x | pub path(&self) {
6685 // | ^ missing `fn`, `type`, or `const`
6687 // ^^ `sp` below will point to this
6688 let sp = prev_span.between(self.prev_span);
6689 let mut err = self.diagnostic().struct_span_err(
6691 &format!("{} for {}-item declaration",
6692 expected_kinds, item_type));
6693 err.span_label(sp, expected_kinds);
6697 /// Parse a method or a macro invocation in a trait impl.
6698 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6699 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6700 ast::ImplItemKind)> {
6701 // code copied from parse_macro_use_or_failure... abstraction!
6702 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6704 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6705 ast::ImplItemKind::Macro(mac)))
6707 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6708 let ident = self.parse_ident()?;
6709 let mut generics = self.parse_generics()?;
6710 let mut decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6711 generics.where_clause = self.parse_where_clause()?;
6712 self.construct_async_arguments(&mut asyncness, &mut decl);
6714 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6715 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6716 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6717 ast::MethodSig { header, decl },
6723 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6724 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6725 let ident = self.parse_ident()?;
6726 let mut tps = self.parse_generics()?;
6728 // Parse optional colon and supertrait bounds.
6729 let bounds = if self.eat(&token::Colon) {
6730 self.parse_generic_bounds(Some(self.prev_span))?
6735 if self.eat(&token::Eq) {
6736 // it's a trait alias
6737 let bounds = self.parse_generic_bounds(None)?;
6738 tps.where_clause = self.parse_where_clause()?;
6739 self.expect(&token::Semi)?;
6740 if is_auto == IsAuto::Yes {
6741 let msg = "trait aliases cannot be `auto`";
6742 self.struct_span_err(self.prev_span, msg)
6743 .span_label(self.prev_span, msg)
6746 if unsafety != Unsafety::Normal {
6747 let msg = "trait aliases cannot be `unsafe`";
6748 self.struct_span_err(self.prev_span, msg)
6749 .span_label(self.prev_span, msg)
6752 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6754 // it's a normal trait
6755 tps.where_clause = self.parse_where_clause()?;
6756 self.expect(&token::OpenDelim(token::Brace))?;
6757 let mut trait_items = vec![];
6758 while !self.eat(&token::CloseDelim(token::Brace)) {
6759 if let token::DocComment(_) = self.token {
6760 if self.look_ahead(1,
6761 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6762 let mut err = self.diagnostic().struct_span_err_with_code(
6764 "found a documentation comment that doesn't document anything",
6765 DiagnosticId::Error("E0584".into()),
6767 err.help("doc comments must come before what they document, maybe a \
6768 comment was intended with `//`?",
6775 let mut at_end = false;
6776 match self.parse_trait_item(&mut at_end) {
6777 Ok(item) => trait_items.push(item),
6781 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6786 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6790 fn choose_generics_over_qpath(&self) -> bool {
6791 // There's an ambiguity between generic parameters and qualified paths in impls.
6792 // If we see `<` it may start both, so we have to inspect some following tokens.
6793 // The following combinations can only start generics,
6794 // but not qualified paths (with one exception):
6795 // `<` `>` - empty generic parameters
6796 // `<` `#` - generic parameters with attributes
6797 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6798 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6799 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6800 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6801 // `<` const - generic const parameter
6802 // The only truly ambiguous case is
6803 // `<` IDENT `>` `::` IDENT ...
6804 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6805 // because this is what almost always expected in practice, qualified paths in impls
6806 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6807 self.token == token::Lt &&
6808 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6809 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6810 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6811 t == &token::Colon || t == &token::Eq) ||
6812 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6815 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6816 self.expect(&token::OpenDelim(token::Brace))?;
6817 let attrs = self.parse_inner_attributes()?;
6819 let mut impl_items = Vec::new();
6820 while !self.eat(&token::CloseDelim(token::Brace)) {
6821 let mut at_end = false;
6822 match self.parse_impl_item(&mut at_end) {
6823 Ok(impl_item) => impl_items.push(impl_item),
6827 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6832 Ok((impl_items, attrs))
6835 /// Parses an implementation item, `impl` keyword is already parsed.
6837 /// impl<'a, T> TYPE { /* impl items */ }
6838 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6839 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6841 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6842 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6843 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6844 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6845 -> PResult<'a, ItemInfo> {
6846 // First, parse generic parameters if necessary.
6847 let mut generics = if self.choose_generics_over_qpath() {
6848 self.parse_generics()?
6850 ast::Generics::default()
6853 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6854 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6856 ast::ImplPolarity::Negative
6858 ast::ImplPolarity::Positive
6861 // Parse both types and traits as a type, then reinterpret if necessary.
6862 let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6863 let ty_first = if self.token.is_keyword(keywords::For) &&
6864 self.look_ahead(1, |t| t != &token::Lt) {
6865 let span = self.prev_span.between(self.span);
6866 self.struct_span_err(span, "missing trait in a trait impl").emit();
6867 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6872 // If `for` is missing we try to recover.
6873 let has_for = self.eat_keyword(keywords::For);
6874 let missing_for_span = self.prev_span.between(self.span);
6876 let ty_second = if self.token == token::DotDot {
6877 // We need to report this error after `cfg` expansion for compatibility reasons
6878 self.bump(); // `..`, do not add it to expected tokens
6879 Some(DummyResult::raw_ty(self.prev_span, true))
6880 } else if has_for || self.token.can_begin_type() {
6881 Some(self.parse_ty()?)
6886 generics.where_clause = self.parse_where_clause()?;
6888 let (impl_items, attrs) = self.parse_impl_body()?;
6890 let item_kind = match ty_second {
6891 Some(ty_second) => {
6892 // impl Trait for Type
6894 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6895 .span_suggestion_short(
6898 " for ".to_string(),
6899 Applicability::MachineApplicable,
6903 let ty_first = ty_first.into_inner();
6904 let path = match ty_first.node {
6905 // This notably includes paths passed through `ty` macro fragments (#46438).
6906 TyKind::Path(None, path) => path,
6908 self.span_err(ty_first.span, "expected a trait, found type");
6909 err_path(ty_first.span)
6912 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6914 ItemKind::Impl(unsafety, polarity, defaultness,
6915 generics, Some(trait_ref), ty_second, impl_items)
6919 ItemKind::Impl(unsafety, polarity, defaultness,
6920 generics, None, ty_first, impl_items)
6924 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6927 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6928 if self.eat_keyword(keywords::For) {
6930 let params = self.parse_generic_params()?;
6932 // We rely on AST validation to rule out invalid cases: There must not be type
6933 // parameters, and the lifetime parameters must not have bounds.
6940 /// Parses `struct Foo { ... }`.
6941 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6942 let class_name = self.parse_ident()?;
6944 let mut generics = self.parse_generics()?;
6946 // There is a special case worth noting here, as reported in issue #17904.
6947 // If we are parsing a tuple struct it is the case that the where clause
6948 // should follow the field list. Like so:
6950 // struct Foo<T>(T) where T: Copy;
6952 // If we are parsing a normal record-style struct it is the case
6953 // that the where clause comes before the body, and after the generics.
6954 // So if we look ahead and see a brace or a where-clause we begin
6955 // parsing a record style struct.
6957 // Otherwise if we look ahead and see a paren we parse a tuple-style
6960 let vdata = if self.token.is_keyword(keywords::Where) {
6961 generics.where_clause = self.parse_where_clause()?;
6962 if self.eat(&token::Semi) {
6963 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6964 VariantData::Unit(ast::DUMMY_NODE_ID)
6966 // If we see: `struct Foo<T> where T: Copy { ... }`
6967 let (fields, recovered) = self.parse_record_struct_body()?;
6968 VariantData::Struct(fields, recovered)
6970 // No `where` so: `struct Foo<T>;`
6971 } else if self.eat(&token::Semi) {
6972 VariantData::Unit(ast::DUMMY_NODE_ID)
6973 // Record-style struct definition
6974 } else if self.token == token::OpenDelim(token::Brace) {
6975 let (fields, recovered) = self.parse_record_struct_body()?;
6976 VariantData::Struct(fields, recovered)
6977 // Tuple-style struct definition with optional where-clause.
6978 } else if self.token == token::OpenDelim(token::Paren) {
6979 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6980 generics.where_clause = self.parse_where_clause()?;
6981 self.expect(&token::Semi)?;
6984 let token_str = self.this_token_descr();
6985 let mut err = self.fatal(&format!(
6986 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6989 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6993 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6996 /// Parses `union Foo { ... }`.
6997 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6998 let class_name = self.parse_ident()?;
7000 let mut generics = self.parse_generics()?;
7002 let vdata = if self.token.is_keyword(keywords::Where) {
7003 generics.where_clause = self.parse_where_clause()?;
7004 let (fields, recovered) = self.parse_record_struct_body()?;
7005 VariantData::Struct(fields, recovered)
7006 } else if self.token == token::OpenDelim(token::Brace) {
7007 let (fields, recovered) = self.parse_record_struct_body()?;
7008 VariantData::Struct(fields, recovered)
7010 let token_str = self.this_token_descr();
7011 let mut err = self.fatal(&format!(
7012 "expected `where` or `{{` after union name, found {}", token_str));
7013 err.span_label(self.span, "expected `where` or `{` after union name");
7017 Ok((class_name, ItemKind::Union(vdata, generics), None))
7020 fn consume_block(&mut self, delim: token::DelimToken) {
7021 let mut brace_depth = 0;
7023 if self.eat(&token::OpenDelim(delim)) {
7025 } else if self.eat(&token::CloseDelim(delim)) {
7026 if brace_depth == 0 {
7032 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
7040 fn parse_record_struct_body(
7042 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
7043 let mut fields = Vec::new();
7044 let mut recovered = false;
7045 if self.eat(&token::OpenDelim(token::Brace)) {
7046 while self.token != token::CloseDelim(token::Brace) {
7047 let field = self.parse_struct_decl_field().map_err(|e| {
7048 self.recover_stmt();
7053 Ok(field) => fields.push(field),
7059 self.eat(&token::CloseDelim(token::Brace));
7061 let token_str = self.this_token_descr();
7062 let mut err = self.fatal(&format!(
7063 "expected `where`, or `{{` after struct name, found {}", token_str));
7064 err.span_label(self.span, "expected `where`, or `{` after struct name");
7068 Ok((fields, recovered))
7071 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
7072 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
7073 // Unit like structs are handled in parse_item_struct function
7074 let fields = self.parse_unspanned_seq(
7075 &token::OpenDelim(token::Paren),
7076 &token::CloseDelim(token::Paren),
7077 SeqSep::trailing_allowed(token::Comma),
7079 let attrs = p.parse_outer_attributes()?;
7081 let vis = p.parse_visibility(true)?;
7082 let ty = p.parse_ty()?;
7084 span: lo.to(ty.span),
7087 id: ast::DUMMY_NODE_ID,
7096 /// Parses a structure field declaration.
7097 fn parse_single_struct_field(&mut self,
7100 attrs: Vec<Attribute> )
7101 -> PResult<'a, StructField> {
7102 let mut seen_comma: bool = false;
7103 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
7104 if self.token == token::Comma {
7111 token::CloseDelim(token::Brace) => {}
7112 token::DocComment(_) => {
7113 let previous_span = self.prev_span;
7114 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
7115 self.bump(); // consume the doc comment
7116 let comma_after_doc_seen = self.eat(&token::Comma);
7117 // `seen_comma` is always false, because we are inside doc block
7118 // condition is here to make code more readable
7119 if seen_comma == false && comma_after_doc_seen == true {
7122 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7125 if seen_comma == false {
7126 let sp = self.sess.source_map().next_point(previous_span);
7127 err.span_suggestion(
7129 "missing comma here",
7131 Applicability::MachineApplicable
7138 let sp = self.sess.source_map().next_point(self.prev_span);
7139 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7140 self.this_token_descr()));
7141 if self.token.is_ident() {
7142 // This is likely another field; emit the diagnostic and keep going
7143 err.span_suggestion(
7145 "try adding a comma",
7147 Applicability::MachineApplicable,
7158 /// Parses an element of a struct declaration.
7159 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7160 let attrs = self.parse_outer_attributes()?;
7162 let vis = self.parse_visibility(false)?;
7163 self.parse_single_struct_field(lo, vis, attrs)
7166 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7167 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7168 /// If the following element can't be a tuple (i.e., it's a function definition), then
7169 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7170 /// so emit a proper diagnostic.
7171 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7172 maybe_whole!(self, NtVis, |x| x);
7174 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7175 if self.is_crate_vis() {
7176 self.bump(); // `crate`
7177 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7180 if !self.eat_keyword(keywords::Pub) {
7181 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7182 // keyword to grab a span from for inherited visibility; an empty span at the
7183 // beginning of the current token would seem to be the "Schelling span".
7184 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7186 let lo = self.prev_span;
7188 if self.check(&token::OpenDelim(token::Paren)) {
7189 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7190 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7191 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7192 // by the following tokens.
7193 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) &&
7194 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
7198 self.bump(); // `crate`
7199 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7201 lo.to(self.prev_span),
7202 VisibilityKind::Crate(CrateSugar::PubCrate),
7205 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7208 self.bump(); // `in`
7209 let path = self.parse_path(PathStyle::Mod)?; // `path`
7210 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7211 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7213 id: ast::DUMMY_NODE_ID,
7216 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7217 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7218 t.is_keyword(keywords::SelfLower))
7220 // `pub(self)` or `pub(super)`
7222 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7223 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7224 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7226 id: ast::DUMMY_NODE_ID,
7229 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7230 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7232 let msg = "incorrect visibility restriction";
7233 let suggestion = r##"some possible visibility restrictions are:
7234 `pub(crate)`: visible only on the current crate
7235 `pub(super)`: visible only in the current module's parent
7236 `pub(in path::to::module)`: visible only on the specified path"##;
7237 let path = self.parse_path(PathStyle::Mod)?;
7239 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7240 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7241 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7242 err.help(suggestion);
7243 err.span_suggestion(
7244 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7246 err.emit(); // emit diagnostic, but continue with public visibility
7250 Ok(respan(lo, VisibilityKind::Public))
7253 /// Parses defaultness (i.e., `default` or nothing).
7254 fn parse_defaultness(&mut self) -> Defaultness {
7255 // `pub` is included for better error messages
7256 if self.check_keyword(keywords::Default) &&
7257 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7258 t.is_keyword(keywords::Const) ||
7259 t.is_keyword(keywords::Fn) ||
7260 t.is_keyword(keywords::Unsafe) ||
7261 t.is_keyword(keywords::Extern) ||
7262 t.is_keyword(keywords::Type) ||
7263 t.is_keyword(keywords::Pub)) {
7264 self.bump(); // `default`
7265 Defaultness::Default
7271 /// Given a termination token, parses all of the items in a module.
7272 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7273 let mut items = vec![];
7274 while let Some(item) = self.parse_item()? {
7276 self.maybe_consume_incorrect_semicolon(&items);
7279 if !self.eat(term) {
7280 let token_str = self.this_token_descr();
7281 if !self.maybe_consume_incorrect_semicolon(&items) {
7282 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7283 err.span_label(self.span, "expected item");
7288 let hi = if self.span.is_dummy() {
7295 inner: inner_lo.to(hi),
7301 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7302 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7303 self.expect(&token::Colon)?;
7304 let ty = self.parse_ty()?;
7305 self.expect(&token::Eq)?;
7306 let e = self.parse_expr()?;
7307 self.expect(&token::Semi)?;
7308 let item = match m {
7309 Some(m) => ItemKind::Static(ty, m, e),
7310 None => ItemKind::Const(ty, e),
7312 Ok((id, item, None))
7315 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7316 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7317 let (in_cfg, outer_attrs) = {
7318 let mut strip_unconfigured = crate::config::StripUnconfigured {
7320 features: None, // don't perform gated feature checking
7322 let mut outer_attrs = outer_attrs.to_owned();
7323 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7324 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7327 let id_span = self.span;
7328 let id = self.parse_ident()?;
7329 if self.eat(&token::Semi) {
7330 if in_cfg && self.recurse_into_file_modules {
7331 // This mod is in an external file. Let's go get it!
7332 let ModulePathSuccess { path, directory_ownership, warn } =
7333 self.submod_path(id, &outer_attrs, id_span)?;
7334 let (module, mut attrs) =
7335 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7336 // Record that we fetched the mod from an external file
7338 let attr = Attribute {
7339 id: attr::mk_attr_id(),
7340 style: ast::AttrStyle::Outer,
7341 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7342 tokens: TokenStream::empty(),
7343 is_sugared_doc: false,
7344 span: syntax_pos::DUMMY_SP,
7346 attr::mark_known(&attr);
7349 Ok((id, ItemKind::Mod(module), Some(attrs)))
7351 let placeholder = ast::Mod {
7352 inner: syntax_pos::DUMMY_SP,
7356 Ok((id, ItemKind::Mod(placeholder), None))
7359 let old_directory = self.directory.clone();
7360 self.push_directory(id, &outer_attrs);
7362 self.expect(&token::OpenDelim(token::Brace))?;
7363 let mod_inner_lo = self.span;
7364 let attrs = self.parse_inner_attributes()?;
7365 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7367 self.directory = old_directory;
7368 Ok((id, ItemKind::Mod(module), Some(attrs)))
7372 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7373 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7374 self.directory.path.to_mut().push(&path.as_str());
7375 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7377 // We have to push on the current module name in the case of relative
7378 // paths in order to ensure that any additional module paths from inline
7379 // `mod x { ... }` come after the relative extension.
7381 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7382 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7383 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7384 if let Some(ident) = relative.take() { // remove the relative offset
7385 self.directory.path.to_mut().push(ident.as_str());
7388 self.directory.path.to_mut().push(&id.as_str());
7392 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7393 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7396 // On windows, the base path might have the form
7397 // `\\?\foo\bar` in which case it does not tolerate
7398 // mixed `/` and `\` separators, so canonicalize
7401 let s = s.replace("/", "\\");
7402 Some(dir_path.join(s))
7408 /// Returns a path to a module.
7409 pub fn default_submod_path(
7411 relative: Option<ast::Ident>,
7413 source_map: &SourceMap) -> ModulePath
7415 // If we're in a foo.rs file instead of a mod.rs file,
7416 // we need to look for submodules in
7417 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7418 // `./<id>.rs` and `./<id>/mod.rs`.
7419 let relative_prefix_string;
7420 let relative_prefix = if let Some(ident) = relative {
7421 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7422 &relative_prefix_string
7427 let mod_name = id.to_string();
7428 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7429 let secondary_path_str = format!("{}{}{}mod.rs",
7430 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7431 let default_path = dir_path.join(&default_path_str);
7432 let secondary_path = dir_path.join(&secondary_path_str);
7433 let default_exists = source_map.file_exists(&default_path);
7434 let secondary_exists = source_map.file_exists(&secondary_path);
7436 let result = match (default_exists, secondary_exists) {
7437 (true, false) => Ok(ModulePathSuccess {
7439 directory_ownership: DirectoryOwnership::Owned {
7444 (false, true) => Ok(ModulePathSuccess {
7445 path: secondary_path,
7446 directory_ownership: DirectoryOwnership::Owned {
7451 (false, false) => Err(Error::FileNotFoundForModule {
7452 mod_name: mod_name.clone(),
7453 default_path: default_path_str,
7454 secondary_path: secondary_path_str,
7455 dir_path: dir_path.display().to_string(),
7457 (true, true) => Err(Error::DuplicatePaths {
7458 mod_name: mod_name.clone(),
7459 default_path: default_path_str,
7460 secondary_path: secondary_path_str,
7466 path_exists: default_exists || secondary_exists,
7471 fn submod_path(&mut self,
7473 outer_attrs: &[Attribute],
7475 -> PResult<'a, ModulePathSuccess> {
7476 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7477 return Ok(ModulePathSuccess {
7478 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7479 // All `#[path]` files are treated as though they are a `mod.rs` file.
7480 // This means that `mod foo;` declarations inside `#[path]`-included
7481 // files are siblings,
7483 // Note that this will produce weirdness when a file named `foo.rs` is
7484 // `#[path]` included and contains a `mod foo;` declaration.
7485 // If you encounter this, it's your own darn fault :P
7486 Some(_) => DirectoryOwnership::Owned { relative: None },
7487 _ => DirectoryOwnership::UnownedViaMod(true),
7494 let relative = match self.directory.ownership {
7495 DirectoryOwnership::Owned { relative } => relative,
7496 DirectoryOwnership::UnownedViaBlock |
7497 DirectoryOwnership::UnownedViaMod(_) => None,
7499 let paths = Parser::default_submod_path(
7500 id, relative, &self.directory.path, self.sess.source_map());
7502 match self.directory.ownership {
7503 DirectoryOwnership::Owned { .. } => {
7504 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7506 DirectoryOwnership::UnownedViaBlock => {
7508 "Cannot declare a non-inline module inside a block \
7509 unless it has a path attribute";
7510 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7511 if paths.path_exists {
7512 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7514 err.span_note(id_sp, &msg);
7518 DirectoryOwnership::UnownedViaMod(warn) => {
7520 if let Ok(result) = paths.result {
7521 return Ok(ModulePathSuccess { warn: true, ..result });
7524 let mut err = self.diagnostic().struct_span_err(id_sp,
7525 "cannot declare a new module at this location");
7526 if !id_sp.is_dummy() {
7527 let src_path = self.sess.source_map().span_to_filename(id_sp);
7528 if let FileName::Real(src_path) = src_path {
7529 if let Some(stem) = src_path.file_stem() {
7530 let mut dest_path = src_path.clone();
7531 dest_path.set_file_name(stem);
7532 dest_path.push("mod.rs");
7533 err.span_note(id_sp,
7534 &format!("maybe move this module `{}` to its own \
7535 directory via `{}`", src_path.display(),
7536 dest_path.display()));
7540 if paths.path_exists {
7541 err.span_note(id_sp,
7542 &format!("... or maybe `use` the module `{}` instead \
7543 of possibly redeclaring it",
7551 /// Reads a module from a source file.
7552 fn eval_src_mod(&mut self,
7554 directory_ownership: DirectoryOwnership,
7557 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7558 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7559 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7560 let mut err = String::from("circular modules: ");
7561 let len = included_mod_stack.len();
7562 for p in &included_mod_stack[i.. len] {
7563 err.push_str(&p.to_string_lossy());
7564 err.push_str(" -> ");
7566 err.push_str(&path.to_string_lossy());
7567 return Err(self.span_fatal(id_sp, &err[..]));
7569 included_mod_stack.push(path.clone());
7570 drop(included_mod_stack);
7573 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7574 p0.cfg_mods = self.cfg_mods;
7575 let mod_inner_lo = p0.span;
7576 let mod_attrs = p0.parse_inner_attributes()?;
7577 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7579 self.sess.included_mod_stack.borrow_mut().pop();
7583 /// Parses a function declaration from a foreign module.
7584 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7585 -> PResult<'a, ForeignItem> {
7586 self.expect_keyword(keywords::Fn)?;
7588 let (ident, mut generics) = self.parse_fn_header()?;
7589 let decl = self.parse_fn_decl(true)?;
7590 generics.where_clause = self.parse_where_clause()?;
7592 self.expect(&token::Semi)?;
7593 Ok(ast::ForeignItem {
7596 node: ForeignItemKind::Fn(decl, generics),
7597 id: ast::DUMMY_NODE_ID,
7603 /// Parses a static item from a foreign module.
7604 /// Assumes that the `static` keyword is already parsed.
7605 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7606 -> PResult<'a, ForeignItem> {
7607 let mutbl = self.parse_mutability();
7608 let ident = self.parse_ident()?;
7609 self.expect(&token::Colon)?;
7610 let ty = self.parse_ty()?;
7612 self.expect(&token::Semi)?;
7616 node: ForeignItemKind::Static(ty, mutbl),
7617 id: ast::DUMMY_NODE_ID,
7623 /// Parses a type from a foreign module.
7624 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7625 -> PResult<'a, ForeignItem> {
7626 self.expect_keyword(keywords::Type)?;
7628 let ident = self.parse_ident()?;
7630 self.expect(&token::Semi)?;
7631 Ok(ast::ForeignItem {
7634 node: ForeignItemKind::Ty,
7635 id: ast::DUMMY_NODE_ID,
7641 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7642 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7643 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7645 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7646 self.parse_path_segment_ident()
7650 let mut idents = vec![];
7651 let mut replacement = vec![];
7652 let mut fixed_crate_name = false;
7653 // Accept `extern crate name-like-this` for better diagnostics
7654 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7655 if self.token == dash { // Do not include `-` as part of the expected tokens list
7656 while self.eat(&dash) {
7657 fixed_crate_name = true;
7658 replacement.push((self.prev_span, "_".to_string()));
7659 idents.push(self.parse_ident()?);
7662 if fixed_crate_name {
7663 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7664 let mut fixed_name = format!("{}", ident.name);
7665 for part in idents {
7666 fixed_name.push_str(&format!("_{}", part.name));
7668 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7670 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7671 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7672 err.multipart_suggestion(
7675 Applicability::MachineApplicable,
7682 /// Parses `extern crate` links.
7687 /// extern crate foo;
7688 /// extern crate bar as foo;
7690 fn parse_item_extern_crate(&mut self,
7692 visibility: Visibility,
7693 attrs: Vec<Attribute>)
7694 -> PResult<'a, P<Item>> {
7695 // Accept `extern crate name-like-this` for better diagnostics
7696 let orig_name = self.parse_crate_name_with_dashes()?;
7697 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7698 (rename, Some(orig_name.name))
7702 self.expect(&token::Semi)?;
7704 let span = lo.to(self.prev_span);
7705 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7708 /// Parses `extern` for foreign ABIs modules.
7710 /// `extern` is expected to have been
7711 /// consumed before calling this method.
7715 /// ```ignore (only-for-syntax-highlight)
7719 fn parse_item_foreign_mod(&mut self,
7721 opt_abi: Option<Abi>,
7722 visibility: Visibility,
7723 mut attrs: Vec<Attribute>)
7724 -> PResult<'a, P<Item>> {
7725 self.expect(&token::OpenDelim(token::Brace))?;
7727 let abi = opt_abi.unwrap_or(Abi::C);
7729 attrs.extend(self.parse_inner_attributes()?);
7731 let mut foreign_items = vec![];
7732 while !self.eat(&token::CloseDelim(token::Brace)) {
7733 foreign_items.push(self.parse_foreign_item()?);
7736 let prev_span = self.prev_span;
7737 let m = ast::ForeignMod {
7739 items: foreign_items
7741 let invalid = keywords::Invalid.ident();
7742 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7745 /// Parses `type Foo = Bar;`
7747 /// `existential type Foo: Bar;`
7750 /// without modifying the parser state.
7751 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7752 // This parses the grammar:
7753 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7754 if self.check_keyword(keywords::Type) ||
7755 self.check_keyword(keywords::Existential) &&
7756 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7757 let existential = self.eat_keyword(keywords::Existential);
7758 assert!(self.eat_keyword(keywords::Type));
7759 Some(self.parse_existential_or_alias(existential))
7765 /// Parses a type alias or existential type.
7766 fn parse_existential_or_alias(
7769 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7770 let ident = self.parse_ident()?;
7771 let mut tps = self.parse_generics()?;
7772 tps.where_clause = self.parse_where_clause()?;
7773 let alias = if existential {
7774 self.expect(&token::Colon)?;
7775 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7776 AliasKind::Existential(bounds)
7778 self.expect(&token::Eq)?;
7779 let ty = self.parse_ty()?;
7782 self.expect(&token::Semi)?;
7783 Ok((ident, alias, tps))
7786 /// Parses the part of an enum declaration following the `{`.
7787 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7788 let mut variants = Vec::new();
7789 let mut all_nullary = true;
7790 let mut any_disr = vec![];
7791 while self.token != token::CloseDelim(token::Brace) {
7792 let variant_attrs = self.parse_outer_attributes()?;
7793 let vlo = self.span;
7796 let mut disr_expr = None;
7798 let ident = self.parse_ident()?;
7799 if self.check(&token::OpenDelim(token::Brace)) {
7800 // Parse a struct variant.
7801 all_nullary = false;
7802 let (fields, recovered) = self.parse_record_struct_body()?;
7803 struct_def = VariantData::Struct(fields, recovered);
7804 } else if self.check(&token::OpenDelim(token::Paren)) {
7805 all_nullary = false;
7806 struct_def = VariantData::Tuple(
7807 self.parse_tuple_struct_body()?,
7810 } else if self.eat(&token::Eq) {
7811 disr_expr = Some(AnonConst {
7812 id: ast::DUMMY_NODE_ID,
7813 value: self.parse_expr()?,
7815 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7818 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7820 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7823 let vr = ast::Variant_ {
7825 id: ast::DUMMY_NODE_ID,
7826 attrs: variant_attrs,
7830 variants.push(respan(vlo.to(self.prev_span), vr));
7832 if !self.eat(&token::Comma) {
7833 if self.token.is_ident() && !self.token.is_reserved_ident() {
7834 let sp = self.sess.source_map().next_point(self.prev_span);
7835 let mut err = self.struct_span_err(sp, "missing comma");
7836 err.span_suggestion_short(
7840 Applicability::MaybeIncorrect,
7848 self.expect(&token::CloseDelim(token::Brace))?;
7849 if !any_disr.is_empty() && !all_nullary {
7850 let mut err = self.struct_span_err(
7852 "discriminator values can only be used with a field-less enum",
7854 for sp in any_disr {
7855 err.span_label(sp, "only valid in field-less enums");
7860 Ok(ast::EnumDef { variants })
7863 /// Parses an enum declaration.
7864 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7865 let id = self.parse_ident()?;
7866 let mut generics = self.parse_generics()?;
7867 generics.where_clause = self.parse_where_clause()?;
7868 self.expect(&token::OpenDelim(token::Brace))?;
7870 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7871 self.recover_stmt();
7872 self.eat(&token::CloseDelim(token::Brace));
7875 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7878 /// Parses a string as an ABI spec on an extern type or module. Consumes
7879 /// the `extern` keyword, if one is found.
7880 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7882 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7884 self.expect_no_suffix(sp, "an ABI spec", suf);
7886 match abi::lookup(&s.as_str()) {
7887 Some(abi) => Ok(Some(abi)),
7889 let prev_span = self.prev_span;
7890 let mut err = struct_span_err!(
7891 self.sess.span_diagnostic,
7894 "invalid ABI: found `{}`",
7896 err.span_label(prev_span, "invalid ABI");
7897 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7908 fn is_static_global(&mut self) -> bool {
7909 if self.check_keyword(keywords::Static) {
7910 // Check if this could be a closure
7911 !self.look_ahead(1, |token| {
7912 if token.is_keyword(keywords::Move) {
7916 token::BinOp(token::Or) | token::OrOr => true,
7927 attrs: Vec<Attribute>,
7928 macros_allowed: bool,
7929 attributes_allowed: bool,
7930 ) -> PResult<'a, Option<P<Item>>> {
7931 let mut unclosed_delims = vec![];
7932 let (ret, tokens) = self.collect_tokens(|this| {
7933 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7934 unclosed_delims.append(&mut this.unclosed_delims);
7937 self.unclosed_delims.append(&mut unclosed_delims);
7939 // Once we've parsed an item and recorded the tokens we got while
7940 // parsing we may want to store `tokens` into the item we're about to
7941 // return. Note, though, that we specifically didn't capture tokens
7942 // related to outer attributes. The `tokens` field here may later be
7943 // used with procedural macros to convert this item back into a token
7944 // stream, but during expansion we may be removing attributes as we go
7947 // If we've got inner attributes then the `tokens` we've got above holds
7948 // these inner attributes. If an inner attribute is expanded we won't
7949 // actually remove it from the token stream, so we'll just keep yielding
7950 // it (bad!). To work around this case for now we just avoid recording
7951 // `tokens` if we detect any inner attributes. This should help keep
7952 // expansion correct, but we should fix this bug one day!
7955 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7956 i.tokens = Some(tokens);
7963 /// Parses one of the items allowed by the flags.
7964 fn parse_item_implementation(
7966 attrs: Vec<Attribute>,
7967 macros_allowed: bool,
7968 attributes_allowed: bool,
7969 ) -> PResult<'a, Option<P<Item>>> {
7970 maybe_whole!(self, NtItem, |item| {
7971 let mut item = item.into_inner();
7972 let mut attrs = attrs;
7973 mem::swap(&mut item.attrs, &mut attrs);
7974 item.attrs.extend(attrs);
7980 let visibility = self.parse_visibility(false)?;
7982 if self.eat_keyword(keywords::Use) {
7984 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7985 self.expect(&token::Semi)?;
7987 let span = lo.to(self.prev_span);
7988 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7989 return Ok(Some(item));
7992 if self.eat_keyword(keywords::Extern) {
7993 if self.eat_keyword(keywords::Crate) {
7994 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7997 let opt_abi = self.parse_opt_abi()?;
7999 if self.eat_keyword(keywords::Fn) {
8000 // EXTERN FUNCTION ITEM
8001 let fn_span = self.prev_span;
8002 let abi = opt_abi.unwrap_or(Abi::C);
8003 let (ident, item_, extra_attrs) =
8004 self.parse_item_fn(Unsafety::Normal,
8005 respan(fn_span, IsAsync::NotAsync),
8006 respan(fn_span, Constness::NotConst),
8008 let prev_span = self.prev_span;
8009 let item = self.mk_item(lo.to(prev_span),
8013 maybe_append(attrs, extra_attrs));
8014 return Ok(Some(item));
8015 } else if self.check(&token::OpenDelim(token::Brace)) {
8016 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
8022 if self.is_static_global() {
8025 let m = if self.eat_keyword(keywords::Mut) {
8028 Mutability::Immutable
8030 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
8031 let prev_span = self.prev_span;
8032 let item = self.mk_item(lo.to(prev_span),
8036 maybe_append(attrs, extra_attrs));
8037 return Ok(Some(item));
8039 if self.eat_keyword(keywords::Const) {
8040 let const_span = self.prev_span;
8041 if self.check_keyword(keywords::Fn)
8042 || (self.check_keyword(keywords::Unsafe)
8043 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
8044 // CONST FUNCTION ITEM
8045 let unsafety = self.parse_unsafety();
8047 let (ident, item_, extra_attrs) =
8048 self.parse_item_fn(unsafety,
8049 respan(const_span, IsAsync::NotAsync),
8050 respan(const_span, Constness::Const),
8052 let prev_span = self.prev_span;
8053 let item = self.mk_item(lo.to(prev_span),
8057 maybe_append(attrs, extra_attrs));
8058 return Ok(Some(item));
8062 if self.eat_keyword(keywords::Mut) {
8063 let prev_span = self.prev_span;
8064 let mut err = self.diagnostic()
8065 .struct_span_err(prev_span, "const globals cannot be mutable");
8066 err.span_label(prev_span, "cannot be mutable");
8067 err.span_suggestion(
8069 "you might want to declare a static instead",
8070 "static".to_owned(),
8071 Applicability::MaybeIncorrect,
8075 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
8076 let prev_span = self.prev_span;
8077 let item = self.mk_item(lo.to(prev_span),
8081 maybe_append(attrs, extra_attrs));
8082 return Ok(Some(item));
8085 // `unsafe async fn` or `async fn`
8087 self.check_keyword(keywords::Unsafe) &&
8088 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
8090 self.check_keyword(keywords::Async) &&
8091 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
8094 // ASYNC FUNCTION ITEM
8095 let unsafety = self.parse_unsafety();
8096 self.expect_keyword(keywords::Async)?;
8097 let async_span = self.prev_span;
8098 self.expect_keyword(keywords::Fn)?;
8099 let fn_span = self.prev_span;
8100 let (ident, item_, extra_attrs) =
8101 self.parse_item_fn(unsafety,
8102 respan(async_span, IsAsync::Async {
8103 closure_id: ast::DUMMY_NODE_ID,
8104 return_impl_trait_id: ast::DUMMY_NODE_ID,
8105 arguments: Vec::new(),
8107 respan(fn_span, Constness::NotConst),
8109 let prev_span = self.prev_span;
8110 let item = self.mk_item(lo.to(prev_span),
8114 maybe_append(attrs, extra_attrs));
8115 if self.span.rust_2015() {
8116 self.diagnostic().struct_span_err_with_code(
8118 "`async fn` is not permitted in the 2015 edition",
8119 DiagnosticId::Error("E0670".into())
8122 return Ok(Some(item));
8124 if self.check_keyword(keywords::Unsafe) &&
8125 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8126 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8128 // UNSAFE TRAIT ITEM
8129 self.bump(); // `unsafe`
8130 let is_auto = if self.eat_keyword(keywords::Trait) {
8133 self.expect_keyword(keywords::Auto)?;
8134 self.expect_keyword(keywords::Trait)?;
8137 let (ident, item_, extra_attrs) =
8138 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8139 let prev_span = self.prev_span;
8140 let item = self.mk_item(lo.to(prev_span),
8144 maybe_append(attrs, extra_attrs));
8145 return Ok(Some(item));
8147 if self.check_keyword(keywords::Impl) ||
8148 self.check_keyword(keywords::Unsafe) &&
8149 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8150 self.check_keyword(keywords::Default) &&
8151 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8152 self.check_keyword(keywords::Default) &&
8153 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8155 let defaultness = self.parse_defaultness();
8156 let unsafety = self.parse_unsafety();
8157 self.expect_keyword(keywords::Impl)?;
8158 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8159 let span = lo.to(self.prev_span);
8160 return Ok(Some(self.mk_item(span, ident, item, visibility,
8161 maybe_append(attrs, extra_attrs))));
8163 if self.check_keyword(keywords::Fn) {
8166 let fn_span = self.prev_span;
8167 let (ident, item_, extra_attrs) =
8168 self.parse_item_fn(Unsafety::Normal,
8169 respan(fn_span, IsAsync::NotAsync),
8170 respan(fn_span, Constness::NotConst),
8172 let prev_span = self.prev_span;
8173 let item = self.mk_item(lo.to(prev_span),
8177 maybe_append(attrs, extra_attrs));
8178 return Ok(Some(item));
8180 if self.check_keyword(keywords::Unsafe)
8181 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8182 // UNSAFE FUNCTION ITEM
8183 self.bump(); // `unsafe`
8184 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8185 self.check(&token::OpenDelim(token::Brace));
8186 let abi = if self.eat_keyword(keywords::Extern) {
8187 self.parse_opt_abi()?.unwrap_or(Abi::C)
8191 self.expect_keyword(keywords::Fn)?;
8192 let fn_span = self.prev_span;
8193 let (ident, item_, extra_attrs) =
8194 self.parse_item_fn(Unsafety::Unsafe,
8195 respan(fn_span, IsAsync::NotAsync),
8196 respan(fn_span, Constness::NotConst),
8198 let prev_span = self.prev_span;
8199 let item = self.mk_item(lo.to(prev_span),
8203 maybe_append(attrs, extra_attrs));
8204 return Ok(Some(item));
8206 if self.eat_keyword(keywords::Mod) {
8208 let (ident, item_, extra_attrs) =
8209 self.parse_item_mod(&attrs[..])?;
8210 let prev_span = self.prev_span;
8211 let item = self.mk_item(lo.to(prev_span),
8215 maybe_append(attrs, extra_attrs));
8216 return Ok(Some(item));
8218 if let Some(type_) = self.eat_type() {
8219 let (ident, alias, generics) = type_?;
8221 let item_ = match alias {
8222 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8223 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8225 let prev_span = self.prev_span;
8226 let item = self.mk_item(lo.to(prev_span),
8231 return Ok(Some(item));
8233 if self.eat_keyword(keywords::Enum) {
8235 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8236 let prev_span = self.prev_span;
8237 let item = self.mk_item(lo.to(prev_span),
8241 maybe_append(attrs, extra_attrs));
8242 return Ok(Some(item));
8244 if self.check_keyword(keywords::Trait)
8245 || (self.check_keyword(keywords::Auto)
8246 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8248 let is_auto = if self.eat_keyword(keywords::Trait) {
8251 self.expect_keyword(keywords::Auto)?;
8252 self.expect_keyword(keywords::Trait)?;
8256 let (ident, item_, extra_attrs) =
8257 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8258 let prev_span = self.prev_span;
8259 let item = self.mk_item(lo.to(prev_span),
8263 maybe_append(attrs, extra_attrs));
8264 return Ok(Some(item));
8266 if self.eat_keyword(keywords::Struct) {
8268 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8269 let prev_span = self.prev_span;
8270 let item = self.mk_item(lo.to(prev_span),
8274 maybe_append(attrs, extra_attrs));
8275 return Ok(Some(item));
8277 if self.is_union_item() {
8280 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8281 let prev_span = self.prev_span;
8282 let item = self.mk_item(lo.to(prev_span),
8286 maybe_append(attrs, extra_attrs));
8287 return Ok(Some(item));
8289 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8290 return Ok(Some(macro_def));
8293 // Verify whether we have encountered a struct or method definition where the user forgot to
8294 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8295 if visibility.node.is_pub() &&
8296 self.check_ident() &&
8297 self.look_ahead(1, |t| *t != token::Not)
8299 // Space between `pub` keyword and the identifier
8302 // ^^^ `sp` points here
8303 let sp = self.prev_span.between(self.span);
8304 let full_sp = self.prev_span.to(self.span);
8305 let ident_sp = self.span;
8306 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8307 // possible public struct definition where `struct` was forgotten
8308 let ident = self.parse_ident().unwrap();
8309 let msg = format!("add `struct` here to parse `{}` as a public struct",
8311 let mut err = self.diagnostic()
8312 .struct_span_err(sp, "missing `struct` for struct definition");
8313 err.span_suggestion_short(
8314 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8317 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8318 let ident = self.parse_ident().unwrap();
8320 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8325 self.consume_block(token::Paren);
8326 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8327 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8329 ("fn", kw_name, false)
8330 } else if self.check(&token::OpenDelim(token::Brace)) {
8332 ("fn", kw_name, false)
8333 } else if self.check(&token::Colon) {
8337 ("fn` or `struct", "function or struct", true)
8340 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8341 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8343 self.consume_block(token::Brace);
8344 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8348 err.span_suggestion_short(
8349 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8352 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8353 err.span_suggestion(
8355 "if you meant to call a macro, try",
8356 format!("{}!", snippet),
8357 // this is the `ambiguous` conditional branch
8358 Applicability::MaybeIncorrect
8361 err.help("if you meant to call a macro, remove the `pub` \
8362 and add a trailing `!` after the identifier");
8366 } else if self.look_ahead(1, |t| *t == token::Lt) {
8367 let ident = self.parse_ident().unwrap();
8368 self.eat_to_tokens(&[&token::Gt]);
8370 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8371 if let Ok(Some(_)) = self.parse_self_arg() {
8372 ("fn", "method", false)
8374 ("fn", "function", false)
8376 } else if self.check(&token::OpenDelim(token::Brace)) {
8377 ("struct", "struct", false)
8379 ("fn` or `struct", "function or struct", true)
8381 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8382 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8384 err.span_suggestion_short(
8386 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8387 format!(" {} ", kw),
8388 Applicability::MachineApplicable,
8394 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8397 /// Parses a foreign item.
8398 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8399 maybe_whole!(self, NtForeignItem, |ni| ni);
8401 let attrs = self.parse_outer_attributes()?;
8403 let visibility = self.parse_visibility(false)?;
8405 // FOREIGN STATIC ITEM
8406 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8407 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8408 if self.token.is_keyword(keywords::Const) {
8410 .struct_span_err(self.span, "extern items cannot be `const`")
8413 "try using a static value",
8414 "static".to_owned(),
8415 Applicability::MachineApplicable
8418 self.bump(); // `static` or `const`
8419 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8421 // FOREIGN FUNCTION ITEM
8422 if self.check_keyword(keywords::Fn) {
8423 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8425 // FOREIGN TYPE ITEM
8426 if self.check_keyword(keywords::Type) {
8427 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8430 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8434 ident: keywords::Invalid.ident(),
8435 span: lo.to(self.prev_span),
8436 id: ast::DUMMY_NODE_ID,
8439 node: ForeignItemKind::Macro(mac),
8444 if !attrs.is_empty() {
8445 self.expected_item_err(&attrs)?;
8453 /// This is the fall-through for parsing items.
8454 fn parse_macro_use_or_failure(
8456 attrs: Vec<Attribute> ,
8457 macros_allowed: bool,
8458 attributes_allowed: bool,
8460 visibility: Visibility
8461 ) -> PResult<'a, Option<P<Item>>> {
8462 if macros_allowed && self.token.is_path_start() &&
8463 !(self.is_async_fn() && self.span.rust_2015()) {
8464 // MACRO INVOCATION ITEM
8466 let prev_span = self.prev_span;
8467 self.complain_if_pub_macro(&visibility.node, prev_span);
8469 let mac_lo = self.span;
8472 let pth = self.parse_path(PathStyle::Mod)?;
8473 self.expect(&token::Not)?;
8475 // a 'special' identifier (like what `macro_rules!` uses)
8476 // is optional. We should eventually unify invoc syntax
8478 let id = if self.token.is_ident() {
8481 keywords::Invalid.ident() // no special identifier
8483 // eat a matched-delimiter token tree:
8484 let (delim, tts) = self.expect_delimited_token_tree()?;
8485 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8486 self.report_invalid_macro_expansion_item();
8489 let hi = self.prev_span;
8490 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8491 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8492 return Ok(Some(item));
8495 // FAILURE TO PARSE ITEM
8496 match visibility.node {
8497 VisibilityKind::Inherited => {}
8499 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8503 if !attributes_allowed && !attrs.is_empty() {
8504 self.expected_item_err(&attrs)?;
8509 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8510 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8511 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8513 if self.token.is_path_start() &&
8514 !(self.is_async_fn() && self.span.rust_2015()) {
8515 let prev_span = self.prev_span;
8517 let pth = self.parse_path(PathStyle::Mod)?;
8519 if pth.segments.len() == 1 {
8520 if !self.eat(&token::Not) {
8521 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8524 self.expect(&token::Not)?;
8527 if let Some(vis) = vis {
8528 self.complain_if_pub_macro(&vis.node, prev_span);
8533 // eat a matched-delimiter token tree:
8534 let (delim, tts) = self.expect_delimited_token_tree()?;
8535 if delim != MacDelimiter::Brace {
8536 self.expect(&token::Semi)?;
8539 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8545 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8546 where F: FnOnce(&mut Self) -> PResult<'a, R>
8548 // Record all tokens we parse when parsing this item.
8549 let mut tokens = Vec::new();
8550 let prev_collecting = match self.token_cursor.frame.last_token {
8551 LastToken::Collecting(ref mut list) => {
8552 Some(mem::replace(list, Vec::new()))
8554 LastToken::Was(ref mut last) => {
8555 tokens.extend(last.take());
8559 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8560 let prev = self.token_cursor.stack.len();
8562 let last_token = if self.token_cursor.stack.len() == prev {
8563 &mut self.token_cursor.frame.last_token
8565 &mut self.token_cursor.stack[prev].last_token
8568 // Pull out the tokens that we've collected from the call to `f` above.
8569 let mut collected_tokens = match *last_token {
8570 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8571 LastToken::Was(_) => panic!("our vector went away?"),
8574 // If we're not at EOF our current token wasn't actually consumed by
8575 // `f`, but it'll still be in our list that we pulled out. In that case
8577 let extra_token = if self.token != token::Eof {
8578 collected_tokens.pop()
8583 // If we were previously collecting tokens, then this was a recursive
8584 // call. In that case we need to record all the tokens we collected in
8585 // our parent list as well. To do that we push a clone of our stream
8586 // onto the previous list.
8587 match prev_collecting {
8589 list.extend(collected_tokens.iter().cloned());
8590 list.extend(extra_token);
8591 *last_token = LastToken::Collecting(list);
8594 *last_token = LastToken::Was(extra_token);
8598 Ok((ret?, TokenStream::new(collected_tokens)))
8601 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8602 let attrs = self.parse_outer_attributes()?;
8603 self.parse_item_(attrs, true, false)
8607 fn is_import_coupler(&mut self) -> bool {
8608 self.check(&token::ModSep) &&
8609 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8610 *t == token::BinOp(token::Star))
8613 /// Parses a `UseTree`.
8616 /// USE_TREE = [`::`] `*` |
8617 /// [`::`] `{` USE_TREE_LIST `}` |
8619 /// PATH `::` `{` USE_TREE_LIST `}` |
8620 /// PATH [`as` IDENT]
8622 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8625 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8626 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8627 self.check(&token::BinOp(token::Star)) ||
8628 self.is_import_coupler() {
8629 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8630 let mod_sep_ctxt = self.span.ctxt();
8631 if self.eat(&token::ModSep) {
8632 prefix.segments.push(
8633 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8637 if self.eat(&token::BinOp(token::Star)) {
8640 UseTreeKind::Nested(self.parse_use_tree_list()?)
8643 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8644 prefix = self.parse_path(PathStyle::Mod)?;
8646 if self.eat(&token::ModSep) {
8647 if self.eat(&token::BinOp(token::Star)) {
8650 UseTreeKind::Nested(self.parse_use_tree_list()?)
8653 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8657 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8660 /// Parses a `UseTreeKind::Nested(list)`.
8663 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8665 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8666 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8667 &token::CloseDelim(token::Brace),
8668 SeqSep::trailing_allowed(token::Comma), |this| {
8669 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8673 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8674 if self.eat_keyword(keywords::As) {
8675 self.parse_ident_or_underscore().map(Some)
8681 /// Parses a source module as a crate. This is the main entry point for the parser.
8682 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8684 let krate = Ok(ast::Crate {
8685 attrs: self.parse_inner_attributes()?,
8686 module: self.parse_mod_items(&token::Eof, lo)?,
8687 span: lo.to(self.span),
8692 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8693 let ret = match self.token {
8694 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8695 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8702 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8703 match self.parse_optional_str() {
8704 Some((s, style, suf)) => {
8705 let sp = self.prev_span;
8706 self.expect_no_suffix(sp, "a string literal", suf);
8710 let msg = "expected string literal";
8711 let mut err = self.fatal(msg);
8712 err.span_label(self.span, msg);
8718 fn report_invalid_macro_expansion_item(&self) {
8719 self.struct_span_err(
8721 "macros that expand to items must be delimited with braces or followed by a semicolon",
8722 ).multipart_suggestion(
8723 "change the delimiters to curly braces",
8725 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8726 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8728 Applicability::MaybeIncorrect,
8730 self.sess.source_map.next_point(self.prev_span),
8733 Applicability::MaybeIncorrect,
8737 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8738 fn eat_bad_pub(&mut self) {
8739 if self.token.is_keyword(keywords::Pub) {
8740 match self.parse_visibility(false) {
8742 let mut err = self.diagnostic()
8743 .struct_span_err(vis.span, "unnecessary visibility qualifier");
8744 err.span_label(vis.span, "`pub` not permitted here");
8747 Err(mut err) => err.emit(),
8752 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8753 /// into the generated closure so that they are dropped when the future is polled and not when
8756 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8757 /// this function and the statements created here are inserted at the top of the closure body.
8758 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &mut FnDecl) {
8759 // FIXME(davidtwco): This function should really live in the HIR lowering but because
8760 // the types constructed here need to be used in parts of resolve so that the correct
8761 // locals are considered upvars, it is currently easier for it to live here in the parser,
8762 // where it can be constructed once.
8763 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8764 for (index, input) in decl.inputs.iter_mut().enumerate() {
8765 let id = ast::DUMMY_NODE_ID;
8766 let span = input.pat.span;
8768 // Construct a name for our temporary argument.
8769 let name = format!("__arg{}", index);
8770 let ident = Ident::from_str(&name).gensym();
8772 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
8773 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
8775 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
8776 PatKind::Ident(binding_mode @ BindingMode::ByValue(_), ident, _) => {
8777 // Simple patterns like this don't have a generated argument, but they are
8778 // moved into the closure with a statement, so any `mut` bindings on the
8779 // argument will be unused. This binding mode can't be removed, because
8780 // this would affect the input to procedural macros, but they can have
8781 // their span marked as being the result of a compiler desugaring so
8782 // that they aren't linted against.
8783 input.pat.span = self.sess.source_map().mark_span_with_reason(
8784 CompilerDesugaringKind::Async, span, None);
8786 (binding_mode, ident, true)
8788 _ => (BindingMode::ByValue(Mutability::Mutable), ident, false),
8791 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8792 // async function if it isn't a simple pattern.
8793 let arg = if is_simple_pattern {
8797 ty: input.ty.clone(),
8801 node: PatKind::Ident(
8802 BindingMode::ByValue(Mutability::Immutable), ident, None,
8806 source: ArgSource::AsyncFn(input.pat.clone()),
8810 // Construct a `let __argN = __argN;` statement to insert at the top of the
8811 // async closure. This makes sure that the argument is captured by the closure and
8812 // that the drop order is correct.
8813 let move_local = Local {
8816 node: PatKind::Ident(binding_mode, ident, None),
8819 // We explicitly do not specify the type for this statement. When the user's
8820 // argument type is `impl Trait` then this would require the
8821 // `impl_trait_in_bindings` feature to also be present for that same type to
8822 // be valid in this binding. At the time of writing (13 Mar 19),
8823 // `impl_trait_in_bindings` is not stable.
8827 node: ExprKind::Path(None, ast::Path {
8829 segments: vec![PathSegment { ident, id, args: None }],
8832 attrs: ThinVec::new(),
8836 attrs: ThinVec::new(),
8837 source: LocalSource::AsyncFn,
8840 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8841 // async closure if this isn't a simple pattern.
8842 let pat_stmt = if is_simple_pattern {
8847 node: StmtKind::Local(P(Local {
8848 pat: input.pat.clone(),
8849 ..move_local.clone()
8855 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
8856 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
8862 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8863 for unmatched in unclosed_delims.iter() {
8864 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8865 "incorrect close delimiter: `{}`",
8866 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8868 err.span_label(unmatched.found_span, "incorrect close delimiter");
8869 if let Some(sp) = unmatched.candidate_span {
8870 err.span_label(sp, "close delimiter possibly meant for this");
8872 if let Some(sp) = unmatched.unclosed_span {
8873 err.span_label(sp, "un-closed delimiter");
8877 unclosed_delims.clear();