1 // ignore-tidy-filelength
3 use crate::ast::{AngleBracketedArgs, AsyncArgument, ParenthesizedArgs, AttrStyle, BareFnTy};
4 use crate::ast::{GenericBound, TraitBoundModifier};
5 use crate::ast::Unsafety;
6 use crate::ast::{Mod, AnonConst, Arg, ArgSource, Arm, Guard, Attribute, BindingMode, TraitItemKind};
8 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
9 use crate::ast::{Constness, Crate};
10 use crate::ast::Defaultness;
11 use crate::ast::EnumDef;
12 use crate::ast::{Expr, ExprKind, RangeLimits};
13 use crate::ast::{Field, FnDecl, FnHeader};
14 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
15 use crate::ast::{GenericParam, GenericParamKind};
16 use crate::ast::GenericArg;
17 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
18 use crate::ast::{Label, Lifetime, Lit, LitKind};
19 use crate::ast::{Local, LocalSource};
20 use crate::ast::MacStmtStyle;
21 use crate::ast::{Mac, Mac_, MacDelimiter};
22 use crate::ast::{MutTy, Mutability};
23 use crate::ast::{Pat, PatKind, PathSegment};
24 use crate::ast::{PolyTraitRef, QSelf};
25 use crate::ast::{Stmt, StmtKind};
26 use crate::ast::{VariantData, StructField};
27 use crate::ast::StrStyle;
28 use crate::ast::SelfKind;
29 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
30 use crate::ast::{Ty, TyKind, TypeBinding, GenericBounds};
31 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
32 use crate::ast::{UseTree, UseTreeKind};
33 use crate::ast::{BinOpKind, UnOp};
34 use crate::ast::{RangeEnd, RangeSyntax};
35 use crate::{ast, attr};
36 use crate::ext::base::DummyResult;
37 use crate::source_map::{self, SourceMap, Spanned, respan};
38 use crate::parse::{self, SeqSep, classify, token};
39 use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace};
40 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
41 use crate::parse::token::DelimToken;
42 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
43 use crate::util::parser::{AssocOp, Fixity};
44 use crate::print::pprust;
46 use crate::parse::PResult;
48 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
49 use crate::symbol::{Symbol, keywords};
51 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
52 use rustc_target::spec::abi::{self, Abi};
54 Span, MultiSpan, BytePos, FileName,
55 hygiene::CompilerDesugaringKind,
57 use log::{debug, trace};
62 use std::path::{self, Path, PathBuf};
66 /// Whether the type alias or associated type is a concrete type or an existential type
68 /// Just a new name for the same type
70 /// Only trait impls of the type will be usable, not the actual type itself
71 Existential(GenericBounds),
75 struct Restrictions: u8 {
76 const STMT_EXPR = 1 << 0;
77 const NO_STRUCT_LITERAL = 1 << 1;
81 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
83 /// Specifies how to parse a path.
84 #[derive(Copy, Clone, PartialEq)]
86 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
87 /// with something else. For example, in expressions `segment < ....` can be interpreted
88 /// as a comparison and `segment ( ....` can be interpreted as a function call.
89 /// In all such contexts the non-path interpretation is preferred by default for practical
90 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
91 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
93 /// In other contexts, notably in types, no ambiguity exists and paths can be written
94 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
95 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
97 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
98 /// visibilities or attributes.
99 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
100 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
101 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
102 /// tokens when something goes wrong.
106 #[derive(Clone, Copy, PartialEq, Debug)]
113 #[derive(Clone, Copy, PartialEq, Debug)]
119 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
120 /// dropped into the token stream, which happens while parsing the result of
121 /// macro expansion). Placement of these is not as complex as I feared it would
122 /// be. The important thing is to make sure that lookahead doesn't balk at
123 /// `token::Interpolated` tokens.
124 macro_rules! maybe_whole_expr {
126 if let token::Interpolated(nt) = &$p.token {
128 token::NtExpr(e) | token::NtLiteral(e) => {
133 token::NtPath(path) => {
134 let path = path.clone();
136 return Ok($p.mk_expr($p.span, ExprKind::Path(None, path), ThinVec::new()));
138 token::NtBlock(block) => {
139 let block = block.clone();
141 return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
149 /// As maybe_whole_expr, but for things other than expressions
150 macro_rules! maybe_whole {
151 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
152 if let token::Interpolated(nt) = &$p.token {
153 if let token::$constructor(x) = &**nt {
162 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
163 macro_rules! maybe_recover_from_interpolated_ty_qpath {
164 ($self: expr, $allow_qpath_recovery: expr) => {
165 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
166 if let token::Interpolated(nt) = &$self.token {
167 if let token::NtTy(ty) = &**nt {
170 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
177 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
178 if let Some(ref mut rhs) = rhs {
184 #[derive(Debug, Clone, Copy, PartialEq)]
196 /* ident is handled by common.rs */
199 pub struct Parser<'a> {
200 pub sess: &'a ParseSess,
201 /// the current token:
202 pub token: token::Token,
203 /// the span of the current token:
205 /// the span of the previous token:
206 meta_var_span: Option<Span>,
208 /// the previous token kind
209 prev_token_kind: PrevTokenKind,
210 restrictions: Restrictions,
211 /// Used to determine the path to externally loaded source files
212 crate directory: Directory<'a>,
213 /// Whether to parse sub-modules in other files.
214 pub recurse_into_file_modules: bool,
215 /// Name of the root module this parser originated from. If `None`, then the
216 /// name is not known. This does not change while the parser is descending
217 /// into modules, and sub-parsers have new values for this name.
218 pub root_module_name: Option<String>,
219 crate expected_tokens: Vec<TokenType>,
220 token_cursor: TokenCursor,
221 desugar_doc_comments: bool,
222 /// Whether we should configure out of line modules as we parse.
224 /// This field is used to keep track of how many left angle brackets we have seen. This is
225 /// required in order to detect extra leading left angle brackets (`<` characters) and error
228 /// See the comments in the `parse_path_segment` function for more details.
229 crate unmatched_angle_bracket_count: u32,
230 crate max_angle_bracket_count: u32,
231 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
232 /// it gets removed from here. Every entry left at the end gets emitted as an independent
234 crate unclosed_delims: Vec<UnmatchedBrace>,
235 last_unexpected_token_span: Option<Span>,
238 impl<'a> Drop for Parser<'a> {
240 let diag = self.diagnostic();
241 emit_unclosed_delims(&mut self.unclosed_delims, diag);
247 frame: TokenCursorFrame,
248 stack: Vec<TokenCursorFrame>,
252 struct TokenCursorFrame {
253 delim: token::DelimToken,
256 tree_cursor: tokenstream::Cursor,
258 last_token: LastToken,
261 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
262 /// by the parser, and then that's transitively used to record the tokens that
263 /// each parse AST item is created with.
265 /// Right now this has two states, either collecting tokens or not collecting
266 /// tokens. If we're collecting tokens we just save everything off into a local
267 /// `Vec`. This should eventually though likely save tokens from the original
268 /// token stream and just use slicing of token streams to avoid creation of a
269 /// whole new vector.
271 /// The second state is where we're passively not recording tokens, but the last
272 /// token is still tracked for when we want to start recording tokens. This
273 /// "last token" means that when we start recording tokens we'll want to ensure
274 /// that this, the first token, is included in the output.
276 /// You can find some more example usage of this in the `collect_tokens` method
280 Collecting(Vec<TreeAndJoint>),
281 Was(Option<TreeAndJoint>),
284 impl TokenCursorFrame {
285 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
289 open_delim: delim == token::NoDelim,
290 tree_cursor: tts.clone().into_trees(),
291 close_delim: delim == token::NoDelim,
292 last_token: LastToken::Was(None),
298 fn next(&mut self) -> TokenAndSpan {
300 let tree = if !self.frame.open_delim {
301 self.frame.open_delim = true;
302 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
303 } else if let Some(tree) = self.frame.tree_cursor.next() {
305 } else if !self.frame.close_delim {
306 self.frame.close_delim = true;
307 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
308 } else if let Some(frame) = self.stack.pop() {
312 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
315 match self.frame.last_token {
316 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
317 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
321 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
322 TokenTree::Delimited(sp, delim, tts) => {
323 let frame = TokenCursorFrame::new(sp, delim, &tts);
324 self.stack.push(mem::replace(&mut self.frame, frame));
330 fn next_desugared(&mut self) -> TokenAndSpan {
331 let (sp, name) = match self.next() {
332 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
336 let stripped = strip_doc_comment_decoration(&name.as_str());
338 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
339 // required to wrap the text.
340 let mut num_of_hashes = 0;
342 for ch in stripped.chars() {
345 '#' if count > 0 => count + 1,
348 num_of_hashes = cmp::max(num_of_hashes, count);
351 let delim_span = DelimSpan::from_single(sp);
352 let body = TokenTree::Delimited(
355 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
356 TokenTree::Token(sp, token::Eq),
357 TokenTree::Token(sp, token::Literal(
358 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
360 .iter().cloned().collect::<TokenStream>().into(),
363 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
366 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
367 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
368 .iter().cloned().collect::<TokenStream>().into()
370 [TokenTree::Token(sp, token::Pound), body]
371 .iter().cloned().collect::<TokenStream>().into()
379 #[derive(Clone, PartialEq)]
380 crate enum TokenType {
382 Keyword(keywords::Keyword),
392 fn to_string(&self) -> String {
394 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
395 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
396 TokenType::Operator => "an operator".to_string(),
397 TokenType::Lifetime => "lifetime".to_string(),
398 TokenType::Ident => "identifier".to_string(),
399 TokenType::Path => "path".to_string(),
400 TokenType::Type => "type".to_string(),
401 TokenType::Const => "const".to_string(),
406 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
407 /// `IDENT<<u8 as Trait>::AssocTy>`.
409 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
410 /// that `IDENT` is not the ident of a fn trait.
411 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
412 t == &token::ModSep || t == &token::Lt ||
413 t == &token::BinOp(token::Shl)
416 /// Information about the path to a module.
417 pub struct ModulePath {
420 pub result: Result<ModulePathSuccess, Error>,
423 pub struct ModulePathSuccess {
425 pub directory_ownership: DirectoryOwnership,
430 FileNotFoundForModule {
432 default_path: String,
433 secondary_path: String,
438 default_path: String,
439 secondary_path: String,
442 InclusiveRangeWithNoEnd,
446 fn span_err<S: Into<MultiSpan>>(self,
448 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
450 Error::FileNotFoundForModule { ref mod_name,
454 let mut err = struct_span_err!(handler, sp, E0583,
455 "file not found for module `{}`", mod_name);
456 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
462 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
463 let mut err = struct_span_err!(handler, sp, E0584,
464 "file for module `{}` found at both {} and {}",
468 err.help("delete or rename one of them to remove the ambiguity");
471 Error::UselessDocComment => {
472 let mut err = struct_span_err!(handler, sp, E0585,
473 "found a documentation comment that doesn't document anything");
474 err.help("doc comments must come before what they document, maybe a comment was \
475 intended with `//`?");
478 Error::InclusiveRangeWithNoEnd => {
479 let mut err = struct_span_err!(handler, sp, E0586,
480 "inclusive range with no end");
481 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
491 AttributesParsed(ThinVec<Attribute>),
492 AlreadyParsed(P<Expr>),
495 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
496 fn from(o: Option<ThinVec<Attribute>>) -> Self {
497 if let Some(attrs) = o {
498 LhsExpr::AttributesParsed(attrs)
500 LhsExpr::NotYetParsed
505 impl From<P<Expr>> for LhsExpr {
506 fn from(expr: P<Expr>) -> Self {
507 LhsExpr::AlreadyParsed(expr)
511 /// Creates a placeholder argument.
512 fn dummy_arg(span: Span) -> Arg {
513 let ident = Ident::new(keywords::Invalid.name(), span);
515 id: ast::DUMMY_NODE_ID,
516 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
522 id: ast::DUMMY_NODE_ID
524 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal }
527 #[derive(Copy, Clone, Debug)]
528 enum TokenExpectType {
533 impl<'a> Parser<'a> {
534 pub fn new(sess: &'a ParseSess,
536 directory: Option<Directory<'a>>,
537 recurse_into_file_modules: bool,
538 desugar_doc_comments: bool)
540 let mut parser = Parser {
542 token: token::Whitespace,
543 span: syntax_pos::DUMMY_SP,
544 prev_span: syntax_pos::DUMMY_SP,
546 prev_token_kind: PrevTokenKind::Other,
547 restrictions: Restrictions::empty(),
548 recurse_into_file_modules,
549 directory: Directory {
550 path: Cow::from(PathBuf::new()),
551 ownership: DirectoryOwnership::Owned { relative: None }
553 root_module_name: None,
554 expected_tokens: Vec::new(),
555 token_cursor: TokenCursor {
556 frame: TokenCursorFrame::new(
563 desugar_doc_comments,
565 unmatched_angle_bracket_count: 0,
566 max_angle_bracket_count: 0,
567 unclosed_delims: Vec::new(),
568 last_unexpected_token_span: None,
571 let tok = parser.next_tok();
572 parser.token = tok.tok;
573 parser.span = tok.sp;
575 if let Some(directory) = directory {
576 parser.directory = directory;
577 } else if !parser.span.is_dummy() {
578 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
580 parser.directory.path = Cow::from(path);
584 parser.process_potential_macro_variable();
588 fn next_tok(&mut self) -> TokenAndSpan {
589 let mut next = if self.desugar_doc_comments {
590 self.token_cursor.next_desugared()
592 self.token_cursor.next()
594 if next.sp.is_dummy() {
595 // Tweak the location for better diagnostics, but keep syntactic context intact.
596 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
601 /// Converts the current token to a string using `self`'s reader.
602 pub fn this_token_to_string(&self) -> String {
603 pprust::token_to_string(&self.token)
606 fn token_descr(&self) -> Option<&'static str> {
607 Some(match &self.token {
608 t if t.is_special_ident() => "reserved identifier",
609 t if t.is_used_keyword() => "keyword",
610 t if t.is_unused_keyword() => "reserved keyword",
611 token::DocComment(..) => "doc comment",
616 fn this_token_descr(&self) -> String {
617 if let Some(prefix) = self.token_descr() {
618 format!("{} `{}`", prefix, self.this_token_to_string())
620 format!("`{}`", self.this_token_to_string())
624 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
625 let token_str = pprust::token_to_string(t);
626 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
629 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
630 match self.expect_one_of(&[], &[]) {
632 Ok(_) => unreachable!(),
636 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
637 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
638 if self.expected_tokens.is_empty() {
639 if self.token == *t {
643 let token_str = pprust::token_to_string(t);
644 let this_token_str = self.this_token_descr();
645 let mut err = self.fatal(&format!("expected `{}`, found {}",
649 let sp = if self.token == token::Token::Eof {
650 // EOF, don't want to point at the following char, but rather the last token
653 self.sess.source_map().next_point(self.prev_span)
655 let label_exp = format!("expected `{}`", token_str);
656 match self.recover_closing_delimiter(&[t.clone()], err) {
659 return Ok(recovered);
662 let cm = self.sess.source_map();
663 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
664 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
665 // When the spans are in the same line, it means that the only content
666 // between them is whitespace, point only at the found token.
667 err.span_label(self.span, label_exp);
670 err.span_label(sp, label_exp);
671 err.span_label(self.span, "unexpected token");
677 self.expect_one_of(slice::from_ref(t), &[])
681 fn recover_closing_delimiter(
683 tokens: &[token::Token],
684 mut err: DiagnosticBuilder<'a>,
685 ) -> PResult<'a, bool> {
687 // we want to use the last closing delim that would apply
688 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
689 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
690 && Some(self.span) > unmatched.unclosed_span
697 // Recover and assume that the detected unclosed delimiter was meant for
698 // this location. Emit the diagnostic and act as if the delimiter was
699 // present for the parser's sake.
701 // Don't attempt to recover from this unclosed delimiter more than once.
702 let unmatched = self.unclosed_delims.remove(pos);
703 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
705 // We want to suggest the inclusion of the closing delimiter where it makes
706 // the most sense, which is immediately after the last token:
711 // | help: `)` may belong here (FIXME: #58270)
713 // unclosed delimiter
714 if let Some(sp) = unmatched.unclosed_span {
715 err.span_label(sp, "unclosed delimiter");
717 err.span_suggestion_short(
718 self.sess.source_map().next_point(self.prev_span),
719 &format!("{} may belong here", delim.to_string()),
721 Applicability::MaybeIncorrect,
724 self.expected_tokens.clear(); // reduce errors
731 /// Expect next token to be edible or inedible token. If edible,
732 /// then consume it; if inedible, then return without consuming
733 /// anything. Signal a fatal error if next token is unexpected.
734 pub fn expect_one_of(
736 edible: &[token::Token],
737 inedible: &[token::Token],
738 ) -> PResult<'a, bool /* recovered */> {
739 fn tokens_to_string(tokens: &[TokenType]) -> String {
740 let mut i = tokens.iter();
741 // This might be a sign we need a connect method on Iterator.
743 .map_or(String::new(), |t| t.to_string());
744 i.enumerate().fold(b, |mut b, (i, a)| {
745 if tokens.len() > 2 && i == tokens.len() - 2 {
747 } else if tokens.len() == 2 && i == tokens.len() - 2 {
752 b.push_str(&a.to_string());
756 if edible.contains(&self.token) {
759 } else if inedible.contains(&self.token) {
760 // leave it in the input
762 } else if self.last_unexpected_token_span == Some(self.span) {
765 let mut expected = edible.iter()
766 .map(|x| TokenType::Token(x.clone()))
767 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
768 .chain(self.expected_tokens.iter().cloned())
769 .collect::<Vec<_>>();
770 expected.sort_by_cached_key(|x| x.to_string());
772 let expect = tokens_to_string(&expected[..]);
773 let actual = self.this_token_to_string();
774 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
775 let short_expect = if expected.len() > 6 {
776 format!("{} possible tokens", expected.len())
780 (format!("expected one of {}, found `{}`", expect, actual),
781 (self.sess.source_map().next_point(self.prev_span),
782 format!("expected one of {} here", short_expect)))
783 } else if expected.is_empty() {
784 (format!("unexpected token: `{}`", actual),
785 (self.prev_span, "unexpected token after this".to_string()))
787 (format!("expected {}, found `{}`", expect, actual),
788 (self.sess.source_map().next_point(self.prev_span),
789 format!("expected {} here", expect)))
791 self.last_unexpected_token_span = Some(self.span);
792 let mut err = self.fatal(&msg_exp);
793 if self.token.is_ident_named("and") {
794 err.span_suggestion_short(
796 "use `&&` instead of `and` for the boolean operator",
798 Applicability::MaybeIncorrect,
801 if self.token.is_ident_named("or") {
802 err.span_suggestion_short(
804 "use `||` instead of `or` for the boolean operator",
806 Applicability::MaybeIncorrect,
809 let sp = if self.token == token::Token::Eof {
810 // This is EOF, don't want to point at the following char, but rather the last token
815 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
816 TokenType::Token(t) => Some(t.clone()),
818 }).collect::<Vec<_>>(), err) {
821 return Ok(recovered);
825 let is_semi_suggestable = expected.iter().any(|t| match t {
826 TokenType::Token(token::Semi) => true, // we expect a `;` here
828 }) && ( // a `;` would be expected before the current keyword
829 self.token.is_keyword(keywords::Break) ||
830 self.token.is_keyword(keywords::Continue) ||
831 self.token.is_keyword(keywords::For) ||
832 self.token.is_keyword(keywords::If) ||
833 self.token.is_keyword(keywords::Let) ||
834 self.token.is_keyword(keywords::Loop) ||
835 self.token.is_keyword(keywords::Match) ||
836 self.token.is_keyword(keywords::Return) ||
837 self.token.is_keyword(keywords::While)
839 let cm = self.sess.source_map();
840 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
841 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
842 // The spans are in different lines, expected `;` and found `let` or `return`.
843 // High likelihood that it is only a missing `;`.
844 err.span_suggestion_short(
846 "a semicolon may be missing here",
848 Applicability::MaybeIncorrect,
853 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
854 // When the spans are in the same line, it means that the only content between
855 // them is whitespace, point at the found token in that case:
857 // X | () => { syntax error };
858 // | ^^^^^ expected one of 8 possible tokens here
860 // instead of having:
862 // X | () => { syntax error };
863 // | -^^^^^ unexpected token
865 // | expected one of 8 possible tokens here
866 err.span_label(self.span, label_exp);
868 _ if self.prev_span == syntax_pos::DUMMY_SP => {
869 // Account for macro context where the previous span might not be
870 // available to avoid incorrect output (#54841).
871 err.span_label(self.span, "unexpected token");
874 err.span_label(sp, label_exp);
875 err.span_label(self.span, "unexpected token");
882 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
883 fn interpolated_or_expr_span(&self,
884 expr: PResult<'a, P<Expr>>)
885 -> PResult<'a, (Span, P<Expr>)> {
887 if self.prev_token_kind == PrevTokenKind::Interpolated {
895 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
896 let mut err = self.struct_span_err(self.span,
897 &format!("expected identifier, found {}",
898 self.this_token_descr()));
899 if let token::Ident(ident, false) = &self.token {
900 if ident.is_raw_guess() {
903 "you can escape reserved keywords to use them as identifiers",
904 format!("r#{}", ident),
905 Applicability::MaybeIncorrect,
909 if let Some(token_descr) = self.token_descr() {
910 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
912 err.span_label(self.span, "expected identifier");
913 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
918 Applicability::MachineApplicable,
925 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
926 self.parse_ident_common(true)
929 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
931 token::Ident(ident, _) => {
932 if self.token.is_reserved_ident() {
933 let mut err = self.expected_ident_found();
940 let span = self.span;
942 Ok(Ident::new(ident.name, span))
945 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
946 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
948 self.expected_ident_found()
954 /// Checks if the next token is `tok`, and returns `true` if so.
956 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
958 crate fn check(&mut self, tok: &token::Token) -> bool {
959 let is_present = self.token == *tok;
960 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
964 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
965 pub fn eat(&mut self, tok: &token::Token) -> bool {
966 let is_present = self.check(tok);
967 if is_present { self.bump() }
971 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
972 self.expected_tokens.push(TokenType::Keyword(kw));
973 self.token.is_keyword(kw)
976 /// If the next token is the given keyword, eats it and returns
977 /// `true`. Otherwise, returns `false`.
978 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
979 if self.check_keyword(kw) {
987 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
988 if self.token.is_keyword(kw) {
996 /// If the given word is not a keyword, signals an error.
997 /// If the next token is not the given word, signals an error.
998 /// Otherwise, eats it.
999 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
1000 if !self.eat_keyword(kw) {
1007 fn check_ident(&mut self) -> bool {
1008 if self.token.is_ident() {
1011 self.expected_tokens.push(TokenType::Ident);
1016 fn check_path(&mut self) -> bool {
1017 if self.token.is_path_start() {
1020 self.expected_tokens.push(TokenType::Path);
1025 fn check_type(&mut self) -> bool {
1026 if self.token.can_begin_type() {
1029 self.expected_tokens.push(TokenType::Type);
1034 fn check_const_arg(&mut self) -> bool {
1035 if self.token.can_begin_const_arg() {
1038 self.expected_tokens.push(TokenType::Const);
1043 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
1044 /// and continues. If a `+` is not seen, returns `false`.
1046 /// This is used when token-splitting `+=` into `+`.
1047 /// See issue #47856 for an example of when this may occur.
1048 fn eat_plus(&mut self) -> bool {
1049 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1051 token::BinOp(token::Plus) => {
1055 token::BinOpEq(token::Plus) => {
1056 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1057 self.bump_with(token::Eq, span);
1065 /// Checks to see if the next token is either `+` or `+=`.
1066 /// Otherwise returns `false`.
1067 fn check_plus(&mut self) -> bool {
1068 if self.token.is_like_plus() {
1072 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1077 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1078 /// `&` and continues. If an `&` is not seen, signals an error.
1079 fn expect_and(&mut self) -> PResult<'a, ()> {
1080 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1082 token::BinOp(token::And) => {
1087 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1088 Ok(self.bump_with(token::BinOp(token::And), span))
1090 _ => self.unexpected()
1094 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1095 /// `|` and continues. If an `|` is not seen, signals an error.
1096 fn expect_or(&mut self) -> PResult<'a, ()> {
1097 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1099 token::BinOp(token::Or) => {
1104 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1105 Ok(self.bump_with(token::BinOp(token::Or), span))
1107 _ => self.unexpected()
1111 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1113 None => {/* everything ok */}
1115 let text = suf.as_str();
1116 if text.is_empty() {
1117 self.span_bug(sp, "found empty literal suffix in Some")
1119 let mut err = if kind == "a tuple index" &&
1120 ["i32", "u32", "isize", "usize"].contains(&text.to_string().as_str())
1122 // #59553: warn instead of reject out of hand to allow the fix to percolate
1123 // through the ecosystem when people fix their macros
1124 let mut err = self.struct_span_warn(
1126 &format!("suffixes on {} are invalid", kind),
1129 "`{}` is *temporarily* accepted on tuple index fields as it was \
1130 incorrectly accepted on stable for a few releases",
1134 "on proc macros, you'll want to use `syn::Index::from` or \
1135 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1136 to tuple field access",
1139 "for more context, see https://github.com/rust-lang/rust/issues/60210",
1143 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1145 err.span_label(sp, format!("invalid suffix `{}`", text));
1151 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1152 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1153 /// and continue. If a `<` is not seen, returns false.
1155 /// This is meant to be used when parsing generics on a path to get the
1157 fn eat_lt(&mut self) -> bool {
1158 self.expected_tokens.push(TokenType::Token(token::Lt));
1159 let ate = match self.token {
1164 token::BinOp(token::Shl) => {
1165 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1166 self.bump_with(token::Lt, span);
1170 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1171 self.bump_with(token::BinOp(token::Minus), span);
1178 // See doc comment for `unmatched_angle_bracket_count`.
1179 self.unmatched_angle_bracket_count += 1;
1180 self.max_angle_bracket_count += 1;
1181 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1187 fn expect_lt(&mut self) -> PResult<'a, ()> {
1195 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1196 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1197 fn expect_gt(&mut self) -> PResult<'a, ()> {
1198 self.expected_tokens.push(TokenType::Token(token::Gt));
1199 let ate = match self.token {
1204 token::BinOp(token::Shr) => {
1205 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1206 Some(self.bump_with(token::Gt, span))
1208 token::BinOpEq(token::Shr) => {
1209 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1210 Some(self.bump_with(token::Ge, span))
1213 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1214 Some(self.bump_with(token::Eq, span))
1221 // See doc comment for `unmatched_angle_bracket_count`.
1222 if self.unmatched_angle_bracket_count > 0 {
1223 self.unmatched_angle_bracket_count -= 1;
1224 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1229 None => self.unexpected(),
1233 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1234 /// passes through any errors encountered. Used for error recovery.
1235 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1236 let handler = self.diagnostic();
1238 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1240 TokenExpectType::Expect,
1241 |p| Ok(p.parse_token_tree())) {
1242 handler.cancel(err);
1246 /// Parses a sequence, including the closing delimiter. The function
1247 /// `f` must consume tokens until reaching the next separator or
1248 /// closing bracket.
1249 pub fn parse_seq_to_end<T, F>(&mut self,
1253 -> PResult<'a, Vec<T>> where
1254 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1256 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1263 /// Parses a sequence, not including the closing delimiter. The function
1264 /// `f` must consume tokens until reaching the next separator or
1265 /// closing bracket.
1266 pub fn parse_seq_to_before_end<T, F>(
1271 ) -> PResult<'a, (Vec<T>, bool)>
1272 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1274 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1277 fn parse_seq_to_before_tokens<T, F>(
1279 kets: &[&token::Token],
1281 expect: TokenExpectType,
1283 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1284 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1286 let mut first = true;
1287 let mut recovered = false;
1289 while !kets.iter().any(|k| {
1291 TokenExpectType::Expect => self.check(k),
1292 TokenExpectType::NoExpect => self.token == **k,
1296 token::CloseDelim(..) | token::Eof => break,
1299 if let Some(ref t) = sep.sep {
1303 match self.expect(t) {
1310 // Attempt to keep parsing if it was a similar separator
1311 if let Some(ref tokens) = t.similar_tokens() {
1312 if tokens.contains(&self.token) {
1317 // Attempt to keep parsing if it was an omitted separator
1332 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1334 TokenExpectType::Expect => self.check(k),
1335 TokenExpectType::NoExpect => self.token == **k,
1348 /// Parses a sequence, including the closing delimiter. The function
1349 /// `f` must consume tokens until reaching the next separator or
1350 /// closing bracket.
1351 fn parse_unspanned_seq<T, F>(
1357 ) -> PResult<'a, Vec<T>> where
1358 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1361 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1368 /// Advance the parser by one token
1369 pub fn bump(&mut self) {
1370 if self.prev_token_kind == PrevTokenKind::Eof {
1371 // Bumping after EOF is a bad sign, usually an infinite loop.
1372 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1375 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1377 // Record last token kind for possible error recovery.
1378 self.prev_token_kind = match self.token {
1379 token::DocComment(..) => PrevTokenKind::DocComment,
1380 token::Comma => PrevTokenKind::Comma,
1381 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1382 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1383 token::Interpolated(..) => PrevTokenKind::Interpolated,
1384 token::Eof => PrevTokenKind::Eof,
1385 token::Ident(..) => PrevTokenKind::Ident,
1386 _ => PrevTokenKind::Other,
1389 let next = self.next_tok();
1390 self.span = next.sp;
1391 self.token = next.tok;
1392 self.expected_tokens.clear();
1393 // check after each token
1394 self.process_potential_macro_variable();
1397 /// Advance the parser using provided token as a next one. Use this when
1398 /// consuming a part of a token. For example a single `<` from `<<`.
1399 fn bump_with(&mut self, next: token::Token, span: Span) {
1400 self.prev_span = self.span.with_hi(span.lo());
1401 // It would be incorrect to record the kind of the current token, but
1402 // fortunately for tokens currently using `bump_with`, the
1403 // prev_token_kind will be of no use anyway.
1404 self.prev_token_kind = PrevTokenKind::Other;
1407 self.expected_tokens.clear();
1410 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1411 F: FnOnce(&token::Token) -> R,
1414 return f(&self.token)
1417 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1418 Some(tree) => match tree {
1419 TokenTree::Token(_, tok) => tok,
1420 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1422 None => token::CloseDelim(self.token_cursor.frame.delim),
1426 fn look_ahead_span(&self, dist: usize) -> Span {
1431 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1432 Some(TokenTree::Token(span, _)) => span,
1433 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1434 None => self.look_ahead_span(dist - 1),
1437 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1438 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1440 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1441 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1443 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1444 err.span_err(sp, self.diagnostic())
1446 fn bug(&self, m: &str) -> ! {
1447 self.sess.span_diagnostic.span_bug(self.span, m)
1449 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1450 self.sess.span_diagnostic.span_err(sp, m)
1452 crate fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1453 self.sess.span_diagnostic.struct_span_err(sp, m)
1455 fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1456 self.sess.span_diagnostic.struct_span_warn(sp, m)
1458 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1459 self.sess.span_diagnostic.span_bug(sp, m)
1462 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1463 self.sess.span_diagnostic.cancel(err)
1466 crate fn diagnostic(&self) -> &'a errors::Handler {
1467 &self.sess.span_diagnostic
1470 /// Is the current token one of the keywords that signals a bare function type?
1471 fn token_is_bare_fn_keyword(&mut self) -> bool {
1472 self.check_keyword(keywords::Fn) ||
1473 self.check_keyword(keywords::Unsafe) ||
1474 self.check_keyword(keywords::Extern)
1477 /// Parses a `TyKind::BareFn` type.
1478 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1481 [unsafe] [extern "ABI"] fn (S) -> T
1491 let unsafety = self.parse_unsafety();
1492 let abi = if self.eat_keyword(keywords::Extern) {
1493 self.parse_opt_abi()?.unwrap_or(Abi::C)
1498 self.expect_keyword(keywords::Fn)?;
1499 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1500 let ret_ty = self.parse_ret_ty(false)?;
1501 let decl = P(FnDecl {
1506 Ok(TyKind::BareFn(P(BareFnTy {
1514 /// Parses asyncness: `async` or nothing.
1515 fn parse_asyncness(&mut self) -> IsAsync {
1516 if self.eat_keyword(keywords::Async) {
1518 closure_id: ast::DUMMY_NODE_ID,
1519 return_impl_trait_id: ast::DUMMY_NODE_ID,
1520 arguments: Vec::new(),
1527 /// Parses unsafety: `unsafe` or nothing.
1528 fn parse_unsafety(&mut self) -> Unsafety {
1529 if self.eat_keyword(keywords::Unsafe) {
1536 /// Parses the items in a trait declaration.
1537 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1538 maybe_whole!(self, NtTraitItem, |x| x);
1539 let attrs = self.parse_outer_attributes()?;
1540 let mut unclosed_delims = vec![];
1541 let (mut item, tokens) = self.collect_tokens(|this| {
1542 let item = this.parse_trait_item_(at_end, attrs);
1543 unclosed_delims.append(&mut this.unclosed_delims);
1546 self.unclosed_delims.append(&mut unclosed_delims);
1547 // See `parse_item` for why this clause is here.
1548 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1549 item.tokens = Some(tokens);
1554 fn parse_trait_item_(&mut self,
1556 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1559 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1560 self.parse_trait_item_assoc_ty()?
1561 } else if self.is_const_item() {
1562 self.expect_keyword(keywords::Const)?;
1563 let ident = self.parse_ident()?;
1564 self.expect(&token::Colon)?;
1565 let ty = self.parse_ty()?;
1566 let default = if self.eat(&token::Eq) {
1567 let expr = self.parse_expr()?;
1568 self.expect(&token::Semi)?;
1571 self.expect(&token::Semi)?;
1574 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1575 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1576 // trait item macro.
1577 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1579 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
1581 let ident = self.parse_ident()?;
1582 let mut generics = self.parse_generics()?;
1584 let mut decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1585 // This is somewhat dubious; We don't want to allow
1586 // argument names to be left off if there is a
1589 // We don't allow argument names to be left off in edition 2018.
1590 p.parse_arg_general(p.span.rust_2018(), true, false)
1592 generics.where_clause = self.parse_where_clause()?;
1593 self.construct_async_arguments(&mut asyncness, &mut decl);
1595 let sig = ast::MethodSig {
1605 let body = match self.token {
1609 debug!("parse_trait_methods(): parsing required method");
1612 token::OpenDelim(token::Brace) => {
1613 debug!("parse_trait_methods(): parsing provided method");
1615 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1616 attrs.extend(inner_attrs.iter().cloned());
1619 token::Interpolated(ref nt) => {
1621 token::NtBlock(..) => {
1623 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1624 attrs.extend(inner_attrs.iter().cloned());
1628 let token_str = self.this_token_descr();
1629 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1631 err.span_label(self.span, "expected `;` or `{`");
1637 let token_str = self.this_token_descr();
1638 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1640 err.span_label(self.span, "expected `;` or `{`");
1644 (ident, ast::TraitItemKind::Method(sig, body), generics)
1648 id: ast::DUMMY_NODE_ID,
1653 span: lo.to(self.prev_span),
1658 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1659 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1660 if self.eat(&token::RArrow) {
1661 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1663 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1668 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1669 self.parse_ty_common(true, true, false)
1672 /// Parses a type in restricted contexts where `+` is not permitted.
1674 /// Example 1: `&'a TYPE`
1675 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1676 /// Example 2: `value1 as TYPE + value2`
1677 /// `+` is prohibited to avoid interactions with expression grammar.
1678 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1679 self.parse_ty_common(false, true, false)
1682 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1683 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1684 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1685 maybe_whole!(self, NtTy, |x| x);
1688 let mut impl_dyn_multi = false;
1689 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1690 // `(TYPE)` is a parenthesized type.
1691 // `(TYPE,)` is a tuple with a single field of type TYPE.
1692 let mut ts = vec![];
1693 let mut last_comma = false;
1694 while self.token != token::CloseDelim(token::Paren) {
1695 ts.push(self.parse_ty()?);
1696 if self.eat(&token::Comma) {
1703 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1704 self.expect(&token::CloseDelim(token::Paren))?;
1706 if ts.len() == 1 && !last_comma {
1707 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1708 let maybe_bounds = allow_plus && self.token.is_like_plus();
1710 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1711 TyKind::Path(None, ref path) if maybe_bounds => {
1712 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1714 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1715 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1716 let path = match bounds[0] {
1717 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1718 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1720 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1723 _ => TyKind::Paren(P(ty))
1728 } else if self.eat(&token::Not) {
1731 } else if self.eat(&token::BinOp(token::Star)) {
1733 TyKind::Ptr(self.parse_ptr()?)
1734 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1736 let t = self.parse_ty()?;
1737 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1738 let t = match self.maybe_parse_fixed_length_of_vec()? {
1739 None => TyKind::Slice(t),
1740 Some(length) => TyKind::Array(t, AnonConst {
1741 id: ast::DUMMY_NODE_ID,
1745 self.expect(&token::CloseDelim(token::Bracket))?;
1747 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1750 self.parse_borrowed_pointee()?
1751 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1753 // In order to not be ambiguous, the type must be surrounded by parens.
1754 self.expect(&token::OpenDelim(token::Paren))?;
1756 id: ast::DUMMY_NODE_ID,
1757 value: self.parse_expr()?,
1759 self.expect(&token::CloseDelim(token::Paren))?;
1761 } else if self.eat_keyword(keywords::Underscore) {
1762 // A type to be inferred `_`
1764 } else if self.token_is_bare_fn_keyword() {
1765 // Function pointer type
1766 self.parse_ty_bare_fn(Vec::new())?
1767 } else if self.check_keyword(keywords::For) {
1768 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1769 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1770 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1772 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1773 if self.token_is_bare_fn_keyword() {
1774 self.parse_ty_bare_fn(lifetime_defs)?
1776 let path = self.parse_path(PathStyle::Type)?;
1777 let parse_plus = allow_plus && self.check_plus();
1778 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1780 } else if self.eat_keyword(keywords::Impl) {
1781 // Always parse bounds greedily for better error recovery.
1782 let bounds = self.parse_generic_bounds(None)?;
1783 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1784 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1785 } else if self.check_keyword(keywords::Dyn) &&
1786 (self.span.rust_2018() ||
1787 self.look_ahead(1, |t| t.can_begin_bound() &&
1788 !can_continue_type_after_non_fn_ident(t))) {
1789 self.bump(); // `dyn`
1790 // Always parse bounds greedily for better error recovery.
1791 let bounds = self.parse_generic_bounds(None)?;
1792 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1793 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1794 } else if self.check(&token::Question) ||
1795 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1796 // Bound list (trait object type)
1797 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1798 TraitObjectSyntax::None)
1799 } else if self.eat_lt() {
1801 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1802 TyKind::Path(Some(qself), path)
1803 } else if self.token.is_path_start() {
1805 let path = self.parse_path(PathStyle::Type)?;
1806 if self.eat(&token::Not) {
1807 // Macro invocation in type position
1808 let (delim, tts) = self.expect_delimited_token_tree()?;
1809 let node = Mac_ { path, tts, delim };
1810 TyKind::Mac(respan(lo.to(self.prev_span), node))
1812 // Just a type path or bound list (trait object type) starting with a trait.
1814 // `Trait1 + Trait2 + 'a`
1815 if allow_plus && self.check_plus() {
1816 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1818 TyKind::Path(None, path)
1821 } else if self.check(&token::DotDotDot) {
1822 if allow_c_variadic {
1823 self.eat(&token::DotDotDot);
1826 return Err(self.fatal(
1827 "only foreign functions are allowed to be C-variadic"
1831 let msg = format!("expected type, found {}", self.this_token_descr());
1832 return Err(self.fatal(&msg));
1835 let span = lo.to(self.prev_span);
1836 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1838 // Try to recover from use of `+` with incorrect priority.
1839 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1840 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1841 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1844 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1845 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1846 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1847 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1849 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1850 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1852 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1855 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1856 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1857 let mutbl = self.parse_mutability();
1858 let ty = self.parse_ty_no_plus()?;
1859 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1862 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1863 let mutbl = if self.eat_keyword(keywords::Mut) {
1865 } else if self.eat_keyword(keywords::Const) {
1866 Mutability::Immutable
1868 let span = self.prev_span;
1869 let msg = "expected mut or const in raw pointer type";
1870 self.struct_span_err(span, msg)
1871 .span_label(span, msg)
1872 .help("use `*mut T` or `*const T` as appropriate")
1874 Mutability::Immutable
1876 let t = self.parse_ty_no_plus()?;
1877 Ok(MutTy { ty: t, mutbl: mutbl })
1880 fn is_named_argument(&mut self) -> bool {
1881 let offset = match self.token {
1882 token::Interpolated(ref nt) => match **nt {
1883 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1886 token::BinOp(token::And) | token::AndAnd => 1,
1887 _ if self.token.is_keyword(keywords::Mut) => 1,
1891 self.look_ahead(offset, |t| t.is_ident()) &&
1892 self.look_ahead(offset + 1, |t| t == &token::Colon)
1895 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1897 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1898 if let token::DocComment(_) = self.token {
1899 let mut err = self.diagnostic().struct_span_err(
1901 &format!("documentation comments cannot be applied to {}", applied_to),
1903 err.span_label(self.span, "doc comments are not allowed here");
1906 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1907 *t == token::OpenDelim(token::Bracket)
1910 // Skip every token until next possible arg.
1911 while self.token != token::CloseDelim(token::Bracket) {
1914 let sp = lo.to(self.span);
1916 let mut err = self.diagnostic().struct_span_err(
1918 &format!("attributes cannot be applied to {}", applied_to),
1920 err.span_label(sp, "attributes are not allowed here");
1925 /// This version of parse arg doesn't necessarily require identifier names.
1926 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
1927 allow_c_variadic: bool) -> PResult<'a, Arg> {
1928 maybe_whole!(self, NtArg, |x| x);
1930 if let Ok(Some(_)) = self.parse_self_arg() {
1931 let mut err = self.struct_span_err(self.prev_span,
1932 "unexpected `self` argument in function");
1933 err.span_label(self.prev_span,
1934 "`self` is only valid as the first argument of an associated function");
1938 let (pat, ty) = if require_name || self.is_named_argument() {
1939 debug!("parse_arg_general parse_pat (require_name:{})",
1941 self.eat_incorrect_doc_comment("method arguments");
1942 let pat = self.parse_pat(Some("argument name"))?;
1944 if let Err(mut err) = self.expect(&token::Colon) {
1945 // If we find a pattern followed by an identifier, it could be an (incorrect)
1946 // C-style parameter declaration.
1947 if self.check_ident() && self.look_ahead(1, |t| {
1948 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1950 let ident = self.parse_ident().unwrap();
1951 let span = pat.span.with_hi(ident.span.hi());
1953 err.span_suggestion(
1955 "declare the type after the parameter binding",
1956 String::from("<identifier>: <type>"),
1957 Applicability::HasPlaceholders,
1959 } else if require_name && is_trait_item {
1960 if let PatKind::Ident(_, ident, _) = pat.node {
1961 err.span_suggestion(
1963 "explicitly ignore parameter",
1964 format!("_: {}", ident),
1965 Applicability::MachineApplicable,
1969 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1975 self.eat_incorrect_doc_comment("a method argument's type");
1976 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1978 debug!("parse_arg_general ident_to_pat");
1979 let parser_snapshot_before_ty = self.clone();
1980 self.eat_incorrect_doc_comment("a method argument's type");
1981 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1982 if ty.is_ok() && self.token != token::Comma &&
1983 self.token != token::CloseDelim(token::Paren) {
1984 // This wasn't actually a type, but a pattern looking like a type,
1985 // so we are going to rollback and re-parse for recovery.
1986 ty = self.unexpected();
1990 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1992 id: ast::DUMMY_NODE_ID,
1993 node: PatKind::Ident(
1994 BindingMode::ByValue(Mutability::Immutable), ident, None),
2000 // If this is a C-variadic argument and we hit an error, return the
2002 if self.token == token::DotDotDot {
2005 // Recover from attempting to parse the argument as a type without pattern.
2007 mem::replace(self, parser_snapshot_before_ty);
2008 let pat = self.parse_pat(Some("argument name"))?;
2009 self.expect(&token::Colon)?;
2010 let ty = self.parse_ty()?;
2012 let mut err = self.diagnostic().struct_span_err_with_code(
2014 "patterns aren't allowed in methods without bodies",
2015 DiagnosticId::Error("E0642".into()),
2017 err.span_suggestion_short(
2019 "give this argument a name or use an underscore to ignore it",
2021 Applicability::MachineApplicable,
2025 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2027 node: PatKind::Wild,
2029 id: ast::DUMMY_NODE_ID
2036 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
2039 /// Parses a single function argument.
2040 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2041 self.parse_arg_general(true, false, false)
2044 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2045 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2046 let pat = self.parse_pat(Some("argument name"))?;
2047 let t = if self.eat(&token::Colon) {
2051 id: ast::DUMMY_NODE_ID,
2052 node: TyKind::Infer,
2053 span: self.prev_span,
2059 id: ast::DUMMY_NODE_ID,
2060 source: ast::ArgSource::Normal,
2064 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2065 if self.eat(&token::Semi) {
2066 Ok(Some(self.parse_expr()?))
2072 /// Matches `token_lit = LIT_INTEGER | ...`.
2073 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2074 let out = match self.token {
2075 token::Interpolated(ref nt) => match **nt {
2076 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2077 ExprKind::Lit(ref lit) => { lit.node.clone() }
2078 _ => { return self.unexpected_last(&self.token); }
2080 _ => { return self.unexpected_last(&self.token); }
2082 token::Literal(lit, suf) => {
2083 let diag = Some((self.span, &self.sess.span_diagnostic));
2084 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2088 self.expect_no_suffix(sp, &format!("a {}", lit.literal_name()), suf)
2093 token::Dot if self.look_ahead(1, |t| match t {
2094 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2096 }) => { // recover from `let x = .4;`
2099 if let token::Literal(
2100 parse::token::Lit::Integer(val),
2103 let suffix = suffix.and_then(|s| {
2107 } else if s == "f64" {
2114 let sp = lo.to(self.prev_span);
2115 let mut err = self.diagnostic()
2116 .struct_span_err(sp, "float literals must have an integer part");
2117 err.span_suggestion(
2119 "must have an integer part",
2120 format!("0.{}{}", val, suffix),
2121 Applicability::MachineApplicable,
2124 return Ok(match suffix {
2125 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2126 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2127 _ => ast::LitKind::FloatUnsuffixed(val),
2133 _ => { return self.unexpected_last(&self.token); }
2140 /// Matches `lit = true | false | token_lit`.
2141 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2143 let lit = if self.eat_keyword(keywords::True) {
2145 } else if self.eat_keyword(keywords::False) {
2146 LitKind::Bool(false)
2148 let lit = self.parse_lit_token()?;
2151 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2154 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2155 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2156 maybe_whole_expr!(self);
2158 let minus_lo = self.span;
2159 let minus_present = self.eat(&token::BinOp(token::Minus));
2161 let literal = self.parse_lit()?;
2162 let hi = self.prev_span;
2163 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2166 let minus_hi = self.prev_span;
2167 let unary = self.mk_unary(UnOp::Neg, expr);
2168 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2174 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2176 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2177 let span = self.span;
2179 Ok(Ident::new(ident.name, span))
2181 _ => self.parse_ident(),
2185 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2187 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2188 let span = self.span;
2190 Ok(Ident::new(ident.name, span))
2192 _ => self.parse_ident(),
2196 /// Parses a qualified path.
2197 /// Assumes that the leading `<` has been parsed already.
2199 /// `qualified_path = <type [as trait_ref]>::path`
2204 /// `<T as U>::F::a<S>` (without disambiguator)
2205 /// `<T as U>::F::a::<S>` (with disambiguator)
2206 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2207 let lo = self.prev_span;
2208 let ty = self.parse_ty()?;
2210 // `path` will contain the prefix of the path up to the `>`,
2211 // if any (e.g., `U` in the `<T as U>::*` examples
2212 // above). `path_span` has the span of that path, or an empty
2213 // span in the case of something like `<T>::Bar`.
2214 let (mut path, path_span);
2215 if self.eat_keyword(keywords::As) {
2216 let path_lo = self.span;
2217 path = self.parse_path(PathStyle::Type)?;
2218 path_span = path_lo.to(self.prev_span);
2220 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2221 path_span = self.span.to(self.span);
2224 // See doc comment for `unmatched_angle_bracket_count`.
2225 self.expect(&token::Gt)?;
2226 if self.unmatched_angle_bracket_count > 0 {
2227 self.unmatched_angle_bracket_count -= 1;
2228 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2231 self.expect(&token::ModSep)?;
2233 let qself = QSelf { ty, path_span, position: path.segments.len() };
2234 self.parse_path_segments(&mut path.segments, style)?;
2236 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2239 /// Parses simple paths.
2241 /// `path = [::] segment+`
2242 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2245 /// `a::b::C<D>` (without disambiguator)
2246 /// `a::b::C::<D>` (with disambiguator)
2247 /// `Fn(Args)` (without disambiguator)
2248 /// `Fn::(Args)` (with disambiguator)
2249 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2250 maybe_whole!(self, NtPath, |path| {
2251 if style == PathStyle::Mod &&
2252 path.segments.iter().any(|segment| segment.args.is_some()) {
2253 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2258 let lo = self.meta_var_span.unwrap_or(self.span);
2259 let mut segments = Vec::new();
2260 let mod_sep_ctxt = self.span.ctxt();
2261 if self.eat(&token::ModSep) {
2262 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2264 self.parse_path_segments(&mut segments, style)?;
2266 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2269 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2270 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2272 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2273 let meta_ident = match self.token {
2274 token::Interpolated(ref nt) => match **nt {
2275 token::NtMeta(ref meta) => match meta.node {
2276 ast::MetaItemKind::Word => Some(meta.path.clone()),
2283 if let Some(path) = meta_ident {
2287 self.parse_path(style)
2290 crate fn parse_path_segments(&mut self,
2291 segments: &mut Vec<PathSegment>,
2293 -> PResult<'a, ()> {
2295 let segment = self.parse_path_segment(style)?;
2296 if style == PathStyle::Expr {
2297 // In order to check for trailing angle brackets, we must have finished
2298 // recursing (`parse_path_segment` can indirectly call this function),
2299 // that is, the next token must be the highlighted part of the below example:
2301 // `Foo::<Bar as Baz<T>>::Qux`
2304 // As opposed to the below highlight (if we had only finished the first
2307 // `Foo::<Bar as Baz<T>>::Qux`
2310 // `PathStyle::Expr` is only provided at the root invocation and never in
2311 // `parse_path_segment` to recurse and therefore can be checked to maintain
2313 self.check_trailing_angle_brackets(&segment, token::ModSep);
2315 segments.push(segment);
2317 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2323 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2324 let ident = self.parse_path_segment_ident()?;
2326 let is_args_start = |token: &token::Token| match *token {
2327 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
2328 | token::LArrow => true,
2331 let check_args_start = |this: &mut Self| {
2332 this.expected_tokens.extend_from_slice(
2333 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2335 is_args_start(&this.token)
2338 Ok(if style == PathStyle::Type && check_args_start(self) ||
2339 style != PathStyle::Mod && self.check(&token::ModSep)
2340 && self.look_ahead(1, |t| is_args_start(t)) {
2341 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2342 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2343 // parsing a new path.
2344 if style == PathStyle::Expr {
2345 self.unmatched_angle_bracket_count = 0;
2346 self.max_angle_bracket_count = 0;
2349 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2350 self.eat(&token::ModSep);
2352 let args = if self.eat_lt() {
2354 let (args, bindings) =
2355 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2357 let span = lo.to(self.prev_span);
2358 AngleBracketedArgs { args, bindings, span }.into()
2362 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2363 &[&token::CloseDelim(token::Paren)],
2364 SeqSep::trailing_allowed(token::Comma),
2365 TokenExpectType::Expect,
2370 let span = lo.to(self.prev_span);
2371 let output = if self.eat(&token::RArrow) {
2372 Some(self.parse_ty_common(false, false, false)?)
2376 ParenthesizedArgs { inputs, output, span }.into()
2379 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2381 // Generic arguments are not found.
2382 PathSegment::from_ident(ident)
2386 crate fn check_lifetime(&mut self) -> bool {
2387 self.expected_tokens.push(TokenType::Lifetime);
2388 self.token.is_lifetime()
2391 /// Parses a single lifetime `'a` or panics.
2392 crate fn expect_lifetime(&mut self) -> Lifetime {
2393 if let Some(ident) = self.token.lifetime() {
2394 let span = self.span;
2396 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2398 self.span_bug(self.span, "not a lifetime")
2402 fn eat_label(&mut self) -> Option<Label> {
2403 if let Some(ident) = self.token.lifetime() {
2404 let span = self.span;
2406 Some(Label { ident: Ident::new(ident.name, span) })
2412 /// Parses mutability (`mut` or nothing).
2413 fn parse_mutability(&mut self) -> Mutability {
2414 if self.eat_keyword(keywords::Mut) {
2417 Mutability::Immutable
2421 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2422 if let token::Literal(token::Integer(name), suffix) = self.token {
2423 self.expect_no_suffix(self.span, "a tuple index", suffix);
2425 Ok(Ident::new(name, self.prev_span))
2427 self.parse_ident_common(false)
2431 /// Parse ident (COLON expr)?
2432 fn parse_field(&mut self) -> PResult<'a, Field> {
2433 let attrs = self.parse_outer_attributes()?;
2436 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2437 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2438 t == &token::Colon || t == &token::Eq
2440 let fieldname = self.parse_field_name()?;
2442 // Check for an equals token. This means the source incorrectly attempts to
2443 // initialize a field with an eq rather than a colon.
2444 if self.token == token::Eq {
2446 .struct_span_err(self.span, "expected `:`, found `=`")
2448 fieldname.span.shrink_to_hi().to(self.span),
2449 "replace equals symbol with a colon",
2451 Applicability::MachineApplicable,
2456 (fieldname, self.parse_expr()?, false)
2458 let fieldname = self.parse_ident_common(false)?;
2460 // Mimic `x: x` for the `x` field shorthand.
2461 let path = ast::Path::from_ident(fieldname);
2462 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2463 (fieldname, expr, true)
2467 span: lo.to(expr.span),
2470 attrs: attrs.into(),
2474 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2475 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2478 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2479 ExprKind::Unary(unop, expr)
2482 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2483 ExprKind::Binary(binop, lhs, rhs)
2486 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2487 ExprKind::Call(f, args)
2490 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2491 ExprKind::Index(expr, idx)
2494 fn mk_range(&mut self,
2495 start: Option<P<Expr>>,
2496 end: Option<P<Expr>>,
2497 limits: RangeLimits)
2498 -> PResult<'a, ast::ExprKind> {
2499 if end.is_none() && limits == RangeLimits::Closed {
2500 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2502 Ok(ExprKind::Range(start, end, limits))
2506 fn mk_assign_op(&mut self, binop: ast::BinOp,
2507 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2508 ExprKind::AssignOp(binop, lhs, rhs)
2511 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2512 let delim = match self.token {
2513 token::OpenDelim(delim) => delim,
2515 let msg = "expected open delimiter";
2516 let mut err = self.fatal(msg);
2517 err.span_label(self.span, msg);
2521 let tts = match self.parse_token_tree() {
2522 TokenTree::Delimited(_, _, tts) => tts,
2523 _ => unreachable!(),
2525 let delim = match delim {
2526 token::Paren => MacDelimiter::Parenthesis,
2527 token::Bracket => MacDelimiter::Bracket,
2528 token::Brace => MacDelimiter::Brace,
2529 token::NoDelim => self.bug("unexpected no delimiter"),
2531 Ok((delim, tts.into()))
2534 /// At the bottom (top?) of the precedence hierarchy,
2535 /// Parses things like parenthesized exprs, macros, `return`, etc.
2537 /// N.B., this does not parse outer attributes, and is private because it only works
2538 /// correctly if called from `parse_dot_or_call_expr()`.
2539 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2540 maybe_recover_from_interpolated_ty_qpath!(self, true);
2541 maybe_whole_expr!(self);
2543 // Outer attributes are already parsed and will be
2544 // added to the return value after the fact.
2546 // Therefore, prevent sub-parser from parsing
2547 // attributes by giving them a empty "already parsed" list.
2548 let mut attrs = ThinVec::new();
2551 let mut hi = self.span;
2555 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2557 token::OpenDelim(token::Paren) => {
2560 attrs.extend(self.parse_inner_attributes()?);
2562 // (e) is parenthesized e
2563 // (e,) is a tuple with only one field, e
2564 let mut es = vec![];
2565 let mut trailing_comma = false;
2566 let mut recovered = false;
2567 while self.token != token::CloseDelim(token::Paren) {
2568 es.push(match self.parse_expr() {
2571 // recover from parse error in tuple list
2572 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2575 recovered = self.expect_one_of(
2577 &[token::Comma, token::CloseDelim(token::Paren)],
2579 if self.eat(&token::Comma) {
2580 trailing_comma = true;
2582 trailing_comma = false;
2590 hi = self.prev_span;
2591 ex = if es.len() == 1 && !trailing_comma {
2592 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2597 token::OpenDelim(token::Brace) => {
2598 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2600 token::BinOp(token::Or) | token::OrOr => {
2601 return self.parse_lambda_expr(attrs);
2603 token::OpenDelim(token::Bracket) => {
2606 attrs.extend(self.parse_inner_attributes()?);
2608 if self.eat(&token::CloseDelim(token::Bracket)) {
2610 ex = ExprKind::Array(Vec::new());
2613 let first_expr = self.parse_expr()?;
2614 if self.eat(&token::Semi) {
2615 // Repeating array syntax: [ 0; 512 ]
2616 let count = AnonConst {
2617 id: ast::DUMMY_NODE_ID,
2618 value: self.parse_expr()?,
2620 self.expect(&token::CloseDelim(token::Bracket))?;
2621 ex = ExprKind::Repeat(first_expr, count);
2622 } else if self.eat(&token::Comma) {
2623 // Vector with two or more elements.
2624 let remaining_exprs = self.parse_seq_to_end(
2625 &token::CloseDelim(token::Bracket),
2626 SeqSep::trailing_allowed(token::Comma),
2627 |p| Ok(p.parse_expr()?)
2629 let mut exprs = vec![first_expr];
2630 exprs.extend(remaining_exprs);
2631 ex = ExprKind::Array(exprs);
2633 // Vector with one element.
2634 self.expect(&token::CloseDelim(token::Bracket))?;
2635 ex = ExprKind::Array(vec![first_expr]);
2638 hi = self.prev_span;
2642 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2644 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2646 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2648 if self.is_async_block() { // check for `async {` and `async move {`
2649 return self.parse_async_block(attrs);
2651 return self.parse_lambda_expr(attrs);
2654 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2655 return self.parse_lambda_expr(attrs);
2657 if self.eat_keyword(keywords::If) {
2658 return self.parse_if_expr(attrs);
2660 if self.eat_keyword(keywords::For) {
2661 let lo = self.prev_span;
2662 return self.parse_for_expr(None, lo, attrs);
2664 if self.eat_keyword(keywords::While) {
2665 let lo = self.prev_span;
2666 return self.parse_while_expr(None, lo, attrs);
2668 if let Some(label) = self.eat_label() {
2669 let lo = label.ident.span;
2670 self.expect(&token::Colon)?;
2671 if self.eat_keyword(keywords::While) {
2672 return self.parse_while_expr(Some(label), lo, attrs)
2674 if self.eat_keyword(keywords::For) {
2675 return self.parse_for_expr(Some(label), lo, attrs)
2677 if self.eat_keyword(keywords::Loop) {
2678 return self.parse_loop_expr(Some(label), lo, attrs)
2680 if self.token == token::OpenDelim(token::Brace) {
2681 return self.parse_block_expr(Some(label),
2683 BlockCheckMode::Default,
2686 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2687 let mut err = self.fatal(msg);
2688 err.span_label(self.span, msg);
2691 if self.eat_keyword(keywords::Loop) {
2692 let lo = self.prev_span;
2693 return self.parse_loop_expr(None, lo, attrs);
2695 if self.eat_keyword(keywords::Continue) {
2696 let label = self.eat_label();
2697 let ex = ExprKind::Continue(label);
2698 let hi = self.prev_span;
2699 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2701 if self.eat_keyword(keywords::Match) {
2702 let match_sp = self.prev_span;
2703 return self.parse_match_expr(attrs).map_err(|mut err| {
2704 err.span_label(match_sp, "while parsing this match expression");
2708 if self.eat_keyword(keywords::Unsafe) {
2709 return self.parse_block_expr(
2712 BlockCheckMode::Unsafe(ast::UserProvided),
2715 if self.is_do_catch_block() {
2716 let mut db = self.fatal("found removed `do catch` syntax");
2717 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2720 if self.is_try_block() {
2722 assert!(self.eat_keyword(keywords::Try));
2723 return self.parse_try_block(lo, attrs);
2725 if self.eat_keyword(keywords::Return) {
2726 if self.token.can_begin_expr() {
2727 let e = self.parse_expr()?;
2729 ex = ExprKind::Ret(Some(e));
2731 ex = ExprKind::Ret(None);
2733 } else if self.eat_keyword(keywords::Break) {
2734 let label = self.eat_label();
2735 let e = if self.token.can_begin_expr()
2736 && !(self.token == token::OpenDelim(token::Brace)
2737 && self.restrictions.contains(
2738 Restrictions::NO_STRUCT_LITERAL)) {
2739 Some(self.parse_expr()?)
2743 ex = ExprKind::Break(label, e);
2744 hi = self.prev_span;
2745 } else if self.eat_keyword(keywords::Yield) {
2746 if self.token.can_begin_expr() {
2747 let e = self.parse_expr()?;
2749 ex = ExprKind::Yield(Some(e));
2751 ex = ExprKind::Yield(None);
2753 } else if self.token.is_keyword(keywords::Let) {
2754 // Catch this syntax error here, instead of in `parse_ident`, so
2755 // that we can explicitly mention that let is not to be used as an expression
2756 let mut db = self.fatal("expected expression, found statement (`let`)");
2757 db.span_label(self.span, "expected expression");
2758 db.note("variable declaration using `let` is a statement");
2760 } else if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
2761 // FIXME: remove this branch when `await!` is no longer supported
2762 // https://github.com/rust-lang/rust/issues/60610
2763 self.expect(&token::Not)?;
2764 self.expect(&token::OpenDelim(token::Paren))?;
2765 let expr = self.parse_expr()?;
2766 self.expect(&token::CloseDelim(token::Paren))?;
2767 ex = ExprKind::Await(ast::AwaitOrigin::MacroLike, expr);
2768 } else if self.token.is_path_start() {
2769 let path = self.parse_path(PathStyle::Expr)?;
2771 // `!`, as an operator, is prefix, so we know this isn't that
2772 if self.eat(&token::Not) {
2773 // MACRO INVOCATION expression
2774 let (delim, tts) = self.expect_delimited_token_tree()?;
2775 hi = self.prev_span;
2776 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2777 } else if self.check(&token::OpenDelim(token::Brace)) {
2778 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2782 ex = ExprKind::Path(None, path);
2786 ex = ExprKind::Path(None, path);
2789 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2790 // Don't complain about bare semicolons after unclosed braces
2791 // recovery in order to keep the error count down. Fixing the
2792 // delimiters will possibly also fix the bare semicolon found in
2793 // expression context. For example, silence the following error:
2795 // error: expected expression, found `;`
2799 // | ^ expected expression
2802 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2804 match self.parse_literal_maybe_minus() {
2807 ex = expr.node.clone();
2810 self.cancel(&mut err);
2811 let msg = format!("expected expression, found {}",
2812 self.this_token_descr());
2813 let mut err = self.fatal(&msg);
2814 let sp = self.sess.source_map().start_point(self.span);
2815 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow()
2818 self.sess.expr_parentheses_needed(&mut err, *sp, None);
2820 err.span_label(self.span, "expected expression");
2828 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2829 self.maybe_recover_from_bad_qpath(expr, true)
2832 fn maybe_parse_struct_expr(
2836 attrs: &ThinVec<Attribute>,
2837 ) -> Option<PResult<'a, P<Expr>>> {
2838 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2839 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2840 // `{ ident, ` cannot start a block
2841 self.look_ahead(2, |t| t == &token::Comma) ||
2842 self.look_ahead(2, |t| t == &token::Colon) && (
2843 // `{ ident: token, ` cannot start a block
2844 self.look_ahead(4, |t| t == &token::Comma) ||
2845 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2846 self.look_ahead(3, |t| !t.can_begin_type())
2850 if struct_allowed || certainly_not_a_block() {
2851 // This is a struct literal, but we don't can't accept them here
2852 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2853 if let (Ok(expr), false) = (&expr, struct_allowed) {
2854 let mut err = self.diagnostic().struct_span_err(
2856 "struct literals are not allowed here",
2858 err.multipart_suggestion(
2859 "surround the struct literal with parentheses",
2861 (lo.shrink_to_lo(), "(".to_string()),
2862 (expr.span.shrink_to_hi(), ")".to_string()),
2864 Applicability::MachineApplicable,
2873 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2874 -> PResult<'a, P<Expr>> {
2875 let struct_sp = lo.to(self.prev_span);
2877 let mut fields = Vec::new();
2878 let mut base = None;
2880 attrs.extend(self.parse_inner_attributes()?);
2882 while self.token != token::CloseDelim(token::Brace) {
2883 if self.eat(&token::DotDot) {
2884 let exp_span = self.prev_span;
2885 match self.parse_expr() {
2891 self.recover_stmt();
2894 if self.token == token::Comma {
2895 let mut err = self.sess.span_diagnostic.mut_span_err(
2896 exp_span.to(self.prev_span),
2897 "cannot use a comma after the base struct",
2899 err.span_suggestion_short(
2901 "remove this comma",
2903 Applicability::MachineApplicable
2905 err.note("the base struct must always be the last field");
2907 self.recover_stmt();
2912 let mut recovery_field = None;
2913 if let token::Ident(ident, _) = self.token {
2914 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2915 // Use in case of error after field-looking code: `S { foo: () with a }`
2916 let mut ident = ident.clone();
2917 ident.span = self.span;
2918 recovery_field = Some(ast::Field {
2921 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2922 is_shorthand: false,
2923 attrs: ThinVec::new(),
2927 let mut parsed_field = None;
2928 match self.parse_field() {
2929 Ok(f) => parsed_field = Some(f),
2931 e.span_label(struct_sp, "while parsing this struct");
2934 // If the next token is a comma, then try to parse
2935 // what comes next as additional fields, rather than
2936 // bailing out until next `}`.
2937 if self.token != token::Comma {
2938 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2939 if self.token != token::Comma {
2946 match self.expect_one_of(&[token::Comma],
2947 &[token::CloseDelim(token::Brace)]) {
2948 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2949 // only include the field if there's no parse error for the field name
2953 if let Some(f) = recovery_field {
2956 e.span_label(struct_sp, "while parsing this struct");
2958 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2959 self.eat(&token::Comma);
2964 let span = lo.to(self.span);
2965 self.expect(&token::CloseDelim(token::Brace))?;
2966 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2969 fn parse_or_use_outer_attributes(&mut self,
2970 already_parsed_attrs: Option<ThinVec<Attribute>>)
2971 -> PResult<'a, ThinVec<Attribute>> {
2972 if let Some(attrs) = already_parsed_attrs {
2975 self.parse_outer_attributes().map(|a| a.into())
2979 /// Parses a block or unsafe block.
2980 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2981 lo: Span, blk_mode: BlockCheckMode,
2982 outer_attrs: ThinVec<Attribute>)
2983 -> PResult<'a, P<Expr>> {
2984 self.expect(&token::OpenDelim(token::Brace))?;
2986 let mut attrs = outer_attrs;
2987 attrs.extend(self.parse_inner_attributes()?);
2989 let blk = self.parse_block_tail(lo, blk_mode)?;
2990 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2993 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2994 fn parse_dot_or_call_expr(&mut self,
2995 already_parsed_attrs: Option<ThinVec<Attribute>>)
2996 -> PResult<'a, P<Expr>> {
2997 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2999 let b = self.parse_bottom_expr();
3000 let (span, b) = self.interpolated_or_expr_span(b)?;
3001 self.parse_dot_or_call_expr_with(b, span, attrs)
3004 fn parse_dot_or_call_expr_with(&mut self,
3007 mut attrs: ThinVec<Attribute>)
3008 -> PResult<'a, P<Expr>> {
3009 // Stitch the list of outer attributes onto the return value.
3010 // A little bit ugly, but the best way given the current code
3012 self.parse_dot_or_call_expr_with_(e0, lo)
3014 expr.map(|mut expr| {
3015 attrs.extend::<Vec<_>>(expr.attrs.into());
3018 ExprKind::If(..) | ExprKind::IfLet(..) => {
3019 if !expr.attrs.is_empty() {
3020 // Just point to the first attribute in there...
3021 let span = expr.attrs[0].span;
3024 "attributes are not yet allowed on `if` \
3035 // Assuming we have just parsed `.`, continue parsing into an expression.
3036 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3037 if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
3038 let span = lo.to(self.prev_span);
3039 let await_expr = self.mk_expr(
3041 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
3044 return Ok(await_expr);
3046 let segment = self.parse_path_segment(PathStyle::Expr)?;
3047 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3049 Ok(match self.token {
3050 token::OpenDelim(token::Paren) => {
3051 // Method call `expr.f()`
3052 let mut args = self.parse_unspanned_seq(
3053 &token::OpenDelim(token::Paren),
3054 &token::CloseDelim(token::Paren),
3055 SeqSep::trailing_allowed(token::Comma),
3056 |p| Ok(p.parse_expr()?)
3058 args.insert(0, self_arg);
3060 let span = lo.to(self.prev_span);
3061 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3064 // Field access `expr.f`
3065 if let Some(args) = segment.args {
3066 self.span_err(args.span(),
3067 "field expressions may not have generic arguments");
3070 let span = lo.to(self.prev_span);
3071 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3076 /// This function checks if there are trailing angle brackets and produces
3077 /// a diagnostic to suggest removing them.
3079 /// ```ignore (diagnostic)
3080 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3081 /// ^^ help: remove extra angle brackets
3083 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3084 // This function is intended to be invoked after parsing a path segment where there are two
3087 // 1. A specific token is expected after the path segment.
3088 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3089 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3090 // 2. No specific token is expected after the path segment.
3091 // eg. `x.foo` (field access)
3093 // This function is called after parsing `.foo` and before parsing the token `end` (if
3094 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3097 // We only care about trailing angle brackets if we previously parsed angle bracket
3098 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3099 // removed in this case:
3101 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3103 // This case is particularly tricky as we won't notice it just looking at the tokens -
3104 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3105 // have already been parsed):
3107 // `x.foo::<u32>>>(3)`
3108 let parsed_angle_bracket_args = segment.args
3110 .map(|args| args.is_angle_bracketed())
3114 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3115 parsed_angle_bracket_args,
3117 if !parsed_angle_bracket_args {
3121 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3125 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3126 // (since we might have the field access case and the characters we're eating are
3127 // actual operators and not trailing characters - ie `x.foo >> 3`).
3128 let mut position = 0;
3130 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3131 // many of each (so we can correctly pluralize our error messages) and continue to
3133 let mut number_of_shr = 0;
3134 let mut number_of_gt = 0;
3135 while self.look_ahead(position, |t| {
3136 trace!("check_trailing_angle_brackets: t={:?}", t);
3137 if *t == token::BinOp(token::BinOpToken::Shr) {
3140 } else if *t == token::Gt {
3150 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3152 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3153 number_of_gt, number_of_shr,
3155 if number_of_gt < 1 && number_of_shr < 1 {
3159 // Finally, double check that we have our end token as otherwise this is the
3161 if self.look_ahead(position, |t| {
3162 trace!("check_trailing_angle_brackets: t={:?}", t);
3165 // Eat from where we started until the end token so that parsing can continue
3166 // as if we didn't have those extra angle brackets.
3167 self.eat_to_tokens(&[&end]);
3168 let span = lo.until(self.span);
3170 let plural = number_of_gt > 1 || number_of_shr >= 1;
3174 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3178 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3180 Applicability::MachineApplicable,
3186 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3191 while self.eat(&token::Question) {
3192 let hi = self.prev_span;
3193 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3197 if self.eat(&token::Dot) {
3199 token::Ident(..) => {
3200 e = self.parse_dot_suffix(e, lo)?;
3202 token::Literal(token::Integer(name), suffix) => {
3203 let span = self.span;
3205 let field = ExprKind::Field(e, Ident::new(name, span));
3206 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3208 self.expect_no_suffix(span, "a tuple index", suffix);
3210 token::Literal(token::Float(n), _suf) => {
3212 let fstr = n.as_str();
3213 let mut err = self.diagnostic()
3214 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3215 err.span_label(self.prev_span, "unexpected token");
3216 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3217 let float = match fstr.parse::<f64>().ok() {
3221 let sugg = pprust::to_string(|s| {
3222 use crate::print::pprust::PrintState;
3226 s.print_usize(float.trunc() as usize)?;
3229 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3231 err.span_suggestion(
3232 lo.to(self.prev_span),
3233 "try parenthesizing the first index",
3235 Applicability::MachineApplicable
3242 // FIXME Could factor this out into non_fatal_unexpected or something.
3243 let actual = self.this_token_to_string();
3244 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3249 if self.expr_is_complete(&e) { break; }
3252 token::OpenDelim(token::Paren) => {
3253 let seq = self.parse_unspanned_seq(
3254 &token::OpenDelim(token::Paren),
3255 &token::CloseDelim(token::Paren),
3256 SeqSep::trailing_allowed(token::Comma),
3257 |p| Ok(p.parse_expr()?)
3259 let nd = self.mk_call(e, es);
3260 let hi = self.prev_span;
3261 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3263 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3267 // Could be either an index expression or a slicing expression.
3268 token::OpenDelim(token::Bracket) => {
3270 let ix = self.parse_expr()?;
3272 self.expect(&token::CloseDelim(token::Bracket))?;
3273 let index = self.mk_index(e, ix);
3274 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3282 fn recover_seq_parse_error(
3284 delim: token::DelimToken,
3286 result: PResult<'a, P<Expr>>,
3292 // recover from parse error
3293 self.consume_block(delim);
3294 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
3299 crate fn process_potential_macro_variable(&mut self) {
3300 let (token, span) = match self.token {
3301 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3302 self.look_ahead(1, |t| t.is_ident()) => {
3304 let name = match self.token {
3305 token::Ident(ident, _) => ident,
3308 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3309 err.span_label(self.span, "unknown macro variable");
3314 token::Interpolated(ref nt) => {
3315 self.meta_var_span = Some(self.span);
3316 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3317 // and lifetime tokens, so the former are never encountered during normal parsing.
3319 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3320 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3330 /// Parses a single token tree from the input.
3331 crate fn parse_token_tree(&mut self) -> TokenTree {
3333 token::OpenDelim(..) => {
3334 let frame = mem::replace(&mut self.token_cursor.frame,
3335 self.token_cursor.stack.pop().unwrap());
3336 self.span = frame.span.entire();
3338 TokenTree::Delimited(
3341 frame.tree_cursor.stream.into(),
3344 token::CloseDelim(_) | token::Eof => unreachable!(),
3346 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3348 TokenTree::Token(span, token)
3353 // parse a stream of tokens into a list of TokenTree's,
3355 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3356 let mut tts = Vec::new();
3357 while self.token != token::Eof {
3358 tts.push(self.parse_token_tree());
3363 pub fn parse_tokens(&mut self) -> TokenStream {
3364 let mut result = Vec::new();
3367 token::Eof | token::CloseDelim(..) => break,
3368 _ => result.push(self.parse_token_tree().into()),
3371 TokenStream::new(result)
3374 /// Parse a prefix-unary-operator expr
3375 fn parse_prefix_expr(&mut self,
3376 already_parsed_attrs: Option<ThinVec<Attribute>>)
3377 -> PResult<'a, P<Expr>> {
3378 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3380 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3381 let (hi, ex) = match self.token {
3384 let e = self.parse_prefix_expr(None);
3385 let (span, e) = self.interpolated_or_expr_span(e)?;
3386 (lo.to(span), self.mk_unary(UnOp::Not, e))
3388 // Suggest `!` for bitwise negation when encountering a `~`
3391 let e = self.parse_prefix_expr(None);
3392 let (span, e) = self.interpolated_or_expr_span(e)?;
3393 let span_of_tilde = lo;
3394 let mut err = self.diagnostic()
3395 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3396 err.span_suggestion_short(
3398 "use `!` to perform bitwise negation",
3400 Applicability::MachineApplicable
3403 (lo.to(span), self.mk_unary(UnOp::Not, e))
3405 token::BinOp(token::Minus) => {
3407 let e = self.parse_prefix_expr(None);
3408 let (span, e) = self.interpolated_or_expr_span(e)?;
3409 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3411 token::BinOp(token::Star) => {
3413 let e = self.parse_prefix_expr(None);
3414 let (span, e) = self.interpolated_or_expr_span(e)?;
3415 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3417 token::BinOp(token::And) | token::AndAnd => {
3419 let m = self.parse_mutability();
3420 let e = self.parse_prefix_expr(None);
3421 let (span, e) = self.interpolated_or_expr_span(e)?;
3422 (lo.to(span), ExprKind::AddrOf(m, e))
3424 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3426 let place = self.parse_expr_res(
3427 Restrictions::NO_STRUCT_LITERAL,
3430 let blk = self.parse_block()?;
3431 let span = blk.span;
3432 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3433 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3435 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3437 let e = self.parse_prefix_expr(None);
3438 let (span, e) = self.interpolated_or_expr_span(e)?;
3439 (lo.to(span), ExprKind::Box(e))
3441 token::Ident(..) if self.token.is_ident_named("not") => {
3442 // `not` is just an ordinary identifier in Rust-the-language,
3443 // but as `rustc`-the-compiler, we can issue clever diagnostics
3444 // for confused users who really want to say `!`
3445 let token_cannot_continue_expr = |t: &token::Token| match *t {
3446 // These tokens can start an expression after `!`, but
3447 // can't continue an expression after an ident
3448 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3449 token::Literal(..) | token::Pound => true,
3450 token::Interpolated(ref nt) => match **nt {
3451 token::NtIdent(..) | token::NtExpr(..) |
3452 token::NtBlock(..) | token::NtPath(..) => true,
3457 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3458 if cannot_continue_expr {
3460 // Emit the error ...
3461 let mut err = self.diagnostic()
3462 .struct_span_err(self.span,
3463 &format!("unexpected {} after identifier",
3464 self.this_token_descr()));
3465 // span the `not` plus trailing whitespace to avoid
3466 // trailing whitespace after the `!` in our suggestion
3467 let to_replace = self.sess.source_map()
3468 .span_until_non_whitespace(lo.to(self.span));
3469 err.span_suggestion_short(
3471 "use `!` to perform logical negation",
3473 Applicability::MachineApplicable
3476 // —and recover! (just as if we were in the block
3477 // for the `token::Not` arm)
3478 let e = self.parse_prefix_expr(None);
3479 let (span, e) = self.interpolated_or_expr_span(e)?;
3480 (lo.to(span), self.mk_unary(UnOp::Not, e))
3482 return self.parse_dot_or_call_expr(Some(attrs));
3485 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3487 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3490 /// Parses an associative expression.
3492 /// This parses an expression accounting for associativity and precedence of the operators in
3495 fn parse_assoc_expr(&mut self,
3496 already_parsed_attrs: Option<ThinVec<Attribute>>)
3497 -> PResult<'a, P<Expr>> {
3498 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3501 /// Parses an associative expression with operators of at least `min_prec` precedence.
3502 fn parse_assoc_expr_with(&mut self,
3505 -> PResult<'a, P<Expr>> {
3506 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3509 let attrs = match lhs {
3510 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3513 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3514 return self.parse_prefix_range_expr(attrs);
3516 self.parse_prefix_expr(attrs)?
3520 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
3522 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3525 (false, _) => {} // continue parsing the expression
3526 // An exhaustive check is done in the following block, but these are checked first
3527 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
3528 // want to keep their span info to improve diagnostics in these cases in a later stage.
3529 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
3530 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
3531 (true, Some(AssocOp::Add)) => { // `{ 42 } + 42
3532 // These cases are ambiguous and can't be identified in the parser alone
3533 let sp = self.sess.source_map().start_point(self.span);
3534 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
3537 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
3540 (true, Some(_)) => {
3541 // We've found an expression that would be parsed as a statement, but the next
3542 // token implies this should be parsed as an expression.
3543 // For example: `if let Some(x) = x { x } else { 0 } / 2`
3544 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
3545 "expected expression, found `{}`",
3546 pprust::token_to_string(&self.token),
3548 err.span_label(self.span, "expected expression");
3549 self.sess.expr_parentheses_needed(
3552 Some(pprust::expr_to_string(&lhs),
3557 self.expected_tokens.push(TokenType::Operator);
3558 while let Some(op) = AssocOp::from_token(&self.token) {
3560 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3561 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3562 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3563 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3564 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3565 (PrevTokenKind::Interpolated, _) => self.prev_span,
3566 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3567 if path.segments.len() == 1 => self.prev_span,
3571 let cur_op_span = self.span;
3572 let restrictions = if op.is_assign_like() {
3573 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3577 if op.precedence() < min_prec {
3580 // Check for deprecated `...` syntax
3581 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3582 self.err_dotdotdot_syntax(self.span);
3586 if op.is_comparison() {
3587 self.check_no_chained_comparison(&lhs, &op);
3590 if op == AssocOp::As {
3591 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3593 } else if op == AssocOp::Colon {
3594 let maybe_path = self.could_ascription_be_path(&lhs.node);
3595 let next_sp = self.span;
3597 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3600 self.bad_type_ascription(
3611 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3612 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3613 // generalise it to the Fixity::None code.
3615 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3616 // two variants are handled with `parse_prefix_range_expr` call above.
3617 let rhs = if self.is_at_start_of_range_notation_rhs() {
3618 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3619 LhsExpr::NotYetParsed)?)
3623 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3628 let limits = if op == AssocOp::DotDot {
3629 RangeLimits::HalfOpen
3634 let r = self.mk_range(Some(lhs), rhs, limits)?;
3635 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3639 let rhs = match op.fixity() {
3640 Fixity::Right => self.with_res(
3641 restrictions - Restrictions::STMT_EXPR,
3643 this.parse_assoc_expr_with(op.precedence(),
3644 LhsExpr::NotYetParsed)
3646 Fixity::Left => self.with_res(
3647 restrictions - Restrictions::STMT_EXPR,
3649 this.parse_assoc_expr_with(op.precedence() + 1,
3650 LhsExpr::NotYetParsed)
3652 // We currently have no non-associative operators that are not handled above by
3653 // the special cases. The code is here only for future convenience.
3654 Fixity::None => self.with_res(
3655 restrictions - Restrictions::STMT_EXPR,
3657 this.parse_assoc_expr_with(op.precedence() + 1,
3658 LhsExpr::NotYetParsed)
3662 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3663 // including the attributes.
3667 .filter(|a| a.style == AttrStyle::Outer)
3669 .map_or(lhs_span, |a| a.span);
3670 let span = lhs_span.to(rhs.span);
3672 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3673 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3674 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3675 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3676 AssocOp::Greater | AssocOp::GreaterEqual => {
3677 let ast_op = op.to_ast_binop().unwrap();
3678 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3679 self.mk_expr(span, binary, ThinVec::new())
3682 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3683 AssocOp::ObsoleteInPlace =>
3684 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3685 AssocOp::AssignOp(k) => {
3687 token::Plus => BinOpKind::Add,
3688 token::Minus => BinOpKind::Sub,
3689 token::Star => BinOpKind::Mul,
3690 token::Slash => BinOpKind::Div,
3691 token::Percent => BinOpKind::Rem,
3692 token::Caret => BinOpKind::BitXor,
3693 token::And => BinOpKind::BitAnd,
3694 token::Or => BinOpKind::BitOr,
3695 token::Shl => BinOpKind::Shl,
3696 token::Shr => BinOpKind::Shr,
3698 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3699 self.mk_expr(span, aopexpr, ThinVec::new())
3701 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3702 self.bug("AssocOp should have been handled by special case")
3706 if op.fixity() == Fixity::None { break }
3711 fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
3712 self.token.is_ident() &&
3713 if let ast::ExprKind::Path(..) = node { true } else { false } &&
3714 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
3715 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
3716 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
3717 self.look_ahead(2, |t| t.is_ident()) ||
3718 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
3719 self.look_ahead(2, |t| t.is_ident()) ||
3720 self.look_ahead(1, |t| t == &token::ModSep) && // `foo:bar::baz`
3721 self.look_ahead(2, |t| t.is_ident())
3724 fn bad_type_ascription(
3726 err: &mut DiagnosticBuilder<'a>,
3732 err.span_label(self.span, "expecting a type here because of type ascription");
3733 let cm = self.sess.source_map();
3734 let next_pos = cm.lookup_char_pos(next_sp.lo());
3735 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3736 if op_pos.line != next_pos.line {
3737 err.span_suggestion(
3739 "try using a semicolon",
3741 Applicability::MaybeIncorrect,
3745 err.span_suggestion(
3747 "maybe you meant to write a path separator here",
3749 Applicability::MaybeIncorrect,
3752 err.note("type ascription is a nightly-only feature that lets \
3753 you annotate an expression with a type: `<expr>: <type>`");
3756 "this expression expects an ascribed type after the colon",
3758 err.help("this might be indicative of a syntax error elsewhere");
3763 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3764 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3765 -> PResult<'a, P<Expr>> {
3766 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3767 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3770 // Save the state of the parser before parsing type normally, in case there is a
3771 // LessThan comparison after this cast.
3772 let parser_snapshot_before_type = self.clone();
3773 match self.parse_ty_no_plus() {
3775 Ok(mk_expr(self, rhs))
3777 Err(mut type_err) => {
3778 // Rewind to before attempting to parse the type with generics, to recover
3779 // from situations like `x as usize < y` in which we first tried to parse
3780 // `usize < y` as a type with generic arguments.
3781 let parser_snapshot_after_type = self.clone();
3782 mem::replace(self, parser_snapshot_before_type);
3784 match self.parse_path(PathStyle::Expr) {
3786 let (op_noun, op_verb) = match self.token {
3787 token::Lt => ("comparison", "comparing"),
3788 token::BinOp(token::Shl) => ("shift", "shifting"),
3790 // We can end up here even without `<` being the next token, for
3791 // example because `parse_ty_no_plus` returns `Err` on keywords,
3792 // but `parse_path` returns `Ok` on them due to error recovery.
3793 // Return original error and parser state.
3794 mem::replace(self, parser_snapshot_after_type);
3795 return Err(type_err);
3799 // Successfully parsed the type path leaving a `<` yet to parse.
3802 // Report non-fatal diagnostics, keep `x as usize` as an expression
3803 // in AST and continue parsing.
3804 let msg = format!("`<` is interpreted as a start of generic \
3805 arguments for `{}`, not a {}", path, op_noun);
3806 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3807 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3808 "interpreted as generic arguments");
3809 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3811 let expr = mk_expr(self, P(Ty {
3813 node: TyKind::Path(None, path),
3814 id: ast::DUMMY_NODE_ID
3817 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3818 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3819 err.span_suggestion(
3821 &format!("try {} the cast value", op_verb),
3822 format!("({})", expr_str),
3823 Applicability::MachineApplicable
3829 Err(mut path_err) => {
3830 // Couldn't parse as a path, return original error and parser state.
3832 mem::replace(self, parser_snapshot_after_type);
3840 /// Produce an error if comparison operators are chained (RFC #558).
3841 /// We only need to check lhs, not rhs, because all comparison ops
3842 /// have same precedence and are left-associative
3843 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3844 debug_assert!(outer_op.is_comparison(),
3845 "check_no_chained_comparison: {:?} is not comparison",
3848 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3849 // respan to include both operators
3850 let op_span = op.span.to(self.span);
3851 let mut err = self.diagnostic().struct_span_err(op_span,
3852 "chained comparison operators require parentheses");
3853 if op.node == BinOpKind::Lt &&
3854 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3855 *outer_op == AssocOp::Greater // even in a case like the following:
3856 { // Foo<Bar<Baz<Qux, ()>>>
3858 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3859 err.help("or use `(...)` if you meant to specify fn arguments");
3867 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3868 fn parse_prefix_range_expr(&mut self,
3869 already_parsed_attrs: Option<ThinVec<Attribute>>)
3870 -> PResult<'a, P<Expr>> {
3871 // Check for deprecated `...` syntax
3872 if self.token == token::DotDotDot {
3873 self.err_dotdotdot_syntax(self.span);
3876 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3877 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3879 let tok = self.token.clone();
3880 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3882 let mut hi = self.span;
3884 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3885 // RHS must be parsed with more associativity than the dots.
3886 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3887 Some(self.parse_assoc_expr_with(next_prec,
3888 LhsExpr::NotYetParsed)
3896 let limits = if tok == token::DotDot {
3897 RangeLimits::HalfOpen
3902 let r = self.mk_range(None, opt_end, limits)?;
3903 Ok(self.mk_expr(lo.to(hi), r, attrs))
3906 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3907 if self.token.can_begin_expr() {
3908 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3909 if self.token == token::OpenDelim(token::Brace) {
3910 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3918 /// Parses an `if` or `if let` expression (`if` token already eaten).
3919 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3920 if self.check_keyword(keywords::Let) {
3921 return self.parse_if_let_expr(attrs);
3923 let lo = self.prev_span;
3924 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3926 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3927 // verify that the last statement is either an implicit return (no `;`) or an explicit
3928 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3929 // the dead code lint.
3930 if self.eat_keyword(keywords::Else) || !cond.returns() {
3931 let sp = self.sess.source_map().next_point(lo);
3932 let mut err = self.diagnostic()
3933 .struct_span_err(sp, "missing condition for `if` statemement");
3934 err.span_label(sp, "expected if condition here");
3937 let not_block = self.token != token::OpenDelim(token::Brace);
3938 let thn = self.parse_block().map_err(|mut err| {
3940 err.span_label(lo, "this `if` statement has a condition, but no block");
3944 let mut els: Option<P<Expr>> = None;
3945 let mut hi = thn.span;
3946 if self.eat_keyword(keywords::Else) {
3947 let elexpr = self.parse_else_expr()?;
3951 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3954 /// Parses an `if let` expression (`if` token already eaten).
3955 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3956 -> PResult<'a, P<Expr>> {
3957 let lo = self.prev_span;
3958 self.expect_keyword(keywords::Let)?;
3959 let pats = self.parse_pats()?;
3960 self.expect(&token::Eq)?;
3961 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3962 let thn = self.parse_block()?;
3963 let (hi, els) = if self.eat_keyword(keywords::Else) {
3964 let expr = self.parse_else_expr()?;
3965 (expr.span, Some(expr))
3969 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3972 /// Parses `move |args| expr`.
3973 fn parse_lambda_expr(&mut self,
3974 attrs: ThinVec<Attribute>)
3975 -> PResult<'a, P<Expr>>
3978 let movability = if self.eat_keyword(keywords::Static) {
3983 let asyncness = if self.span.rust_2018() {
3984 self.parse_asyncness()
3988 let capture_clause = if self.eat_keyword(keywords::Move) {
3993 let decl = self.parse_fn_block_decl()?;
3994 let decl_hi = self.prev_span;
3995 let body = match decl.output {
3996 FunctionRetTy::Default(_) => {
3997 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3998 self.parse_expr_res(restrictions, None)?
4001 // If an explicit return type is given, require a
4002 // block to appear (RFC 968).
4003 let body_lo = self.span;
4004 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
4010 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
4014 // `else` token already eaten
4015 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
4016 if self.eat_keyword(keywords::If) {
4017 return self.parse_if_expr(ThinVec::new());
4019 let blk = self.parse_block()?;
4020 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
4024 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
4025 fn parse_for_expr(&mut self, opt_label: Option<Label>,
4027 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4028 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
4030 let pat = self.parse_top_level_pat()?;
4031 if !self.eat_keyword(keywords::In) {
4032 let in_span = self.prev_span.between(self.span);
4033 let mut err = self.sess.span_diagnostic
4034 .struct_span_err(in_span, "missing `in` in `for` loop");
4035 err.span_suggestion_short(
4036 in_span, "try adding `in` here", " in ".into(),
4037 // has been misleading, at least in the past (closed Issue #48492)
4038 Applicability::MaybeIncorrect
4042 let in_span = self.prev_span;
4043 if self.eat_keyword(keywords::In) {
4044 // a common typo: `for _ in in bar {}`
4045 let mut err = self.sess.span_diagnostic.struct_span_err(
4047 "expected iterable, found keyword `in`",
4049 err.span_suggestion_short(
4050 in_span.until(self.prev_span),
4051 "remove the duplicated `in`",
4053 Applicability::MachineApplicable,
4055 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
4056 err.note("for more information on the status of emplacement syntax, see <\
4057 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
4060 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4061 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
4062 attrs.extend(iattrs);
4064 let hi = self.prev_span;
4065 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
4068 /// Parses a `while` or `while let` expression (`while` token already eaten).
4069 fn parse_while_expr(&mut self, opt_label: Option<Label>,
4071 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4072 if self.token.is_keyword(keywords::Let) {
4073 return self.parse_while_let_expr(opt_label, span_lo, attrs);
4075 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4076 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4077 attrs.extend(iattrs);
4078 let span = span_lo.to(body.span);
4079 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
4082 /// Parses a `while let` expression (`while` token already eaten).
4083 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
4085 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4086 self.expect_keyword(keywords::Let)?;
4087 let pats = self.parse_pats()?;
4088 self.expect(&token::Eq)?;
4089 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4090 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4091 attrs.extend(iattrs);
4092 let span = span_lo.to(body.span);
4093 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
4096 // parse `loop {...}`, `loop` token already eaten
4097 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
4099 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4100 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4101 attrs.extend(iattrs);
4102 let span = span_lo.to(body.span);
4103 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
4106 /// Parses an `async move {...}` expression.
4107 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4108 -> PResult<'a, P<Expr>>
4110 let span_lo = self.span;
4111 self.expect_keyword(keywords::Async)?;
4112 let capture_clause = if self.eat_keyword(keywords::Move) {
4117 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4118 attrs.extend(iattrs);
4120 span_lo.to(body.span),
4121 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4124 /// Parses a `try {...}` expression (`try` token already eaten).
4125 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4126 -> PResult<'a, P<Expr>>
4128 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4129 attrs.extend(iattrs);
4130 if self.eat_keyword(keywords::Catch) {
4131 let mut error = self.struct_span_err(self.prev_span,
4132 "keyword `catch` cannot follow a `try` block");
4133 error.help("try using `match` on the result of the `try` block instead");
4137 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4141 // `match` token already eaten
4142 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4143 let match_span = self.prev_span;
4144 let lo = self.prev_span;
4145 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4147 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4148 if self.token == token::Token::Semi {
4149 e.span_suggestion_short(
4151 "try removing this `match`",
4153 Applicability::MaybeIncorrect // speculative
4158 attrs.extend(self.parse_inner_attributes()?);
4160 let mut arms: Vec<Arm> = Vec::new();
4161 while self.token != token::CloseDelim(token::Brace) {
4162 match self.parse_arm() {
4163 Ok(arm) => arms.push(arm),
4165 // Recover by skipping to the end of the block.
4167 self.recover_stmt();
4168 let span = lo.to(self.span);
4169 if self.token == token::CloseDelim(token::Brace) {
4172 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4178 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4181 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4182 maybe_whole!(self, NtArm, |x| x);
4184 let attrs = self.parse_outer_attributes()?;
4185 let pats = self.parse_pats()?;
4186 let guard = if self.eat_keyword(keywords::If) {
4187 Some(Guard::If(self.parse_expr()?))
4191 let arrow_span = self.span;
4192 self.expect(&token::FatArrow)?;
4193 let arm_start_span = self.span;
4195 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4196 .map_err(|mut err| {
4197 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4201 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4202 && self.token != token::CloseDelim(token::Brace);
4205 let cm = self.sess.source_map();
4206 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4207 .map_err(|mut err| {
4208 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4209 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4210 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4211 && expr_lines.lines.len() == 2
4212 && self.token == token::FatArrow => {
4213 // We check whether there's any trailing code in the parse span,
4214 // if there isn't, we very likely have the following:
4217 // | -- - missing comma
4223 // | parsed until here as `"y" & X`
4224 err.span_suggestion_short(
4225 cm.next_point(arm_start_span),
4226 "missing a comma here to end this `match` arm",
4228 Applicability::MachineApplicable
4232 err.span_label(arrow_span,
4233 "while parsing the `match` arm starting here");
4239 self.eat(&token::Comma);
4250 /// Parses an expression.
4252 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4253 self.parse_expr_res(Restrictions::empty(), None)
4256 /// Evaluates the closure with restrictions in place.
4258 /// Afters the closure is evaluated, restrictions are reset.
4259 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4260 where F: FnOnce(&mut Self) -> T
4262 let old = self.restrictions;
4263 self.restrictions = r;
4265 self.restrictions = old;
4270 /// Parses an expression, subject to the given restrictions.
4272 fn parse_expr_res(&mut self, r: Restrictions,
4273 already_parsed_attrs: Option<ThinVec<Attribute>>)
4274 -> PResult<'a, P<Expr>> {
4275 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4278 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4279 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4280 if self.eat(&token::Eq) {
4281 Ok(Some(self.parse_expr()?))
4283 Ok(Some(self.parse_expr()?))
4289 /// Parses patterns, separated by '|' s.
4290 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4291 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4292 self.eat(&token::BinOp(token::Or));
4294 let mut pats = Vec::new();
4296 pats.push(self.parse_top_level_pat()?);
4298 if self.token == token::OrOr {
4299 let mut err = self.struct_span_err(self.span,
4300 "unexpected token `||` after pattern");
4301 err.span_suggestion(
4303 "use a single `|` to specify multiple patterns",
4305 Applicability::MachineApplicable
4309 } else if self.eat(&token::BinOp(token::Or)) {
4310 // This is a No-op. Continue the loop to parse the next
4318 // Parses a parenthesized list of patterns like
4319 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4320 // - a vector of the patterns that were parsed
4321 // - an option indicating the index of the `..` element
4322 // - a boolean indicating whether a trailing comma was present.
4323 // Trailing commas are significant because (p) and (p,) are different patterns.
4324 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4325 self.expect(&token::OpenDelim(token::Paren))?;
4326 let result = match self.parse_pat_list() {
4327 Ok(result) => result,
4328 Err(mut err) => { // recover from parse error in tuple pattern list
4330 self.consume_block(token::Paren);
4331 return Ok((vec![], Some(0), false));
4334 self.expect(&token::CloseDelim(token::Paren))?;
4338 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4339 let mut fields = Vec::new();
4340 let mut ddpos = None;
4341 let mut prev_dd_sp = None;
4342 let mut trailing_comma = false;
4344 if self.eat(&token::DotDot) {
4345 if ddpos.is_none() {
4346 ddpos = Some(fields.len());
4347 prev_dd_sp = Some(self.prev_span);
4349 // Emit a friendly error, ignore `..` and continue parsing
4350 let mut err = self.struct_span_err(
4352 "`..` can only be used once per tuple or tuple struct pattern",
4354 err.span_label(self.prev_span, "can only be used once per pattern");
4355 if let Some(sp) = prev_dd_sp {
4356 err.span_label(sp, "previously present here");
4360 } else if !self.check(&token::CloseDelim(token::Paren)) {
4361 fields.push(self.parse_pat(None)?);
4366 trailing_comma = self.eat(&token::Comma);
4367 if !trailing_comma {
4372 if ddpos == Some(fields.len()) && trailing_comma {
4373 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4374 let msg = "trailing comma is not permitted after `..`";
4375 self.struct_span_err(self.prev_span, msg)
4376 .span_label(self.prev_span, msg)
4380 Ok((fields, ddpos, trailing_comma))
4383 fn parse_pat_vec_elements(
4385 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4386 let mut before = Vec::new();
4387 let mut slice = None;
4388 let mut after = Vec::new();
4389 let mut first = true;
4390 let mut before_slice = true;
4392 while self.token != token::CloseDelim(token::Bracket) {
4396 self.expect(&token::Comma)?;
4398 if self.token == token::CloseDelim(token::Bracket)
4399 && (before_slice || !after.is_empty()) {
4405 if self.eat(&token::DotDot) {
4407 if self.check(&token::Comma) ||
4408 self.check(&token::CloseDelim(token::Bracket)) {
4409 slice = Some(P(Pat {
4410 id: ast::DUMMY_NODE_ID,
4411 node: PatKind::Wild,
4412 span: self.prev_span,
4414 before_slice = false;
4420 let subpat = self.parse_pat(None)?;
4421 if before_slice && self.eat(&token::DotDot) {
4422 slice = Some(subpat);
4423 before_slice = false;
4424 } else if before_slice {
4425 before.push(subpat);
4431 Ok((before, slice, after))
4437 attrs: Vec<Attribute>
4438 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4439 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4441 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4442 // Parsing a pattern of the form "fieldname: pat"
4443 let fieldname = self.parse_field_name()?;
4445 let pat = self.parse_pat(None)?;
4447 (pat, fieldname, false)
4449 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4450 let is_box = self.eat_keyword(keywords::Box);
4451 let boxed_span = self.span;
4452 let is_ref = self.eat_keyword(keywords::Ref);
4453 let is_mut = self.eat_keyword(keywords::Mut);
4454 let fieldname = self.parse_ident()?;
4455 hi = self.prev_span;
4457 let bind_type = match (is_ref, is_mut) {
4458 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4459 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4460 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4461 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4463 let fieldpat = P(Pat {
4464 id: ast::DUMMY_NODE_ID,
4465 node: PatKind::Ident(bind_type, fieldname, None),
4466 span: boxed_span.to(hi),
4469 let subpat = if is_box {
4471 id: ast::DUMMY_NODE_ID,
4472 node: PatKind::Box(fieldpat),
4478 (subpat, fieldname, true)
4481 Ok(source_map::Spanned {
4483 node: ast::FieldPat {
4487 attrs: attrs.into(),
4492 /// Parses the fields of a struct-like pattern.
4493 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4494 let mut fields = Vec::new();
4495 let mut etc = false;
4496 let mut ate_comma = true;
4497 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4498 let mut etc_span = None;
4500 while self.token != token::CloseDelim(token::Brace) {
4501 let attrs = self.parse_outer_attributes()?;
4504 // check that a comma comes after every field
4506 let err = self.struct_span_err(self.prev_span, "expected `,`");
4507 if let Some(mut delayed) = delayed_err {
4514 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4516 let mut etc_sp = self.span;
4518 if self.token == token::DotDotDot { // Issue #46718
4519 // Accept `...` as if it were `..` to avoid further errors
4520 let mut err = self.struct_span_err(self.span,
4521 "expected field pattern, found `...`");
4522 err.span_suggestion(
4524 "to omit remaining fields, use one fewer `.`",
4526 Applicability::MachineApplicable
4530 self.bump(); // `..` || `...`
4532 if self.token == token::CloseDelim(token::Brace) {
4533 etc_span = Some(etc_sp);
4536 let token_str = self.this_token_descr();
4537 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4539 err.span_label(self.span, "expected `}`");
4540 let mut comma_sp = None;
4541 if self.token == token::Comma { // Issue #49257
4542 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4543 err.span_label(etc_sp,
4544 "`..` must be at the end and cannot have a trailing comma");
4545 comma_sp = Some(self.span);
4550 etc_span = Some(etc_sp.until(self.span));
4551 if self.token == token::CloseDelim(token::Brace) {
4552 // If the struct looks otherwise well formed, recover and continue.
4553 if let Some(sp) = comma_sp {
4554 err.span_suggestion_short(
4556 "remove this comma",
4558 Applicability::MachineApplicable,
4563 } else if self.token.is_ident() && ate_comma {
4564 // Accept fields coming after `..,`.
4565 // This way we avoid "pattern missing fields" errors afterwards.
4566 // We delay this error until the end in order to have a span for a
4568 if let Some(mut delayed_err) = delayed_err {
4572 delayed_err = Some(err);
4575 if let Some(mut err) = delayed_err {
4582 fields.push(match self.parse_pat_field(lo, attrs) {
4585 if let Some(mut delayed_err) = delayed_err {
4591 ate_comma = self.eat(&token::Comma);
4594 if let Some(mut err) = delayed_err {
4595 if let Some(etc_span) = etc_span {
4596 err.multipart_suggestion(
4597 "move the `..` to the end of the field list",
4599 (etc_span, String::new()),
4600 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4602 Applicability::MachineApplicable,
4607 return Ok((fields, etc));
4610 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4611 if self.token.is_path_start() {
4613 let (qself, path) = if self.eat_lt() {
4614 // Parse a qualified path
4615 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4618 // Parse an unqualified path
4619 (None, self.parse_path(PathStyle::Expr)?)
4621 let hi = self.prev_span;
4622 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4624 self.parse_literal_maybe_minus()
4628 // helper function to decide whether to parse as ident binding or to try to do
4629 // something more complex like range patterns
4630 fn parse_as_ident(&mut self) -> bool {
4631 self.look_ahead(1, |t| match *t {
4632 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4633 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4634 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4635 // range pattern branch
4636 token::DotDot => None,
4638 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4639 token::Comma | token::CloseDelim(token::Bracket) => true,
4644 /// A wrapper around `parse_pat` with some special error handling for the
4645 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4646 /// to subpatterns within such).
4647 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4648 let pat = self.parse_pat(None)?;
4649 if self.token == token::Comma {
4650 // An unexpected comma after a top-level pattern is a clue that the
4651 // user (perhaps more accustomed to some other language) forgot the
4652 // parentheses in what should have been a tuple pattern; return a
4653 // suggestion-enhanced error here rather than choking on the comma
4655 let comma_span = self.span;
4657 if let Err(mut err) = self.parse_pat_list() {
4658 // We didn't expect this to work anyway; we just wanted
4659 // to advance to the end of the comma-sequence so we know
4660 // the span to suggest parenthesizing
4663 let seq_span = pat.span.to(self.prev_span);
4664 let mut err = self.struct_span_err(comma_span,
4665 "unexpected `,` in pattern");
4666 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4667 err.span_suggestion(
4669 "try adding parentheses to match on a tuple..",
4670 format!("({})", seq_snippet),
4671 Applicability::MachineApplicable
4674 "..or a vertical bar to match on multiple alternatives",
4675 format!("{}", seq_snippet.replace(",", " |")),
4676 Applicability::MachineApplicable
4684 /// Parses a pattern.
4685 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4686 self.parse_pat_with_range_pat(true, expected)
4689 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4691 fn parse_pat_with_range_pat(
4693 allow_range_pat: bool,
4694 expected: Option<&'static str>,
4695 ) -> PResult<'a, P<Pat>> {
4696 maybe_recover_from_interpolated_ty_qpath!(self, true);
4697 maybe_whole!(self, NtPat, |x| x);
4702 token::BinOp(token::And) | token::AndAnd => {
4703 // Parse &pat / &mut pat
4705 let mutbl = self.parse_mutability();
4706 if let token::Lifetime(ident) = self.token {
4707 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4709 err.span_label(self.span, "unexpected lifetime");
4712 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4713 pat = PatKind::Ref(subpat, mutbl);
4715 token::OpenDelim(token::Paren) => {
4716 // Parse (pat,pat,pat,...) as tuple pattern
4717 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4718 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4719 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4721 PatKind::Tuple(fields, ddpos)
4724 token::OpenDelim(token::Bracket) => {
4725 // Parse [pat,pat,...] as slice pattern
4727 let (before, slice, after) = self.parse_pat_vec_elements()?;
4728 self.expect(&token::CloseDelim(token::Bracket))?;
4729 pat = PatKind::Slice(before, slice, after);
4731 // At this point, token != &, &&, (, [
4732 _ => if self.eat_keyword(keywords::Underscore) {
4734 pat = PatKind::Wild;
4735 } else if self.eat_keyword(keywords::Mut) {
4736 // Parse mut ident @ pat / mut ref ident @ pat
4737 let mutref_span = self.prev_span.to(self.span);
4738 let binding_mode = if self.eat_keyword(keywords::Ref) {
4740 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4743 "try switching the order",
4745 Applicability::MachineApplicable
4747 BindingMode::ByRef(Mutability::Mutable)
4749 BindingMode::ByValue(Mutability::Mutable)
4751 pat = self.parse_pat_ident(binding_mode)?;
4752 } else if self.eat_keyword(keywords::Ref) {
4753 // Parse ref ident @ pat / ref mut ident @ pat
4754 let mutbl = self.parse_mutability();
4755 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4756 } else if self.eat_keyword(keywords::Box) {
4758 let subpat = self.parse_pat_with_range_pat(false, None)?;
4759 pat = PatKind::Box(subpat);
4760 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4761 self.parse_as_ident() {
4762 // Parse ident @ pat
4763 // This can give false positives and parse nullary enums,
4764 // they are dealt with later in resolve
4765 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4766 pat = self.parse_pat_ident(binding_mode)?;
4767 } else if self.token.is_path_start() {
4768 // Parse pattern starting with a path
4769 let (qself, path) = if self.eat_lt() {
4770 // Parse a qualified path
4771 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4774 // Parse an unqualified path
4775 (None, self.parse_path(PathStyle::Expr)?)
4778 token::Not if qself.is_none() => {
4779 // Parse macro invocation
4781 let (delim, tts) = self.expect_delimited_token_tree()?;
4782 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4783 pat = PatKind::Mac(mac);
4785 token::DotDotDot | token::DotDotEq | token::DotDot => {
4786 let end_kind = match self.token {
4787 token::DotDot => RangeEnd::Excluded,
4788 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4789 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4790 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4793 let op_span = self.span;
4795 let span = lo.to(self.prev_span);
4796 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4798 let end = self.parse_pat_range_end()?;
4799 let op = Spanned { span: op_span, node: end_kind };
4800 pat = PatKind::Range(begin, end, op);
4802 token::OpenDelim(token::Brace) => {
4803 if qself.is_some() {
4804 let msg = "unexpected `{` after qualified path";
4805 let mut err = self.fatal(msg);
4806 err.span_label(self.span, msg);
4809 // Parse struct pattern
4811 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4813 self.recover_stmt();
4817 pat = PatKind::Struct(path, fields, etc);
4819 token::OpenDelim(token::Paren) => {
4820 if qself.is_some() {
4821 let msg = "unexpected `(` after qualified path";
4822 let mut err = self.fatal(msg);
4823 err.span_label(self.span, msg);
4826 // Parse tuple struct or enum pattern
4827 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4828 pat = PatKind::TupleStruct(path, fields, ddpos)
4830 _ => pat = PatKind::Path(qself, path),
4833 // Try to parse everything else as literal with optional minus
4834 match self.parse_literal_maybe_minus() {
4836 let op_span = self.span;
4837 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4838 self.check(&token::DotDotDot) {
4839 let end_kind = if self.eat(&token::DotDotDot) {
4840 RangeEnd::Included(RangeSyntax::DotDotDot)
4841 } else if self.eat(&token::DotDotEq) {
4842 RangeEnd::Included(RangeSyntax::DotDotEq)
4843 } else if self.eat(&token::DotDot) {
4846 panic!("impossible case: we already matched \
4847 on a range-operator token")
4849 let end = self.parse_pat_range_end()?;
4850 let op = Spanned { span: op_span, node: end_kind };
4851 pat = PatKind::Range(begin, end, op);
4853 pat = PatKind::Lit(begin);
4857 self.cancel(&mut err);
4858 let expected = expected.unwrap_or("pattern");
4860 "expected {}, found {}",
4862 self.this_token_descr(),
4864 let mut err = self.fatal(&msg);
4865 err.span_label(self.span, format!("expected {}", expected));
4866 let sp = self.sess.source_map().start_point(self.span);
4867 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4868 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4876 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4877 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4879 if !allow_range_pat {
4882 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4884 PatKind::Range(..) => {
4885 let mut err = self.struct_span_err(
4887 "the range pattern here has ambiguous interpretation",
4889 err.span_suggestion(
4891 "add parentheses to clarify the precedence",
4892 format!("({})", pprust::pat_to_string(&pat)),
4893 // "ambiguous interpretation" implies that we have to be guessing
4894 Applicability::MaybeIncorrect
4905 /// Parses `ident` or `ident @ pat`.
4906 /// used by the copy foo and ref foo patterns to give a good
4907 /// error message when parsing mistakes like `ref foo(a, b)`.
4908 fn parse_pat_ident(&mut self,
4909 binding_mode: ast::BindingMode)
4910 -> PResult<'a, PatKind> {
4911 let ident = self.parse_ident()?;
4912 let sub = if self.eat(&token::At) {
4913 Some(self.parse_pat(Some("binding pattern"))?)
4918 // just to be friendly, if they write something like
4920 // we end up here with ( as the current token. This shortly
4921 // leads to a parse error. Note that if there is no explicit
4922 // binding mode then we do not end up here, because the lookahead
4923 // will direct us over to parse_enum_variant()
4924 if self.token == token::OpenDelim(token::Paren) {
4925 return Err(self.span_fatal(
4927 "expected identifier, found enum pattern"))
4930 Ok(PatKind::Ident(binding_mode, ident, sub))
4933 /// Parses a local variable declaration.
4934 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4935 let lo = self.prev_span;
4936 let pat = self.parse_top_level_pat()?;
4938 let (err, ty) = if self.eat(&token::Colon) {
4939 // Save the state of the parser before parsing type normally, in case there is a `:`
4940 // instead of an `=` typo.
4941 let parser_snapshot_before_type = self.clone();
4942 let colon_sp = self.prev_span;
4943 match self.parse_ty() {
4944 Ok(ty) => (None, Some(ty)),
4946 // Rewind to before attempting to parse the type and continue parsing
4947 let parser_snapshot_after_type = self.clone();
4948 mem::replace(self, parser_snapshot_before_type);
4950 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4951 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4952 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4958 let init = match (self.parse_initializer(err.is_some()), err) {
4959 (Ok(init), None) => { // init parsed, ty parsed
4962 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4963 // Could parse the type as if it were the initializer, it is likely there was a
4964 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4965 err.span_suggestion_short(
4967 "use `=` if you meant to assign",
4969 Applicability::MachineApplicable
4972 // As this was parsed successfully, continue as if the code has been fixed for the
4973 // rest of the file. It will still fail due to the emitted error, but we avoid
4977 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4979 // Couldn't parse the type nor the initializer, only raise the type error and
4980 // return to the parser state before parsing the type as the initializer.
4981 // let x: <parse_error>;
4982 mem::replace(self, snapshot);
4985 (Err(err), None) => { // init error, ty parsed
4986 // Couldn't parse the initializer and we're not attempting to recover a failed
4987 // parse of the type, return the error.
4991 let hi = if self.token == token::Semi {
5000 id: ast::DUMMY_NODE_ID,
5003 source: LocalSource::Normal,
5007 /// Parses a structure field.
5008 fn parse_name_and_ty(&mut self,
5011 attrs: Vec<Attribute>)
5012 -> PResult<'a, StructField> {
5013 let name = self.parse_ident()?;
5014 self.expect(&token::Colon)?;
5015 let ty = self.parse_ty()?;
5017 span: lo.to(self.prev_span),
5020 id: ast::DUMMY_NODE_ID,
5026 /// Emits an expected-item-after-attributes error.
5027 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
5028 let message = match attrs.last() {
5029 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
5030 _ => "expected item after attributes",
5033 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
5034 if attrs.last().unwrap().is_sugared_doc {
5035 err.span_label(self.prev_span, "this doc comment doesn't document anything");
5040 /// Parse a statement. This stops just before trailing semicolons on everything but items.
5041 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
5042 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
5043 Ok(self.parse_stmt_(true))
5046 // Eat tokens until we can be relatively sure we reached the end of the
5047 // statement. This is something of a best-effort heuristic.
5049 // We terminate when we find an unmatched `}` (without consuming it).
5050 fn recover_stmt(&mut self) {
5051 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
5054 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
5055 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
5056 // approximate - it can mean we break too early due to macros, but that
5057 // should only lead to sub-optimal recovery, not inaccurate parsing).
5059 // If `break_on_block` is `Break`, then we will stop consuming tokens
5060 // after finding (and consuming) a brace-delimited block.
5061 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
5062 let mut brace_depth = 0;
5063 let mut bracket_depth = 0;
5064 let mut in_block = false;
5065 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
5066 break_on_semi, break_on_block);
5068 debug!("recover_stmt_ loop {:?}", self.token);
5070 token::OpenDelim(token::DelimToken::Brace) => {
5073 if break_on_block == BlockMode::Break &&
5075 bracket_depth == 0 {
5079 token::OpenDelim(token::DelimToken::Bracket) => {
5083 token::CloseDelim(token::DelimToken::Brace) => {
5084 if brace_depth == 0 {
5085 debug!("recover_stmt_ return - close delim {:?}", self.token);
5090 if in_block && bracket_depth == 0 && brace_depth == 0 {
5091 debug!("recover_stmt_ return - block end {:?}", self.token);
5095 token::CloseDelim(token::DelimToken::Bracket) => {
5097 if bracket_depth < 0 {
5103 debug!("recover_stmt_ return - Eof");
5108 if break_on_semi == SemiColonMode::Break &&
5110 bracket_depth == 0 {
5111 debug!("recover_stmt_ return - Semi");
5116 if break_on_semi == SemiColonMode::Comma &&
5118 bracket_depth == 0 {
5119 debug!("recover_stmt_ return - Semi");
5132 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5133 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5135 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5140 fn is_async_block(&mut self) -> bool {
5141 self.token.is_keyword(keywords::Async) &&
5144 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5145 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5147 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5152 fn is_async_fn(&mut self) -> bool {
5153 self.token.is_keyword(keywords::Async) &&
5154 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5157 fn is_do_catch_block(&mut self) -> bool {
5158 self.token.is_keyword(keywords::Do) &&
5159 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5160 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5161 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5164 fn is_try_block(&mut self) -> bool {
5165 self.token.is_keyword(keywords::Try) &&
5166 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5167 self.span.rust_2018() &&
5168 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5169 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5172 fn is_union_item(&self) -> bool {
5173 self.token.is_keyword(keywords::Union) &&
5174 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5177 fn is_crate_vis(&self) -> bool {
5178 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5181 fn is_existential_type_decl(&self) -> bool {
5182 self.token.is_keyword(keywords::Existential) &&
5183 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5186 fn is_auto_trait_item(&mut self) -> bool {
5188 (self.token.is_keyword(keywords::Auto)
5189 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5190 || // unsafe auto trait
5191 (self.token.is_keyword(keywords::Unsafe) &&
5192 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5193 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5196 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5197 -> PResult<'a, Option<P<Item>>> {
5198 let token_lo = self.span;
5199 let (ident, def) = match self.token {
5200 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5202 let ident = self.parse_ident()?;
5203 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5204 match self.parse_token_tree() {
5205 TokenTree::Delimited(_, _, tts) => tts,
5206 _ => unreachable!(),
5208 } else if self.check(&token::OpenDelim(token::Paren)) {
5209 let args = self.parse_token_tree();
5210 let body = if self.check(&token::OpenDelim(token::Brace)) {
5211 self.parse_token_tree()
5216 TokenStream::new(vec![
5218 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5226 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5228 token::Ident(ident, _) if ident.name == "macro_rules" &&
5229 self.look_ahead(1, |t| *t == token::Not) => {
5230 let prev_span = self.prev_span;
5231 self.complain_if_pub_macro(&vis.node, prev_span);
5235 let ident = self.parse_ident()?;
5236 let (delim, tokens) = self.expect_delimited_token_tree()?;
5237 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5238 self.report_invalid_macro_expansion_item();
5241 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5243 _ => return Ok(None),
5246 let span = lo.to(self.prev_span);
5247 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5250 fn parse_stmt_without_recovery(&mut self,
5251 macro_legacy_warnings: bool)
5252 -> PResult<'a, Option<Stmt>> {
5253 maybe_whole!(self, NtStmt, |x| Some(x));
5255 let attrs = self.parse_outer_attributes()?;
5258 Ok(Some(if self.eat_keyword(keywords::Let) {
5260 id: ast::DUMMY_NODE_ID,
5261 node: StmtKind::Local(self.parse_local(attrs.into())?),
5262 span: lo.to(self.prev_span),
5264 } else if let Some(macro_def) = self.eat_macro_def(
5266 &source_map::respan(lo, VisibilityKind::Inherited),
5270 id: ast::DUMMY_NODE_ID,
5271 node: StmtKind::Item(macro_def),
5272 span: lo.to(self.prev_span),
5274 // Starts like a simple path, being careful to avoid contextual keywords
5275 // such as a union items, item with `crate` visibility or auto trait items.
5276 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5277 // like a path (1 token), but it fact not a path.
5278 // `union::b::c` - path, `union U { ... }` - not a path.
5279 // `crate::b::c` - path, `crate struct S;` - not a path.
5280 } else if self.token.is_path_start() &&
5281 !self.token.is_qpath_start() &&
5282 !self.is_union_item() &&
5283 !self.is_crate_vis() &&
5284 !self.is_existential_type_decl() &&
5285 !self.is_auto_trait_item() &&
5286 !self.is_async_fn() {
5287 let pth = self.parse_path(PathStyle::Expr)?;
5289 if !self.eat(&token::Not) {
5290 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5291 self.parse_struct_expr(lo, pth, ThinVec::new())?
5293 let hi = self.prev_span;
5294 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5297 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5298 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5299 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5302 return Ok(Some(Stmt {
5303 id: ast::DUMMY_NODE_ID,
5304 node: StmtKind::Expr(expr),
5305 span: lo.to(self.prev_span),
5309 // it's a macro invocation
5310 let id = match self.token {
5311 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5312 _ => self.parse_ident()?,
5315 // check that we're pointing at delimiters (need to check
5316 // again after the `if`, because of `parse_ident`
5317 // consuming more tokens).
5319 token::OpenDelim(_) => {}
5321 // we only expect an ident if we didn't parse one
5323 let ident_str = if id.name == keywords::Invalid.name() {
5328 let tok_str = self.this_token_descr();
5329 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5332 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5337 let (delim, tts) = self.expect_delimited_token_tree()?;
5338 let hi = self.prev_span;
5340 let style = if delim == MacDelimiter::Brace {
5341 MacStmtStyle::Braces
5343 MacStmtStyle::NoBraces
5346 if id.name == keywords::Invalid.name() {
5347 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5348 let node = if delim == MacDelimiter::Brace ||
5349 self.token == token::Semi || self.token == token::Eof {
5350 StmtKind::Mac(P((mac, style, attrs.into())))
5352 // We used to incorrectly stop parsing macro-expanded statements here.
5353 // If the next token will be an error anyway but could have parsed with the
5354 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5355 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5356 // These can continue an expression, so we can't stop parsing and warn.
5357 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5358 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5359 token::BinOp(token::And) | token::BinOp(token::Or) |
5360 token::AndAnd | token::OrOr |
5361 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5364 self.warn_missing_semicolon();
5365 StmtKind::Mac(P((mac, style, attrs.into())))
5367 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5368 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5369 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5370 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5374 id: ast::DUMMY_NODE_ID,
5379 // if it has a special ident, it's definitely an item
5381 // Require a semicolon or braces.
5382 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5383 self.report_invalid_macro_expansion_item();
5385 let span = lo.to(hi);
5387 id: ast::DUMMY_NODE_ID,
5389 node: StmtKind::Item({
5391 span, id /*id is good here*/,
5392 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5393 respan(lo, VisibilityKind::Inherited),
5399 // FIXME: Bad copy of attrs
5400 let old_directory_ownership =
5401 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5402 let item = self.parse_item_(attrs.clone(), false, true)?;
5403 self.directory.ownership = old_directory_ownership;
5407 id: ast::DUMMY_NODE_ID,
5408 span: lo.to(i.span),
5409 node: StmtKind::Item(i),
5412 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5413 if !attrs.is_empty() {
5414 if s.prev_token_kind == PrevTokenKind::DocComment {
5415 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5416 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5417 s.span_err(s.span, "expected statement after outer attribute");
5422 // Do not attempt to parse an expression if we're done here.
5423 if self.token == token::Semi {
5424 unused_attrs(&attrs, self);
5429 if self.token == token::CloseDelim(token::Brace) {
5430 unused_attrs(&attrs, self);
5434 // Remainder are line-expr stmts.
5435 let e = self.parse_expr_res(
5436 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5438 id: ast::DUMMY_NODE_ID,
5439 span: lo.to(e.span),
5440 node: StmtKind::Expr(e),
5447 /// Checks if this expression is a successfully parsed statement.
5448 fn expr_is_complete(&mut self, e: &Expr) -> bool {
5449 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5450 !classify::expr_requires_semi_to_be_stmt(e)
5453 /// Parses a block. No inner attributes are allowed.
5454 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5455 maybe_whole!(self, NtBlock, |x| x);
5459 if !self.eat(&token::OpenDelim(token::Brace)) {
5461 let tok = self.this_token_descr();
5462 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5463 let do_not_suggest_help =
5464 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5466 if self.token.is_ident_named("and") {
5467 e.span_suggestion_short(
5469 "use `&&` instead of `and` for the boolean operator",
5471 Applicability::MaybeIncorrect,
5474 if self.token.is_ident_named("or") {
5475 e.span_suggestion_short(
5477 "use `||` instead of `or` for the boolean operator",
5479 Applicability::MaybeIncorrect,
5483 // Check to see if the user has written something like
5488 // Which is valid in other languages, but not Rust.
5489 match self.parse_stmt_without_recovery(false) {
5491 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5492 || do_not_suggest_help {
5493 // if the next token is an open brace (e.g., `if a b {`), the place-
5494 // inside-a-block suggestion would be more likely wrong than right
5495 e.span_label(sp, "expected `{`");
5498 let mut stmt_span = stmt.span;
5499 // expand the span to include the semicolon, if it exists
5500 if self.eat(&token::Semi) {
5501 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5503 let sugg = pprust::to_string(|s| {
5504 use crate::print::pprust::{PrintState, INDENT_UNIT};
5505 s.ibox(INDENT_UNIT)?;
5507 s.print_stmt(&stmt)?;
5508 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5512 "try placing this code inside a block",
5514 // speculative, has been misleading in the past (closed Issue #46836)
5515 Applicability::MaybeIncorrect
5519 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5520 self.cancel(&mut e);
5524 e.span_label(sp, "expected `{`");
5528 self.parse_block_tail(lo, BlockCheckMode::Default)
5531 /// Parses a block. Inner attributes are allowed.
5532 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5533 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5536 self.expect(&token::OpenDelim(token::Brace))?;
5537 Ok((self.parse_inner_attributes()?,
5538 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5541 /// Parses the rest of a block expression or function body.
5542 /// Precondition: already parsed the '{'.
5543 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5544 let mut stmts = vec![];
5545 while !self.eat(&token::CloseDelim(token::Brace)) {
5546 let stmt = match self.parse_full_stmt(false) {
5549 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5551 id: ast::DUMMY_NODE_ID,
5552 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5558 if let Some(stmt) = stmt {
5560 } else if self.token == token::Eof {
5563 // Found only `;` or `}`.
5569 id: ast::DUMMY_NODE_ID,
5571 span: lo.to(self.prev_span),
5575 /// Parses a statement, including the trailing semicolon.
5576 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5577 // skip looking for a trailing semicolon when we have an interpolated statement
5578 maybe_whole!(self, NtStmt, |x| Some(x));
5580 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5582 None => return Ok(None),
5586 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5587 // expression without semicolon
5588 if classify::expr_requires_semi_to_be_stmt(expr) {
5589 // Just check for errors and recover; do not eat semicolon yet.
5591 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5594 self.recover_stmt();
5598 StmtKind::Local(..) => {
5599 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5600 if macro_legacy_warnings && self.token != token::Semi {
5601 self.warn_missing_semicolon();
5603 self.expect_one_of(&[], &[token::Semi])?;
5609 if self.eat(&token::Semi) {
5610 stmt = stmt.add_trailing_semicolon();
5613 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5617 fn warn_missing_semicolon(&self) {
5618 self.diagnostic().struct_span_warn(self.span, {
5619 &format!("expected `;`, found {}", self.this_token_descr())
5621 "This was erroneously allowed and will become a hard error in a future release"
5625 fn err_dotdotdot_syntax(&self, span: Span) {
5626 self.diagnostic().struct_span_err(span, {
5627 "unexpected token: `...`"
5629 span, "use `..` for an exclusive range", "..".to_owned(),
5630 Applicability::MaybeIncorrect
5632 span, "or `..=` for an inclusive range", "..=".to_owned(),
5633 Applicability::MaybeIncorrect
5637 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5640 /// BOUND = TY_BOUND | LT_BOUND
5641 /// LT_BOUND = LIFETIME (e.g., `'a`)
5642 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5643 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5645 fn parse_generic_bounds_common(&mut self,
5647 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5648 let mut bounds = Vec::new();
5649 let mut negative_bounds = Vec::new();
5650 let mut last_plus_span = None;
5651 let mut was_negative = false;
5653 // This needs to be synchronized with `Token::can_begin_bound`.
5654 let is_bound_start = self.check_path() || self.check_lifetime() ||
5655 self.check(&token::Not) || // used for error reporting only
5656 self.check(&token::Question) ||
5657 self.check_keyword(keywords::For) ||
5658 self.check(&token::OpenDelim(token::Paren));
5661 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5662 let inner_lo = self.span;
5663 let is_negative = self.eat(&token::Not);
5664 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5665 if self.token.is_lifetime() {
5666 if let Some(question_span) = question {
5667 self.span_err(question_span,
5668 "`?` may only modify trait bounds, not lifetime bounds");
5670 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5672 let inner_span = inner_lo.to(self.prev_span);
5673 self.expect(&token::CloseDelim(token::Paren))?;
5674 let mut err = self.struct_span_err(
5675 lo.to(self.prev_span),
5676 "parenthesized lifetime bounds are not supported"
5678 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5679 err.span_suggestion_short(
5680 lo.to(self.prev_span),
5681 "remove the parentheses",
5683 Applicability::MachineApplicable
5689 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5690 let path = self.parse_path(PathStyle::Type)?;
5692 self.expect(&token::CloseDelim(token::Paren))?;
5694 let poly_span = lo.to(self.prev_span);
5696 was_negative = true;
5697 if let Some(sp) = last_plus_span.or(colon_span) {
5698 negative_bounds.push(sp.to(poly_span));
5701 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5702 let modifier = if question.is_some() {
5703 TraitBoundModifier::Maybe
5705 TraitBoundModifier::None
5707 bounds.push(GenericBound::Trait(poly_trait, modifier));
5714 if !allow_plus || !self.eat_plus() {
5717 last_plus_span = Some(self.prev_span);
5721 if !negative_bounds.is_empty() || was_negative {
5722 let plural = negative_bounds.len() > 1;
5723 let last_span = negative_bounds.last().map(|sp| *sp);
5724 let mut err = self.struct_span_err(
5726 "negative trait bounds are not supported",
5728 if let Some(sp) = last_span {
5729 err.span_label(sp, "negative trait bounds are not supported");
5731 if let Some(bound_list) = colon_span {
5732 let bound_list = bound_list.to(self.prev_span);
5733 let mut new_bound_list = String::new();
5734 if !bounds.is_empty() {
5735 let mut snippets = bounds.iter().map(|bound| bound.span())
5736 .map(|span| self.sess.source_map().span_to_snippet(span));
5737 while let Some(Ok(snippet)) = snippets.next() {
5738 new_bound_list.push_str(" + ");
5739 new_bound_list.push_str(&snippet);
5741 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5743 err.span_suggestion_hidden(
5745 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5747 Applicability::MachineApplicable,
5756 crate fn parse_generic_bounds(&mut self,
5757 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5758 self.parse_generic_bounds_common(true, colon_span)
5761 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5764 /// BOUND = LT_BOUND (e.g., `'a`)
5766 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5767 let mut lifetimes = Vec::new();
5768 while self.check_lifetime() {
5769 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5771 if !self.eat_plus() {
5778 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5779 fn parse_ty_param(&mut self,
5780 preceding_attrs: Vec<Attribute>)
5781 -> PResult<'a, GenericParam> {
5782 let ident = self.parse_ident()?;
5784 // Parse optional colon and param bounds.
5785 let bounds = if self.eat(&token::Colon) {
5786 self.parse_generic_bounds(Some(self.prev_span))?
5791 let default = if self.eat(&token::Eq) {
5792 Some(self.parse_ty()?)
5799 id: ast::DUMMY_NODE_ID,
5800 attrs: preceding_attrs.into(),
5802 kind: GenericParamKind::Type {
5808 /// Parses the following grammar:
5810 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5811 fn parse_trait_item_assoc_ty(&mut self)
5812 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5813 let ident = self.parse_ident()?;
5814 let mut generics = self.parse_generics()?;
5816 // Parse optional colon and param bounds.
5817 let bounds = if self.eat(&token::Colon) {
5818 self.parse_generic_bounds(None)?
5822 generics.where_clause = self.parse_where_clause()?;
5824 let default = if self.eat(&token::Eq) {
5825 Some(self.parse_ty()?)
5829 self.expect(&token::Semi)?;
5831 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5834 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5835 self.expect_keyword(keywords::Const)?;
5836 let ident = self.parse_ident()?;
5837 self.expect(&token::Colon)?;
5838 let ty = self.parse_ty()?;
5842 id: ast::DUMMY_NODE_ID,
5843 attrs: preceding_attrs.into(),
5845 kind: GenericParamKind::Const {
5851 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5852 /// a trailing comma and erroneous trailing attributes.
5853 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5854 let mut params = Vec::new();
5856 let attrs = self.parse_outer_attributes()?;
5857 if self.check_lifetime() {
5858 let lifetime = self.expect_lifetime();
5859 // Parse lifetime parameter.
5860 let bounds = if self.eat(&token::Colon) {
5861 self.parse_lt_param_bounds()
5865 params.push(ast::GenericParam {
5866 ident: lifetime.ident,
5868 attrs: attrs.into(),
5870 kind: ast::GenericParamKind::Lifetime,
5872 } else if self.check_keyword(keywords::Const) {
5873 // Parse const parameter.
5874 params.push(self.parse_const_param(attrs)?);
5875 } else if self.check_ident() {
5876 // Parse type parameter.
5877 params.push(self.parse_ty_param(attrs)?);
5879 // Check for trailing attributes and stop parsing.
5880 if !attrs.is_empty() {
5881 if !params.is_empty() {
5882 self.struct_span_err(
5884 &format!("trailing attribute after generic parameter"),
5886 .span_label(attrs[0].span, "attributes must go before parameters")
5889 self.struct_span_err(
5891 &format!("attribute without generic parameters"),
5895 "attributes are only permitted when preceding parameters",
5903 if !self.eat(&token::Comma) {
5910 /// Parses a set of optional generic type parameter declarations. Where
5911 /// clauses are not parsed here, and must be added later via
5912 /// `parse_where_clause()`.
5914 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5915 /// | ( < lifetimes , typaramseq ( , )? > )
5916 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5917 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5918 maybe_whole!(self, NtGenerics, |x| x);
5920 let span_lo = self.span;
5922 let params = self.parse_generic_params()?;
5926 where_clause: WhereClause {
5927 id: ast::DUMMY_NODE_ID,
5928 predicates: Vec::new(),
5929 span: syntax_pos::DUMMY_SP,
5931 span: span_lo.to(self.prev_span),
5934 Ok(ast::Generics::default())
5938 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5939 /// For the purposes of understanding the parsing logic of generic arguments, this function
5940 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5941 /// had the correct amount of leading angle brackets.
5943 /// ```ignore (diagnostics)
5944 /// bar::<<<<T as Foo>::Output>();
5945 /// ^^ help: remove extra angle brackets
5947 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5951 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5952 // We need to detect whether there are extra leading left angle brackets and produce an
5953 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5954 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5955 // then there won't be matching `>` tokens to find.
5957 // To explain how this detection works, consider the following example:
5959 // ```ignore (diagnostics)
5960 // bar::<<<<T as Foo>::Output>();
5961 // ^^ help: remove extra angle brackets
5964 // Parsing of the left angle brackets starts in this function. We start by parsing the
5965 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5968 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5969 // *Unmatched count:* 1
5970 // *`parse_path_segment` calls deep:* 0
5972 // This has the effect of recursing as this function is called if a `<` character
5973 // is found within the expected generic arguments:
5975 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5976 // *Unmatched count:* 2
5977 // *`parse_path_segment` calls deep:* 1
5979 // Eventually we will have recursed until having consumed all of the `<` tokens and
5980 // this will be reflected in the count:
5982 // *Upcoming tokens:* `T as Foo>::Output>;`
5983 // *Unmatched count:* 4
5984 // `parse_path_segment` calls deep:* 3
5986 // The parser will continue until reaching the first `>` - this will decrement the
5987 // unmatched angle bracket count and return to the parent invocation of this function
5988 // having succeeded in parsing:
5990 // *Upcoming tokens:* `::Output>;`
5991 // *Unmatched count:* 3
5992 // *`parse_path_segment` calls deep:* 2
5994 // This will continue until the next `>` character which will also return successfully
5995 // to the parent invocation of this function and decrement the count:
5997 // *Upcoming tokens:* `;`
5998 // *Unmatched count:* 2
5999 // *`parse_path_segment` calls deep:* 1
6001 // At this point, this function will expect to find another matching `>` character but
6002 // won't be able to and will return an error. This will continue all the way up the
6003 // call stack until the first invocation:
6005 // *Upcoming tokens:* `;`
6006 // *Unmatched count:* 2
6007 // *`parse_path_segment` calls deep:* 0
6009 // In doing this, we have managed to work out how many unmatched leading left angle
6010 // brackets there are, but we cannot recover as the unmatched angle brackets have
6011 // already been consumed. To remedy this, we keep a snapshot of the parser state
6012 // before we do the above. We can then inspect whether we ended up with a parsing error
6013 // and unmatched left angle brackets and if so, restore the parser state before we
6014 // consumed any `<` characters to emit an error and consume the erroneous tokens to
6015 // recover by attempting to parse again.
6017 // In practice, the recursion of this function is indirect and there will be other
6018 // locations that consume some `<` characters - as long as we update the count when
6019 // this happens, it isn't an issue.
6021 let is_first_invocation = style == PathStyle::Expr;
6022 // Take a snapshot before attempting to parse - we can restore this later.
6023 let snapshot = if is_first_invocation {
6029 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
6030 match self.parse_generic_args() {
6031 Ok(value) => Ok(value),
6032 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
6033 // Cancel error from being unable to find `>`. We know the error
6034 // must have been this due to a non-zero unmatched angle bracket
6038 // Swap `self` with our backup of the parser state before attempting to parse
6039 // generic arguments.
6040 let snapshot = mem::replace(self, snapshot.unwrap());
6043 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
6044 snapshot.count={:?}",
6045 snapshot.unmatched_angle_bracket_count,
6048 // Eat the unmatched angle brackets.
6049 for _ in 0..snapshot.unmatched_angle_bracket_count {
6053 // Make a span over ${unmatched angle bracket count} characters.
6054 let span = lo.with_hi(
6055 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
6057 let plural = snapshot.unmatched_angle_bracket_count > 1;
6062 "unmatched angle bracket{}",
6063 if plural { "s" } else { "" }
6069 "remove extra angle bracket{}",
6070 if plural { "s" } else { "" }
6073 Applicability::MachineApplicable,
6077 // Try again without unmatched angle bracket characters.
6078 self.parse_generic_args()
6084 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
6085 /// possibly including trailing comma.
6086 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6087 let mut args = Vec::new();
6088 let mut bindings = Vec::new();
6089 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
6090 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
6092 let args_lo = self.span;
6095 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6096 // Parse lifetime argument.
6097 args.push(GenericArg::Lifetime(self.expect_lifetime()));
6098 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6099 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
6100 // Parse associated type binding.
6102 let ident = self.parse_ident()?;
6104 let ty = self.parse_ty()?;
6105 let span = lo.to(self.prev_span);
6106 bindings.push(TypeBinding {
6107 id: ast::DUMMY_NODE_ID,
6112 assoc_ty_bindings.push(span);
6113 } else if self.check_const_arg() {
6114 // Parse const argument.
6115 let expr = if let token::OpenDelim(token::Brace) = self.token {
6116 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
6117 } else if self.token.is_ident() {
6118 // FIXME(const_generics): to distinguish between idents for types and consts,
6119 // we should introduce a GenericArg::Ident in the AST and distinguish when
6120 // lowering to the HIR. For now, idents for const args are not permitted.
6122 self.fatal("identifiers may currently not be used for const generics")
6125 self.parse_literal_maybe_minus()?
6127 let value = AnonConst {
6128 id: ast::DUMMY_NODE_ID,
6131 args.push(GenericArg::Const(value));
6132 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6133 } else if self.check_type() {
6134 // Parse type argument.
6135 args.push(GenericArg::Type(self.parse_ty()?));
6136 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6141 if !self.eat(&token::Comma) {
6146 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6147 // preserve ordering of generic parameters with respect to associated type binding, so we
6148 // lose that information after parsing.
6149 if misplaced_assoc_ty_bindings.len() > 0 {
6150 let mut err = self.struct_span_err(
6151 args_lo.to(self.prev_span),
6152 "associated type bindings must be declared after generic parameters",
6154 for span in misplaced_assoc_ty_bindings {
6157 "this associated type binding should be moved after the generic parameters",
6163 Ok((args, bindings))
6166 /// Parses an optional where-clause and places it in `generics`.
6168 /// ```ignore (only-for-syntax-highlight)
6169 /// where T : Trait<U, V> + 'b, 'a : 'b
6171 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6172 maybe_whole!(self, NtWhereClause, |x| x);
6174 let mut where_clause = WhereClause {
6175 id: ast::DUMMY_NODE_ID,
6176 predicates: Vec::new(),
6177 span: syntax_pos::DUMMY_SP,
6180 if !self.eat_keyword(keywords::Where) {
6181 return Ok(where_clause);
6183 let lo = self.prev_span;
6185 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6186 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6187 // change we parse those generics now, but report an error.
6188 if self.choose_generics_over_qpath() {
6189 let generics = self.parse_generics()?;
6190 self.struct_span_err(
6192 "generic parameters on `where` clauses are reserved for future use",
6194 .span_label(generics.span, "currently unsupported")
6200 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6201 let lifetime = self.expect_lifetime();
6202 // Bounds starting with a colon are mandatory, but possibly empty.
6203 self.expect(&token::Colon)?;
6204 let bounds = self.parse_lt_param_bounds();
6205 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6206 ast::WhereRegionPredicate {
6207 span: lo.to(self.prev_span),
6212 } else if self.check_type() {
6213 // Parse optional `for<'a, 'b>`.
6214 // This `for` is parsed greedily and applies to the whole predicate,
6215 // the bounded type can have its own `for` applying only to it.
6216 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6217 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6218 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6219 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6221 // Parse type with mandatory colon and (possibly empty) bounds,
6222 // or with mandatory equality sign and the second type.
6223 let ty = self.parse_ty()?;
6224 if self.eat(&token::Colon) {
6225 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6226 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6227 ast::WhereBoundPredicate {
6228 span: lo.to(self.prev_span),
6229 bound_generic_params: lifetime_defs,
6234 // FIXME: Decide what should be used here, `=` or `==`.
6235 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6236 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6237 let rhs_ty = self.parse_ty()?;
6238 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6239 ast::WhereEqPredicate {
6240 span: lo.to(self.prev_span),
6243 id: ast::DUMMY_NODE_ID,
6247 return self.unexpected();
6253 if !self.eat(&token::Comma) {
6258 where_clause.span = lo.to(self.prev_span);
6262 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6263 -> PResult<'a, (Vec<Arg> , bool)> {
6264 self.expect(&token::OpenDelim(token::Paren))?;
6267 let mut c_variadic = false;
6268 let (args, recovered): (Vec<Option<Arg>>, bool) =
6269 self.parse_seq_to_before_end(
6270 &token::CloseDelim(token::Paren),
6271 SeqSep::trailing_allowed(token::Comma),
6273 // If the argument is a C-variadic argument we should not
6274 // enforce named arguments.
6275 let enforce_named_args = if p.token == token::DotDotDot {
6280 match p.parse_arg_general(enforce_named_args, false,
6283 if let TyKind::CVarArgs = arg.ty.node {
6285 if p.token != token::CloseDelim(token::Paren) {
6288 "`...` must be the last argument of a C-variadic function");
6299 let lo = p.prev_span;
6300 // Skip every token until next possible arg or end.
6301 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6302 // Create a placeholder argument for proper arg count (issue #34264).
6303 let span = lo.to(p.prev_span);
6304 Ok(Some(dummy_arg(span)))
6311 self.eat(&token::CloseDelim(token::Paren));
6314 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6316 if c_variadic && args.is_empty() {
6318 "C-variadic function must be declared with at least one named argument");
6321 Ok((args, c_variadic))
6324 /// Parses the argument list and result type of a function declaration.
6325 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6327 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6328 let ret_ty = self.parse_ret_ty(true)?;
6337 /// Returns the parsed optional self argument and whether a self shortcut was used.
6338 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6339 let expect_ident = |this: &mut Self| match this.token {
6340 // Preserve hygienic context.
6341 token::Ident(ident, _) =>
6342 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6345 let isolated_self = |this: &mut Self, n| {
6346 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6347 this.look_ahead(n + 1, |t| t != &token::ModSep)
6350 // Parse optional self parameter of a method.
6351 // Only a limited set of initial token sequences is considered self parameters, anything
6352 // else is parsed as a normal function parameter list, so some lookahead is required.
6353 let eself_lo = self.span;
6354 let (eself, eself_ident, eself_hi) = match self.token {
6355 token::BinOp(token::And) => {
6361 (if isolated_self(self, 1) {
6363 SelfKind::Region(None, Mutability::Immutable)
6364 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6365 isolated_self(self, 2) {
6368 SelfKind::Region(None, Mutability::Mutable)
6369 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6370 isolated_self(self, 2) {
6372 let lt = self.expect_lifetime();
6373 SelfKind::Region(Some(lt), Mutability::Immutable)
6374 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6375 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6376 isolated_self(self, 3) {
6378 let lt = self.expect_lifetime();
6380 SelfKind::Region(Some(lt), Mutability::Mutable)
6383 }, expect_ident(self), self.prev_span)
6385 token::BinOp(token::Star) => {
6390 // Emit special error for `self` cases.
6391 let msg = "cannot pass `self` by raw pointer";
6392 (if isolated_self(self, 1) {
6394 self.struct_span_err(self.span, msg)
6395 .span_label(self.span, msg)
6397 SelfKind::Value(Mutability::Immutable)
6398 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6399 isolated_self(self, 2) {
6402 self.struct_span_err(self.span, msg)
6403 .span_label(self.span, msg)
6405 SelfKind::Value(Mutability::Immutable)
6408 }, expect_ident(self), self.prev_span)
6410 token::Ident(..) => {
6411 if isolated_self(self, 0) {
6414 let eself_ident = expect_ident(self);
6415 let eself_hi = self.prev_span;
6416 (if self.eat(&token::Colon) {
6417 let ty = self.parse_ty()?;
6418 SelfKind::Explicit(ty, Mutability::Immutable)
6420 SelfKind::Value(Mutability::Immutable)
6421 }, eself_ident, eself_hi)
6422 } else if self.token.is_keyword(keywords::Mut) &&
6423 isolated_self(self, 1) {
6427 let eself_ident = expect_ident(self);
6428 let eself_hi = self.prev_span;
6429 (if self.eat(&token::Colon) {
6430 let ty = self.parse_ty()?;
6431 SelfKind::Explicit(ty, Mutability::Mutable)
6433 SelfKind::Value(Mutability::Mutable)
6434 }, eself_ident, eself_hi)
6439 _ => return Ok(None),
6442 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6443 Ok(Some(Arg::from_self(eself, eself_ident)))
6446 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6447 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6448 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6450 self.expect(&token::OpenDelim(token::Paren))?;
6452 // Parse optional self argument
6453 let self_arg = self.parse_self_arg()?;
6455 // Parse the rest of the function parameter list.
6456 let sep = SeqSep::trailing_allowed(token::Comma);
6457 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6458 if self.check(&token::CloseDelim(token::Paren)) {
6459 (vec![self_arg], false)
6460 } else if self.eat(&token::Comma) {
6461 let mut fn_inputs = vec![self_arg];
6462 let (mut input, recovered) = self.parse_seq_to_before_end(
6463 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6464 fn_inputs.append(&mut input);
6465 (fn_inputs, recovered)
6467 match self.expect_one_of(&[], &[]) {
6468 Err(err) => return Err(err),
6469 Ok(recovered) => (vec![self_arg], recovered),
6473 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6477 // Parse closing paren and return type.
6478 self.expect(&token::CloseDelim(token::Paren))?;
6482 output: self.parse_ret_ty(true)?,
6487 /// Parses the `|arg, arg|` header of a closure.
6488 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6489 let inputs_captures = {
6490 if self.eat(&token::OrOr) {
6493 self.expect(&token::BinOp(token::Or))?;
6494 let args = self.parse_seq_to_before_tokens(
6495 &[&token::BinOp(token::Or), &token::OrOr],
6496 SeqSep::trailing_allowed(token::Comma),
6497 TokenExpectType::NoExpect,
6498 |p| p.parse_fn_block_arg()
6504 let output = self.parse_ret_ty(true)?;
6507 inputs: inputs_captures,
6513 /// Parses the name and optional generic types of a function header.
6514 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6515 let id = self.parse_ident()?;
6516 let generics = self.parse_generics()?;
6520 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6521 attrs: Vec<Attribute>) -> P<Item> {
6525 id: ast::DUMMY_NODE_ID,
6533 /// Parses an item-position function declaration.
6534 fn parse_item_fn(&mut self,
6536 mut asyncness: Spanned<IsAsync>,
6537 constness: Spanned<Constness>,
6539 -> PResult<'a, ItemInfo> {
6540 let (ident, mut generics) = self.parse_fn_header()?;
6541 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6542 let mut decl = self.parse_fn_decl(allow_c_variadic)?;
6543 generics.where_clause = self.parse_where_clause()?;
6544 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6545 self.construct_async_arguments(&mut asyncness, &mut decl);
6546 let header = FnHeader { unsafety, asyncness, constness, abi };
6547 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6550 /// Returns `true` if we are looking at `const ID`
6551 /// (returns `false` for things like `const fn`, etc.).
6552 fn is_const_item(&mut self) -> bool {
6553 self.token.is_keyword(keywords::Const) &&
6554 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6555 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6558 /// Parses all the "front matter" for a `fn` declaration, up to
6559 /// and including the `fn` keyword:
6563 /// - `const unsafe fn`
6566 fn parse_fn_front_matter(&mut self)
6574 let is_const_fn = self.eat_keyword(keywords::Const);
6575 let const_span = self.prev_span;
6576 let unsafety = self.parse_unsafety();
6577 let asyncness = self.parse_asyncness();
6578 let asyncness = respan(self.prev_span, asyncness);
6579 let (constness, unsafety, abi) = if is_const_fn {
6580 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6582 let abi = if self.eat_keyword(keywords::Extern) {
6583 self.parse_opt_abi()?.unwrap_or(Abi::C)
6587 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6589 if !self.eat_keyword(keywords::Fn) {
6590 // It is possible for `expect_one_of` to recover given the contents of
6591 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6592 // account for this.
6593 if !self.expect_one_of(&[], &[])? { unreachable!() }
6595 Ok((constness, unsafety, asyncness, abi))
6598 /// Parses an impl item.
6599 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6600 maybe_whole!(self, NtImplItem, |x| x);
6601 let attrs = self.parse_outer_attributes()?;
6602 let mut unclosed_delims = vec![];
6603 let (mut item, tokens) = self.collect_tokens(|this| {
6604 let item = this.parse_impl_item_(at_end, attrs);
6605 unclosed_delims.append(&mut this.unclosed_delims);
6608 self.unclosed_delims.append(&mut unclosed_delims);
6610 // See `parse_item` for why this clause is here.
6611 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6612 item.tokens = Some(tokens);
6617 fn parse_impl_item_(&mut self,
6619 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6621 let vis = self.parse_visibility(false)?;
6622 let defaultness = self.parse_defaultness();
6623 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6624 let (name, alias, generics) = type_?;
6625 let kind = match alias {
6626 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6627 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6629 (name, kind, generics)
6630 } else if self.is_const_item() {
6631 // This parses the grammar:
6632 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6633 self.expect_keyword(keywords::Const)?;
6634 let name = self.parse_ident()?;
6635 self.expect(&token::Colon)?;
6636 let typ = self.parse_ty()?;
6637 self.expect(&token::Eq)?;
6638 let expr = self.parse_expr()?;
6639 self.expect(&token::Semi)?;
6640 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6642 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6643 attrs.extend(inner_attrs);
6644 (name, node, generics)
6648 id: ast::DUMMY_NODE_ID,
6649 span: lo.to(self.prev_span),
6660 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6662 VisibilityKind::Inherited => {}
6664 let is_macro_rules: bool = match self.token {
6665 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6668 let mut err = if is_macro_rules {
6669 let mut err = self.diagnostic()
6670 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6671 err.span_suggestion(
6673 "try exporting the macro",
6674 "#[macro_export]".to_owned(),
6675 Applicability::MaybeIncorrect // speculative
6679 let mut err = self.diagnostic()
6680 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6681 err.help("try adjusting the macro to put `pub` inside the invocation");
6689 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6690 -> DiagnosticBuilder<'a>
6692 let expected_kinds = if item_type == "extern" {
6693 "missing `fn`, `type`, or `static`"
6695 "missing `fn`, `type`, or `const`"
6698 // Given this code `path(`, it seems like this is not
6699 // setting the visibility of a macro invocation, but rather
6700 // a mistyped method declaration.
6701 // Create a diagnostic pointing out that `fn` is missing.
6703 // x | pub path(&self) {
6704 // | ^ missing `fn`, `type`, or `const`
6706 // ^^ `sp` below will point to this
6707 let sp = prev_span.between(self.prev_span);
6708 let mut err = self.diagnostic().struct_span_err(
6710 &format!("{} for {}-item declaration",
6711 expected_kinds, item_type));
6712 err.span_label(sp, expected_kinds);
6716 /// Parse a method or a macro invocation in a trait impl.
6717 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6718 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6719 ast::ImplItemKind)> {
6720 // code copied from parse_macro_use_or_failure... abstraction!
6721 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6723 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6724 ast::ImplItemKind::Macro(mac)))
6726 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6727 let ident = self.parse_ident()?;
6728 let mut generics = self.parse_generics()?;
6729 let mut decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6730 generics.where_clause = self.parse_where_clause()?;
6731 self.construct_async_arguments(&mut asyncness, &mut decl);
6733 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6734 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6735 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6736 ast::MethodSig { header, decl },
6742 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6743 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6744 let ident = self.parse_ident()?;
6745 let mut tps = self.parse_generics()?;
6747 // Parse optional colon and supertrait bounds.
6748 let bounds = if self.eat(&token::Colon) {
6749 self.parse_generic_bounds(Some(self.prev_span))?
6754 if self.eat(&token::Eq) {
6755 // it's a trait alias
6756 let bounds = self.parse_generic_bounds(None)?;
6757 tps.where_clause = self.parse_where_clause()?;
6758 self.expect(&token::Semi)?;
6759 if is_auto == IsAuto::Yes {
6760 let msg = "trait aliases cannot be `auto`";
6761 self.struct_span_err(self.prev_span, msg)
6762 .span_label(self.prev_span, msg)
6765 if unsafety != Unsafety::Normal {
6766 let msg = "trait aliases cannot be `unsafe`";
6767 self.struct_span_err(self.prev_span, msg)
6768 .span_label(self.prev_span, msg)
6771 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6773 // it's a normal trait
6774 tps.where_clause = self.parse_where_clause()?;
6775 self.expect(&token::OpenDelim(token::Brace))?;
6776 let mut trait_items = vec![];
6777 while !self.eat(&token::CloseDelim(token::Brace)) {
6778 if let token::DocComment(_) = self.token {
6779 if self.look_ahead(1,
6780 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6781 let mut err = self.diagnostic().struct_span_err_with_code(
6783 "found a documentation comment that doesn't document anything",
6784 DiagnosticId::Error("E0584".into()),
6786 err.help("doc comments must come before what they document, maybe a \
6787 comment was intended with `//`?",
6794 let mut at_end = false;
6795 match self.parse_trait_item(&mut at_end) {
6796 Ok(item) => trait_items.push(item),
6800 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6805 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6809 fn choose_generics_over_qpath(&self) -> bool {
6810 // There's an ambiguity between generic parameters and qualified paths in impls.
6811 // If we see `<` it may start both, so we have to inspect some following tokens.
6812 // The following combinations can only start generics,
6813 // but not qualified paths (with one exception):
6814 // `<` `>` - empty generic parameters
6815 // `<` `#` - generic parameters with attributes
6816 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6817 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6818 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6819 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6820 // `<` const - generic const parameter
6821 // The only truly ambiguous case is
6822 // `<` IDENT `>` `::` IDENT ...
6823 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6824 // because this is what almost always expected in practice, qualified paths in impls
6825 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6826 self.token == token::Lt &&
6827 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6828 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6829 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6830 t == &token::Colon || t == &token::Eq) ||
6831 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6834 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6835 self.expect(&token::OpenDelim(token::Brace))?;
6836 let attrs = self.parse_inner_attributes()?;
6838 let mut impl_items = Vec::new();
6839 while !self.eat(&token::CloseDelim(token::Brace)) {
6840 let mut at_end = false;
6841 match self.parse_impl_item(&mut at_end) {
6842 Ok(impl_item) => impl_items.push(impl_item),
6846 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6851 Ok((impl_items, attrs))
6854 /// Parses an implementation item, `impl` keyword is already parsed.
6856 /// impl<'a, T> TYPE { /* impl items */ }
6857 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6858 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6860 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6861 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6862 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6863 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6864 -> PResult<'a, ItemInfo> {
6865 // First, parse generic parameters if necessary.
6866 let mut generics = if self.choose_generics_over_qpath() {
6867 self.parse_generics()?
6869 ast::Generics::default()
6872 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6873 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6875 ast::ImplPolarity::Negative
6877 ast::ImplPolarity::Positive
6880 // Parse both types and traits as a type, then reinterpret if necessary.
6881 let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6882 let ty_first = if self.token.is_keyword(keywords::For) &&
6883 self.look_ahead(1, |t| t != &token::Lt) {
6884 let span = self.prev_span.between(self.span);
6885 self.struct_span_err(span, "missing trait in a trait impl").emit();
6886 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6891 // If `for` is missing we try to recover.
6892 let has_for = self.eat_keyword(keywords::For);
6893 let missing_for_span = self.prev_span.between(self.span);
6895 let ty_second = if self.token == token::DotDot {
6896 // We need to report this error after `cfg` expansion for compatibility reasons
6897 self.bump(); // `..`, do not add it to expected tokens
6898 Some(DummyResult::raw_ty(self.prev_span, true))
6899 } else if has_for || self.token.can_begin_type() {
6900 Some(self.parse_ty()?)
6905 generics.where_clause = self.parse_where_clause()?;
6907 let (impl_items, attrs) = self.parse_impl_body()?;
6909 let item_kind = match ty_second {
6910 Some(ty_second) => {
6911 // impl Trait for Type
6913 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6914 .span_suggestion_short(
6917 " for ".to_string(),
6918 Applicability::MachineApplicable,
6922 let ty_first = ty_first.into_inner();
6923 let path = match ty_first.node {
6924 // This notably includes paths passed through `ty` macro fragments (#46438).
6925 TyKind::Path(None, path) => path,
6927 self.span_err(ty_first.span, "expected a trait, found type");
6928 err_path(ty_first.span)
6931 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6933 ItemKind::Impl(unsafety, polarity, defaultness,
6934 generics, Some(trait_ref), ty_second, impl_items)
6938 ItemKind::Impl(unsafety, polarity, defaultness,
6939 generics, None, ty_first, impl_items)
6943 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6946 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6947 if self.eat_keyword(keywords::For) {
6949 let params = self.parse_generic_params()?;
6951 // We rely on AST validation to rule out invalid cases: There must not be type
6952 // parameters, and the lifetime parameters must not have bounds.
6959 /// Parses `struct Foo { ... }`.
6960 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6961 let class_name = self.parse_ident()?;
6963 let mut generics = self.parse_generics()?;
6965 // There is a special case worth noting here, as reported in issue #17904.
6966 // If we are parsing a tuple struct it is the case that the where clause
6967 // should follow the field list. Like so:
6969 // struct Foo<T>(T) where T: Copy;
6971 // If we are parsing a normal record-style struct it is the case
6972 // that the where clause comes before the body, and after the generics.
6973 // So if we look ahead and see a brace or a where-clause we begin
6974 // parsing a record style struct.
6976 // Otherwise if we look ahead and see a paren we parse a tuple-style
6979 let vdata = if self.token.is_keyword(keywords::Where) {
6980 generics.where_clause = self.parse_where_clause()?;
6981 if self.eat(&token::Semi) {
6982 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6983 VariantData::Unit(ast::DUMMY_NODE_ID)
6985 // If we see: `struct Foo<T> where T: Copy { ... }`
6986 let (fields, recovered) = self.parse_record_struct_body()?;
6987 VariantData::Struct(fields, recovered)
6989 // No `where` so: `struct Foo<T>;`
6990 } else if self.eat(&token::Semi) {
6991 VariantData::Unit(ast::DUMMY_NODE_ID)
6992 // Record-style struct definition
6993 } else if self.token == token::OpenDelim(token::Brace) {
6994 let (fields, recovered) = self.parse_record_struct_body()?;
6995 VariantData::Struct(fields, recovered)
6996 // Tuple-style struct definition with optional where-clause.
6997 } else if self.token == token::OpenDelim(token::Paren) {
6998 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6999 generics.where_clause = self.parse_where_clause()?;
7000 self.expect(&token::Semi)?;
7003 let token_str = self.this_token_descr();
7004 let mut err = self.fatal(&format!(
7005 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
7008 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
7012 Ok((class_name, ItemKind::Struct(vdata, generics), None))
7015 /// Parses `union Foo { ... }`.
7016 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
7017 let class_name = self.parse_ident()?;
7019 let mut generics = self.parse_generics()?;
7021 let vdata = if self.token.is_keyword(keywords::Where) {
7022 generics.where_clause = self.parse_where_clause()?;
7023 let (fields, recovered) = self.parse_record_struct_body()?;
7024 VariantData::Struct(fields, recovered)
7025 } else if self.token == token::OpenDelim(token::Brace) {
7026 let (fields, recovered) = self.parse_record_struct_body()?;
7027 VariantData::Struct(fields, recovered)
7029 let token_str = self.this_token_descr();
7030 let mut err = self.fatal(&format!(
7031 "expected `where` or `{{` after union name, found {}", token_str));
7032 err.span_label(self.span, "expected `where` or `{` after union name");
7036 Ok((class_name, ItemKind::Union(vdata, generics), None))
7039 fn consume_block(&mut self, delim: token::DelimToken) {
7040 let mut brace_depth = 0;
7042 if self.eat(&token::OpenDelim(delim)) {
7044 } else if self.eat(&token::CloseDelim(delim)) {
7045 if brace_depth == 0 {
7051 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
7059 fn parse_record_struct_body(
7061 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
7062 let mut fields = Vec::new();
7063 let mut recovered = false;
7064 if self.eat(&token::OpenDelim(token::Brace)) {
7065 while self.token != token::CloseDelim(token::Brace) {
7066 let field = self.parse_struct_decl_field().map_err(|e| {
7067 self.recover_stmt();
7072 Ok(field) => fields.push(field),
7078 self.eat(&token::CloseDelim(token::Brace));
7080 let token_str = self.this_token_descr();
7081 let mut err = self.fatal(&format!(
7082 "expected `where`, or `{{` after struct name, found {}", token_str));
7083 err.span_label(self.span, "expected `where`, or `{` after struct name");
7087 Ok((fields, recovered))
7090 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
7091 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
7092 // Unit like structs are handled in parse_item_struct function
7093 let fields = self.parse_unspanned_seq(
7094 &token::OpenDelim(token::Paren),
7095 &token::CloseDelim(token::Paren),
7096 SeqSep::trailing_allowed(token::Comma),
7098 let attrs = p.parse_outer_attributes()?;
7100 let vis = p.parse_visibility(true)?;
7101 let ty = p.parse_ty()?;
7103 span: lo.to(ty.span),
7106 id: ast::DUMMY_NODE_ID,
7115 /// Parses a structure field declaration.
7116 fn parse_single_struct_field(&mut self,
7119 attrs: Vec<Attribute> )
7120 -> PResult<'a, StructField> {
7121 let mut seen_comma: bool = false;
7122 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
7123 if self.token == token::Comma {
7130 token::CloseDelim(token::Brace) => {}
7131 token::DocComment(_) => {
7132 let previous_span = self.prev_span;
7133 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
7134 self.bump(); // consume the doc comment
7135 let comma_after_doc_seen = self.eat(&token::Comma);
7136 // `seen_comma` is always false, because we are inside doc block
7137 // condition is here to make code more readable
7138 if seen_comma == false && comma_after_doc_seen == true {
7141 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7144 if seen_comma == false {
7145 let sp = self.sess.source_map().next_point(previous_span);
7146 err.span_suggestion(
7148 "missing comma here",
7150 Applicability::MachineApplicable
7157 let sp = self.sess.source_map().next_point(self.prev_span);
7158 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7159 self.this_token_descr()));
7160 if self.token.is_ident() {
7161 // This is likely another field; emit the diagnostic and keep going
7162 err.span_suggestion(
7164 "try adding a comma",
7166 Applicability::MachineApplicable,
7177 /// Parses an element of a struct declaration.
7178 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7179 let attrs = self.parse_outer_attributes()?;
7181 let vis = self.parse_visibility(false)?;
7182 self.parse_single_struct_field(lo, vis, attrs)
7185 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7186 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7187 /// If the following element can't be a tuple (i.e., it's a function definition), then
7188 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7189 /// so emit a proper diagnostic.
7190 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7191 maybe_whole!(self, NtVis, |x| x);
7193 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7194 if self.is_crate_vis() {
7195 self.bump(); // `crate`
7196 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7199 if !self.eat_keyword(keywords::Pub) {
7200 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7201 // keyword to grab a span from for inherited visibility; an empty span at the
7202 // beginning of the current token would seem to be the "Schelling span".
7203 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7205 let lo = self.prev_span;
7207 if self.check(&token::OpenDelim(token::Paren)) {
7208 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7209 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7210 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7211 // by the following tokens.
7212 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) &&
7213 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
7217 self.bump(); // `crate`
7218 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7220 lo.to(self.prev_span),
7221 VisibilityKind::Crate(CrateSugar::PubCrate),
7224 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7227 self.bump(); // `in`
7228 let path = self.parse_path(PathStyle::Mod)?; // `path`
7229 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7230 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7232 id: ast::DUMMY_NODE_ID,
7235 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7236 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7237 t.is_keyword(keywords::SelfLower))
7239 // `pub(self)` or `pub(super)`
7241 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7242 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7243 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7245 id: ast::DUMMY_NODE_ID,
7248 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7249 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7251 let msg = "incorrect visibility restriction";
7252 let suggestion = r##"some possible visibility restrictions are:
7253 `pub(crate)`: visible only on the current crate
7254 `pub(super)`: visible only in the current module's parent
7255 `pub(in path::to::module)`: visible only on the specified path"##;
7256 let path = self.parse_path(PathStyle::Mod)?;
7258 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7259 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7260 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7261 err.help(suggestion);
7262 err.span_suggestion(
7263 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7265 err.emit(); // emit diagnostic, but continue with public visibility
7269 Ok(respan(lo, VisibilityKind::Public))
7272 /// Parses defaultness (i.e., `default` or nothing).
7273 fn parse_defaultness(&mut self) -> Defaultness {
7274 // `pub` is included for better error messages
7275 if self.check_keyword(keywords::Default) &&
7276 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7277 t.is_keyword(keywords::Const) ||
7278 t.is_keyword(keywords::Fn) ||
7279 t.is_keyword(keywords::Unsafe) ||
7280 t.is_keyword(keywords::Extern) ||
7281 t.is_keyword(keywords::Type) ||
7282 t.is_keyword(keywords::Pub)) {
7283 self.bump(); // `default`
7284 Defaultness::Default
7290 /// Given a termination token, parses all of the items in a module.
7291 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7292 let mut items = vec![];
7293 while let Some(item) = self.parse_item()? {
7295 self.maybe_consume_incorrect_semicolon(&items);
7298 if !self.eat(term) {
7299 let token_str = self.this_token_descr();
7300 if !self.maybe_consume_incorrect_semicolon(&items) {
7301 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7302 err.span_label(self.span, "expected item");
7307 let hi = if self.span.is_dummy() {
7314 inner: inner_lo.to(hi),
7320 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7321 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7322 self.expect(&token::Colon)?;
7323 let ty = self.parse_ty()?;
7324 self.expect(&token::Eq)?;
7325 let e = self.parse_expr()?;
7326 self.expect(&token::Semi)?;
7327 let item = match m {
7328 Some(m) => ItemKind::Static(ty, m, e),
7329 None => ItemKind::Const(ty, e),
7331 Ok((id, item, None))
7334 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7335 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7336 let (in_cfg, outer_attrs) = {
7337 let mut strip_unconfigured = crate::config::StripUnconfigured {
7339 features: None, // don't perform gated feature checking
7341 let mut outer_attrs = outer_attrs.to_owned();
7342 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7343 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7346 let id_span = self.span;
7347 let id = self.parse_ident()?;
7348 if self.eat(&token::Semi) {
7349 if in_cfg && self.recurse_into_file_modules {
7350 // This mod is in an external file. Let's go get it!
7351 let ModulePathSuccess { path, directory_ownership, warn } =
7352 self.submod_path(id, &outer_attrs, id_span)?;
7353 let (module, mut attrs) =
7354 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7355 // Record that we fetched the mod from an external file
7357 let attr = Attribute {
7358 id: attr::mk_attr_id(),
7359 style: ast::AttrStyle::Outer,
7360 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7361 tokens: TokenStream::empty(),
7362 is_sugared_doc: false,
7363 span: syntax_pos::DUMMY_SP,
7365 attr::mark_known(&attr);
7368 Ok((id, ItemKind::Mod(module), Some(attrs)))
7370 let placeholder = ast::Mod {
7371 inner: syntax_pos::DUMMY_SP,
7375 Ok((id, ItemKind::Mod(placeholder), None))
7378 let old_directory = self.directory.clone();
7379 self.push_directory(id, &outer_attrs);
7381 self.expect(&token::OpenDelim(token::Brace))?;
7382 let mod_inner_lo = self.span;
7383 let attrs = self.parse_inner_attributes()?;
7384 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7386 self.directory = old_directory;
7387 Ok((id, ItemKind::Mod(module), Some(attrs)))
7391 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7392 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7393 self.directory.path.to_mut().push(&path.as_str());
7394 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7396 // We have to push on the current module name in the case of relative
7397 // paths in order to ensure that any additional module paths from inline
7398 // `mod x { ... }` come after the relative extension.
7400 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7401 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7402 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7403 if let Some(ident) = relative.take() { // remove the relative offset
7404 self.directory.path.to_mut().push(ident.as_str());
7407 self.directory.path.to_mut().push(&id.as_str());
7411 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7412 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7415 // On windows, the base path might have the form
7416 // `\\?\foo\bar` in which case it does not tolerate
7417 // mixed `/` and `\` separators, so canonicalize
7420 let s = s.replace("/", "\\");
7421 Some(dir_path.join(s))
7427 /// Returns a path to a module.
7428 pub fn default_submod_path(
7430 relative: Option<ast::Ident>,
7432 source_map: &SourceMap) -> ModulePath
7434 // If we're in a foo.rs file instead of a mod.rs file,
7435 // we need to look for submodules in
7436 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7437 // `./<id>.rs` and `./<id>/mod.rs`.
7438 let relative_prefix_string;
7439 let relative_prefix = if let Some(ident) = relative {
7440 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7441 &relative_prefix_string
7446 let mod_name = id.to_string();
7447 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7448 let secondary_path_str = format!("{}{}{}mod.rs",
7449 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7450 let default_path = dir_path.join(&default_path_str);
7451 let secondary_path = dir_path.join(&secondary_path_str);
7452 let default_exists = source_map.file_exists(&default_path);
7453 let secondary_exists = source_map.file_exists(&secondary_path);
7455 let result = match (default_exists, secondary_exists) {
7456 (true, false) => Ok(ModulePathSuccess {
7458 directory_ownership: DirectoryOwnership::Owned {
7463 (false, true) => Ok(ModulePathSuccess {
7464 path: secondary_path,
7465 directory_ownership: DirectoryOwnership::Owned {
7470 (false, false) => Err(Error::FileNotFoundForModule {
7471 mod_name: mod_name.clone(),
7472 default_path: default_path_str,
7473 secondary_path: secondary_path_str,
7474 dir_path: dir_path.display().to_string(),
7476 (true, true) => Err(Error::DuplicatePaths {
7477 mod_name: mod_name.clone(),
7478 default_path: default_path_str,
7479 secondary_path: secondary_path_str,
7485 path_exists: default_exists || secondary_exists,
7490 fn submod_path(&mut self,
7492 outer_attrs: &[Attribute],
7494 -> PResult<'a, ModulePathSuccess> {
7495 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7496 return Ok(ModulePathSuccess {
7497 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7498 // All `#[path]` files are treated as though they are a `mod.rs` file.
7499 // This means that `mod foo;` declarations inside `#[path]`-included
7500 // files are siblings,
7502 // Note that this will produce weirdness when a file named `foo.rs` is
7503 // `#[path]` included and contains a `mod foo;` declaration.
7504 // If you encounter this, it's your own darn fault :P
7505 Some(_) => DirectoryOwnership::Owned { relative: None },
7506 _ => DirectoryOwnership::UnownedViaMod(true),
7513 let relative = match self.directory.ownership {
7514 DirectoryOwnership::Owned { relative } => relative,
7515 DirectoryOwnership::UnownedViaBlock |
7516 DirectoryOwnership::UnownedViaMod(_) => None,
7518 let paths = Parser::default_submod_path(
7519 id, relative, &self.directory.path, self.sess.source_map());
7521 match self.directory.ownership {
7522 DirectoryOwnership::Owned { .. } => {
7523 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7525 DirectoryOwnership::UnownedViaBlock => {
7527 "Cannot declare a non-inline module inside a block \
7528 unless it has a path attribute";
7529 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7530 if paths.path_exists {
7531 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7533 err.span_note(id_sp, &msg);
7537 DirectoryOwnership::UnownedViaMod(warn) => {
7539 if let Ok(result) = paths.result {
7540 return Ok(ModulePathSuccess { warn: true, ..result });
7543 let mut err = self.diagnostic().struct_span_err(id_sp,
7544 "cannot declare a new module at this location");
7545 if !id_sp.is_dummy() {
7546 let src_path = self.sess.source_map().span_to_filename(id_sp);
7547 if let FileName::Real(src_path) = src_path {
7548 if let Some(stem) = src_path.file_stem() {
7549 let mut dest_path = src_path.clone();
7550 dest_path.set_file_name(stem);
7551 dest_path.push("mod.rs");
7552 err.span_note(id_sp,
7553 &format!("maybe move this module `{}` to its own \
7554 directory via `{}`", src_path.display(),
7555 dest_path.display()));
7559 if paths.path_exists {
7560 err.span_note(id_sp,
7561 &format!("... or maybe `use` the module `{}` instead \
7562 of possibly redeclaring it",
7570 /// Reads a module from a source file.
7571 fn eval_src_mod(&mut self,
7573 directory_ownership: DirectoryOwnership,
7576 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7577 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7578 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7579 let mut err = String::from("circular modules: ");
7580 let len = included_mod_stack.len();
7581 for p in &included_mod_stack[i.. len] {
7582 err.push_str(&p.to_string_lossy());
7583 err.push_str(" -> ");
7585 err.push_str(&path.to_string_lossy());
7586 return Err(self.span_fatal(id_sp, &err[..]));
7588 included_mod_stack.push(path.clone());
7589 drop(included_mod_stack);
7592 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7593 p0.cfg_mods = self.cfg_mods;
7594 let mod_inner_lo = p0.span;
7595 let mod_attrs = p0.parse_inner_attributes()?;
7596 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7598 self.sess.included_mod_stack.borrow_mut().pop();
7602 /// Parses a function declaration from a foreign module.
7603 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7604 -> PResult<'a, ForeignItem> {
7605 self.expect_keyword(keywords::Fn)?;
7607 let (ident, mut generics) = self.parse_fn_header()?;
7608 let decl = self.parse_fn_decl(true)?;
7609 generics.where_clause = self.parse_where_clause()?;
7611 self.expect(&token::Semi)?;
7612 Ok(ast::ForeignItem {
7615 node: ForeignItemKind::Fn(decl, generics),
7616 id: ast::DUMMY_NODE_ID,
7622 /// Parses a static item from a foreign module.
7623 /// Assumes that the `static` keyword is already parsed.
7624 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7625 -> PResult<'a, ForeignItem> {
7626 let mutbl = self.parse_mutability();
7627 let ident = self.parse_ident()?;
7628 self.expect(&token::Colon)?;
7629 let ty = self.parse_ty()?;
7631 self.expect(&token::Semi)?;
7635 node: ForeignItemKind::Static(ty, mutbl),
7636 id: ast::DUMMY_NODE_ID,
7642 /// Parses a type from a foreign module.
7643 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7644 -> PResult<'a, ForeignItem> {
7645 self.expect_keyword(keywords::Type)?;
7647 let ident = self.parse_ident()?;
7649 self.expect(&token::Semi)?;
7650 Ok(ast::ForeignItem {
7653 node: ForeignItemKind::Ty,
7654 id: ast::DUMMY_NODE_ID,
7660 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7661 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7662 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7664 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7665 self.parse_path_segment_ident()
7669 let mut idents = vec![];
7670 let mut replacement = vec![];
7671 let mut fixed_crate_name = false;
7672 // Accept `extern crate name-like-this` for better diagnostics
7673 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7674 if self.token == dash { // Do not include `-` as part of the expected tokens list
7675 while self.eat(&dash) {
7676 fixed_crate_name = true;
7677 replacement.push((self.prev_span, "_".to_string()));
7678 idents.push(self.parse_ident()?);
7681 if fixed_crate_name {
7682 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7683 let mut fixed_name = format!("{}", ident.name);
7684 for part in idents {
7685 fixed_name.push_str(&format!("_{}", part.name));
7687 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7689 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7690 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7691 err.multipart_suggestion(
7694 Applicability::MachineApplicable,
7701 /// Parses `extern crate` links.
7706 /// extern crate foo;
7707 /// extern crate bar as foo;
7709 fn parse_item_extern_crate(&mut self,
7711 visibility: Visibility,
7712 attrs: Vec<Attribute>)
7713 -> PResult<'a, P<Item>> {
7714 // Accept `extern crate name-like-this` for better diagnostics
7715 let orig_name = self.parse_crate_name_with_dashes()?;
7716 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7717 (rename, Some(orig_name.name))
7721 self.expect(&token::Semi)?;
7723 let span = lo.to(self.prev_span);
7724 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7727 /// Parses `extern` for foreign ABIs modules.
7729 /// `extern` is expected to have been
7730 /// consumed before calling this method.
7734 /// ```ignore (only-for-syntax-highlight)
7738 fn parse_item_foreign_mod(&mut self,
7740 opt_abi: Option<Abi>,
7741 visibility: Visibility,
7742 mut attrs: Vec<Attribute>)
7743 -> PResult<'a, P<Item>> {
7744 self.expect(&token::OpenDelim(token::Brace))?;
7746 let abi = opt_abi.unwrap_or(Abi::C);
7748 attrs.extend(self.parse_inner_attributes()?);
7750 let mut foreign_items = vec![];
7751 while !self.eat(&token::CloseDelim(token::Brace)) {
7752 foreign_items.push(self.parse_foreign_item()?);
7755 let prev_span = self.prev_span;
7756 let m = ast::ForeignMod {
7758 items: foreign_items
7760 let invalid = keywords::Invalid.ident();
7761 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7764 /// Parses `type Foo = Bar;`
7766 /// `existential type Foo: Bar;`
7769 /// without modifying the parser state.
7770 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7771 // This parses the grammar:
7772 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7773 if self.check_keyword(keywords::Type) ||
7774 self.check_keyword(keywords::Existential) &&
7775 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7776 let existential = self.eat_keyword(keywords::Existential);
7777 assert!(self.eat_keyword(keywords::Type));
7778 Some(self.parse_existential_or_alias(existential))
7784 /// Parses a type alias or existential type.
7785 fn parse_existential_or_alias(
7788 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7789 let ident = self.parse_ident()?;
7790 let mut tps = self.parse_generics()?;
7791 tps.where_clause = self.parse_where_clause()?;
7792 let alias = if existential {
7793 self.expect(&token::Colon)?;
7794 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7795 AliasKind::Existential(bounds)
7797 self.expect(&token::Eq)?;
7798 let ty = self.parse_ty()?;
7801 self.expect(&token::Semi)?;
7802 Ok((ident, alias, tps))
7805 /// Parses the part of an enum declaration following the `{`.
7806 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7807 let mut variants = Vec::new();
7808 let mut all_nullary = true;
7809 let mut any_disr = vec![];
7810 while self.token != token::CloseDelim(token::Brace) {
7811 let variant_attrs = self.parse_outer_attributes()?;
7812 let vlo = self.span;
7815 let mut disr_expr = None;
7817 let ident = self.parse_ident()?;
7818 if self.check(&token::OpenDelim(token::Brace)) {
7819 // Parse a struct variant.
7820 all_nullary = false;
7821 let (fields, recovered) = self.parse_record_struct_body()?;
7822 struct_def = VariantData::Struct(fields, recovered);
7823 } else if self.check(&token::OpenDelim(token::Paren)) {
7824 all_nullary = false;
7825 struct_def = VariantData::Tuple(
7826 self.parse_tuple_struct_body()?,
7829 } else if self.eat(&token::Eq) {
7830 disr_expr = Some(AnonConst {
7831 id: ast::DUMMY_NODE_ID,
7832 value: self.parse_expr()?,
7834 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7837 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7839 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7842 let vr = ast::Variant_ {
7844 id: ast::DUMMY_NODE_ID,
7845 attrs: variant_attrs,
7849 variants.push(respan(vlo.to(self.prev_span), vr));
7851 if !self.eat(&token::Comma) {
7852 if self.token.is_ident() && !self.token.is_reserved_ident() {
7853 let sp = self.sess.source_map().next_point(self.prev_span);
7854 let mut err = self.struct_span_err(sp, "missing comma");
7855 err.span_suggestion_short(
7859 Applicability::MaybeIncorrect,
7867 self.expect(&token::CloseDelim(token::Brace))?;
7868 if !any_disr.is_empty() && !all_nullary {
7869 let mut err = self.struct_span_err(
7871 "discriminator values can only be used with a field-less enum",
7873 for sp in any_disr {
7874 err.span_label(sp, "only valid in field-less enums");
7879 Ok(ast::EnumDef { variants })
7882 /// Parses an enum declaration.
7883 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7884 let id = self.parse_ident()?;
7885 let mut generics = self.parse_generics()?;
7886 generics.where_clause = self.parse_where_clause()?;
7887 self.expect(&token::OpenDelim(token::Brace))?;
7889 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7890 self.recover_stmt();
7891 self.eat(&token::CloseDelim(token::Brace));
7894 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7897 /// Parses a string as an ABI spec on an extern type or module. Consumes
7898 /// the `extern` keyword, if one is found.
7899 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7901 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7903 self.expect_no_suffix(sp, "an ABI spec", suf);
7905 match abi::lookup(&s.as_str()) {
7906 Some(abi) => Ok(Some(abi)),
7908 let prev_span = self.prev_span;
7909 let mut err = struct_span_err!(
7910 self.sess.span_diagnostic,
7913 "invalid ABI: found `{}`",
7915 err.span_label(prev_span, "invalid ABI");
7916 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7927 fn is_static_global(&mut self) -> bool {
7928 if self.check_keyword(keywords::Static) {
7929 // Check if this could be a closure
7930 !self.look_ahead(1, |token| {
7931 if token.is_keyword(keywords::Move) {
7935 token::BinOp(token::Or) | token::OrOr => true,
7946 attrs: Vec<Attribute>,
7947 macros_allowed: bool,
7948 attributes_allowed: bool,
7949 ) -> PResult<'a, Option<P<Item>>> {
7950 let mut unclosed_delims = vec![];
7951 let (ret, tokens) = self.collect_tokens(|this| {
7952 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7953 unclosed_delims.append(&mut this.unclosed_delims);
7956 self.unclosed_delims.append(&mut unclosed_delims);
7958 // Once we've parsed an item and recorded the tokens we got while
7959 // parsing we may want to store `tokens` into the item we're about to
7960 // return. Note, though, that we specifically didn't capture tokens
7961 // related to outer attributes. The `tokens` field here may later be
7962 // used with procedural macros to convert this item back into a token
7963 // stream, but during expansion we may be removing attributes as we go
7966 // If we've got inner attributes then the `tokens` we've got above holds
7967 // these inner attributes. If an inner attribute is expanded we won't
7968 // actually remove it from the token stream, so we'll just keep yielding
7969 // it (bad!). To work around this case for now we just avoid recording
7970 // `tokens` if we detect any inner attributes. This should help keep
7971 // expansion correct, but we should fix this bug one day!
7974 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7975 i.tokens = Some(tokens);
7982 /// Parses one of the items allowed by the flags.
7983 fn parse_item_implementation(
7985 attrs: Vec<Attribute>,
7986 macros_allowed: bool,
7987 attributes_allowed: bool,
7988 ) -> PResult<'a, Option<P<Item>>> {
7989 maybe_whole!(self, NtItem, |item| {
7990 let mut item = item.into_inner();
7991 let mut attrs = attrs;
7992 mem::swap(&mut item.attrs, &mut attrs);
7993 item.attrs.extend(attrs);
7999 let visibility = self.parse_visibility(false)?;
8001 if self.eat_keyword(keywords::Use) {
8003 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
8004 self.expect(&token::Semi)?;
8006 let span = lo.to(self.prev_span);
8007 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
8008 return Ok(Some(item));
8011 if self.eat_keyword(keywords::Extern) {
8012 if self.eat_keyword(keywords::Crate) {
8013 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
8016 let opt_abi = self.parse_opt_abi()?;
8018 if self.eat_keyword(keywords::Fn) {
8019 // EXTERN FUNCTION ITEM
8020 let fn_span = self.prev_span;
8021 let abi = opt_abi.unwrap_or(Abi::C);
8022 let (ident, item_, extra_attrs) =
8023 self.parse_item_fn(Unsafety::Normal,
8024 respan(fn_span, IsAsync::NotAsync),
8025 respan(fn_span, Constness::NotConst),
8027 let prev_span = self.prev_span;
8028 let item = self.mk_item(lo.to(prev_span),
8032 maybe_append(attrs, extra_attrs));
8033 return Ok(Some(item));
8034 } else if self.check(&token::OpenDelim(token::Brace)) {
8035 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
8041 if self.is_static_global() {
8044 let m = if self.eat_keyword(keywords::Mut) {
8047 Mutability::Immutable
8049 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
8050 let prev_span = self.prev_span;
8051 let item = self.mk_item(lo.to(prev_span),
8055 maybe_append(attrs, extra_attrs));
8056 return Ok(Some(item));
8058 if self.eat_keyword(keywords::Const) {
8059 let const_span = self.prev_span;
8060 if self.check_keyword(keywords::Fn)
8061 || (self.check_keyword(keywords::Unsafe)
8062 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
8063 // CONST FUNCTION ITEM
8064 let unsafety = self.parse_unsafety();
8066 let (ident, item_, extra_attrs) =
8067 self.parse_item_fn(unsafety,
8068 respan(const_span, IsAsync::NotAsync),
8069 respan(const_span, Constness::Const),
8071 let prev_span = self.prev_span;
8072 let item = self.mk_item(lo.to(prev_span),
8076 maybe_append(attrs, extra_attrs));
8077 return Ok(Some(item));
8081 if self.eat_keyword(keywords::Mut) {
8082 let prev_span = self.prev_span;
8083 let mut err = self.diagnostic()
8084 .struct_span_err(prev_span, "const globals cannot be mutable");
8085 err.span_label(prev_span, "cannot be mutable");
8086 err.span_suggestion(
8088 "you might want to declare a static instead",
8089 "static".to_owned(),
8090 Applicability::MaybeIncorrect,
8094 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
8095 let prev_span = self.prev_span;
8096 let item = self.mk_item(lo.to(prev_span),
8100 maybe_append(attrs, extra_attrs));
8101 return Ok(Some(item));
8104 // `unsafe async fn` or `async fn`
8106 self.check_keyword(keywords::Unsafe) &&
8107 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
8109 self.check_keyword(keywords::Async) &&
8110 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
8113 // ASYNC FUNCTION ITEM
8114 let unsafety = self.parse_unsafety();
8115 self.expect_keyword(keywords::Async)?;
8116 let async_span = self.prev_span;
8117 self.expect_keyword(keywords::Fn)?;
8118 let fn_span = self.prev_span;
8119 let (ident, item_, extra_attrs) =
8120 self.parse_item_fn(unsafety,
8121 respan(async_span, IsAsync::Async {
8122 closure_id: ast::DUMMY_NODE_ID,
8123 return_impl_trait_id: ast::DUMMY_NODE_ID,
8124 arguments: Vec::new(),
8126 respan(fn_span, Constness::NotConst),
8128 let prev_span = self.prev_span;
8129 let item = self.mk_item(lo.to(prev_span),
8133 maybe_append(attrs, extra_attrs));
8134 if self.span.rust_2015() {
8135 self.diagnostic().struct_span_err_with_code(
8137 "`async fn` is not permitted in the 2015 edition",
8138 DiagnosticId::Error("E0670".into())
8141 return Ok(Some(item));
8143 if self.check_keyword(keywords::Unsafe) &&
8144 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8145 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8147 // UNSAFE TRAIT ITEM
8148 self.bump(); // `unsafe`
8149 let is_auto = if self.eat_keyword(keywords::Trait) {
8152 self.expect_keyword(keywords::Auto)?;
8153 self.expect_keyword(keywords::Trait)?;
8156 let (ident, item_, extra_attrs) =
8157 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8158 let prev_span = self.prev_span;
8159 let item = self.mk_item(lo.to(prev_span),
8163 maybe_append(attrs, extra_attrs));
8164 return Ok(Some(item));
8166 if self.check_keyword(keywords::Impl) ||
8167 self.check_keyword(keywords::Unsafe) &&
8168 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8169 self.check_keyword(keywords::Default) &&
8170 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8171 self.check_keyword(keywords::Default) &&
8172 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8174 let defaultness = self.parse_defaultness();
8175 let unsafety = self.parse_unsafety();
8176 self.expect_keyword(keywords::Impl)?;
8177 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8178 let span = lo.to(self.prev_span);
8179 return Ok(Some(self.mk_item(span, ident, item, visibility,
8180 maybe_append(attrs, extra_attrs))));
8182 if self.check_keyword(keywords::Fn) {
8185 let fn_span = self.prev_span;
8186 let (ident, item_, extra_attrs) =
8187 self.parse_item_fn(Unsafety::Normal,
8188 respan(fn_span, IsAsync::NotAsync),
8189 respan(fn_span, Constness::NotConst),
8191 let prev_span = self.prev_span;
8192 let item = self.mk_item(lo.to(prev_span),
8196 maybe_append(attrs, extra_attrs));
8197 return Ok(Some(item));
8199 if self.check_keyword(keywords::Unsafe)
8200 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8201 // UNSAFE FUNCTION ITEM
8202 self.bump(); // `unsafe`
8203 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8204 self.check(&token::OpenDelim(token::Brace));
8205 let abi = if self.eat_keyword(keywords::Extern) {
8206 self.parse_opt_abi()?.unwrap_or(Abi::C)
8210 self.expect_keyword(keywords::Fn)?;
8211 let fn_span = self.prev_span;
8212 let (ident, item_, extra_attrs) =
8213 self.parse_item_fn(Unsafety::Unsafe,
8214 respan(fn_span, IsAsync::NotAsync),
8215 respan(fn_span, Constness::NotConst),
8217 let prev_span = self.prev_span;
8218 let item = self.mk_item(lo.to(prev_span),
8222 maybe_append(attrs, extra_attrs));
8223 return Ok(Some(item));
8225 if self.eat_keyword(keywords::Mod) {
8227 let (ident, item_, extra_attrs) =
8228 self.parse_item_mod(&attrs[..])?;
8229 let prev_span = self.prev_span;
8230 let item = self.mk_item(lo.to(prev_span),
8234 maybe_append(attrs, extra_attrs));
8235 return Ok(Some(item));
8237 if let Some(type_) = self.eat_type() {
8238 let (ident, alias, generics) = type_?;
8240 let item_ = match alias {
8241 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8242 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8244 let prev_span = self.prev_span;
8245 let item = self.mk_item(lo.to(prev_span),
8250 return Ok(Some(item));
8252 if self.eat_keyword(keywords::Enum) {
8254 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8255 let prev_span = self.prev_span;
8256 let item = self.mk_item(lo.to(prev_span),
8260 maybe_append(attrs, extra_attrs));
8261 return Ok(Some(item));
8263 if self.check_keyword(keywords::Trait)
8264 || (self.check_keyword(keywords::Auto)
8265 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8267 let is_auto = if self.eat_keyword(keywords::Trait) {
8270 self.expect_keyword(keywords::Auto)?;
8271 self.expect_keyword(keywords::Trait)?;
8275 let (ident, item_, extra_attrs) =
8276 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8277 let prev_span = self.prev_span;
8278 let item = self.mk_item(lo.to(prev_span),
8282 maybe_append(attrs, extra_attrs));
8283 return Ok(Some(item));
8285 if self.eat_keyword(keywords::Struct) {
8287 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8288 let prev_span = self.prev_span;
8289 let item = self.mk_item(lo.to(prev_span),
8293 maybe_append(attrs, extra_attrs));
8294 return Ok(Some(item));
8296 if self.is_union_item() {
8299 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8300 let prev_span = self.prev_span;
8301 let item = self.mk_item(lo.to(prev_span),
8305 maybe_append(attrs, extra_attrs));
8306 return Ok(Some(item));
8308 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8309 return Ok(Some(macro_def));
8312 // Verify whether we have encountered a struct or method definition where the user forgot to
8313 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8314 if visibility.node.is_pub() &&
8315 self.check_ident() &&
8316 self.look_ahead(1, |t| *t != token::Not)
8318 // Space between `pub` keyword and the identifier
8321 // ^^^ `sp` points here
8322 let sp = self.prev_span.between(self.span);
8323 let full_sp = self.prev_span.to(self.span);
8324 let ident_sp = self.span;
8325 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8326 // possible public struct definition where `struct` was forgotten
8327 let ident = self.parse_ident().unwrap();
8328 let msg = format!("add `struct` here to parse `{}` as a public struct",
8330 let mut err = self.diagnostic()
8331 .struct_span_err(sp, "missing `struct` for struct definition");
8332 err.span_suggestion_short(
8333 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8336 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8337 let ident = self.parse_ident().unwrap();
8339 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8344 self.consume_block(token::Paren);
8345 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8346 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8348 ("fn", kw_name, false)
8349 } else if self.check(&token::OpenDelim(token::Brace)) {
8351 ("fn", kw_name, false)
8352 } else if self.check(&token::Colon) {
8356 ("fn` or `struct", "function or struct", true)
8359 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8360 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8362 self.consume_block(token::Brace);
8363 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8367 err.span_suggestion_short(
8368 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8371 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8372 err.span_suggestion(
8374 "if you meant to call a macro, try",
8375 format!("{}!", snippet),
8376 // this is the `ambiguous` conditional branch
8377 Applicability::MaybeIncorrect
8380 err.help("if you meant to call a macro, remove the `pub` \
8381 and add a trailing `!` after the identifier");
8385 } else if self.look_ahead(1, |t| *t == token::Lt) {
8386 let ident = self.parse_ident().unwrap();
8387 self.eat_to_tokens(&[&token::Gt]);
8389 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8390 if let Ok(Some(_)) = self.parse_self_arg() {
8391 ("fn", "method", false)
8393 ("fn", "function", false)
8395 } else if self.check(&token::OpenDelim(token::Brace)) {
8396 ("struct", "struct", false)
8398 ("fn` or `struct", "function or struct", true)
8400 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8401 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8403 err.span_suggestion_short(
8405 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8406 format!(" {} ", kw),
8407 Applicability::MachineApplicable,
8413 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8416 /// Parses a foreign item.
8417 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8418 maybe_whole!(self, NtForeignItem, |ni| ni);
8420 let attrs = self.parse_outer_attributes()?;
8422 let visibility = self.parse_visibility(false)?;
8424 // FOREIGN STATIC ITEM
8425 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8426 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8427 if self.token.is_keyword(keywords::Const) {
8429 .struct_span_err(self.span, "extern items cannot be `const`")
8432 "try using a static value",
8433 "static".to_owned(),
8434 Applicability::MachineApplicable
8437 self.bump(); // `static` or `const`
8438 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8440 // FOREIGN FUNCTION ITEM
8441 if self.check_keyword(keywords::Fn) {
8442 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8444 // FOREIGN TYPE ITEM
8445 if self.check_keyword(keywords::Type) {
8446 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8449 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8453 ident: keywords::Invalid.ident(),
8454 span: lo.to(self.prev_span),
8455 id: ast::DUMMY_NODE_ID,
8458 node: ForeignItemKind::Macro(mac),
8463 if !attrs.is_empty() {
8464 self.expected_item_err(&attrs)?;
8472 /// This is the fall-through for parsing items.
8473 fn parse_macro_use_or_failure(
8475 attrs: Vec<Attribute> ,
8476 macros_allowed: bool,
8477 attributes_allowed: bool,
8479 visibility: Visibility
8480 ) -> PResult<'a, Option<P<Item>>> {
8481 if macros_allowed && self.token.is_path_start() &&
8482 !(self.is_async_fn() && self.span.rust_2015()) {
8483 // MACRO INVOCATION ITEM
8485 let prev_span = self.prev_span;
8486 self.complain_if_pub_macro(&visibility.node, prev_span);
8488 let mac_lo = self.span;
8491 let pth = self.parse_path(PathStyle::Mod)?;
8492 self.expect(&token::Not)?;
8494 // a 'special' identifier (like what `macro_rules!` uses)
8495 // is optional. We should eventually unify invoc syntax
8497 let id = if self.token.is_ident() {
8500 keywords::Invalid.ident() // no special identifier
8502 // eat a matched-delimiter token tree:
8503 let (delim, tts) = self.expect_delimited_token_tree()?;
8504 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8505 self.report_invalid_macro_expansion_item();
8508 let hi = self.prev_span;
8509 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8510 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8511 return Ok(Some(item));
8514 // FAILURE TO PARSE ITEM
8515 match visibility.node {
8516 VisibilityKind::Inherited => {}
8518 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8522 if !attributes_allowed && !attrs.is_empty() {
8523 self.expected_item_err(&attrs)?;
8528 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8529 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8530 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8532 if self.token.is_path_start() &&
8533 !(self.is_async_fn() && self.span.rust_2015()) {
8534 let prev_span = self.prev_span;
8536 let pth = self.parse_path(PathStyle::Mod)?;
8538 if pth.segments.len() == 1 {
8539 if !self.eat(&token::Not) {
8540 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8543 self.expect(&token::Not)?;
8546 if let Some(vis) = vis {
8547 self.complain_if_pub_macro(&vis.node, prev_span);
8552 // eat a matched-delimiter token tree:
8553 let (delim, tts) = self.expect_delimited_token_tree()?;
8554 if delim != MacDelimiter::Brace {
8555 self.expect(&token::Semi)?;
8558 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8564 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8565 where F: FnOnce(&mut Self) -> PResult<'a, R>
8567 // Record all tokens we parse when parsing this item.
8568 let mut tokens = Vec::new();
8569 let prev_collecting = match self.token_cursor.frame.last_token {
8570 LastToken::Collecting(ref mut list) => {
8571 Some(mem::replace(list, Vec::new()))
8573 LastToken::Was(ref mut last) => {
8574 tokens.extend(last.take());
8578 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8579 let prev = self.token_cursor.stack.len();
8581 let last_token = if self.token_cursor.stack.len() == prev {
8582 &mut self.token_cursor.frame.last_token
8584 &mut self.token_cursor.stack[prev].last_token
8587 // Pull out the tokens that we've collected from the call to `f` above.
8588 let mut collected_tokens = match *last_token {
8589 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8590 LastToken::Was(_) => panic!("our vector went away?"),
8593 // If we're not at EOF our current token wasn't actually consumed by
8594 // `f`, but it'll still be in our list that we pulled out. In that case
8596 let extra_token = if self.token != token::Eof {
8597 collected_tokens.pop()
8602 // If we were previously collecting tokens, then this was a recursive
8603 // call. In that case we need to record all the tokens we collected in
8604 // our parent list as well. To do that we push a clone of our stream
8605 // onto the previous list.
8606 match prev_collecting {
8608 list.extend(collected_tokens.iter().cloned());
8609 list.extend(extra_token);
8610 *last_token = LastToken::Collecting(list);
8613 *last_token = LastToken::Was(extra_token);
8617 Ok((ret?, TokenStream::new(collected_tokens)))
8620 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8621 let attrs = self.parse_outer_attributes()?;
8622 self.parse_item_(attrs, true, false)
8626 fn is_import_coupler(&mut self) -> bool {
8627 self.check(&token::ModSep) &&
8628 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8629 *t == token::BinOp(token::Star))
8632 /// Parses a `UseTree`.
8635 /// USE_TREE = [`::`] `*` |
8636 /// [`::`] `{` USE_TREE_LIST `}` |
8638 /// PATH `::` `{` USE_TREE_LIST `}` |
8639 /// PATH [`as` IDENT]
8641 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8644 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8645 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8646 self.check(&token::BinOp(token::Star)) ||
8647 self.is_import_coupler() {
8648 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8649 let mod_sep_ctxt = self.span.ctxt();
8650 if self.eat(&token::ModSep) {
8651 prefix.segments.push(
8652 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8656 if self.eat(&token::BinOp(token::Star)) {
8659 UseTreeKind::Nested(self.parse_use_tree_list()?)
8662 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8663 prefix = self.parse_path(PathStyle::Mod)?;
8665 if self.eat(&token::ModSep) {
8666 if self.eat(&token::BinOp(token::Star)) {
8669 UseTreeKind::Nested(self.parse_use_tree_list()?)
8672 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8676 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8679 /// Parses a `UseTreeKind::Nested(list)`.
8682 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8684 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8685 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8686 &token::CloseDelim(token::Brace),
8687 SeqSep::trailing_allowed(token::Comma), |this| {
8688 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8692 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8693 if self.eat_keyword(keywords::As) {
8694 self.parse_ident_or_underscore().map(Some)
8700 /// Parses a source module as a crate. This is the main entry point for the parser.
8701 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8703 let krate = Ok(ast::Crate {
8704 attrs: self.parse_inner_attributes()?,
8705 module: self.parse_mod_items(&token::Eof, lo)?,
8706 span: lo.to(self.span),
8711 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8712 let ret = match self.token {
8713 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8714 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8721 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8722 match self.parse_optional_str() {
8723 Some((s, style, suf)) => {
8724 let sp = self.prev_span;
8725 self.expect_no_suffix(sp, "a string literal", suf);
8729 let msg = "expected string literal";
8730 let mut err = self.fatal(msg);
8731 err.span_label(self.span, msg);
8737 fn report_invalid_macro_expansion_item(&self) {
8738 self.struct_span_err(
8740 "macros that expand to items must be delimited with braces or followed by a semicolon",
8741 ).multipart_suggestion(
8742 "change the delimiters to curly braces",
8744 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8745 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8747 Applicability::MaybeIncorrect,
8749 self.sess.source_map.next_point(self.prev_span),
8752 Applicability::MaybeIncorrect,
8756 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8757 fn eat_bad_pub(&mut self) {
8758 if self.token.is_keyword(keywords::Pub) {
8759 match self.parse_visibility(false) {
8761 let mut err = self.diagnostic()
8762 .struct_span_err(vis.span, "unnecessary visibility qualifier");
8763 err.span_label(vis.span, "`pub` not permitted here");
8766 Err(mut err) => err.emit(),
8771 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8772 /// into the generated closure so that they are dropped when the future is polled and not when
8775 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8776 /// this function and the statements created here are inserted at the top of the closure body.
8777 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &mut FnDecl) {
8778 // FIXME(davidtwco): This function should really live in the HIR lowering but because
8779 // the types constructed here need to be used in parts of resolve so that the correct
8780 // locals are considered upvars, it is currently easier for it to live here in the parser,
8781 // where it can be constructed once.
8782 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8783 for (index, input) in decl.inputs.iter_mut().enumerate() {
8784 let id = ast::DUMMY_NODE_ID;
8785 let span = input.pat.span;
8787 // Construct a name for our temporary argument.
8788 let name = format!("__arg{}", index);
8789 let ident = Ident::from_str(&name).gensym();
8791 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
8792 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
8794 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
8795 PatKind::Ident(binding_mode @ BindingMode::ByValue(_), ident, _) => {
8796 // Simple patterns like this don't have a generated argument, but they are
8797 // moved into the closure with a statement, so any `mut` bindings on the
8798 // argument will be unused. This binding mode can't be removed, because
8799 // this would affect the input to procedural macros, but they can have
8800 // their span marked as being the result of a compiler desugaring so
8801 // that they aren't linted against.
8802 input.pat.span = self.sess.source_map().mark_span_with_reason(
8803 CompilerDesugaringKind::Async, span, None);
8805 (binding_mode, ident, true)
8807 _ => (BindingMode::ByValue(Mutability::Mutable), ident, false),
8810 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8811 // async function if it isn't a simple pattern.
8812 let arg = if is_simple_pattern {
8816 ty: input.ty.clone(),
8820 node: PatKind::Ident(
8821 BindingMode::ByValue(Mutability::Immutable), ident, None,
8825 source: ArgSource::AsyncFn(input.pat.clone()),
8829 // Construct a `let __argN = __argN;` statement to insert at the top of the
8830 // async closure. This makes sure that the argument is captured by the closure and
8831 // that the drop order is correct.
8832 let move_local = Local {
8835 node: PatKind::Ident(binding_mode, ident, None),
8838 // We explicitly do not specify the type for this statement. When the user's
8839 // argument type is `impl Trait` then this would require the
8840 // `impl_trait_in_bindings` feature to also be present for that same type to
8841 // be valid in this binding. At the time of writing (13 Mar 19),
8842 // `impl_trait_in_bindings` is not stable.
8846 node: ExprKind::Path(None, ast::Path {
8848 segments: vec![PathSegment { ident, id, args: None }],
8851 attrs: ThinVec::new(),
8855 attrs: ThinVec::new(),
8856 source: LocalSource::AsyncFn,
8859 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8860 // async closure if this isn't a simple pattern.
8861 let pat_stmt = if is_simple_pattern {
8866 node: StmtKind::Local(P(Local {
8867 pat: input.pat.clone(),
8868 ..move_local.clone()
8874 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
8875 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
8881 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8882 for unmatched in unclosed_delims.iter() {
8883 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8884 "incorrect close delimiter: `{}`",
8885 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8887 err.span_label(unmatched.found_span, "incorrect close delimiter");
8888 if let Some(sp) = unmatched.candidate_span {
8889 err.span_label(sp, "close delimiter possibly meant for this");
8891 if let Some(sp) = unmatched.unclosed_span {
8892 err.span_label(sp, "un-closed delimiter");
8896 unclosed_delims.clear();