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};
53 use syntax_pos::{Span, MultiSpan, BytePos, FileName};
54 use log::{debug, trace};
59 use std::path::{self, Path, PathBuf};
63 /// Whether the type alias or associated type is a concrete type or an existential type
65 /// Just a new name for the same type
67 /// Only trait impls of the type will be usable, not the actual type itself
68 Existential(GenericBounds),
72 struct Restrictions: u8 {
73 const STMT_EXPR = 1 << 0;
74 const NO_STRUCT_LITERAL = 1 << 1;
78 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
80 /// Specifies how to parse a path.
81 #[derive(Copy, Clone, PartialEq)]
83 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
84 /// with something else. For example, in expressions `segment < ....` can be interpreted
85 /// as a comparison and `segment ( ....` can be interpreted as a function call.
86 /// In all such contexts the non-path interpretation is preferred by default for practical
87 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
88 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
90 /// In other contexts, notably in types, no ambiguity exists and paths can be written
91 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
92 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
94 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
95 /// visibilities or attributes.
96 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
97 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
98 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
99 /// tokens when something goes wrong.
103 #[derive(Clone, Copy, PartialEq, Debug)]
110 #[derive(Clone, Copy, PartialEq, Debug)]
116 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
117 /// dropped into the token stream, which happens while parsing the result of
118 /// macro expansion). Placement of these is not as complex as I feared it would
119 /// be. The important thing is to make sure that lookahead doesn't balk at
120 /// `token::Interpolated` tokens.
121 macro_rules! maybe_whole_expr {
123 if let token::Interpolated(nt) = &$p.token {
125 token::NtExpr(e) | token::NtLiteral(e) => {
130 token::NtPath(path) => {
131 let path = path.clone();
133 return Ok($p.mk_expr($p.span, ExprKind::Path(None, path), ThinVec::new()));
135 token::NtBlock(block) => {
136 let block = block.clone();
138 return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
146 /// As maybe_whole_expr, but for things other than expressions
147 macro_rules! maybe_whole {
148 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
149 if let token::Interpolated(nt) = &$p.token {
150 if let token::$constructor(x) = &**nt {
159 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
160 macro_rules! maybe_recover_from_interpolated_ty_qpath {
161 ($self: expr, $allow_qpath_recovery: expr) => {
162 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
163 if let token::Interpolated(nt) = &$self.token {
164 if let token::NtTy(ty) = &**nt {
167 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
174 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
175 if let Some(ref mut rhs) = rhs {
181 #[derive(Debug, Clone, Copy, PartialEq)]
193 /* ident is handled by common.rs */
196 pub struct Parser<'a> {
197 pub sess: &'a ParseSess,
198 /// the current token:
199 pub token: token::Token,
200 /// the span of the current token:
202 /// the span of the previous token:
203 meta_var_span: Option<Span>,
205 /// the previous token kind
206 prev_token_kind: PrevTokenKind,
207 restrictions: Restrictions,
208 /// Used to determine the path to externally loaded source files
209 crate directory: Directory<'a>,
210 /// Whether to parse sub-modules in other files.
211 pub recurse_into_file_modules: bool,
212 /// Name of the root module this parser originated from. If `None`, then the
213 /// name is not known. This does not change while the parser is descending
214 /// into modules, and sub-parsers have new values for this name.
215 pub root_module_name: Option<String>,
216 crate expected_tokens: Vec<TokenType>,
217 token_cursor: TokenCursor,
218 desugar_doc_comments: bool,
219 /// Whether we should configure out of line modules as we parse.
221 /// This field is used to keep track of how many left angle brackets we have seen. This is
222 /// required in order to detect extra leading left angle brackets (`<` characters) and error
225 /// See the comments in the `parse_path_segment` function for more details.
226 crate unmatched_angle_bracket_count: u32,
227 crate max_angle_bracket_count: u32,
228 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
229 /// it gets removed from here. Every entry left at the end gets emitted as an independent
231 crate unclosed_delims: Vec<UnmatchedBrace>,
232 last_unexpected_token_span: Option<Span>,
235 impl<'a> Drop for Parser<'a> {
237 let diag = self.diagnostic();
238 emit_unclosed_delims(&mut self.unclosed_delims, diag);
244 frame: TokenCursorFrame,
245 stack: Vec<TokenCursorFrame>,
249 struct TokenCursorFrame {
250 delim: token::DelimToken,
253 tree_cursor: tokenstream::Cursor,
255 last_token: LastToken,
258 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
259 /// by the parser, and then that's transitively used to record the tokens that
260 /// each parse AST item is created with.
262 /// Right now this has two states, either collecting tokens or not collecting
263 /// tokens. If we're collecting tokens we just save everything off into a local
264 /// `Vec`. This should eventually though likely save tokens from the original
265 /// token stream and just use slicing of token streams to avoid creation of a
266 /// whole new vector.
268 /// The second state is where we're passively not recording tokens, but the last
269 /// token is still tracked for when we want to start recording tokens. This
270 /// "last token" means that when we start recording tokens we'll want to ensure
271 /// that this, the first token, is included in the output.
273 /// You can find some more example usage of this in the `collect_tokens` method
277 Collecting(Vec<TreeAndJoint>),
278 Was(Option<TreeAndJoint>),
281 impl TokenCursorFrame {
282 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
286 open_delim: delim == token::NoDelim,
287 tree_cursor: tts.clone().into_trees(),
288 close_delim: delim == token::NoDelim,
289 last_token: LastToken::Was(None),
295 fn next(&mut self) -> TokenAndSpan {
297 let tree = if !self.frame.open_delim {
298 self.frame.open_delim = true;
299 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
300 } else if let Some(tree) = self.frame.tree_cursor.next() {
302 } else if !self.frame.close_delim {
303 self.frame.close_delim = true;
304 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
305 } else if let Some(frame) = self.stack.pop() {
309 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
312 match self.frame.last_token {
313 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
314 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
318 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
319 TokenTree::Delimited(sp, delim, tts) => {
320 let frame = TokenCursorFrame::new(sp, delim, &tts);
321 self.stack.push(mem::replace(&mut self.frame, frame));
327 fn next_desugared(&mut self) -> TokenAndSpan {
328 let (sp, name) = match self.next() {
329 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
333 let stripped = strip_doc_comment_decoration(&name.as_str());
335 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
336 // required to wrap the text.
337 let mut num_of_hashes = 0;
339 for ch in stripped.chars() {
342 '#' if count > 0 => count + 1,
345 num_of_hashes = cmp::max(num_of_hashes, count);
348 let delim_span = DelimSpan::from_single(sp);
349 let body = TokenTree::Delimited(
352 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
353 TokenTree::Token(sp, token::Eq),
354 TokenTree::Token(sp, token::Literal(
355 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
357 .iter().cloned().collect::<TokenStream>().into(),
360 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
363 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
364 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
365 .iter().cloned().collect::<TokenStream>().into()
367 [TokenTree::Token(sp, token::Pound), body]
368 .iter().cloned().collect::<TokenStream>().into()
376 #[derive(Clone, PartialEq)]
377 crate enum TokenType {
379 Keyword(keywords::Keyword),
389 fn to_string(&self) -> String {
391 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
392 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
393 TokenType::Operator => "an operator".to_string(),
394 TokenType::Lifetime => "lifetime".to_string(),
395 TokenType::Ident => "identifier".to_string(),
396 TokenType::Path => "path".to_string(),
397 TokenType::Type => "type".to_string(),
398 TokenType::Const => "const".to_string(),
403 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
404 /// `IDENT<<u8 as Trait>::AssocTy>`.
406 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
407 /// that `IDENT` is not the ident of a fn trait.
408 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
409 t == &token::ModSep || t == &token::Lt ||
410 t == &token::BinOp(token::Shl)
413 /// Information about the path to a module.
414 pub struct ModulePath {
417 pub result: Result<ModulePathSuccess, Error>,
420 pub struct ModulePathSuccess {
422 pub directory_ownership: DirectoryOwnership,
427 FileNotFoundForModule {
429 default_path: String,
430 secondary_path: String,
435 default_path: String,
436 secondary_path: String,
439 InclusiveRangeWithNoEnd,
443 fn span_err<S: Into<MultiSpan>>(self,
445 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
447 Error::FileNotFoundForModule { ref mod_name,
451 let mut err = struct_span_err!(handler, sp, E0583,
452 "file not found for module `{}`", mod_name);
453 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
459 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
460 let mut err = struct_span_err!(handler, sp, E0584,
461 "file for module `{}` found at both {} and {}",
465 err.help("delete or rename one of them to remove the ambiguity");
468 Error::UselessDocComment => {
469 let mut err = struct_span_err!(handler, sp, E0585,
470 "found a documentation comment that doesn't document anything");
471 err.help("doc comments must come before what they document, maybe a comment was \
472 intended with `//`?");
475 Error::InclusiveRangeWithNoEnd => {
476 let mut err = struct_span_err!(handler, sp, E0586,
477 "inclusive range with no end");
478 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
488 AttributesParsed(ThinVec<Attribute>),
489 AlreadyParsed(P<Expr>),
492 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
493 fn from(o: Option<ThinVec<Attribute>>) -> Self {
494 if let Some(attrs) = o {
495 LhsExpr::AttributesParsed(attrs)
497 LhsExpr::NotYetParsed
502 impl From<P<Expr>> for LhsExpr {
503 fn from(expr: P<Expr>) -> Self {
504 LhsExpr::AlreadyParsed(expr)
508 /// Creates a placeholder argument.
509 fn dummy_arg(span: Span) -> Arg {
510 let ident = Ident::new(keywords::Invalid.name(), span);
512 id: ast::DUMMY_NODE_ID,
513 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
519 id: ast::DUMMY_NODE_ID
521 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal }
524 #[derive(Copy, Clone, Debug)]
525 enum TokenExpectType {
530 impl<'a> Parser<'a> {
531 pub fn new(sess: &'a ParseSess,
533 directory: Option<Directory<'a>>,
534 recurse_into_file_modules: bool,
535 desugar_doc_comments: bool)
537 let mut parser = Parser {
539 token: token::Whitespace,
540 span: syntax_pos::DUMMY_SP,
541 prev_span: syntax_pos::DUMMY_SP,
543 prev_token_kind: PrevTokenKind::Other,
544 restrictions: Restrictions::empty(),
545 recurse_into_file_modules,
546 directory: Directory {
547 path: Cow::from(PathBuf::new()),
548 ownership: DirectoryOwnership::Owned { relative: None }
550 root_module_name: None,
551 expected_tokens: Vec::new(),
552 token_cursor: TokenCursor {
553 frame: TokenCursorFrame::new(
560 desugar_doc_comments,
562 unmatched_angle_bracket_count: 0,
563 max_angle_bracket_count: 0,
564 unclosed_delims: Vec::new(),
565 last_unexpected_token_span: None,
568 let tok = parser.next_tok();
569 parser.token = tok.tok;
570 parser.span = tok.sp;
572 if let Some(directory) = directory {
573 parser.directory = directory;
574 } else if !parser.span.is_dummy() {
575 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
577 parser.directory.path = Cow::from(path);
581 parser.process_potential_macro_variable();
585 fn next_tok(&mut self) -> TokenAndSpan {
586 let mut next = if self.desugar_doc_comments {
587 self.token_cursor.next_desugared()
589 self.token_cursor.next()
591 if next.sp.is_dummy() {
592 // Tweak the location for better diagnostics, but keep syntactic context intact.
593 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
598 /// Converts the current token to a string using `self`'s reader.
599 pub fn this_token_to_string(&self) -> String {
600 pprust::token_to_string(&self.token)
603 fn token_descr(&self) -> Option<&'static str> {
604 Some(match &self.token {
605 t if t.is_special_ident() => "reserved identifier",
606 t if t.is_used_keyword() => "keyword",
607 t if t.is_unused_keyword() => "reserved keyword",
608 token::DocComment(..) => "doc comment",
613 fn this_token_descr(&self) -> String {
614 if let Some(prefix) = self.token_descr() {
615 format!("{} `{}`", prefix, self.this_token_to_string())
617 format!("`{}`", self.this_token_to_string())
621 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
622 let token_str = pprust::token_to_string(t);
623 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
626 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
627 match self.expect_one_of(&[], &[]) {
629 Ok(_) => unreachable!(),
633 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
634 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
635 if self.expected_tokens.is_empty() {
636 if self.token == *t {
640 let token_str = pprust::token_to_string(t);
641 let this_token_str = self.this_token_descr();
642 let mut err = self.fatal(&format!("expected `{}`, found {}",
646 let sp = if self.token == token::Token::Eof {
647 // EOF, don't want to point at the following char, but rather the last token
650 self.sess.source_map().next_point(self.prev_span)
652 let label_exp = format!("expected `{}`", token_str);
653 match self.recover_closing_delimiter(&[t.clone()], err) {
656 return Ok(recovered);
659 let cm = self.sess.source_map();
660 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
661 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
662 // When the spans are in the same line, it means that the only content
663 // between them is whitespace, point only at the found token.
664 err.span_label(self.span, label_exp);
667 err.span_label(sp, label_exp);
668 err.span_label(self.span, "unexpected token");
674 self.expect_one_of(slice::from_ref(t), &[])
678 fn recover_closing_delimiter(
680 tokens: &[token::Token],
681 mut err: DiagnosticBuilder<'a>,
682 ) -> PResult<'a, bool> {
684 // we want to use the last closing delim that would apply
685 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
686 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
687 && Some(self.span) > unmatched.unclosed_span
694 // Recover and assume that the detected unclosed delimiter was meant for
695 // this location. Emit the diagnostic and act as if the delimiter was
696 // present for the parser's sake.
698 // Don't attempt to recover from this unclosed delimiter more than once.
699 let unmatched = self.unclosed_delims.remove(pos);
700 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
702 // We want to suggest the inclusion of the closing delimiter where it makes
703 // the most sense, which is immediately after the last token:
708 // | help: `)` may belong here (FIXME: #58270)
710 // unclosed delimiter
711 if let Some(sp) = unmatched.unclosed_span {
712 err.span_label(sp, "unclosed delimiter");
714 err.span_suggestion_short(
715 self.sess.source_map().next_point(self.prev_span),
716 &format!("{} may belong here", delim.to_string()),
718 Applicability::MaybeIncorrect,
721 self.expected_tokens.clear(); // reduce errors
728 /// Expect next token to be edible or inedible token. If edible,
729 /// then consume it; if inedible, then return without consuming
730 /// anything. Signal a fatal error if next token is unexpected.
731 pub fn expect_one_of(
733 edible: &[token::Token],
734 inedible: &[token::Token],
735 ) -> PResult<'a, bool /* recovered */> {
736 fn tokens_to_string(tokens: &[TokenType]) -> String {
737 let mut i = tokens.iter();
738 // This might be a sign we need a connect method on Iterator.
740 .map_or(String::new(), |t| t.to_string());
741 i.enumerate().fold(b, |mut b, (i, a)| {
742 if tokens.len() > 2 && i == tokens.len() - 2 {
744 } else if tokens.len() == 2 && i == tokens.len() - 2 {
749 b.push_str(&a.to_string());
753 if edible.contains(&self.token) {
756 } else if inedible.contains(&self.token) {
757 // leave it in the input
759 } else if self.last_unexpected_token_span == Some(self.span) {
762 let mut expected = edible.iter()
763 .map(|x| TokenType::Token(x.clone()))
764 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
765 .chain(self.expected_tokens.iter().cloned())
766 .collect::<Vec<_>>();
767 expected.sort_by_cached_key(|x| x.to_string());
769 let expect = tokens_to_string(&expected[..]);
770 let actual = self.this_token_to_string();
771 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
772 let short_expect = if expected.len() > 6 {
773 format!("{} possible tokens", expected.len())
777 (format!("expected one of {}, found `{}`", expect, actual),
778 (self.sess.source_map().next_point(self.prev_span),
779 format!("expected one of {} here", short_expect)))
780 } else if expected.is_empty() {
781 (format!("unexpected token: `{}`", actual),
782 (self.prev_span, "unexpected token after this".to_string()))
784 (format!("expected {}, found `{}`", expect, actual),
785 (self.sess.source_map().next_point(self.prev_span),
786 format!("expected {} here", expect)))
788 self.last_unexpected_token_span = Some(self.span);
789 let mut err = self.fatal(&msg_exp);
790 if self.token.is_ident_named("and") {
791 err.span_suggestion_short(
793 "use `&&` instead of `and` for the boolean operator",
795 Applicability::MaybeIncorrect,
798 if self.token.is_ident_named("or") {
799 err.span_suggestion_short(
801 "use `||` instead of `or` for the boolean operator",
803 Applicability::MaybeIncorrect,
806 let sp = if self.token == token::Token::Eof {
807 // This is EOF, don't want to point at the following char, but rather the last token
812 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
813 TokenType::Token(t) => Some(t.clone()),
815 }).collect::<Vec<_>>(), err) {
818 return Ok(recovered);
822 let is_semi_suggestable = expected.iter().any(|t| match t {
823 TokenType::Token(token::Semi) => true, // we expect a `;` here
825 }) && ( // a `;` would be expected before the current keyword
826 self.token.is_keyword(keywords::Break) ||
827 self.token.is_keyword(keywords::Continue) ||
828 self.token.is_keyword(keywords::For) ||
829 self.token.is_keyword(keywords::If) ||
830 self.token.is_keyword(keywords::Let) ||
831 self.token.is_keyword(keywords::Loop) ||
832 self.token.is_keyword(keywords::Match) ||
833 self.token.is_keyword(keywords::Return) ||
834 self.token.is_keyword(keywords::While)
836 let cm = self.sess.source_map();
837 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
838 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
839 // The spans are in different lines, expected `;` and found `let` or `return`.
840 // High likelihood that it is only a missing `;`.
841 err.span_suggestion_short(
843 "a semicolon may be missing here",
845 Applicability::MaybeIncorrect,
850 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
851 // When the spans are in the same line, it means that the only content between
852 // them is whitespace, point at the found token in that case:
854 // X | () => { syntax error };
855 // | ^^^^^ expected one of 8 possible tokens here
857 // instead of having:
859 // X | () => { syntax error };
860 // | -^^^^^ unexpected token
862 // | expected one of 8 possible tokens here
863 err.span_label(self.span, label_exp);
865 _ if self.prev_span == syntax_pos::DUMMY_SP => {
866 // Account for macro context where the previous span might not be
867 // available to avoid incorrect output (#54841).
868 err.span_label(self.span, "unexpected token");
871 err.span_label(sp, label_exp);
872 err.span_label(self.span, "unexpected token");
879 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
880 fn interpolated_or_expr_span(&self,
881 expr: PResult<'a, P<Expr>>)
882 -> PResult<'a, (Span, P<Expr>)> {
884 if self.prev_token_kind == PrevTokenKind::Interpolated {
892 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
893 let mut err = self.struct_span_err(self.span,
894 &format!("expected identifier, found {}",
895 self.this_token_descr()));
896 if let token::Ident(ident, false) = &self.token {
897 if ident.is_raw_guess() {
900 "you can escape reserved keywords to use them as identifiers",
901 format!("r#{}", ident),
902 Applicability::MaybeIncorrect,
906 if let Some(token_descr) = self.token_descr() {
907 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
909 err.span_label(self.span, "expected identifier");
910 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
915 Applicability::MachineApplicable,
922 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
923 self.parse_ident_common(true)
926 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
928 token::Ident(ident, _) => {
929 if self.token.is_reserved_ident() {
930 let mut err = self.expected_ident_found();
937 let span = self.span;
939 Ok(Ident::new(ident.name, span))
942 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
943 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
945 self.expected_ident_found()
951 /// Checks if the next token is `tok`, and returns `true` if so.
953 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
955 crate fn check(&mut self, tok: &token::Token) -> bool {
956 let is_present = self.token == *tok;
957 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
961 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
962 pub fn eat(&mut self, tok: &token::Token) -> bool {
963 let is_present = self.check(tok);
964 if is_present { self.bump() }
968 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
969 self.expected_tokens.push(TokenType::Keyword(kw));
970 self.token.is_keyword(kw)
973 /// If the next token is the given keyword, eats it and returns
974 /// `true`. Otherwise, returns `false`.
975 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
976 if self.check_keyword(kw) {
984 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
985 if self.token.is_keyword(kw) {
993 /// If the given word is not a keyword, signals an error.
994 /// If the next token is not the given word, signals an error.
995 /// Otherwise, eats it.
996 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
997 if !self.eat_keyword(kw) {
1004 fn check_ident(&mut self) -> bool {
1005 if self.token.is_ident() {
1008 self.expected_tokens.push(TokenType::Ident);
1013 fn check_path(&mut self) -> bool {
1014 if self.token.is_path_start() {
1017 self.expected_tokens.push(TokenType::Path);
1022 fn check_type(&mut self) -> bool {
1023 if self.token.can_begin_type() {
1026 self.expected_tokens.push(TokenType::Type);
1031 fn check_const_arg(&mut self) -> bool {
1032 if self.token.can_begin_const_arg() {
1035 self.expected_tokens.push(TokenType::Const);
1040 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
1041 /// and continues. If a `+` is not seen, returns `false`.
1043 /// This is used when token-splitting `+=` into `+`.
1044 /// See issue #47856 for an example of when this may occur.
1045 fn eat_plus(&mut self) -> bool {
1046 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1048 token::BinOp(token::Plus) => {
1052 token::BinOpEq(token::Plus) => {
1053 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1054 self.bump_with(token::Eq, span);
1062 /// Checks to see if the next token is either `+` or `+=`.
1063 /// Otherwise returns `false`.
1064 fn check_plus(&mut self) -> bool {
1065 if self.token.is_like_plus() {
1069 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1074 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1075 /// `&` and continues. If an `&` is not seen, signals an error.
1076 fn expect_and(&mut self) -> PResult<'a, ()> {
1077 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1079 token::BinOp(token::And) => {
1084 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1085 Ok(self.bump_with(token::BinOp(token::And), span))
1087 _ => self.unexpected()
1091 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1092 /// `|` and continues. If an `|` is not seen, signals an error.
1093 fn expect_or(&mut self) -> PResult<'a, ()> {
1094 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1096 token::BinOp(token::Or) => {
1101 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1102 Ok(self.bump_with(token::BinOp(token::Or), span))
1104 _ => self.unexpected()
1108 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1110 None => {/* everything ok */}
1112 let text = suf.as_str();
1113 if text.is_empty() {
1114 self.span_bug(sp, "found empty literal suffix in Some")
1116 let mut err = if kind == "a tuple index" &&
1117 ["i32", "u32", "isize", "usize"].contains(&text.to_string().as_str())
1119 // #59553: warn instead of reject out of hand to allow the fix to percolate
1120 // through the ecosystem when people fix their macros
1121 let mut err = self.struct_span_warn(
1123 &format!("suffixes on {} are invalid", kind),
1126 "`{}` is *temporarily* accepted on tuple index fields as it was \
1127 incorrectly accepted on stable for a few releases",
1131 "on proc macros, you'll want to use `syn::Index::from` or \
1132 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1133 to tuple field access",
1136 "for more context, see https://github.com/rust-lang/rust/issues/60210",
1140 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1142 err.span_label(sp, format!("invalid suffix `{}`", text));
1148 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1149 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1150 /// and continue. If a `<` is not seen, returns false.
1152 /// This is meant to be used when parsing generics on a path to get the
1154 fn eat_lt(&mut self) -> bool {
1155 self.expected_tokens.push(TokenType::Token(token::Lt));
1156 let ate = match self.token {
1161 token::BinOp(token::Shl) => {
1162 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1163 self.bump_with(token::Lt, span);
1167 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1168 self.bump_with(token::BinOp(token::Minus), span);
1175 // See doc comment for `unmatched_angle_bracket_count`.
1176 self.unmatched_angle_bracket_count += 1;
1177 self.max_angle_bracket_count += 1;
1178 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1184 fn expect_lt(&mut self) -> PResult<'a, ()> {
1192 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1193 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1194 fn expect_gt(&mut self) -> PResult<'a, ()> {
1195 self.expected_tokens.push(TokenType::Token(token::Gt));
1196 let ate = match self.token {
1201 token::BinOp(token::Shr) => {
1202 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1203 Some(self.bump_with(token::Gt, span))
1205 token::BinOpEq(token::Shr) => {
1206 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1207 Some(self.bump_with(token::Ge, span))
1210 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1211 Some(self.bump_with(token::Eq, span))
1218 // See doc comment for `unmatched_angle_bracket_count`.
1219 if self.unmatched_angle_bracket_count > 0 {
1220 self.unmatched_angle_bracket_count -= 1;
1221 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1226 None => self.unexpected(),
1230 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1231 /// passes through any errors encountered. Used for error recovery.
1232 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1233 let handler = self.diagnostic();
1235 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1237 TokenExpectType::Expect,
1238 |p| Ok(p.parse_token_tree())) {
1239 handler.cancel(err);
1243 /// Parses a sequence, including the closing delimiter. The function
1244 /// `f` must consume tokens until reaching the next separator or
1245 /// closing bracket.
1246 pub fn parse_seq_to_end<T, F>(&mut self,
1250 -> PResult<'a, Vec<T>> where
1251 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1253 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1260 /// Parses a sequence, not including the closing delimiter. The function
1261 /// `f` must consume tokens until reaching the next separator or
1262 /// closing bracket.
1263 pub fn parse_seq_to_before_end<T, F>(
1268 ) -> PResult<'a, (Vec<T>, bool)>
1269 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1271 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1274 fn parse_seq_to_before_tokens<T, F>(
1276 kets: &[&token::Token],
1278 expect: TokenExpectType,
1280 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1281 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1283 let mut first = true;
1284 let mut recovered = false;
1286 while !kets.iter().any(|k| {
1288 TokenExpectType::Expect => self.check(k),
1289 TokenExpectType::NoExpect => self.token == **k,
1293 token::CloseDelim(..) | token::Eof => break,
1296 if let Some(ref t) = sep.sep {
1300 match self.expect(t) {
1307 // Attempt to keep parsing if it was a similar separator
1308 if let Some(ref tokens) = t.similar_tokens() {
1309 if tokens.contains(&self.token) {
1314 // Attempt to keep parsing if it was an omitted separator
1329 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1331 TokenExpectType::Expect => self.check(k),
1332 TokenExpectType::NoExpect => self.token == **k,
1345 /// Parses a sequence, including the closing delimiter. The function
1346 /// `f` must consume tokens until reaching the next separator or
1347 /// closing bracket.
1348 fn parse_unspanned_seq<T, F>(
1354 ) -> PResult<'a, Vec<T>> where
1355 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1358 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1365 /// Advance the parser by one token
1366 pub fn bump(&mut self) {
1367 if self.prev_token_kind == PrevTokenKind::Eof {
1368 // Bumping after EOF is a bad sign, usually an infinite loop.
1369 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1372 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1374 // Record last token kind for possible error recovery.
1375 self.prev_token_kind = match self.token {
1376 token::DocComment(..) => PrevTokenKind::DocComment,
1377 token::Comma => PrevTokenKind::Comma,
1378 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1379 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1380 token::Interpolated(..) => PrevTokenKind::Interpolated,
1381 token::Eof => PrevTokenKind::Eof,
1382 token::Ident(..) => PrevTokenKind::Ident,
1383 _ => PrevTokenKind::Other,
1386 let next = self.next_tok();
1387 self.span = next.sp;
1388 self.token = next.tok;
1389 self.expected_tokens.clear();
1390 // check after each token
1391 self.process_potential_macro_variable();
1394 /// Advance the parser using provided token as a next one. Use this when
1395 /// consuming a part of a token. For example a single `<` from `<<`.
1396 fn bump_with(&mut self, next: token::Token, span: Span) {
1397 self.prev_span = self.span.with_hi(span.lo());
1398 // It would be incorrect to record the kind of the current token, but
1399 // fortunately for tokens currently using `bump_with`, the
1400 // prev_token_kind will be of no use anyway.
1401 self.prev_token_kind = PrevTokenKind::Other;
1404 self.expected_tokens.clear();
1407 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1408 F: FnOnce(&token::Token) -> R,
1411 return f(&self.token)
1414 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1415 Some(tree) => match tree {
1416 TokenTree::Token(_, tok) => tok,
1417 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1419 None => token::CloseDelim(self.token_cursor.frame.delim),
1423 fn look_ahead_span(&self, dist: usize) -> Span {
1428 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1429 Some(TokenTree::Token(span, _)) => span,
1430 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1431 None => self.look_ahead_span(dist - 1),
1434 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1435 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1437 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1438 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1440 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1441 err.span_err(sp, self.diagnostic())
1443 fn bug(&self, m: &str) -> ! {
1444 self.sess.span_diagnostic.span_bug(self.span, m)
1446 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1447 self.sess.span_diagnostic.span_err(sp, m)
1449 crate fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1450 self.sess.span_diagnostic.struct_span_err(sp, m)
1452 fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1453 self.sess.span_diagnostic.struct_span_warn(sp, m)
1455 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1456 self.sess.span_diagnostic.span_bug(sp, m)
1459 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1460 self.sess.span_diagnostic.cancel(err)
1463 crate fn diagnostic(&self) -> &'a errors::Handler {
1464 &self.sess.span_diagnostic
1467 /// Is the current token one of the keywords that signals a bare function type?
1468 fn token_is_bare_fn_keyword(&mut self) -> bool {
1469 self.check_keyword(keywords::Fn) ||
1470 self.check_keyword(keywords::Unsafe) ||
1471 self.check_keyword(keywords::Extern)
1474 /// Parses a `TyKind::BareFn` type.
1475 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1478 [unsafe] [extern "ABI"] fn (S) -> T
1488 let unsafety = self.parse_unsafety();
1489 let abi = if self.eat_keyword(keywords::Extern) {
1490 self.parse_opt_abi()?.unwrap_or(Abi::C)
1495 self.expect_keyword(keywords::Fn)?;
1496 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1497 let ret_ty = self.parse_ret_ty(false)?;
1498 let decl = P(FnDecl {
1503 Ok(TyKind::BareFn(P(BareFnTy {
1511 /// Parses asyncness: `async` or nothing.
1512 fn parse_asyncness(&mut self) -> IsAsync {
1513 if self.eat_keyword(keywords::Async) {
1515 closure_id: ast::DUMMY_NODE_ID,
1516 return_impl_trait_id: ast::DUMMY_NODE_ID,
1517 arguments: Vec::new(),
1524 /// Parses unsafety: `unsafe` or nothing.
1525 fn parse_unsafety(&mut self) -> Unsafety {
1526 if self.eat_keyword(keywords::Unsafe) {
1533 /// Parses the items in a trait declaration.
1534 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1535 maybe_whole!(self, NtTraitItem, |x| x);
1536 let attrs = self.parse_outer_attributes()?;
1537 let mut unclosed_delims = vec![];
1538 let (mut item, tokens) = self.collect_tokens(|this| {
1539 let item = this.parse_trait_item_(at_end, attrs);
1540 unclosed_delims.append(&mut this.unclosed_delims);
1543 self.unclosed_delims.append(&mut unclosed_delims);
1544 // See `parse_item` for why this clause is here.
1545 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1546 item.tokens = Some(tokens);
1551 fn parse_trait_item_(&mut self,
1553 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1556 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1557 self.parse_trait_item_assoc_ty()?
1558 } else if self.is_const_item() {
1559 self.expect_keyword(keywords::Const)?;
1560 let ident = self.parse_ident()?;
1561 self.expect(&token::Colon)?;
1562 let ty = self.parse_ty()?;
1563 let default = if self.eat(&token::Eq) {
1564 let expr = self.parse_expr()?;
1565 self.expect(&token::Semi)?;
1568 self.expect(&token::Semi)?;
1571 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1572 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1573 // trait item macro.
1574 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1576 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
1578 let ident = self.parse_ident()?;
1579 let mut generics = self.parse_generics()?;
1581 let mut decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1582 // This is somewhat dubious; We don't want to allow
1583 // argument names to be left off if there is a
1586 // We don't allow argument names to be left off in edition 2018.
1587 p.parse_arg_general(p.span.rust_2018(), true, false)
1589 generics.where_clause = self.parse_where_clause()?;
1590 self.construct_async_arguments(&mut asyncness, &mut decl);
1592 let sig = ast::MethodSig {
1602 let body = match self.token {
1606 debug!("parse_trait_methods(): parsing required method");
1609 token::OpenDelim(token::Brace) => {
1610 debug!("parse_trait_methods(): parsing provided method");
1612 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1613 attrs.extend(inner_attrs.iter().cloned());
1616 token::Interpolated(ref nt) => {
1618 token::NtBlock(..) => {
1620 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1621 attrs.extend(inner_attrs.iter().cloned());
1625 let token_str = self.this_token_descr();
1626 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1628 err.span_label(self.span, "expected `;` or `{`");
1634 let token_str = self.this_token_descr();
1635 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1637 err.span_label(self.span, "expected `;` or `{`");
1641 (ident, ast::TraitItemKind::Method(sig, body), generics)
1645 id: ast::DUMMY_NODE_ID,
1650 span: lo.to(self.prev_span),
1655 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1656 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1657 if self.eat(&token::RArrow) {
1658 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1660 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1665 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1666 self.parse_ty_common(true, true, false)
1669 /// Parses a type in restricted contexts where `+` is not permitted.
1671 /// Example 1: `&'a TYPE`
1672 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1673 /// Example 2: `value1 as TYPE + value2`
1674 /// `+` is prohibited to avoid interactions with expression grammar.
1675 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1676 self.parse_ty_common(false, true, false)
1679 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1680 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1681 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1682 maybe_whole!(self, NtTy, |x| x);
1685 let mut impl_dyn_multi = false;
1686 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1687 // `(TYPE)` is a parenthesized type.
1688 // `(TYPE,)` is a tuple with a single field of type TYPE.
1689 let mut ts = vec![];
1690 let mut last_comma = false;
1691 while self.token != token::CloseDelim(token::Paren) {
1692 ts.push(self.parse_ty()?);
1693 if self.eat(&token::Comma) {
1700 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1701 self.expect(&token::CloseDelim(token::Paren))?;
1703 if ts.len() == 1 && !last_comma {
1704 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1705 let maybe_bounds = allow_plus && self.token.is_like_plus();
1707 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1708 TyKind::Path(None, ref path) if maybe_bounds => {
1709 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1711 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1712 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1713 let path = match bounds[0] {
1714 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1715 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1717 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1720 _ => TyKind::Paren(P(ty))
1725 } else if self.eat(&token::Not) {
1728 } else if self.eat(&token::BinOp(token::Star)) {
1730 TyKind::Ptr(self.parse_ptr()?)
1731 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1733 let t = self.parse_ty()?;
1734 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1735 let t = match self.maybe_parse_fixed_length_of_vec()? {
1736 None => TyKind::Slice(t),
1737 Some(length) => TyKind::Array(t, AnonConst {
1738 id: ast::DUMMY_NODE_ID,
1742 self.expect(&token::CloseDelim(token::Bracket))?;
1744 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1747 self.parse_borrowed_pointee()?
1748 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1750 // In order to not be ambiguous, the type must be surrounded by parens.
1751 self.expect(&token::OpenDelim(token::Paren))?;
1753 id: ast::DUMMY_NODE_ID,
1754 value: self.parse_expr()?,
1756 self.expect(&token::CloseDelim(token::Paren))?;
1758 } else if self.eat_keyword(keywords::Underscore) {
1759 // A type to be inferred `_`
1761 } else if self.token_is_bare_fn_keyword() {
1762 // Function pointer type
1763 self.parse_ty_bare_fn(Vec::new())?
1764 } else if self.check_keyword(keywords::For) {
1765 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1766 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1767 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1769 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1770 if self.token_is_bare_fn_keyword() {
1771 self.parse_ty_bare_fn(lifetime_defs)?
1773 let path = self.parse_path(PathStyle::Type)?;
1774 let parse_plus = allow_plus && self.check_plus();
1775 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1777 } else if self.eat_keyword(keywords::Impl) {
1778 // Always parse bounds greedily for better error recovery.
1779 let bounds = self.parse_generic_bounds(None)?;
1780 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1781 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1782 } else if self.check_keyword(keywords::Dyn) &&
1783 (self.span.rust_2018() ||
1784 self.look_ahead(1, |t| t.can_begin_bound() &&
1785 !can_continue_type_after_non_fn_ident(t))) {
1786 self.bump(); // `dyn`
1787 // Always parse bounds greedily for better error recovery.
1788 let bounds = self.parse_generic_bounds(None)?;
1789 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1790 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1791 } else if self.check(&token::Question) ||
1792 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1793 // Bound list (trait object type)
1794 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1795 TraitObjectSyntax::None)
1796 } else if self.eat_lt() {
1798 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1799 TyKind::Path(Some(qself), path)
1800 } else if self.token.is_path_start() {
1802 let path = self.parse_path(PathStyle::Type)?;
1803 if self.eat(&token::Not) {
1804 // Macro invocation in type position
1805 let (delim, tts) = self.expect_delimited_token_tree()?;
1806 let node = Mac_ { path, tts, delim };
1807 TyKind::Mac(respan(lo.to(self.prev_span), node))
1809 // Just a type path or bound list (trait object type) starting with a trait.
1811 // `Trait1 + Trait2 + 'a`
1812 if allow_plus && self.check_plus() {
1813 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1815 TyKind::Path(None, path)
1818 } else if self.check(&token::DotDotDot) {
1819 if allow_c_variadic {
1820 self.eat(&token::DotDotDot);
1823 return Err(self.fatal(
1824 "only foreign functions are allowed to be C-variadic"
1828 let msg = format!("expected type, found {}", self.this_token_descr());
1829 return Err(self.fatal(&msg));
1832 let span = lo.to(self.prev_span);
1833 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1835 // Try to recover from use of `+` with incorrect priority.
1836 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1837 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1838 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1841 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1842 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1843 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1844 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1846 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1847 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1849 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1852 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1853 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1854 let mutbl = self.parse_mutability();
1855 let ty = self.parse_ty_no_plus()?;
1856 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1859 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1860 let mutbl = if self.eat_keyword(keywords::Mut) {
1862 } else if self.eat_keyword(keywords::Const) {
1863 Mutability::Immutable
1865 let span = self.prev_span;
1866 let msg = "expected mut or const in raw pointer type";
1867 self.struct_span_err(span, msg)
1868 .span_label(span, msg)
1869 .help("use `*mut T` or `*const T` as appropriate")
1871 Mutability::Immutable
1873 let t = self.parse_ty_no_plus()?;
1874 Ok(MutTy { ty: t, mutbl: mutbl })
1877 fn is_named_argument(&mut self) -> bool {
1878 let offset = match self.token {
1879 token::Interpolated(ref nt) => match **nt {
1880 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1883 token::BinOp(token::And) | token::AndAnd => 1,
1884 _ if self.token.is_keyword(keywords::Mut) => 1,
1888 self.look_ahead(offset, |t| t.is_ident()) &&
1889 self.look_ahead(offset + 1, |t| t == &token::Colon)
1892 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1894 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1895 if let token::DocComment(_) = self.token {
1896 let mut err = self.diagnostic().struct_span_err(
1898 &format!("documentation comments cannot be applied to {}", applied_to),
1900 err.span_label(self.span, "doc comments are not allowed here");
1903 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1904 *t == token::OpenDelim(token::Bracket)
1907 // Skip every token until next possible arg.
1908 while self.token != token::CloseDelim(token::Bracket) {
1911 let sp = lo.to(self.span);
1913 let mut err = self.diagnostic().struct_span_err(
1915 &format!("attributes cannot be applied to {}", applied_to),
1917 err.span_label(sp, "attributes are not allowed here");
1922 /// This version of parse arg doesn't necessarily require identifier names.
1923 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
1924 allow_c_variadic: bool) -> PResult<'a, Arg> {
1925 maybe_whole!(self, NtArg, |x| x);
1927 if let Ok(Some(_)) = self.parse_self_arg() {
1928 let mut err = self.struct_span_err(self.prev_span,
1929 "unexpected `self` argument in function");
1930 err.span_label(self.prev_span,
1931 "`self` is only valid as the first argument of an associated function");
1935 let (pat, ty) = if require_name || self.is_named_argument() {
1936 debug!("parse_arg_general parse_pat (require_name:{})",
1938 self.eat_incorrect_doc_comment("method arguments");
1939 let pat = self.parse_pat(Some("argument name"))?;
1941 if let Err(mut err) = self.expect(&token::Colon) {
1942 // If we find a pattern followed by an identifier, it could be an (incorrect)
1943 // C-style parameter declaration.
1944 if self.check_ident() && self.look_ahead(1, |t| {
1945 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1947 let ident = self.parse_ident().unwrap();
1948 let span = pat.span.with_hi(ident.span.hi());
1950 err.span_suggestion(
1952 "declare the type after the parameter binding",
1953 String::from("<identifier>: <type>"),
1954 Applicability::HasPlaceholders,
1956 } else if require_name && is_trait_item {
1957 if let PatKind::Ident(_, ident, _) = pat.node {
1958 err.span_suggestion(
1960 "explicitly ignore parameter",
1961 format!("_: {}", ident),
1962 Applicability::MachineApplicable,
1966 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1972 self.eat_incorrect_doc_comment("a method argument's type");
1973 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1975 debug!("parse_arg_general ident_to_pat");
1976 let parser_snapshot_before_ty = self.clone();
1977 self.eat_incorrect_doc_comment("a method argument's type");
1978 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1979 if ty.is_ok() && self.token != token::Comma &&
1980 self.token != token::CloseDelim(token::Paren) {
1981 // This wasn't actually a type, but a pattern looking like a type,
1982 // so we are going to rollback and re-parse for recovery.
1983 ty = self.unexpected();
1987 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1989 id: ast::DUMMY_NODE_ID,
1990 node: PatKind::Ident(
1991 BindingMode::ByValue(Mutability::Immutable), ident, None),
1997 // If this is a C-variadic argument and we hit an error, return the
1999 if self.token == token::DotDotDot {
2002 // Recover from attempting to parse the argument as a type without pattern.
2004 mem::replace(self, parser_snapshot_before_ty);
2005 let pat = self.parse_pat(Some("argument name"))?;
2006 self.expect(&token::Colon)?;
2007 let ty = self.parse_ty()?;
2009 let mut err = self.diagnostic().struct_span_err_with_code(
2011 "patterns aren't allowed in methods without bodies",
2012 DiagnosticId::Error("E0642".into()),
2014 err.span_suggestion_short(
2016 "give this argument a name or use an underscore to ignore it",
2018 Applicability::MachineApplicable,
2022 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2024 node: PatKind::Wild,
2026 id: ast::DUMMY_NODE_ID
2033 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
2036 /// Parses a single function argument.
2037 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2038 self.parse_arg_general(true, false, false)
2041 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2042 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2043 let pat = self.parse_pat(Some("argument name"))?;
2044 let t = if self.eat(&token::Colon) {
2048 id: ast::DUMMY_NODE_ID,
2049 node: TyKind::Infer,
2050 span: self.prev_span,
2056 id: ast::DUMMY_NODE_ID,
2057 source: ast::ArgSource::Normal,
2061 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2062 if self.eat(&token::Semi) {
2063 Ok(Some(self.parse_expr()?))
2069 /// Matches `token_lit = LIT_INTEGER | ...`.
2070 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2071 let out = match self.token {
2072 token::Interpolated(ref nt) => match **nt {
2073 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2074 ExprKind::Lit(ref lit) => { lit.node.clone() }
2075 _ => { return self.unexpected_last(&self.token); }
2077 _ => { return self.unexpected_last(&self.token); }
2079 token::Literal(lit, suf) => {
2080 let diag = Some((self.span, &self.sess.span_diagnostic));
2081 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2085 self.expect_no_suffix(sp, &format!("a {}", lit.literal_name()), suf)
2090 token::Dot if self.look_ahead(1, |t| match t {
2091 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2093 }) => { // recover from `let x = .4;`
2096 if let token::Literal(
2097 parse::token::Lit::Integer(val),
2100 let suffix = suffix.and_then(|s| {
2104 } else if s == "f64" {
2111 let sp = lo.to(self.prev_span);
2112 let mut err = self.diagnostic()
2113 .struct_span_err(sp, "float literals must have an integer part");
2114 err.span_suggestion(
2116 "must have an integer part",
2117 format!("0.{}{}", val, suffix),
2118 Applicability::MachineApplicable,
2121 return Ok(match suffix {
2122 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2123 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2124 _ => ast::LitKind::FloatUnsuffixed(val),
2130 _ => { return self.unexpected_last(&self.token); }
2137 /// Matches `lit = true | false | token_lit`.
2138 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2140 let lit = if self.eat_keyword(keywords::True) {
2142 } else if self.eat_keyword(keywords::False) {
2143 LitKind::Bool(false)
2145 let lit = self.parse_lit_token()?;
2148 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2151 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2152 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2153 maybe_whole_expr!(self);
2155 let minus_lo = self.span;
2156 let minus_present = self.eat(&token::BinOp(token::Minus));
2158 let literal = self.parse_lit()?;
2159 let hi = self.prev_span;
2160 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2163 let minus_hi = self.prev_span;
2164 let unary = self.mk_unary(UnOp::Neg, expr);
2165 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2171 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2173 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2174 let span = self.span;
2176 Ok(Ident::new(ident.name, span))
2178 _ => self.parse_ident(),
2182 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2184 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2185 let span = self.span;
2187 Ok(Ident::new(ident.name, span))
2189 _ => self.parse_ident(),
2193 /// Parses a qualified path.
2194 /// Assumes that the leading `<` has been parsed already.
2196 /// `qualified_path = <type [as trait_ref]>::path`
2201 /// `<T as U>::F::a<S>` (without disambiguator)
2202 /// `<T as U>::F::a::<S>` (with disambiguator)
2203 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2204 let lo = self.prev_span;
2205 let ty = self.parse_ty()?;
2207 // `path` will contain the prefix of the path up to the `>`,
2208 // if any (e.g., `U` in the `<T as U>::*` examples
2209 // above). `path_span` has the span of that path, or an empty
2210 // span in the case of something like `<T>::Bar`.
2211 let (mut path, path_span);
2212 if self.eat_keyword(keywords::As) {
2213 let path_lo = self.span;
2214 path = self.parse_path(PathStyle::Type)?;
2215 path_span = path_lo.to(self.prev_span);
2217 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2218 path_span = self.span.to(self.span);
2221 // See doc comment for `unmatched_angle_bracket_count`.
2222 self.expect(&token::Gt)?;
2223 if self.unmatched_angle_bracket_count > 0 {
2224 self.unmatched_angle_bracket_count -= 1;
2225 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2228 self.expect(&token::ModSep)?;
2230 let qself = QSelf { ty, path_span, position: path.segments.len() };
2231 self.parse_path_segments(&mut path.segments, style)?;
2233 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2236 /// Parses simple paths.
2238 /// `path = [::] segment+`
2239 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2242 /// `a::b::C<D>` (without disambiguator)
2243 /// `a::b::C::<D>` (with disambiguator)
2244 /// `Fn(Args)` (without disambiguator)
2245 /// `Fn::(Args)` (with disambiguator)
2246 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2247 maybe_whole!(self, NtPath, |path| {
2248 if style == PathStyle::Mod &&
2249 path.segments.iter().any(|segment| segment.args.is_some()) {
2250 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2255 let lo = self.meta_var_span.unwrap_or(self.span);
2256 let mut segments = Vec::new();
2257 let mod_sep_ctxt = self.span.ctxt();
2258 if self.eat(&token::ModSep) {
2259 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2261 self.parse_path_segments(&mut segments, style)?;
2263 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2266 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2267 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2269 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2270 let meta_ident = match self.token {
2271 token::Interpolated(ref nt) => match **nt {
2272 token::NtMeta(ref meta) => match meta.node {
2273 ast::MetaItemKind::Word => Some(meta.path.clone()),
2280 if let Some(path) = meta_ident {
2284 self.parse_path(style)
2287 crate fn parse_path_segments(&mut self,
2288 segments: &mut Vec<PathSegment>,
2290 -> PResult<'a, ()> {
2292 let segment = self.parse_path_segment(style)?;
2293 if style == PathStyle::Expr {
2294 // In order to check for trailing angle brackets, we must have finished
2295 // recursing (`parse_path_segment` can indirectly call this function),
2296 // that is, the next token must be the highlighted part of the below example:
2298 // `Foo::<Bar as Baz<T>>::Qux`
2301 // As opposed to the below highlight (if we had only finished the first
2304 // `Foo::<Bar as Baz<T>>::Qux`
2307 // `PathStyle::Expr` is only provided at the root invocation and never in
2308 // `parse_path_segment` to recurse and therefore can be checked to maintain
2310 self.check_trailing_angle_brackets(&segment, token::ModSep);
2312 segments.push(segment);
2314 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2320 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2321 let ident = self.parse_path_segment_ident()?;
2323 let is_args_start = |token: &token::Token| match *token {
2324 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
2325 | token::LArrow => true,
2328 let check_args_start = |this: &mut Self| {
2329 this.expected_tokens.extend_from_slice(
2330 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2332 is_args_start(&this.token)
2335 Ok(if style == PathStyle::Type && check_args_start(self) ||
2336 style != PathStyle::Mod && self.check(&token::ModSep)
2337 && self.look_ahead(1, |t| is_args_start(t)) {
2338 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2339 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2340 // parsing a new path.
2341 if style == PathStyle::Expr {
2342 self.unmatched_angle_bracket_count = 0;
2343 self.max_angle_bracket_count = 0;
2346 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2347 self.eat(&token::ModSep);
2349 let args = if self.eat_lt() {
2351 let (args, bindings) =
2352 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2354 let span = lo.to(self.prev_span);
2355 AngleBracketedArgs { args, bindings, span }.into()
2359 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2360 &[&token::CloseDelim(token::Paren)],
2361 SeqSep::trailing_allowed(token::Comma),
2362 TokenExpectType::Expect,
2367 let span = lo.to(self.prev_span);
2368 let output = if self.eat(&token::RArrow) {
2369 Some(self.parse_ty_common(false, false, false)?)
2373 ParenthesizedArgs { inputs, output, span }.into()
2376 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2378 // Generic arguments are not found.
2379 PathSegment::from_ident(ident)
2383 crate fn check_lifetime(&mut self) -> bool {
2384 self.expected_tokens.push(TokenType::Lifetime);
2385 self.token.is_lifetime()
2388 /// Parses a single lifetime `'a` or panics.
2389 crate fn expect_lifetime(&mut self) -> Lifetime {
2390 if let Some(ident) = self.token.lifetime() {
2391 let span = self.span;
2393 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2395 self.span_bug(self.span, "not a lifetime")
2399 fn eat_label(&mut self) -> Option<Label> {
2400 if let Some(ident) = self.token.lifetime() {
2401 let span = self.span;
2403 Some(Label { ident: Ident::new(ident.name, span) })
2409 /// Parses mutability (`mut` or nothing).
2410 fn parse_mutability(&mut self) -> Mutability {
2411 if self.eat_keyword(keywords::Mut) {
2414 Mutability::Immutable
2418 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2419 if let token::Literal(token::Integer(name), suffix) = self.token {
2420 self.expect_no_suffix(self.span, "a tuple index", suffix);
2422 Ok(Ident::new(name, self.prev_span))
2424 self.parse_ident_common(false)
2428 /// Parse ident (COLON expr)?
2429 fn parse_field(&mut self) -> PResult<'a, Field> {
2430 let attrs = self.parse_outer_attributes()?;
2433 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2434 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2435 t == &token::Colon || t == &token::Eq
2437 let fieldname = self.parse_field_name()?;
2439 // Check for an equals token. This means the source incorrectly attempts to
2440 // initialize a field with an eq rather than a colon.
2441 if self.token == token::Eq {
2443 .struct_span_err(self.span, "expected `:`, found `=`")
2445 fieldname.span.shrink_to_hi().to(self.span),
2446 "replace equals symbol with a colon",
2448 Applicability::MachineApplicable,
2453 (fieldname, self.parse_expr()?, false)
2455 let fieldname = self.parse_ident_common(false)?;
2457 // Mimic `x: x` for the `x` field shorthand.
2458 let path = ast::Path::from_ident(fieldname);
2459 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2460 (fieldname, expr, true)
2464 span: lo.to(expr.span),
2467 attrs: attrs.into(),
2471 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2472 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2475 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2476 ExprKind::Unary(unop, expr)
2479 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2480 ExprKind::Binary(binop, lhs, rhs)
2483 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2484 ExprKind::Call(f, args)
2487 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2488 ExprKind::Index(expr, idx)
2491 fn mk_range(&mut self,
2492 start: Option<P<Expr>>,
2493 end: Option<P<Expr>>,
2494 limits: RangeLimits)
2495 -> PResult<'a, ast::ExprKind> {
2496 if end.is_none() && limits == RangeLimits::Closed {
2497 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2499 Ok(ExprKind::Range(start, end, limits))
2503 fn mk_assign_op(&mut self, binop: ast::BinOp,
2504 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2505 ExprKind::AssignOp(binop, lhs, rhs)
2508 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2509 let delim = match self.token {
2510 token::OpenDelim(delim) => delim,
2512 let msg = "expected open delimiter";
2513 let mut err = self.fatal(msg);
2514 err.span_label(self.span, msg);
2518 let tts = match self.parse_token_tree() {
2519 TokenTree::Delimited(_, _, tts) => tts,
2520 _ => unreachable!(),
2522 let delim = match delim {
2523 token::Paren => MacDelimiter::Parenthesis,
2524 token::Bracket => MacDelimiter::Bracket,
2525 token::Brace => MacDelimiter::Brace,
2526 token::NoDelim => self.bug("unexpected no delimiter"),
2528 Ok((delim, tts.into()))
2531 /// At the bottom (top?) of the precedence hierarchy,
2532 /// Parses things like parenthesized exprs, macros, `return`, etc.
2534 /// N.B., this does not parse outer attributes, and is private because it only works
2535 /// correctly if called from `parse_dot_or_call_expr()`.
2536 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2537 maybe_recover_from_interpolated_ty_qpath!(self, true);
2538 maybe_whole_expr!(self);
2540 // Outer attributes are already parsed and will be
2541 // added to the return value after the fact.
2543 // Therefore, prevent sub-parser from parsing
2544 // attributes by giving them a empty "already parsed" list.
2545 let mut attrs = ThinVec::new();
2548 let mut hi = self.span;
2552 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2554 token::OpenDelim(token::Paren) => {
2557 attrs.extend(self.parse_inner_attributes()?);
2559 // (e) is parenthesized e
2560 // (e,) is a tuple with only one field, e
2561 let mut es = vec![];
2562 let mut trailing_comma = false;
2563 let mut recovered = false;
2564 while self.token != token::CloseDelim(token::Paren) {
2565 es.push(match self.parse_expr() {
2568 // recover from parse error in tuple list
2569 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2572 recovered = self.expect_one_of(
2574 &[token::Comma, token::CloseDelim(token::Paren)],
2576 if self.eat(&token::Comma) {
2577 trailing_comma = true;
2579 trailing_comma = false;
2587 hi = self.prev_span;
2588 ex = if es.len() == 1 && !trailing_comma {
2589 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2594 token::OpenDelim(token::Brace) => {
2595 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2597 token::BinOp(token::Or) | token::OrOr => {
2598 return self.parse_lambda_expr(attrs);
2600 token::OpenDelim(token::Bracket) => {
2603 attrs.extend(self.parse_inner_attributes()?);
2605 if self.eat(&token::CloseDelim(token::Bracket)) {
2607 ex = ExprKind::Array(Vec::new());
2610 let first_expr = self.parse_expr()?;
2611 if self.eat(&token::Semi) {
2612 // Repeating array syntax: [ 0; 512 ]
2613 let count = AnonConst {
2614 id: ast::DUMMY_NODE_ID,
2615 value: self.parse_expr()?,
2617 self.expect(&token::CloseDelim(token::Bracket))?;
2618 ex = ExprKind::Repeat(first_expr, count);
2619 } else if self.eat(&token::Comma) {
2620 // Vector with two or more elements.
2621 let remaining_exprs = self.parse_seq_to_end(
2622 &token::CloseDelim(token::Bracket),
2623 SeqSep::trailing_allowed(token::Comma),
2624 |p| Ok(p.parse_expr()?)
2626 let mut exprs = vec![first_expr];
2627 exprs.extend(remaining_exprs);
2628 ex = ExprKind::Array(exprs);
2630 // Vector with one element.
2631 self.expect(&token::CloseDelim(token::Bracket))?;
2632 ex = ExprKind::Array(vec![first_expr]);
2635 hi = self.prev_span;
2639 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2641 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2643 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2645 if self.is_async_block() { // check for `async {` and `async move {`
2646 return self.parse_async_block(attrs);
2648 return self.parse_lambda_expr(attrs);
2651 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2652 return self.parse_lambda_expr(attrs);
2654 if self.eat_keyword(keywords::If) {
2655 return self.parse_if_expr(attrs);
2657 if self.eat_keyword(keywords::For) {
2658 let lo = self.prev_span;
2659 return self.parse_for_expr(None, lo, attrs);
2661 if self.eat_keyword(keywords::While) {
2662 let lo = self.prev_span;
2663 return self.parse_while_expr(None, lo, attrs);
2665 if let Some(label) = self.eat_label() {
2666 let lo = label.ident.span;
2667 self.expect(&token::Colon)?;
2668 if self.eat_keyword(keywords::While) {
2669 return self.parse_while_expr(Some(label), lo, attrs)
2671 if self.eat_keyword(keywords::For) {
2672 return self.parse_for_expr(Some(label), lo, attrs)
2674 if self.eat_keyword(keywords::Loop) {
2675 return self.parse_loop_expr(Some(label), lo, attrs)
2677 if self.token == token::OpenDelim(token::Brace) {
2678 return self.parse_block_expr(Some(label),
2680 BlockCheckMode::Default,
2683 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2684 let mut err = self.fatal(msg);
2685 err.span_label(self.span, msg);
2688 if self.eat_keyword(keywords::Loop) {
2689 let lo = self.prev_span;
2690 return self.parse_loop_expr(None, lo, attrs);
2692 if self.eat_keyword(keywords::Continue) {
2693 let label = self.eat_label();
2694 let ex = ExprKind::Continue(label);
2695 let hi = self.prev_span;
2696 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2698 if self.eat_keyword(keywords::Match) {
2699 let match_sp = self.prev_span;
2700 return self.parse_match_expr(attrs).map_err(|mut err| {
2701 err.span_label(match_sp, "while parsing this match expression");
2705 if self.eat_keyword(keywords::Unsafe) {
2706 return self.parse_block_expr(
2709 BlockCheckMode::Unsafe(ast::UserProvided),
2712 if self.is_do_catch_block() {
2713 let mut db = self.fatal("found removed `do catch` syntax");
2714 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2717 if self.is_try_block() {
2719 assert!(self.eat_keyword(keywords::Try));
2720 return self.parse_try_block(lo, attrs);
2722 if self.eat_keyword(keywords::Return) {
2723 if self.token.can_begin_expr() {
2724 let e = self.parse_expr()?;
2726 ex = ExprKind::Ret(Some(e));
2728 ex = ExprKind::Ret(None);
2730 } else if self.eat_keyword(keywords::Break) {
2731 let label = self.eat_label();
2732 let e = if self.token.can_begin_expr()
2733 && !(self.token == token::OpenDelim(token::Brace)
2734 && self.restrictions.contains(
2735 Restrictions::NO_STRUCT_LITERAL)) {
2736 Some(self.parse_expr()?)
2740 ex = ExprKind::Break(label, e);
2741 hi = self.prev_span;
2742 } else if self.eat_keyword(keywords::Yield) {
2743 if self.token.can_begin_expr() {
2744 let e = self.parse_expr()?;
2746 ex = ExprKind::Yield(Some(e));
2748 ex = ExprKind::Yield(None);
2750 } else if self.token.is_keyword(keywords::Let) {
2751 // Catch this syntax error here, instead of in `parse_ident`, so
2752 // that we can explicitly mention that let is not to be used as an expression
2753 let mut db = self.fatal("expected expression, found statement (`let`)");
2754 db.span_label(self.span, "expected expression");
2755 db.note("variable declaration using `let` is a statement");
2757 } else if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
2758 // FIXME: remove this branch when `await!` is no longer supported
2759 // https://github.com/rust-lang/rust/issues/60610
2760 self.expect(&token::Not)?;
2761 self.expect(&token::OpenDelim(token::Paren))?;
2762 let expr = self.parse_expr()?;
2763 self.expect(&token::CloseDelim(token::Paren))?;
2764 ex = ExprKind::Await(ast::AwaitOrigin::MacroLike, expr);
2765 } else if self.token.is_path_start() {
2766 let path = self.parse_path(PathStyle::Expr)?;
2768 // `!`, as an operator, is prefix, so we know this isn't that
2769 if self.eat(&token::Not) {
2770 // MACRO INVOCATION expression
2771 let (delim, tts) = self.expect_delimited_token_tree()?;
2772 hi = self.prev_span;
2773 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2774 } else if self.check(&token::OpenDelim(token::Brace)) {
2775 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2779 ex = ExprKind::Path(None, path);
2783 ex = ExprKind::Path(None, path);
2786 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2787 // Don't complain about bare semicolons after unclosed braces
2788 // recovery in order to keep the error count down. Fixing the
2789 // delimiters will possibly also fix the bare semicolon found in
2790 // expression context. For example, silence the following error:
2792 // error: expected expression, found `;`
2796 // | ^ expected expression
2799 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2801 match self.parse_literal_maybe_minus() {
2804 ex = expr.node.clone();
2807 self.cancel(&mut err);
2808 let msg = format!("expected expression, found {}",
2809 self.this_token_descr());
2810 let mut err = self.fatal(&msg);
2811 let sp = self.sess.source_map().start_point(self.span);
2812 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow()
2815 self.sess.expr_parentheses_needed(&mut err, *sp, None);
2817 err.span_label(self.span, "expected expression");
2825 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2826 self.maybe_recover_from_bad_qpath(expr, true)
2829 fn maybe_parse_struct_expr(
2833 attrs: &ThinVec<Attribute>,
2834 ) -> Option<PResult<'a, P<Expr>>> {
2835 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2836 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2837 // `{ ident, ` cannot start a block
2838 self.look_ahead(2, |t| t == &token::Comma) ||
2839 self.look_ahead(2, |t| t == &token::Colon) && (
2840 // `{ ident: token, ` cannot start a block
2841 self.look_ahead(4, |t| t == &token::Comma) ||
2842 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2843 self.look_ahead(3, |t| !t.can_begin_type())
2847 if struct_allowed || certainly_not_a_block() {
2848 // This is a struct literal, but we don't can't accept them here
2849 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2850 if let (Ok(expr), false) = (&expr, struct_allowed) {
2851 let mut err = self.diagnostic().struct_span_err(
2853 "struct literals are not allowed here",
2855 err.multipart_suggestion(
2856 "surround the struct literal with parentheses",
2858 (lo.shrink_to_lo(), "(".to_string()),
2859 (expr.span.shrink_to_hi(), ")".to_string()),
2861 Applicability::MachineApplicable,
2870 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2871 -> PResult<'a, P<Expr>> {
2872 let struct_sp = lo.to(self.prev_span);
2874 let mut fields = Vec::new();
2875 let mut base = None;
2877 attrs.extend(self.parse_inner_attributes()?);
2879 while self.token != token::CloseDelim(token::Brace) {
2880 if self.eat(&token::DotDot) {
2881 let exp_span = self.prev_span;
2882 match self.parse_expr() {
2888 self.recover_stmt();
2891 if self.token == token::Comma {
2892 let mut err = self.sess.span_diagnostic.mut_span_err(
2893 exp_span.to(self.prev_span),
2894 "cannot use a comma after the base struct",
2896 err.span_suggestion_short(
2898 "remove this comma",
2900 Applicability::MachineApplicable
2902 err.note("the base struct must always be the last field");
2904 self.recover_stmt();
2909 let mut recovery_field = None;
2910 if let token::Ident(ident, _) = self.token {
2911 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2912 // Use in case of error after field-looking code: `S { foo: () with a }`
2913 let mut ident = ident.clone();
2914 ident.span = self.span;
2915 recovery_field = Some(ast::Field {
2918 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2919 is_shorthand: false,
2920 attrs: ThinVec::new(),
2924 let mut parsed_field = None;
2925 match self.parse_field() {
2926 Ok(f) => parsed_field = Some(f),
2928 e.span_label(struct_sp, "while parsing this struct");
2931 // If the next token is a comma, then try to parse
2932 // what comes next as additional fields, rather than
2933 // bailing out until next `}`.
2934 if self.token != token::Comma {
2935 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2936 if self.token != token::Comma {
2943 match self.expect_one_of(&[token::Comma],
2944 &[token::CloseDelim(token::Brace)]) {
2945 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2946 // only include the field if there's no parse error for the field name
2950 if let Some(f) = recovery_field {
2953 e.span_label(struct_sp, "while parsing this struct");
2955 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2956 self.eat(&token::Comma);
2961 let span = lo.to(self.span);
2962 self.expect(&token::CloseDelim(token::Brace))?;
2963 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2966 fn parse_or_use_outer_attributes(&mut self,
2967 already_parsed_attrs: Option<ThinVec<Attribute>>)
2968 -> PResult<'a, ThinVec<Attribute>> {
2969 if let Some(attrs) = already_parsed_attrs {
2972 self.parse_outer_attributes().map(|a| a.into())
2976 /// Parses a block or unsafe block.
2977 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2978 lo: Span, blk_mode: BlockCheckMode,
2979 outer_attrs: ThinVec<Attribute>)
2980 -> PResult<'a, P<Expr>> {
2981 self.expect(&token::OpenDelim(token::Brace))?;
2983 let mut attrs = outer_attrs;
2984 attrs.extend(self.parse_inner_attributes()?);
2986 let blk = self.parse_block_tail(lo, blk_mode)?;
2987 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2990 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2991 fn parse_dot_or_call_expr(&mut self,
2992 already_parsed_attrs: Option<ThinVec<Attribute>>)
2993 -> PResult<'a, P<Expr>> {
2994 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2996 let b = self.parse_bottom_expr();
2997 let (span, b) = self.interpolated_or_expr_span(b)?;
2998 self.parse_dot_or_call_expr_with(b, span, attrs)
3001 fn parse_dot_or_call_expr_with(&mut self,
3004 mut attrs: ThinVec<Attribute>)
3005 -> PResult<'a, P<Expr>> {
3006 // Stitch the list of outer attributes onto the return value.
3007 // A little bit ugly, but the best way given the current code
3009 self.parse_dot_or_call_expr_with_(e0, lo)
3011 expr.map(|mut expr| {
3012 attrs.extend::<Vec<_>>(expr.attrs.into());
3015 ExprKind::If(..) | ExprKind::IfLet(..) => {
3016 if !expr.attrs.is_empty() {
3017 // Just point to the first attribute in there...
3018 let span = expr.attrs[0].span;
3021 "attributes are not yet allowed on `if` \
3032 // Assuming we have just parsed `.`, continue parsing into an expression.
3033 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3034 if self.span.rust_2018() && self.eat_keyword(keywords::Await) {
3035 let span = lo.to(self.prev_span);
3036 let await_expr = self.mk_expr(
3038 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
3041 return Ok(await_expr);
3043 let segment = self.parse_path_segment(PathStyle::Expr)?;
3044 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3046 Ok(match self.token {
3047 token::OpenDelim(token::Paren) => {
3048 // Method call `expr.f()`
3049 let mut args = self.parse_unspanned_seq(
3050 &token::OpenDelim(token::Paren),
3051 &token::CloseDelim(token::Paren),
3052 SeqSep::trailing_allowed(token::Comma),
3053 |p| Ok(p.parse_expr()?)
3055 args.insert(0, self_arg);
3057 let span = lo.to(self.prev_span);
3058 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3061 // Field access `expr.f`
3062 if let Some(args) = segment.args {
3063 self.span_err(args.span(),
3064 "field expressions may not have generic arguments");
3067 let span = lo.to(self.prev_span);
3068 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3073 /// This function checks if there are trailing angle brackets and produces
3074 /// a diagnostic to suggest removing them.
3076 /// ```ignore (diagnostic)
3077 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3078 /// ^^ help: remove extra angle brackets
3080 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3081 // This function is intended to be invoked after parsing a path segment where there are two
3084 // 1. A specific token is expected after the path segment.
3085 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3086 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3087 // 2. No specific token is expected after the path segment.
3088 // eg. `x.foo` (field access)
3090 // This function is called after parsing `.foo` and before parsing the token `end` (if
3091 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3094 // We only care about trailing angle brackets if we previously parsed angle bracket
3095 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3096 // removed in this case:
3098 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3100 // This case is particularly tricky as we won't notice it just looking at the tokens -
3101 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3102 // have already been parsed):
3104 // `x.foo::<u32>>>(3)`
3105 let parsed_angle_bracket_args = segment.args
3107 .map(|args| args.is_angle_bracketed())
3111 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3112 parsed_angle_bracket_args,
3114 if !parsed_angle_bracket_args {
3118 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3122 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3123 // (since we might have the field access case and the characters we're eating are
3124 // actual operators and not trailing characters - ie `x.foo >> 3`).
3125 let mut position = 0;
3127 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3128 // many of each (so we can correctly pluralize our error messages) and continue to
3130 let mut number_of_shr = 0;
3131 let mut number_of_gt = 0;
3132 while self.look_ahead(position, |t| {
3133 trace!("check_trailing_angle_brackets: t={:?}", t);
3134 if *t == token::BinOp(token::BinOpToken::Shr) {
3137 } else if *t == token::Gt {
3147 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3149 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3150 number_of_gt, number_of_shr,
3152 if number_of_gt < 1 && number_of_shr < 1 {
3156 // Finally, double check that we have our end token as otherwise this is the
3158 if self.look_ahead(position, |t| {
3159 trace!("check_trailing_angle_brackets: t={:?}", t);
3162 // Eat from where we started until the end token so that parsing can continue
3163 // as if we didn't have those extra angle brackets.
3164 self.eat_to_tokens(&[&end]);
3165 let span = lo.until(self.span);
3167 let plural = number_of_gt > 1 || number_of_shr >= 1;
3171 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3175 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3177 Applicability::MachineApplicable,
3183 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3188 while self.eat(&token::Question) {
3189 let hi = self.prev_span;
3190 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3194 if self.eat(&token::Dot) {
3196 token::Ident(..) => {
3197 e = self.parse_dot_suffix(e, lo)?;
3199 token::Literal(token::Integer(name), suffix) => {
3200 let span = self.span;
3202 let field = ExprKind::Field(e, Ident::new(name, span));
3203 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3205 self.expect_no_suffix(span, "a tuple index", suffix);
3207 token::Literal(token::Float(n), _suf) => {
3209 let fstr = n.as_str();
3210 let mut err = self.diagnostic()
3211 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3212 err.span_label(self.prev_span, "unexpected token");
3213 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3214 let float = match fstr.parse::<f64>().ok() {
3218 let sugg = pprust::to_string(|s| {
3219 use crate::print::pprust::PrintState;
3223 s.print_usize(float.trunc() as usize)?;
3226 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3228 err.span_suggestion(
3229 lo.to(self.prev_span),
3230 "try parenthesizing the first index",
3232 Applicability::MachineApplicable
3239 // FIXME Could factor this out into non_fatal_unexpected or something.
3240 let actual = self.this_token_to_string();
3241 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3246 if self.expr_is_complete(&e) { break; }
3249 token::OpenDelim(token::Paren) => {
3250 let seq = self.parse_unspanned_seq(
3251 &token::OpenDelim(token::Paren),
3252 &token::CloseDelim(token::Paren),
3253 SeqSep::trailing_allowed(token::Comma),
3254 |p| Ok(p.parse_expr()?)
3256 let nd = self.mk_call(e, es);
3257 let hi = self.prev_span;
3258 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3260 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3264 // Could be either an index expression or a slicing expression.
3265 token::OpenDelim(token::Bracket) => {
3267 let ix = self.parse_expr()?;
3269 self.expect(&token::CloseDelim(token::Bracket))?;
3270 let index = self.mk_index(e, ix);
3271 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3279 fn recover_seq_parse_error(
3281 delim: token::DelimToken,
3283 result: PResult<'a, P<Expr>>,
3289 // recover from parse error
3290 self.consume_block(delim);
3291 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
3296 crate fn process_potential_macro_variable(&mut self) {
3297 let (token, span) = match self.token {
3298 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3299 self.look_ahead(1, |t| t.is_ident()) => {
3301 let name = match self.token {
3302 token::Ident(ident, _) => ident,
3305 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3306 err.span_label(self.span, "unknown macro variable");
3311 token::Interpolated(ref nt) => {
3312 self.meta_var_span = Some(self.span);
3313 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3314 // and lifetime tokens, so the former are never encountered during normal parsing.
3316 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3317 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3327 /// Parses a single token tree from the input.
3328 crate fn parse_token_tree(&mut self) -> TokenTree {
3330 token::OpenDelim(..) => {
3331 let frame = mem::replace(&mut self.token_cursor.frame,
3332 self.token_cursor.stack.pop().unwrap());
3333 self.span = frame.span.entire();
3335 TokenTree::Delimited(
3338 frame.tree_cursor.stream.into(),
3341 token::CloseDelim(_) | token::Eof => unreachable!(),
3343 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3345 TokenTree::Token(span, token)
3350 // parse a stream of tokens into a list of TokenTree's,
3352 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3353 let mut tts = Vec::new();
3354 while self.token != token::Eof {
3355 tts.push(self.parse_token_tree());
3360 pub fn parse_tokens(&mut self) -> TokenStream {
3361 let mut result = Vec::new();
3364 token::Eof | token::CloseDelim(..) => break,
3365 _ => result.push(self.parse_token_tree().into()),
3368 TokenStream::new(result)
3371 /// Parse a prefix-unary-operator expr
3372 fn parse_prefix_expr(&mut self,
3373 already_parsed_attrs: Option<ThinVec<Attribute>>)
3374 -> PResult<'a, P<Expr>> {
3375 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3377 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3378 let (hi, ex) = match self.token {
3381 let e = self.parse_prefix_expr(None);
3382 let (span, e) = self.interpolated_or_expr_span(e)?;
3383 (lo.to(span), self.mk_unary(UnOp::Not, e))
3385 // Suggest `!` for bitwise negation when encountering a `~`
3388 let e = self.parse_prefix_expr(None);
3389 let (span, e) = self.interpolated_or_expr_span(e)?;
3390 let span_of_tilde = lo;
3391 let mut err = self.diagnostic()
3392 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3393 err.span_suggestion_short(
3395 "use `!` to perform bitwise negation",
3397 Applicability::MachineApplicable
3400 (lo.to(span), self.mk_unary(UnOp::Not, e))
3402 token::BinOp(token::Minus) => {
3404 let e = self.parse_prefix_expr(None);
3405 let (span, e) = self.interpolated_or_expr_span(e)?;
3406 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3408 token::BinOp(token::Star) => {
3410 let e = self.parse_prefix_expr(None);
3411 let (span, e) = self.interpolated_or_expr_span(e)?;
3412 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3414 token::BinOp(token::And) | token::AndAnd => {
3416 let m = self.parse_mutability();
3417 let e = self.parse_prefix_expr(None);
3418 let (span, e) = self.interpolated_or_expr_span(e)?;
3419 (lo.to(span), ExprKind::AddrOf(m, e))
3421 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3423 let place = self.parse_expr_res(
3424 Restrictions::NO_STRUCT_LITERAL,
3427 let blk = self.parse_block()?;
3428 let span = blk.span;
3429 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3430 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3432 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3434 let e = self.parse_prefix_expr(None);
3435 let (span, e) = self.interpolated_or_expr_span(e)?;
3436 (lo.to(span), ExprKind::Box(e))
3438 token::Ident(..) if self.token.is_ident_named("not") => {
3439 // `not` is just an ordinary identifier in Rust-the-language,
3440 // but as `rustc`-the-compiler, we can issue clever diagnostics
3441 // for confused users who really want to say `!`
3442 let token_cannot_continue_expr = |t: &token::Token| match *t {
3443 // These tokens can start an expression after `!`, but
3444 // can't continue an expression after an ident
3445 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3446 token::Literal(..) | token::Pound => true,
3447 token::Interpolated(ref nt) => match **nt {
3448 token::NtIdent(..) | token::NtExpr(..) |
3449 token::NtBlock(..) | token::NtPath(..) => true,
3454 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3455 if cannot_continue_expr {
3457 // Emit the error ...
3458 let mut err = self.diagnostic()
3459 .struct_span_err(self.span,
3460 &format!("unexpected {} after identifier",
3461 self.this_token_descr()));
3462 // span the `not` plus trailing whitespace to avoid
3463 // trailing whitespace after the `!` in our suggestion
3464 let to_replace = self.sess.source_map()
3465 .span_until_non_whitespace(lo.to(self.span));
3466 err.span_suggestion_short(
3468 "use `!` to perform logical negation",
3470 Applicability::MachineApplicable
3473 // —and recover! (just as if we were in the block
3474 // for the `token::Not` arm)
3475 let e = self.parse_prefix_expr(None);
3476 let (span, e) = self.interpolated_or_expr_span(e)?;
3477 (lo.to(span), self.mk_unary(UnOp::Not, e))
3479 return self.parse_dot_or_call_expr(Some(attrs));
3482 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3484 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3487 /// Parses an associative expression.
3489 /// This parses an expression accounting for associativity and precedence of the operators in
3492 fn parse_assoc_expr(&mut self,
3493 already_parsed_attrs: Option<ThinVec<Attribute>>)
3494 -> PResult<'a, P<Expr>> {
3495 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3498 /// Parses an associative expression with operators of at least `min_prec` precedence.
3499 fn parse_assoc_expr_with(&mut self,
3502 -> PResult<'a, P<Expr>> {
3503 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3506 let attrs = match lhs {
3507 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3510 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3511 return self.parse_prefix_range_expr(attrs);
3513 self.parse_prefix_expr(attrs)?
3517 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
3519 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3522 (false, _) => {} // continue parsing the expression
3523 // An exhaustive check is done in the following block, but these are checked first
3524 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
3525 // want to keep their span info to improve diagnostics in these cases in a later stage.
3526 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
3527 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
3528 (true, Some(AssocOp::Add)) => { // `{ 42 } + 42
3529 // These cases are ambiguous and can't be identified in the parser alone
3530 let sp = self.sess.source_map().start_point(self.span);
3531 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
3534 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
3537 (true, Some(_)) => {
3538 // We've found an expression that would be parsed as a statement, but the next
3539 // token implies this should be parsed as an expression.
3540 // For example: `if let Some(x) = x { x } else { 0 } / 2`
3541 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
3542 "expected expression, found `{}`",
3543 pprust::token_to_string(&self.token),
3545 err.span_label(self.span, "expected expression");
3546 self.sess.expr_parentheses_needed(
3549 Some(pprust::expr_to_string(&lhs),
3554 self.expected_tokens.push(TokenType::Operator);
3555 while let Some(op) = AssocOp::from_token(&self.token) {
3557 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3558 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3559 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3560 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3561 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3562 (PrevTokenKind::Interpolated, _) => self.prev_span,
3563 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3564 if path.segments.len() == 1 => self.prev_span,
3568 let cur_op_span = self.span;
3569 let restrictions = if op.is_assign_like() {
3570 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3574 if op.precedence() < min_prec {
3577 // Check for deprecated `...` syntax
3578 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3579 self.err_dotdotdot_syntax(self.span);
3583 if op.is_comparison() {
3584 self.check_no_chained_comparison(&lhs, &op);
3587 if op == AssocOp::As {
3588 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3590 } else if op == AssocOp::Colon {
3591 let maybe_path = self.could_ascription_be_path(&lhs.node);
3592 let next_sp = self.span;
3594 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3597 self.bad_type_ascription(
3608 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3609 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3610 // generalise it to the Fixity::None code.
3612 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3613 // two variants are handled with `parse_prefix_range_expr` call above.
3614 let rhs = if self.is_at_start_of_range_notation_rhs() {
3615 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3616 LhsExpr::NotYetParsed)?)
3620 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3625 let limits = if op == AssocOp::DotDot {
3626 RangeLimits::HalfOpen
3631 let r = self.mk_range(Some(lhs), rhs, limits)?;
3632 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3636 let rhs = match op.fixity() {
3637 Fixity::Right => self.with_res(
3638 restrictions - Restrictions::STMT_EXPR,
3640 this.parse_assoc_expr_with(op.precedence(),
3641 LhsExpr::NotYetParsed)
3643 Fixity::Left => self.with_res(
3644 restrictions - Restrictions::STMT_EXPR,
3646 this.parse_assoc_expr_with(op.precedence() + 1,
3647 LhsExpr::NotYetParsed)
3649 // We currently have no non-associative operators that are not handled above by
3650 // the special cases. The code is here only for future convenience.
3651 Fixity::None => self.with_res(
3652 restrictions - Restrictions::STMT_EXPR,
3654 this.parse_assoc_expr_with(op.precedence() + 1,
3655 LhsExpr::NotYetParsed)
3659 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3660 // including the attributes.
3664 .filter(|a| a.style == AttrStyle::Outer)
3666 .map_or(lhs_span, |a| a.span);
3667 let span = lhs_span.to(rhs.span);
3669 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3670 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3671 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3672 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3673 AssocOp::Greater | AssocOp::GreaterEqual => {
3674 let ast_op = op.to_ast_binop().unwrap();
3675 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3676 self.mk_expr(span, binary, ThinVec::new())
3679 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3680 AssocOp::ObsoleteInPlace =>
3681 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3682 AssocOp::AssignOp(k) => {
3684 token::Plus => BinOpKind::Add,
3685 token::Minus => BinOpKind::Sub,
3686 token::Star => BinOpKind::Mul,
3687 token::Slash => BinOpKind::Div,
3688 token::Percent => BinOpKind::Rem,
3689 token::Caret => BinOpKind::BitXor,
3690 token::And => BinOpKind::BitAnd,
3691 token::Or => BinOpKind::BitOr,
3692 token::Shl => BinOpKind::Shl,
3693 token::Shr => BinOpKind::Shr,
3695 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3696 self.mk_expr(span, aopexpr, ThinVec::new())
3698 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3699 self.bug("AssocOp should have been handled by special case")
3703 if op.fixity() == Fixity::None { break }
3708 fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
3709 self.token.is_ident() &&
3710 if let ast::ExprKind::Path(..) = node { true } else { false } &&
3711 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
3712 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
3713 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
3714 self.look_ahead(2, |t| t.is_ident()) ||
3715 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
3716 self.look_ahead(2, |t| t.is_ident()) ||
3717 self.look_ahead(1, |t| t == &token::ModSep) && // `foo:bar::baz`
3718 self.look_ahead(2, |t| t.is_ident())
3721 fn bad_type_ascription(
3723 err: &mut DiagnosticBuilder<'a>,
3729 err.span_label(self.span, "expecting a type here because of type ascription");
3730 let cm = self.sess.source_map();
3731 let next_pos = cm.lookup_char_pos(next_sp.lo());
3732 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3733 if op_pos.line != next_pos.line {
3734 err.span_suggestion(
3736 "try using a semicolon",
3738 Applicability::MaybeIncorrect,
3742 err.span_suggestion(
3744 "maybe you meant to write a path separator here",
3746 Applicability::MaybeIncorrect,
3749 err.note("type ascription is a nightly-only feature that lets \
3750 you annotate an expression with a type: `<expr>: <type>`");
3753 "this expression expects an ascribed type after the colon",
3755 err.help("this might be indicative of a syntax error elsewhere");
3760 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3761 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3762 -> PResult<'a, P<Expr>> {
3763 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3764 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3767 // Save the state of the parser before parsing type normally, in case there is a
3768 // LessThan comparison after this cast.
3769 let parser_snapshot_before_type = self.clone();
3770 match self.parse_ty_no_plus() {
3772 Ok(mk_expr(self, rhs))
3774 Err(mut type_err) => {
3775 // Rewind to before attempting to parse the type with generics, to recover
3776 // from situations like `x as usize < y` in which we first tried to parse
3777 // `usize < y` as a type with generic arguments.
3778 let parser_snapshot_after_type = self.clone();
3779 mem::replace(self, parser_snapshot_before_type);
3781 match self.parse_path(PathStyle::Expr) {
3783 let (op_noun, op_verb) = match self.token {
3784 token::Lt => ("comparison", "comparing"),
3785 token::BinOp(token::Shl) => ("shift", "shifting"),
3787 // We can end up here even without `<` being the next token, for
3788 // example because `parse_ty_no_plus` returns `Err` on keywords,
3789 // but `parse_path` returns `Ok` on them due to error recovery.
3790 // Return original error and parser state.
3791 mem::replace(self, parser_snapshot_after_type);
3792 return Err(type_err);
3796 // Successfully parsed the type path leaving a `<` yet to parse.
3799 // Report non-fatal diagnostics, keep `x as usize` as an expression
3800 // in AST and continue parsing.
3801 let msg = format!("`<` is interpreted as a start of generic \
3802 arguments for `{}`, not a {}", path, op_noun);
3803 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3804 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3805 "interpreted as generic arguments");
3806 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3808 let expr = mk_expr(self, P(Ty {
3810 node: TyKind::Path(None, path),
3811 id: ast::DUMMY_NODE_ID
3814 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3815 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3816 err.span_suggestion(
3818 &format!("try {} the cast value", op_verb),
3819 format!("({})", expr_str),
3820 Applicability::MachineApplicable
3826 Err(mut path_err) => {
3827 // Couldn't parse as a path, return original error and parser state.
3829 mem::replace(self, parser_snapshot_after_type);
3837 /// Produce an error if comparison operators are chained (RFC #558).
3838 /// We only need to check lhs, not rhs, because all comparison ops
3839 /// have same precedence and are left-associative
3840 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3841 debug_assert!(outer_op.is_comparison(),
3842 "check_no_chained_comparison: {:?} is not comparison",
3845 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3846 // respan to include both operators
3847 let op_span = op.span.to(self.span);
3848 let mut err = self.diagnostic().struct_span_err(op_span,
3849 "chained comparison operators require parentheses");
3850 if op.node == BinOpKind::Lt &&
3851 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3852 *outer_op == AssocOp::Greater // even in a case like the following:
3853 { // Foo<Bar<Baz<Qux, ()>>>
3855 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3856 err.help("or use `(...)` if you meant to specify fn arguments");
3864 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3865 fn parse_prefix_range_expr(&mut self,
3866 already_parsed_attrs: Option<ThinVec<Attribute>>)
3867 -> PResult<'a, P<Expr>> {
3868 // Check for deprecated `...` syntax
3869 if self.token == token::DotDotDot {
3870 self.err_dotdotdot_syntax(self.span);
3873 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3874 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3876 let tok = self.token.clone();
3877 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3879 let mut hi = self.span;
3881 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3882 // RHS must be parsed with more associativity than the dots.
3883 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3884 Some(self.parse_assoc_expr_with(next_prec,
3885 LhsExpr::NotYetParsed)
3893 let limits = if tok == token::DotDot {
3894 RangeLimits::HalfOpen
3899 let r = self.mk_range(None, opt_end, limits)?;
3900 Ok(self.mk_expr(lo.to(hi), r, attrs))
3903 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3904 if self.token.can_begin_expr() {
3905 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3906 if self.token == token::OpenDelim(token::Brace) {
3907 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3915 /// Parses an `if` or `if let` expression (`if` token already eaten).
3916 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3917 if self.check_keyword(keywords::Let) {
3918 return self.parse_if_let_expr(attrs);
3920 let lo = self.prev_span;
3921 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3923 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3924 // verify that the last statement is either an implicit return (no `;`) or an explicit
3925 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3926 // the dead code lint.
3927 if self.eat_keyword(keywords::Else) || !cond.returns() {
3928 let sp = self.sess.source_map().next_point(lo);
3929 let mut err = self.diagnostic()
3930 .struct_span_err(sp, "missing condition for `if` statemement");
3931 err.span_label(sp, "expected if condition here");
3934 let not_block = self.token != token::OpenDelim(token::Brace);
3935 let thn = self.parse_block().map_err(|mut err| {
3937 err.span_label(lo, "this `if` statement has a condition, but no block");
3941 let mut els: Option<P<Expr>> = None;
3942 let mut hi = thn.span;
3943 if self.eat_keyword(keywords::Else) {
3944 let elexpr = self.parse_else_expr()?;
3948 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3951 /// Parses an `if let` expression (`if` token already eaten).
3952 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3953 -> PResult<'a, P<Expr>> {
3954 let lo = self.prev_span;
3955 self.expect_keyword(keywords::Let)?;
3956 let pats = self.parse_pats()?;
3957 self.expect(&token::Eq)?;
3958 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3959 let thn = self.parse_block()?;
3960 let (hi, els) = if self.eat_keyword(keywords::Else) {
3961 let expr = self.parse_else_expr()?;
3962 (expr.span, Some(expr))
3966 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3969 /// Parses `move |args| expr`.
3970 fn parse_lambda_expr(&mut self,
3971 attrs: ThinVec<Attribute>)
3972 -> PResult<'a, P<Expr>>
3975 let movability = if self.eat_keyword(keywords::Static) {
3980 let asyncness = if self.span.rust_2018() {
3981 self.parse_asyncness()
3985 let capture_clause = if self.eat_keyword(keywords::Move) {
3990 let decl = self.parse_fn_block_decl()?;
3991 let decl_hi = self.prev_span;
3992 let body = match decl.output {
3993 FunctionRetTy::Default(_) => {
3994 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3995 self.parse_expr_res(restrictions, None)?
3998 // If an explicit return type is given, require a
3999 // block to appear (RFC 968).
4000 let body_lo = self.span;
4001 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
4007 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
4011 // `else` token already eaten
4012 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
4013 if self.eat_keyword(keywords::If) {
4014 return self.parse_if_expr(ThinVec::new());
4016 let blk = self.parse_block()?;
4017 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
4021 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
4022 fn parse_for_expr(&mut self, opt_label: Option<Label>,
4024 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4025 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
4027 let pat = self.parse_top_level_pat()?;
4028 if !self.eat_keyword(keywords::In) {
4029 let in_span = self.prev_span.between(self.span);
4030 let mut err = self.sess.span_diagnostic
4031 .struct_span_err(in_span, "missing `in` in `for` loop");
4032 err.span_suggestion_short(
4033 in_span, "try adding `in` here", " in ".into(),
4034 // has been misleading, at least in the past (closed Issue #48492)
4035 Applicability::MaybeIncorrect
4039 let in_span = self.prev_span;
4040 if self.eat_keyword(keywords::In) {
4041 // a common typo: `for _ in in bar {}`
4042 let mut err = self.sess.span_diagnostic.struct_span_err(
4044 "expected iterable, found keyword `in`",
4046 err.span_suggestion_short(
4047 in_span.until(self.prev_span),
4048 "remove the duplicated `in`",
4050 Applicability::MachineApplicable,
4052 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
4053 err.note("for more information on the status of emplacement syntax, see <\
4054 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
4057 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4058 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
4059 attrs.extend(iattrs);
4061 let hi = self.prev_span;
4062 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
4065 /// Parses a `while` or `while let` expression (`while` token already eaten).
4066 fn parse_while_expr(&mut self, opt_label: Option<Label>,
4068 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4069 if self.token.is_keyword(keywords::Let) {
4070 return self.parse_while_let_expr(opt_label, span_lo, attrs);
4072 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4073 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4074 attrs.extend(iattrs);
4075 let span = span_lo.to(body.span);
4076 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
4079 /// Parses a `while let` expression (`while` token already eaten).
4080 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
4082 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4083 self.expect_keyword(keywords::Let)?;
4084 let pats = self.parse_pats()?;
4085 self.expect(&token::Eq)?;
4086 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4087 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4088 attrs.extend(iattrs);
4089 let span = span_lo.to(body.span);
4090 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
4093 // parse `loop {...}`, `loop` token already eaten
4094 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
4096 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4097 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4098 attrs.extend(iattrs);
4099 let span = span_lo.to(body.span);
4100 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
4103 /// Parses an `async move {...}` expression.
4104 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4105 -> PResult<'a, P<Expr>>
4107 let span_lo = self.span;
4108 self.expect_keyword(keywords::Async)?;
4109 let capture_clause = if self.eat_keyword(keywords::Move) {
4114 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4115 attrs.extend(iattrs);
4117 span_lo.to(body.span),
4118 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4121 /// Parses a `try {...}` expression (`try` token already eaten).
4122 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4123 -> PResult<'a, P<Expr>>
4125 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4126 attrs.extend(iattrs);
4127 if self.eat_keyword(keywords::Catch) {
4128 let mut error = self.struct_span_err(self.prev_span,
4129 "keyword `catch` cannot follow a `try` block");
4130 error.help("try using `match` on the result of the `try` block instead");
4134 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4138 // `match` token already eaten
4139 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4140 let match_span = self.prev_span;
4141 let lo = self.prev_span;
4142 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4144 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4145 if self.token == token::Token::Semi {
4146 e.span_suggestion_short(
4148 "try removing this `match`",
4150 Applicability::MaybeIncorrect // speculative
4155 attrs.extend(self.parse_inner_attributes()?);
4157 let mut arms: Vec<Arm> = Vec::new();
4158 while self.token != token::CloseDelim(token::Brace) {
4159 match self.parse_arm() {
4160 Ok(arm) => arms.push(arm),
4162 // Recover by skipping to the end of the block.
4164 self.recover_stmt();
4165 let span = lo.to(self.span);
4166 if self.token == token::CloseDelim(token::Brace) {
4169 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4175 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4178 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4179 maybe_whole!(self, NtArm, |x| x);
4181 let attrs = self.parse_outer_attributes()?;
4182 let pats = self.parse_pats()?;
4183 let guard = if self.eat_keyword(keywords::If) {
4184 Some(Guard::If(self.parse_expr()?))
4188 let arrow_span = self.span;
4189 self.expect(&token::FatArrow)?;
4190 let arm_start_span = self.span;
4192 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4193 .map_err(|mut err| {
4194 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4198 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4199 && self.token != token::CloseDelim(token::Brace);
4202 let cm = self.sess.source_map();
4203 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4204 .map_err(|mut err| {
4205 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4206 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4207 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4208 && expr_lines.lines.len() == 2
4209 && self.token == token::FatArrow => {
4210 // We check whether there's any trailing code in the parse span,
4211 // if there isn't, we very likely have the following:
4214 // | -- - missing comma
4220 // | parsed until here as `"y" & X`
4221 err.span_suggestion_short(
4222 cm.next_point(arm_start_span),
4223 "missing a comma here to end this `match` arm",
4225 Applicability::MachineApplicable
4229 err.span_label(arrow_span,
4230 "while parsing the `match` arm starting here");
4236 self.eat(&token::Comma);
4247 /// Parses an expression.
4249 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4250 self.parse_expr_res(Restrictions::empty(), None)
4253 /// Evaluates the closure with restrictions in place.
4255 /// Afters the closure is evaluated, restrictions are reset.
4256 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4257 where F: FnOnce(&mut Self) -> T
4259 let old = self.restrictions;
4260 self.restrictions = r;
4262 self.restrictions = old;
4267 /// Parses an expression, subject to the given restrictions.
4269 fn parse_expr_res(&mut self, r: Restrictions,
4270 already_parsed_attrs: Option<ThinVec<Attribute>>)
4271 -> PResult<'a, P<Expr>> {
4272 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4275 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4276 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4277 if self.eat(&token::Eq) {
4278 Ok(Some(self.parse_expr()?))
4280 Ok(Some(self.parse_expr()?))
4286 /// Parses patterns, separated by '|' s.
4287 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4288 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4289 self.eat(&token::BinOp(token::Or));
4291 let mut pats = Vec::new();
4293 pats.push(self.parse_top_level_pat()?);
4295 if self.token == token::OrOr {
4296 let mut err = self.struct_span_err(self.span,
4297 "unexpected token `||` after pattern");
4298 err.span_suggestion(
4300 "use a single `|` to specify multiple patterns",
4302 Applicability::MachineApplicable
4306 } else if self.eat(&token::BinOp(token::Or)) {
4307 // This is a No-op. Continue the loop to parse the next
4315 // Parses a parenthesized list of patterns like
4316 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4317 // - a vector of the patterns that were parsed
4318 // - an option indicating the index of the `..` element
4319 // - a boolean indicating whether a trailing comma was present.
4320 // Trailing commas are significant because (p) and (p,) are different patterns.
4321 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4322 self.expect(&token::OpenDelim(token::Paren))?;
4323 let result = match self.parse_pat_list() {
4324 Ok(result) => result,
4325 Err(mut err) => { // recover from parse error in tuple pattern list
4327 self.consume_block(token::Paren);
4328 return Ok((vec![], Some(0), false));
4331 self.expect(&token::CloseDelim(token::Paren))?;
4335 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4336 let mut fields = Vec::new();
4337 let mut ddpos = None;
4338 let mut prev_dd_sp = None;
4339 let mut trailing_comma = false;
4341 if self.eat(&token::DotDot) {
4342 if ddpos.is_none() {
4343 ddpos = Some(fields.len());
4344 prev_dd_sp = Some(self.prev_span);
4346 // Emit a friendly error, ignore `..` and continue parsing
4347 let mut err = self.struct_span_err(
4349 "`..` can only be used once per tuple or tuple struct pattern",
4351 err.span_label(self.prev_span, "can only be used once per pattern");
4352 if let Some(sp) = prev_dd_sp {
4353 err.span_label(sp, "previously present here");
4357 } else if !self.check(&token::CloseDelim(token::Paren)) {
4358 fields.push(self.parse_pat(None)?);
4363 trailing_comma = self.eat(&token::Comma);
4364 if !trailing_comma {
4369 if ddpos == Some(fields.len()) && trailing_comma {
4370 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4371 let msg = "trailing comma is not permitted after `..`";
4372 self.struct_span_err(self.prev_span, msg)
4373 .span_label(self.prev_span, msg)
4377 Ok((fields, ddpos, trailing_comma))
4380 fn parse_pat_vec_elements(
4382 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4383 let mut before = Vec::new();
4384 let mut slice = None;
4385 let mut after = Vec::new();
4386 let mut first = true;
4387 let mut before_slice = true;
4389 while self.token != token::CloseDelim(token::Bracket) {
4393 self.expect(&token::Comma)?;
4395 if self.token == token::CloseDelim(token::Bracket)
4396 && (before_slice || !after.is_empty()) {
4402 if self.eat(&token::DotDot) {
4404 if self.check(&token::Comma) ||
4405 self.check(&token::CloseDelim(token::Bracket)) {
4406 slice = Some(P(Pat {
4407 id: ast::DUMMY_NODE_ID,
4408 node: PatKind::Wild,
4409 span: self.prev_span,
4411 before_slice = false;
4417 let subpat = self.parse_pat(None)?;
4418 if before_slice && self.eat(&token::DotDot) {
4419 slice = Some(subpat);
4420 before_slice = false;
4421 } else if before_slice {
4422 before.push(subpat);
4428 Ok((before, slice, after))
4434 attrs: Vec<Attribute>
4435 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4436 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4438 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4439 // Parsing a pattern of the form "fieldname: pat"
4440 let fieldname = self.parse_field_name()?;
4442 let pat = self.parse_pat(None)?;
4444 (pat, fieldname, false)
4446 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4447 let is_box = self.eat_keyword(keywords::Box);
4448 let boxed_span = self.span;
4449 let is_ref = self.eat_keyword(keywords::Ref);
4450 let is_mut = self.eat_keyword(keywords::Mut);
4451 let fieldname = self.parse_ident()?;
4452 hi = self.prev_span;
4454 let bind_type = match (is_ref, is_mut) {
4455 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4456 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4457 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4458 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4460 let fieldpat = P(Pat {
4461 id: ast::DUMMY_NODE_ID,
4462 node: PatKind::Ident(bind_type, fieldname, None),
4463 span: boxed_span.to(hi),
4466 let subpat = if is_box {
4468 id: ast::DUMMY_NODE_ID,
4469 node: PatKind::Box(fieldpat),
4475 (subpat, fieldname, true)
4478 Ok(source_map::Spanned {
4480 node: ast::FieldPat {
4484 attrs: attrs.into(),
4489 /// Parses the fields of a struct-like pattern.
4490 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4491 let mut fields = Vec::new();
4492 let mut etc = false;
4493 let mut ate_comma = true;
4494 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4495 let mut etc_span = None;
4497 while self.token != token::CloseDelim(token::Brace) {
4498 let attrs = self.parse_outer_attributes()?;
4501 // check that a comma comes after every field
4503 let err = self.struct_span_err(self.prev_span, "expected `,`");
4504 if let Some(mut delayed) = delayed_err {
4511 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4513 let mut etc_sp = self.span;
4515 if self.token == token::DotDotDot { // Issue #46718
4516 // Accept `...` as if it were `..` to avoid further errors
4517 let mut err = self.struct_span_err(self.span,
4518 "expected field pattern, found `...`");
4519 err.span_suggestion(
4521 "to omit remaining fields, use one fewer `.`",
4523 Applicability::MachineApplicable
4527 self.bump(); // `..` || `...`
4529 if self.token == token::CloseDelim(token::Brace) {
4530 etc_span = Some(etc_sp);
4533 let token_str = self.this_token_descr();
4534 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4536 err.span_label(self.span, "expected `}`");
4537 let mut comma_sp = None;
4538 if self.token == token::Comma { // Issue #49257
4539 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4540 err.span_label(etc_sp,
4541 "`..` must be at the end and cannot have a trailing comma");
4542 comma_sp = Some(self.span);
4547 etc_span = Some(etc_sp.until(self.span));
4548 if self.token == token::CloseDelim(token::Brace) {
4549 // If the struct looks otherwise well formed, recover and continue.
4550 if let Some(sp) = comma_sp {
4551 err.span_suggestion_short(
4553 "remove this comma",
4555 Applicability::MachineApplicable,
4560 } else if self.token.is_ident() && ate_comma {
4561 // Accept fields coming after `..,`.
4562 // This way we avoid "pattern missing fields" errors afterwards.
4563 // We delay this error until the end in order to have a span for a
4565 if let Some(mut delayed_err) = delayed_err {
4569 delayed_err = Some(err);
4572 if let Some(mut err) = delayed_err {
4579 fields.push(match self.parse_pat_field(lo, attrs) {
4582 if let Some(mut delayed_err) = delayed_err {
4588 ate_comma = self.eat(&token::Comma);
4591 if let Some(mut err) = delayed_err {
4592 if let Some(etc_span) = etc_span {
4593 err.multipart_suggestion(
4594 "move the `..` to the end of the field list",
4596 (etc_span, String::new()),
4597 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4599 Applicability::MachineApplicable,
4604 return Ok((fields, etc));
4607 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4608 if self.token.is_path_start() {
4610 let (qself, path) = if self.eat_lt() {
4611 // Parse a qualified path
4612 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4615 // Parse an unqualified path
4616 (None, self.parse_path(PathStyle::Expr)?)
4618 let hi = self.prev_span;
4619 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4621 self.parse_literal_maybe_minus()
4625 // helper function to decide whether to parse as ident binding or to try to do
4626 // something more complex like range patterns
4627 fn parse_as_ident(&mut self) -> bool {
4628 self.look_ahead(1, |t| match *t {
4629 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4630 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4631 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4632 // range pattern branch
4633 token::DotDot => None,
4635 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4636 token::Comma | token::CloseDelim(token::Bracket) => true,
4641 /// A wrapper around `parse_pat` with some special error handling for the
4642 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4643 /// to subpatterns within such).
4644 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4645 let pat = self.parse_pat(None)?;
4646 if self.token == token::Comma {
4647 // An unexpected comma after a top-level pattern is a clue that the
4648 // user (perhaps more accustomed to some other language) forgot the
4649 // parentheses in what should have been a tuple pattern; return a
4650 // suggestion-enhanced error here rather than choking on the comma
4652 let comma_span = self.span;
4654 if let Err(mut err) = self.parse_pat_list() {
4655 // We didn't expect this to work anyway; we just wanted
4656 // to advance to the end of the comma-sequence so we know
4657 // the span to suggest parenthesizing
4660 let seq_span = pat.span.to(self.prev_span);
4661 let mut err = self.struct_span_err(comma_span,
4662 "unexpected `,` in pattern");
4663 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4664 err.span_suggestion(
4666 "try adding parentheses to match on a tuple..",
4667 format!("({})", seq_snippet),
4668 Applicability::MachineApplicable
4671 "..or a vertical bar to match on multiple alternatives",
4672 format!("{}", seq_snippet.replace(",", " |")),
4673 Applicability::MachineApplicable
4681 /// Parses a pattern.
4682 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4683 self.parse_pat_with_range_pat(true, expected)
4686 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4688 fn parse_pat_with_range_pat(
4690 allow_range_pat: bool,
4691 expected: Option<&'static str>,
4692 ) -> PResult<'a, P<Pat>> {
4693 maybe_recover_from_interpolated_ty_qpath!(self, true);
4694 maybe_whole!(self, NtPat, |x| x);
4699 token::BinOp(token::And) | token::AndAnd => {
4700 // Parse &pat / &mut pat
4702 let mutbl = self.parse_mutability();
4703 if let token::Lifetime(ident) = self.token {
4704 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4706 err.span_label(self.span, "unexpected lifetime");
4709 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4710 pat = PatKind::Ref(subpat, mutbl);
4712 token::OpenDelim(token::Paren) => {
4713 // Parse (pat,pat,pat,...) as tuple pattern
4714 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4715 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4716 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4718 PatKind::Tuple(fields, ddpos)
4721 token::OpenDelim(token::Bracket) => {
4722 // Parse [pat,pat,...] as slice pattern
4724 let (before, slice, after) = self.parse_pat_vec_elements()?;
4725 self.expect(&token::CloseDelim(token::Bracket))?;
4726 pat = PatKind::Slice(before, slice, after);
4728 // At this point, token != &, &&, (, [
4729 _ => if self.eat_keyword(keywords::Underscore) {
4731 pat = PatKind::Wild;
4732 } else if self.eat_keyword(keywords::Mut) {
4733 // Parse mut ident @ pat / mut ref ident @ pat
4734 let mutref_span = self.prev_span.to(self.span);
4735 let binding_mode = if self.eat_keyword(keywords::Ref) {
4737 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4740 "try switching the order",
4742 Applicability::MachineApplicable
4744 BindingMode::ByRef(Mutability::Mutable)
4746 BindingMode::ByValue(Mutability::Mutable)
4748 pat = self.parse_pat_ident(binding_mode)?;
4749 } else if self.eat_keyword(keywords::Ref) {
4750 // Parse ref ident @ pat / ref mut ident @ pat
4751 let mutbl = self.parse_mutability();
4752 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4753 } else if self.eat_keyword(keywords::Box) {
4755 let subpat = self.parse_pat_with_range_pat(false, None)?;
4756 pat = PatKind::Box(subpat);
4757 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4758 self.parse_as_ident() {
4759 // Parse ident @ pat
4760 // This can give false positives and parse nullary enums,
4761 // they are dealt with later in resolve
4762 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4763 pat = self.parse_pat_ident(binding_mode)?;
4764 } else if self.token.is_path_start() {
4765 // Parse pattern starting with a path
4766 let (qself, path) = if self.eat_lt() {
4767 // Parse a qualified path
4768 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4771 // Parse an unqualified path
4772 (None, self.parse_path(PathStyle::Expr)?)
4775 token::Not if qself.is_none() => {
4776 // Parse macro invocation
4778 let (delim, tts) = self.expect_delimited_token_tree()?;
4779 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4780 pat = PatKind::Mac(mac);
4782 token::DotDotDot | token::DotDotEq | token::DotDot => {
4783 let end_kind = match self.token {
4784 token::DotDot => RangeEnd::Excluded,
4785 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4786 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4787 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4790 let op_span = self.span;
4792 let span = lo.to(self.prev_span);
4793 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4795 let end = self.parse_pat_range_end()?;
4796 let op = Spanned { span: op_span, node: end_kind };
4797 pat = PatKind::Range(begin, end, op);
4799 token::OpenDelim(token::Brace) => {
4800 if qself.is_some() {
4801 let msg = "unexpected `{` after qualified path";
4802 let mut err = self.fatal(msg);
4803 err.span_label(self.span, msg);
4806 // Parse struct pattern
4808 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4810 self.recover_stmt();
4814 pat = PatKind::Struct(path, fields, etc);
4816 token::OpenDelim(token::Paren) => {
4817 if qself.is_some() {
4818 let msg = "unexpected `(` after qualified path";
4819 let mut err = self.fatal(msg);
4820 err.span_label(self.span, msg);
4823 // Parse tuple struct or enum pattern
4824 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4825 pat = PatKind::TupleStruct(path, fields, ddpos)
4827 _ => pat = PatKind::Path(qself, path),
4830 // Try to parse everything else as literal with optional minus
4831 match self.parse_literal_maybe_minus() {
4833 let op_span = self.span;
4834 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4835 self.check(&token::DotDotDot) {
4836 let end_kind = if self.eat(&token::DotDotDot) {
4837 RangeEnd::Included(RangeSyntax::DotDotDot)
4838 } else if self.eat(&token::DotDotEq) {
4839 RangeEnd::Included(RangeSyntax::DotDotEq)
4840 } else if self.eat(&token::DotDot) {
4843 panic!("impossible case: we already matched \
4844 on a range-operator token")
4846 let end = self.parse_pat_range_end()?;
4847 let op = Spanned { span: op_span, node: end_kind };
4848 pat = PatKind::Range(begin, end, op);
4850 pat = PatKind::Lit(begin);
4854 self.cancel(&mut err);
4855 let expected = expected.unwrap_or("pattern");
4857 "expected {}, found {}",
4859 self.this_token_descr(),
4861 let mut err = self.fatal(&msg);
4862 err.span_label(self.span, format!("expected {}", expected));
4863 let sp = self.sess.source_map().start_point(self.span);
4864 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4865 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4873 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4874 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4876 if !allow_range_pat {
4879 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4881 PatKind::Range(..) => {
4882 let mut err = self.struct_span_err(
4884 "the range pattern here has ambiguous interpretation",
4886 err.span_suggestion(
4888 "add parentheses to clarify the precedence",
4889 format!("({})", pprust::pat_to_string(&pat)),
4890 // "ambiguous interpretation" implies that we have to be guessing
4891 Applicability::MaybeIncorrect
4902 /// Parses `ident` or `ident @ pat`.
4903 /// used by the copy foo and ref foo patterns to give a good
4904 /// error message when parsing mistakes like `ref foo(a, b)`.
4905 fn parse_pat_ident(&mut self,
4906 binding_mode: ast::BindingMode)
4907 -> PResult<'a, PatKind> {
4908 let ident = self.parse_ident()?;
4909 let sub = if self.eat(&token::At) {
4910 Some(self.parse_pat(Some("binding pattern"))?)
4915 // just to be friendly, if they write something like
4917 // we end up here with ( as the current token. This shortly
4918 // leads to a parse error. Note that if there is no explicit
4919 // binding mode then we do not end up here, because the lookahead
4920 // will direct us over to parse_enum_variant()
4921 if self.token == token::OpenDelim(token::Paren) {
4922 return Err(self.span_fatal(
4924 "expected identifier, found enum pattern"))
4927 Ok(PatKind::Ident(binding_mode, ident, sub))
4930 /// Parses a local variable declaration.
4931 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4932 let lo = self.prev_span;
4933 let pat = self.parse_top_level_pat()?;
4935 let (err, ty) = if self.eat(&token::Colon) {
4936 // Save the state of the parser before parsing type normally, in case there is a `:`
4937 // instead of an `=` typo.
4938 let parser_snapshot_before_type = self.clone();
4939 let colon_sp = self.prev_span;
4940 match self.parse_ty() {
4941 Ok(ty) => (None, Some(ty)),
4943 // Rewind to before attempting to parse the type and continue parsing
4944 let parser_snapshot_after_type = self.clone();
4945 mem::replace(self, parser_snapshot_before_type);
4947 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4948 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4949 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4955 let init = match (self.parse_initializer(err.is_some()), err) {
4956 (Ok(init), None) => { // init parsed, ty parsed
4959 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4960 // Could parse the type as if it were the initializer, it is likely there was a
4961 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4962 err.span_suggestion_short(
4964 "use `=` if you meant to assign",
4966 Applicability::MachineApplicable
4969 // As this was parsed successfully, continue as if the code has been fixed for the
4970 // rest of the file. It will still fail due to the emitted error, but we avoid
4974 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4976 // Couldn't parse the type nor the initializer, only raise the type error and
4977 // return to the parser state before parsing the type as the initializer.
4978 // let x: <parse_error>;
4979 mem::replace(self, snapshot);
4982 (Err(err), None) => { // init error, ty parsed
4983 // Couldn't parse the initializer and we're not attempting to recover a failed
4984 // parse of the type, return the error.
4988 let hi = if self.token == token::Semi {
4997 id: ast::DUMMY_NODE_ID,
5000 source: LocalSource::Normal,
5004 /// Parses a structure field.
5005 fn parse_name_and_ty(&mut self,
5008 attrs: Vec<Attribute>)
5009 -> PResult<'a, StructField> {
5010 let name = self.parse_ident()?;
5011 self.expect(&token::Colon)?;
5012 let ty = self.parse_ty()?;
5014 span: lo.to(self.prev_span),
5017 id: ast::DUMMY_NODE_ID,
5023 /// Emits an expected-item-after-attributes error.
5024 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
5025 let message = match attrs.last() {
5026 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
5027 _ => "expected item after attributes",
5030 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
5031 if attrs.last().unwrap().is_sugared_doc {
5032 err.span_label(self.prev_span, "this doc comment doesn't document anything");
5037 /// Parse a statement. This stops just before trailing semicolons on everything but items.
5038 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
5039 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
5040 Ok(self.parse_stmt_(true))
5043 // Eat tokens until we can be relatively sure we reached the end of the
5044 // statement. This is something of a best-effort heuristic.
5046 // We terminate when we find an unmatched `}` (without consuming it).
5047 fn recover_stmt(&mut self) {
5048 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
5051 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
5052 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
5053 // approximate - it can mean we break too early due to macros, but that
5054 // should only lead to sub-optimal recovery, not inaccurate parsing).
5056 // If `break_on_block` is `Break`, then we will stop consuming tokens
5057 // after finding (and consuming) a brace-delimited block.
5058 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
5059 let mut brace_depth = 0;
5060 let mut bracket_depth = 0;
5061 let mut in_block = false;
5062 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
5063 break_on_semi, break_on_block);
5065 debug!("recover_stmt_ loop {:?}", self.token);
5067 token::OpenDelim(token::DelimToken::Brace) => {
5070 if break_on_block == BlockMode::Break &&
5072 bracket_depth == 0 {
5076 token::OpenDelim(token::DelimToken::Bracket) => {
5080 token::CloseDelim(token::DelimToken::Brace) => {
5081 if brace_depth == 0 {
5082 debug!("recover_stmt_ return - close delim {:?}", self.token);
5087 if in_block && bracket_depth == 0 && brace_depth == 0 {
5088 debug!("recover_stmt_ return - block end {:?}", self.token);
5092 token::CloseDelim(token::DelimToken::Bracket) => {
5094 if bracket_depth < 0 {
5100 debug!("recover_stmt_ return - Eof");
5105 if break_on_semi == SemiColonMode::Break &&
5107 bracket_depth == 0 {
5108 debug!("recover_stmt_ return - Semi");
5113 if break_on_semi == SemiColonMode::Comma &&
5115 bracket_depth == 0 {
5116 debug!("recover_stmt_ return - Semi");
5129 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5130 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5132 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5137 fn is_async_block(&mut self) -> bool {
5138 self.token.is_keyword(keywords::Async) &&
5141 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5142 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5144 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5149 fn is_async_fn(&mut self) -> bool {
5150 self.token.is_keyword(keywords::Async) &&
5151 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5154 fn is_do_catch_block(&mut self) -> bool {
5155 self.token.is_keyword(keywords::Do) &&
5156 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5157 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5158 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5161 fn is_try_block(&mut self) -> bool {
5162 self.token.is_keyword(keywords::Try) &&
5163 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5164 self.span.rust_2018() &&
5165 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5166 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5169 fn is_union_item(&self) -> bool {
5170 self.token.is_keyword(keywords::Union) &&
5171 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5174 fn is_crate_vis(&self) -> bool {
5175 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5178 fn is_existential_type_decl(&self) -> bool {
5179 self.token.is_keyword(keywords::Existential) &&
5180 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5183 fn is_auto_trait_item(&mut self) -> bool {
5185 (self.token.is_keyword(keywords::Auto)
5186 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5187 || // unsafe auto trait
5188 (self.token.is_keyword(keywords::Unsafe) &&
5189 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5190 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5193 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5194 -> PResult<'a, Option<P<Item>>> {
5195 let token_lo = self.span;
5196 let (ident, def) = match self.token {
5197 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5199 let ident = self.parse_ident()?;
5200 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5201 match self.parse_token_tree() {
5202 TokenTree::Delimited(_, _, tts) => tts,
5203 _ => unreachable!(),
5205 } else if self.check(&token::OpenDelim(token::Paren)) {
5206 let args = self.parse_token_tree();
5207 let body = if self.check(&token::OpenDelim(token::Brace)) {
5208 self.parse_token_tree()
5213 TokenStream::new(vec![
5215 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5223 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5225 token::Ident(ident, _) if ident.name == "macro_rules" &&
5226 self.look_ahead(1, |t| *t == token::Not) => {
5227 let prev_span = self.prev_span;
5228 self.complain_if_pub_macro(&vis.node, prev_span);
5232 let ident = self.parse_ident()?;
5233 let (delim, tokens) = self.expect_delimited_token_tree()?;
5234 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5235 self.report_invalid_macro_expansion_item();
5238 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5240 _ => return Ok(None),
5243 let span = lo.to(self.prev_span);
5244 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5247 fn parse_stmt_without_recovery(&mut self,
5248 macro_legacy_warnings: bool)
5249 -> PResult<'a, Option<Stmt>> {
5250 maybe_whole!(self, NtStmt, |x| Some(x));
5252 let attrs = self.parse_outer_attributes()?;
5255 Ok(Some(if self.eat_keyword(keywords::Let) {
5257 id: ast::DUMMY_NODE_ID,
5258 node: StmtKind::Local(self.parse_local(attrs.into())?),
5259 span: lo.to(self.prev_span),
5261 } else if let Some(macro_def) = self.eat_macro_def(
5263 &source_map::respan(lo, VisibilityKind::Inherited),
5267 id: ast::DUMMY_NODE_ID,
5268 node: StmtKind::Item(macro_def),
5269 span: lo.to(self.prev_span),
5271 // Starts like a simple path, being careful to avoid contextual keywords
5272 // such as a union items, item with `crate` visibility or auto trait items.
5273 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5274 // like a path (1 token), but it fact not a path.
5275 // `union::b::c` - path, `union U { ... }` - not a path.
5276 // `crate::b::c` - path, `crate struct S;` - not a path.
5277 } else if self.token.is_path_start() &&
5278 !self.token.is_qpath_start() &&
5279 !self.is_union_item() &&
5280 !self.is_crate_vis() &&
5281 !self.is_existential_type_decl() &&
5282 !self.is_auto_trait_item() &&
5283 !self.is_async_fn() {
5284 let pth = self.parse_path(PathStyle::Expr)?;
5286 if !self.eat(&token::Not) {
5287 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5288 self.parse_struct_expr(lo, pth, ThinVec::new())?
5290 let hi = self.prev_span;
5291 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5294 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5295 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5296 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5299 return Ok(Some(Stmt {
5300 id: ast::DUMMY_NODE_ID,
5301 node: StmtKind::Expr(expr),
5302 span: lo.to(self.prev_span),
5306 // it's a macro invocation
5307 let id = match self.token {
5308 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5309 _ => self.parse_ident()?,
5312 // check that we're pointing at delimiters (need to check
5313 // again after the `if`, because of `parse_ident`
5314 // consuming more tokens).
5316 token::OpenDelim(_) => {}
5318 // we only expect an ident if we didn't parse one
5320 let ident_str = if id.name == keywords::Invalid.name() {
5325 let tok_str = self.this_token_descr();
5326 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5329 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5334 let (delim, tts) = self.expect_delimited_token_tree()?;
5335 let hi = self.prev_span;
5337 let style = if delim == MacDelimiter::Brace {
5338 MacStmtStyle::Braces
5340 MacStmtStyle::NoBraces
5343 if id.name == keywords::Invalid.name() {
5344 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5345 let node = if delim == MacDelimiter::Brace ||
5346 self.token == token::Semi || self.token == token::Eof {
5347 StmtKind::Mac(P((mac, style, attrs.into())))
5349 // We used to incorrectly stop parsing macro-expanded statements here.
5350 // If the next token will be an error anyway but could have parsed with the
5351 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5352 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5353 // These can continue an expression, so we can't stop parsing and warn.
5354 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5355 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5356 token::BinOp(token::And) | token::BinOp(token::Or) |
5357 token::AndAnd | token::OrOr |
5358 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5361 self.warn_missing_semicolon();
5362 StmtKind::Mac(P((mac, style, attrs.into())))
5364 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5365 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5366 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5367 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5371 id: ast::DUMMY_NODE_ID,
5376 // if it has a special ident, it's definitely an item
5378 // Require a semicolon or braces.
5379 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5380 self.report_invalid_macro_expansion_item();
5382 let span = lo.to(hi);
5384 id: ast::DUMMY_NODE_ID,
5386 node: StmtKind::Item({
5388 span, id /*id is good here*/,
5389 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5390 respan(lo, VisibilityKind::Inherited),
5396 // FIXME: Bad copy of attrs
5397 let old_directory_ownership =
5398 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5399 let item = self.parse_item_(attrs.clone(), false, true)?;
5400 self.directory.ownership = old_directory_ownership;
5404 id: ast::DUMMY_NODE_ID,
5405 span: lo.to(i.span),
5406 node: StmtKind::Item(i),
5409 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5410 if !attrs.is_empty() {
5411 if s.prev_token_kind == PrevTokenKind::DocComment {
5412 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5413 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5414 s.span_err(s.span, "expected statement after outer attribute");
5419 // Do not attempt to parse an expression if we're done here.
5420 if self.token == token::Semi {
5421 unused_attrs(&attrs, self);
5426 if self.token == token::CloseDelim(token::Brace) {
5427 unused_attrs(&attrs, self);
5431 // Remainder are line-expr stmts.
5432 let e = self.parse_expr_res(
5433 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5435 id: ast::DUMMY_NODE_ID,
5436 span: lo.to(e.span),
5437 node: StmtKind::Expr(e),
5444 /// Checks if this expression is a successfully parsed statement.
5445 fn expr_is_complete(&mut self, e: &Expr) -> bool {
5446 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5447 !classify::expr_requires_semi_to_be_stmt(e)
5450 /// Parses a block. No inner attributes are allowed.
5451 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5452 maybe_whole!(self, NtBlock, |x| x);
5456 if !self.eat(&token::OpenDelim(token::Brace)) {
5458 let tok = self.this_token_descr();
5459 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5460 let do_not_suggest_help =
5461 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5463 if self.token.is_ident_named("and") {
5464 e.span_suggestion_short(
5466 "use `&&` instead of `and` for the boolean operator",
5468 Applicability::MaybeIncorrect,
5471 if self.token.is_ident_named("or") {
5472 e.span_suggestion_short(
5474 "use `||` instead of `or` for the boolean operator",
5476 Applicability::MaybeIncorrect,
5480 // Check to see if the user has written something like
5485 // Which is valid in other languages, but not Rust.
5486 match self.parse_stmt_without_recovery(false) {
5488 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5489 || do_not_suggest_help {
5490 // if the next token is an open brace (e.g., `if a b {`), the place-
5491 // inside-a-block suggestion would be more likely wrong than right
5492 e.span_label(sp, "expected `{`");
5495 let mut stmt_span = stmt.span;
5496 // expand the span to include the semicolon, if it exists
5497 if self.eat(&token::Semi) {
5498 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5500 let sugg = pprust::to_string(|s| {
5501 use crate::print::pprust::{PrintState, INDENT_UNIT};
5502 s.ibox(INDENT_UNIT)?;
5504 s.print_stmt(&stmt)?;
5505 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5509 "try placing this code inside a block",
5511 // speculative, has been misleading in the past (closed Issue #46836)
5512 Applicability::MaybeIncorrect
5516 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5517 self.cancel(&mut e);
5521 e.span_label(sp, "expected `{`");
5525 self.parse_block_tail(lo, BlockCheckMode::Default)
5528 /// Parses a block. Inner attributes are allowed.
5529 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5530 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5533 self.expect(&token::OpenDelim(token::Brace))?;
5534 Ok((self.parse_inner_attributes()?,
5535 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5538 /// Parses the rest of a block expression or function body.
5539 /// Precondition: already parsed the '{'.
5540 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5541 let mut stmts = vec![];
5542 while !self.eat(&token::CloseDelim(token::Brace)) {
5543 let stmt = match self.parse_full_stmt(false) {
5546 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5548 id: ast::DUMMY_NODE_ID,
5549 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5555 if let Some(stmt) = stmt {
5557 } else if self.token == token::Eof {
5560 // Found only `;` or `}`.
5566 id: ast::DUMMY_NODE_ID,
5568 span: lo.to(self.prev_span),
5572 /// Parses a statement, including the trailing semicolon.
5573 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5574 // skip looking for a trailing semicolon when we have an interpolated statement
5575 maybe_whole!(self, NtStmt, |x| Some(x));
5577 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5579 None => return Ok(None),
5583 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5584 // expression without semicolon
5585 if classify::expr_requires_semi_to_be_stmt(expr) {
5586 // Just check for errors and recover; do not eat semicolon yet.
5588 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5591 self.recover_stmt();
5595 StmtKind::Local(..) => {
5596 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5597 if macro_legacy_warnings && self.token != token::Semi {
5598 self.warn_missing_semicolon();
5600 self.expect_one_of(&[], &[token::Semi])?;
5606 if self.eat(&token::Semi) {
5607 stmt = stmt.add_trailing_semicolon();
5610 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5614 fn warn_missing_semicolon(&self) {
5615 self.diagnostic().struct_span_warn(self.span, {
5616 &format!("expected `;`, found {}", self.this_token_descr())
5618 "This was erroneously allowed and will become a hard error in a future release"
5622 fn err_dotdotdot_syntax(&self, span: Span) {
5623 self.diagnostic().struct_span_err(span, {
5624 "unexpected token: `...`"
5626 span, "use `..` for an exclusive range", "..".to_owned(),
5627 Applicability::MaybeIncorrect
5629 span, "or `..=` for an inclusive range", "..=".to_owned(),
5630 Applicability::MaybeIncorrect
5634 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5637 /// BOUND = TY_BOUND | LT_BOUND
5638 /// LT_BOUND = LIFETIME (e.g., `'a`)
5639 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5640 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5642 fn parse_generic_bounds_common(&mut self,
5644 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5645 let mut bounds = Vec::new();
5646 let mut negative_bounds = Vec::new();
5647 let mut last_plus_span = None;
5648 let mut was_negative = false;
5650 // This needs to be synchronized with `Token::can_begin_bound`.
5651 let is_bound_start = self.check_path() || self.check_lifetime() ||
5652 self.check(&token::Not) || // used for error reporting only
5653 self.check(&token::Question) ||
5654 self.check_keyword(keywords::For) ||
5655 self.check(&token::OpenDelim(token::Paren));
5658 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5659 let inner_lo = self.span;
5660 let is_negative = self.eat(&token::Not);
5661 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5662 if self.token.is_lifetime() {
5663 if let Some(question_span) = question {
5664 self.span_err(question_span,
5665 "`?` may only modify trait bounds, not lifetime bounds");
5667 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5669 let inner_span = inner_lo.to(self.prev_span);
5670 self.expect(&token::CloseDelim(token::Paren))?;
5671 let mut err = self.struct_span_err(
5672 lo.to(self.prev_span),
5673 "parenthesized lifetime bounds are not supported"
5675 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5676 err.span_suggestion_short(
5677 lo.to(self.prev_span),
5678 "remove the parentheses",
5680 Applicability::MachineApplicable
5686 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5687 let path = self.parse_path(PathStyle::Type)?;
5689 self.expect(&token::CloseDelim(token::Paren))?;
5691 let poly_span = lo.to(self.prev_span);
5693 was_negative = true;
5694 if let Some(sp) = last_plus_span.or(colon_span) {
5695 negative_bounds.push(sp.to(poly_span));
5698 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5699 let modifier = if question.is_some() {
5700 TraitBoundModifier::Maybe
5702 TraitBoundModifier::None
5704 bounds.push(GenericBound::Trait(poly_trait, modifier));
5711 if !allow_plus || !self.eat_plus() {
5714 last_plus_span = Some(self.prev_span);
5718 if !negative_bounds.is_empty() || was_negative {
5719 let plural = negative_bounds.len() > 1;
5720 let last_span = negative_bounds.last().map(|sp| *sp);
5721 let mut err = self.struct_span_err(
5723 "negative trait bounds are not supported",
5725 if let Some(sp) = last_span {
5726 err.span_label(sp, "negative trait bounds are not supported");
5728 if let Some(bound_list) = colon_span {
5729 let bound_list = bound_list.to(self.prev_span);
5730 let mut new_bound_list = String::new();
5731 if !bounds.is_empty() {
5732 let mut snippets = bounds.iter().map(|bound| bound.span())
5733 .map(|span| self.sess.source_map().span_to_snippet(span));
5734 while let Some(Ok(snippet)) = snippets.next() {
5735 new_bound_list.push_str(" + ");
5736 new_bound_list.push_str(&snippet);
5738 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5740 err.span_suggestion_hidden(
5742 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5744 Applicability::MachineApplicable,
5753 crate fn parse_generic_bounds(&mut self,
5754 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5755 self.parse_generic_bounds_common(true, colon_span)
5758 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5761 /// BOUND = LT_BOUND (e.g., `'a`)
5763 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5764 let mut lifetimes = Vec::new();
5765 while self.check_lifetime() {
5766 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5768 if !self.eat_plus() {
5775 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5776 fn parse_ty_param(&mut self,
5777 preceding_attrs: Vec<Attribute>)
5778 -> PResult<'a, GenericParam> {
5779 let ident = self.parse_ident()?;
5781 // Parse optional colon and param bounds.
5782 let bounds = if self.eat(&token::Colon) {
5783 self.parse_generic_bounds(Some(self.prev_span))?
5788 let default = if self.eat(&token::Eq) {
5789 Some(self.parse_ty()?)
5796 id: ast::DUMMY_NODE_ID,
5797 attrs: preceding_attrs.into(),
5799 kind: GenericParamKind::Type {
5805 /// Parses the following grammar:
5807 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5808 fn parse_trait_item_assoc_ty(&mut self)
5809 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5810 let ident = self.parse_ident()?;
5811 let mut generics = self.parse_generics()?;
5813 // Parse optional colon and param bounds.
5814 let bounds = if self.eat(&token::Colon) {
5815 self.parse_generic_bounds(None)?
5819 generics.where_clause = self.parse_where_clause()?;
5821 let default = if self.eat(&token::Eq) {
5822 Some(self.parse_ty()?)
5826 self.expect(&token::Semi)?;
5828 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5831 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5832 self.expect_keyword(keywords::Const)?;
5833 let ident = self.parse_ident()?;
5834 self.expect(&token::Colon)?;
5835 let ty = self.parse_ty()?;
5839 id: ast::DUMMY_NODE_ID,
5840 attrs: preceding_attrs.into(),
5842 kind: GenericParamKind::Const {
5848 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5849 /// a trailing comma and erroneous trailing attributes.
5850 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5851 let mut params = Vec::new();
5853 let attrs = self.parse_outer_attributes()?;
5854 if self.check_lifetime() {
5855 let lifetime = self.expect_lifetime();
5856 // Parse lifetime parameter.
5857 let bounds = if self.eat(&token::Colon) {
5858 self.parse_lt_param_bounds()
5862 params.push(ast::GenericParam {
5863 ident: lifetime.ident,
5865 attrs: attrs.into(),
5867 kind: ast::GenericParamKind::Lifetime,
5869 } else if self.check_keyword(keywords::Const) {
5870 // Parse const parameter.
5871 params.push(self.parse_const_param(attrs)?);
5872 } else if self.check_ident() {
5873 // Parse type parameter.
5874 params.push(self.parse_ty_param(attrs)?);
5876 // Check for trailing attributes and stop parsing.
5877 if !attrs.is_empty() {
5878 if !params.is_empty() {
5879 self.struct_span_err(
5881 &format!("trailing attribute after generic parameter"),
5883 .span_label(attrs[0].span, "attributes must go before parameters")
5886 self.struct_span_err(
5888 &format!("attribute without generic parameters"),
5892 "attributes are only permitted when preceding parameters",
5900 if !self.eat(&token::Comma) {
5907 /// Parses a set of optional generic type parameter declarations. Where
5908 /// clauses are not parsed here, and must be added later via
5909 /// `parse_where_clause()`.
5911 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5912 /// | ( < lifetimes , typaramseq ( , )? > )
5913 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5914 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5915 maybe_whole!(self, NtGenerics, |x| x);
5917 let span_lo = self.span;
5919 let params = self.parse_generic_params()?;
5923 where_clause: WhereClause {
5924 id: ast::DUMMY_NODE_ID,
5925 predicates: Vec::new(),
5926 span: syntax_pos::DUMMY_SP,
5928 span: span_lo.to(self.prev_span),
5931 Ok(ast::Generics::default())
5935 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5936 /// For the purposes of understanding the parsing logic of generic arguments, this function
5937 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5938 /// had the correct amount of leading angle brackets.
5940 /// ```ignore (diagnostics)
5941 /// bar::<<<<T as Foo>::Output>();
5942 /// ^^ help: remove extra angle brackets
5944 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5948 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5949 // We need to detect whether there are extra leading left angle brackets and produce an
5950 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5951 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5952 // then there won't be matching `>` tokens to find.
5954 // To explain how this detection works, consider the following example:
5956 // ```ignore (diagnostics)
5957 // bar::<<<<T as Foo>::Output>();
5958 // ^^ help: remove extra angle brackets
5961 // Parsing of the left angle brackets starts in this function. We start by parsing the
5962 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5965 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5966 // *Unmatched count:* 1
5967 // *`parse_path_segment` calls deep:* 0
5969 // This has the effect of recursing as this function is called if a `<` character
5970 // is found within the expected generic arguments:
5972 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5973 // *Unmatched count:* 2
5974 // *`parse_path_segment` calls deep:* 1
5976 // Eventually we will have recursed until having consumed all of the `<` tokens and
5977 // this will be reflected in the count:
5979 // *Upcoming tokens:* `T as Foo>::Output>;`
5980 // *Unmatched count:* 4
5981 // `parse_path_segment` calls deep:* 3
5983 // The parser will continue until reaching the first `>` - this will decrement the
5984 // unmatched angle bracket count and return to the parent invocation of this function
5985 // having succeeded in parsing:
5987 // *Upcoming tokens:* `::Output>;`
5988 // *Unmatched count:* 3
5989 // *`parse_path_segment` calls deep:* 2
5991 // This will continue until the next `>` character which will also return successfully
5992 // to the parent invocation of this function and decrement the count:
5994 // *Upcoming tokens:* `;`
5995 // *Unmatched count:* 2
5996 // *`parse_path_segment` calls deep:* 1
5998 // At this point, this function will expect to find another matching `>` character but
5999 // won't be able to and will return an error. This will continue all the way up the
6000 // call stack until the first invocation:
6002 // *Upcoming tokens:* `;`
6003 // *Unmatched count:* 2
6004 // *`parse_path_segment` calls deep:* 0
6006 // In doing this, we have managed to work out how many unmatched leading left angle
6007 // brackets there are, but we cannot recover as the unmatched angle brackets have
6008 // already been consumed. To remedy this, we keep a snapshot of the parser state
6009 // before we do the above. We can then inspect whether we ended up with a parsing error
6010 // and unmatched left angle brackets and if so, restore the parser state before we
6011 // consumed any `<` characters to emit an error and consume the erroneous tokens to
6012 // recover by attempting to parse again.
6014 // In practice, the recursion of this function is indirect and there will be other
6015 // locations that consume some `<` characters - as long as we update the count when
6016 // this happens, it isn't an issue.
6018 let is_first_invocation = style == PathStyle::Expr;
6019 // Take a snapshot before attempting to parse - we can restore this later.
6020 let snapshot = if is_first_invocation {
6026 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
6027 match self.parse_generic_args() {
6028 Ok(value) => Ok(value),
6029 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
6030 // Cancel error from being unable to find `>`. We know the error
6031 // must have been this due to a non-zero unmatched angle bracket
6035 // Swap `self` with our backup of the parser state before attempting to parse
6036 // generic arguments.
6037 let snapshot = mem::replace(self, snapshot.unwrap());
6040 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
6041 snapshot.count={:?}",
6042 snapshot.unmatched_angle_bracket_count,
6045 // Eat the unmatched angle brackets.
6046 for _ in 0..snapshot.unmatched_angle_bracket_count {
6050 // Make a span over ${unmatched angle bracket count} characters.
6051 let span = lo.with_hi(
6052 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
6054 let plural = snapshot.unmatched_angle_bracket_count > 1;
6059 "unmatched angle bracket{}",
6060 if plural { "s" } else { "" }
6066 "remove extra angle bracket{}",
6067 if plural { "s" } else { "" }
6070 Applicability::MachineApplicable,
6074 // Try again without unmatched angle bracket characters.
6075 self.parse_generic_args()
6081 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
6082 /// possibly including trailing comma.
6083 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6084 let mut args = Vec::new();
6085 let mut bindings = Vec::new();
6086 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
6087 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
6089 let args_lo = self.span;
6092 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6093 // Parse lifetime argument.
6094 args.push(GenericArg::Lifetime(self.expect_lifetime()));
6095 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6096 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
6097 // Parse associated type binding.
6099 let ident = self.parse_ident()?;
6101 let ty = self.parse_ty()?;
6102 let span = lo.to(self.prev_span);
6103 bindings.push(TypeBinding {
6104 id: ast::DUMMY_NODE_ID,
6109 assoc_ty_bindings.push(span);
6110 } else if self.check_const_arg() {
6111 // Parse const argument.
6112 let expr = if let token::OpenDelim(token::Brace) = self.token {
6113 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
6114 } else if self.token.is_ident() {
6115 // FIXME(const_generics): to distinguish between idents for types and consts,
6116 // we should introduce a GenericArg::Ident in the AST and distinguish when
6117 // lowering to the HIR. For now, idents for const args are not permitted.
6119 self.fatal("identifiers may currently not be used for const generics")
6122 self.parse_literal_maybe_minus()?
6124 let value = AnonConst {
6125 id: ast::DUMMY_NODE_ID,
6128 args.push(GenericArg::Const(value));
6129 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6130 } else if self.check_type() {
6131 // Parse type argument.
6132 args.push(GenericArg::Type(self.parse_ty()?));
6133 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6138 if !self.eat(&token::Comma) {
6143 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6144 // preserve ordering of generic parameters with respect to associated type binding, so we
6145 // lose that information after parsing.
6146 if misplaced_assoc_ty_bindings.len() > 0 {
6147 let mut err = self.struct_span_err(
6148 args_lo.to(self.prev_span),
6149 "associated type bindings must be declared after generic parameters",
6151 for span in misplaced_assoc_ty_bindings {
6154 "this associated type binding should be moved after the generic parameters",
6160 Ok((args, bindings))
6163 /// Parses an optional where-clause and places it in `generics`.
6165 /// ```ignore (only-for-syntax-highlight)
6166 /// where T : Trait<U, V> + 'b, 'a : 'b
6168 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6169 maybe_whole!(self, NtWhereClause, |x| x);
6171 let mut where_clause = WhereClause {
6172 id: ast::DUMMY_NODE_ID,
6173 predicates: Vec::new(),
6174 span: syntax_pos::DUMMY_SP,
6177 if !self.eat_keyword(keywords::Where) {
6178 return Ok(where_clause);
6180 let lo = self.prev_span;
6182 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6183 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6184 // change we parse those generics now, but report an error.
6185 if self.choose_generics_over_qpath() {
6186 let generics = self.parse_generics()?;
6187 self.struct_span_err(
6189 "generic parameters on `where` clauses are reserved for future use",
6191 .span_label(generics.span, "currently unsupported")
6197 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6198 let lifetime = self.expect_lifetime();
6199 // Bounds starting with a colon are mandatory, but possibly empty.
6200 self.expect(&token::Colon)?;
6201 let bounds = self.parse_lt_param_bounds();
6202 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6203 ast::WhereRegionPredicate {
6204 span: lo.to(self.prev_span),
6209 } else if self.check_type() {
6210 // Parse optional `for<'a, 'b>`.
6211 // This `for` is parsed greedily and applies to the whole predicate,
6212 // the bounded type can have its own `for` applying only to it.
6213 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6214 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6215 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6216 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6218 // Parse type with mandatory colon and (possibly empty) bounds,
6219 // or with mandatory equality sign and the second type.
6220 let ty = self.parse_ty()?;
6221 if self.eat(&token::Colon) {
6222 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6223 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6224 ast::WhereBoundPredicate {
6225 span: lo.to(self.prev_span),
6226 bound_generic_params: lifetime_defs,
6231 // FIXME: Decide what should be used here, `=` or `==`.
6232 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6233 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6234 let rhs_ty = self.parse_ty()?;
6235 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6236 ast::WhereEqPredicate {
6237 span: lo.to(self.prev_span),
6240 id: ast::DUMMY_NODE_ID,
6244 return self.unexpected();
6250 if !self.eat(&token::Comma) {
6255 where_clause.span = lo.to(self.prev_span);
6259 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6260 -> PResult<'a, (Vec<Arg> , bool)> {
6261 self.expect(&token::OpenDelim(token::Paren))?;
6264 let mut c_variadic = false;
6265 let (args, recovered): (Vec<Option<Arg>>, bool) =
6266 self.parse_seq_to_before_end(
6267 &token::CloseDelim(token::Paren),
6268 SeqSep::trailing_allowed(token::Comma),
6270 // If the argument is a C-variadic argument we should not
6271 // enforce named arguments.
6272 let enforce_named_args = if p.token == token::DotDotDot {
6277 match p.parse_arg_general(enforce_named_args, false,
6280 if let TyKind::CVarArgs = arg.ty.node {
6282 if p.token != token::CloseDelim(token::Paren) {
6285 "`...` must be the last argument of a C-variadic function");
6296 let lo = p.prev_span;
6297 // Skip every token until next possible arg or end.
6298 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6299 // Create a placeholder argument for proper arg count (issue #34264).
6300 let span = lo.to(p.prev_span);
6301 Ok(Some(dummy_arg(span)))
6308 self.eat(&token::CloseDelim(token::Paren));
6311 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6313 if c_variadic && args.is_empty() {
6315 "C-variadic function must be declared with at least one named argument");
6318 Ok((args, c_variadic))
6321 /// Parses the argument list and result type of a function declaration.
6322 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6324 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6325 let ret_ty = self.parse_ret_ty(true)?;
6334 /// Returns the parsed optional self argument and whether a self shortcut was used.
6335 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6336 let expect_ident = |this: &mut Self| match this.token {
6337 // Preserve hygienic context.
6338 token::Ident(ident, _) =>
6339 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6342 let isolated_self = |this: &mut Self, n| {
6343 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6344 this.look_ahead(n + 1, |t| t != &token::ModSep)
6347 // Parse optional self parameter of a method.
6348 // Only a limited set of initial token sequences is considered self parameters, anything
6349 // else is parsed as a normal function parameter list, so some lookahead is required.
6350 let eself_lo = self.span;
6351 let (eself, eself_ident, eself_hi) = match self.token {
6352 token::BinOp(token::And) => {
6358 (if isolated_self(self, 1) {
6360 SelfKind::Region(None, Mutability::Immutable)
6361 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6362 isolated_self(self, 2) {
6365 SelfKind::Region(None, Mutability::Mutable)
6366 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6367 isolated_self(self, 2) {
6369 let lt = self.expect_lifetime();
6370 SelfKind::Region(Some(lt), Mutability::Immutable)
6371 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6372 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6373 isolated_self(self, 3) {
6375 let lt = self.expect_lifetime();
6377 SelfKind::Region(Some(lt), Mutability::Mutable)
6380 }, expect_ident(self), self.prev_span)
6382 token::BinOp(token::Star) => {
6387 // Emit special error for `self` cases.
6388 let msg = "cannot pass `self` by raw pointer";
6389 (if isolated_self(self, 1) {
6391 self.struct_span_err(self.span, msg)
6392 .span_label(self.span, msg)
6394 SelfKind::Value(Mutability::Immutable)
6395 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6396 isolated_self(self, 2) {
6399 self.struct_span_err(self.span, msg)
6400 .span_label(self.span, msg)
6402 SelfKind::Value(Mutability::Immutable)
6405 }, expect_ident(self), self.prev_span)
6407 token::Ident(..) => {
6408 if isolated_self(self, 0) {
6411 let eself_ident = expect_ident(self);
6412 let eself_hi = self.prev_span;
6413 (if self.eat(&token::Colon) {
6414 let ty = self.parse_ty()?;
6415 SelfKind::Explicit(ty, Mutability::Immutable)
6417 SelfKind::Value(Mutability::Immutable)
6418 }, eself_ident, eself_hi)
6419 } else if self.token.is_keyword(keywords::Mut) &&
6420 isolated_self(self, 1) {
6424 let eself_ident = expect_ident(self);
6425 let eself_hi = self.prev_span;
6426 (if self.eat(&token::Colon) {
6427 let ty = self.parse_ty()?;
6428 SelfKind::Explicit(ty, Mutability::Mutable)
6430 SelfKind::Value(Mutability::Mutable)
6431 }, eself_ident, eself_hi)
6436 _ => return Ok(None),
6439 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6440 Ok(Some(Arg::from_self(eself, eself_ident)))
6443 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6444 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6445 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6447 self.expect(&token::OpenDelim(token::Paren))?;
6449 // Parse optional self argument
6450 let self_arg = self.parse_self_arg()?;
6452 // Parse the rest of the function parameter list.
6453 let sep = SeqSep::trailing_allowed(token::Comma);
6454 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6455 if self.check(&token::CloseDelim(token::Paren)) {
6456 (vec![self_arg], false)
6457 } else if self.eat(&token::Comma) {
6458 let mut fn_inputs = vec![self_arg];
6459 let (mut input, recovered) = self.parse_seq_to_before_end(
6460 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6461 fn_inputs.append(&mut input);
6462 (fn_inputs, recovered)
6464 match self.expect_one_of(&[], &[]) {
6465 Err(err) => return Err(err),
6466 Ok(recovered) => (vec![self_arg], recovered),
6470 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6474 // Parse closing paren and return type.
6475 self.expect(&token::CloseDelim(token::Paren))?;
6479 output: self.parse_ret_ty(true)?,
6484 /// Parses the `|arg, arg|` header of a closure.
6485 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6486 let inputs_captures = {
6487 if self.eat(&token::OrOr) {
6490 self.expect(&token::BinOp(token::Or))?;
6491 let args = self.parse_seq_to_before_tokens(
6492 &[&token::BinOp(token::Or), &token::OrOr],
6493 SeqSep::trailing_allowed(token::Comma),
6494 TokenExpectType::NoExpect,
6495 |p| p.parse_fn_block_arg()
6501 let output = self.parse_ret_ty(true)?;
6504 inputs: inputs_captures,
6510 /// Parses the name and optional generic types of a function header.
6511 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6512 let id = self.parse_ident()?;
6513 let generics = self.parse_generics()?;
6517 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6518 attrs: Vec<Attribute>) -> P<Item> {
6522 id: ast::DUMMY_NODE_ID,
6530 /// Parses an item-position function declaration.
6531 fn parse_item_fn(&mut self,
6533 mut asyncness: Spanned<IsAsync>,
6534 constness: Spanned<Constness>,
6536 -> PResult<'a, ItemInfo> {
6537 let (ident, mut generics) = self.parse_fn_header()?;
6538 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6539 let mut decl = self.parse_fn_decl(allow_c_variadic)?;
6540 generics.where_clause = self.parse_where_clause()?;
6541 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6542 self.construct_async_arguments(&mut asyncness, &mut decl);
6543 let header = FnHeader { unsafety, asyncness, constness, abi };
6544 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6547 /// Returns `true` if we are looking at `const ID`
6548 /// (returns `false` for things like `const fn`, etc.).
6549 fn is_const_item(&mut self) -> bool {
6550 self.token.is_keyword(keywords::Const) &&
6551 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6552 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6555 /// Parses all the "front matter" for a `fn` declaration, up to
6556 /// and including the `fn` keyword:
6560 /// - `const unsafe fn`
6563 fn parse_fn_front_matter(&mut self)
6571 let is_const_fn = self.eat_keyword(keywords::Const);
6572 let const_span = self.prev_span;
6573 let unsafety = self.parse_unsafety();
6574 let asyncness = self.parse_asyncness();
6575 let asyncness = respan(self.prev_span, asyncness);
6576 let (constness, unsafety, abi) = if is_const_fn {
6577 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6579 let abi = if self.eat_keyword(keywords::Extern) {
6580 self.parse_opt_abi()?.unwrap_or(Abi::C)
6584 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6586 if !self.eat_keyword(keywords::Fn) {
6587 // It is possible for `expect_one_of` to recover given the contents of
6588 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6589 // account for this.
6590 if !self.expect_one_of(&[], &[])? { unreachable!() }
6592 Ok((constness, unsafety, asyncness, abi))
6595 /// Parses an impl item.
6596 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6597 maybe_whole!(self, NtImplItem, |x| x);
6598 let attrs = self.parse_outer_attributes()?;
6599 let mut unclosed_delims = vec![];
6600 let (mut item, tokens) = self.collect_tokens(|this| {
6601 let item = this.parse_impl_item_(at_end, attrs);
6602 unclosed_delims.append(&mut this.unclosed_delims);
6605 self.unclosed_delims.append(&mut unclosed_delims);
6607 // See `parse_item` for why this clause is here.
6608 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6609 item.tokens = Some(tokens);
6614 fn parse_impl_item_(&mut self,
6616 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6618 let vis = self.parse_visibility(false)?;
6619 let defaultness = self.parse_defaultness();
6620 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6621 let (name, alias, generics) = type_?;
6622 let kind = match alias {
6623 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6624 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6626 (name, kind, generics)
6627 } else if self.is_const_item() {
6628 // This parses the grammar:
6629 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6630 self.expect_keyword(keywords::Const)?;
6631 let name = self.parse_ident()?;
6632 self.expect(&token::Colon)?;
6633 let typ = self.parse_ty()?;
6634 self.expect(&token::Eq)?;
6635 let expr = self.parse_expr()?;
6636 self.expect(&token::Semi)?;
6637 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6639 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6640 attrs.extend(inner_attrs);
6641 (name, node, generics)
6645 id: ast::DUMMY_NODE_ID,
6646 span: lo.to(self.prev_span),
6657 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6659 VisibilityKind::Inherited => {}
6661 let is_macro_rules: bool = match self.token {
6662 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6665 let mut err = if is_macro_rules {
6666 let mut err = self.diagnostic()
6667 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6668 err.span_suggestion(
6670 "try exporting the macro",
6671 "#[macro_export]".to_owned(),
6672 Applicability::MaybeIncorrect // speculative
6676 let mut err = self.diagnostic()
6677 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6678 err.help("try adjusting the macro to put `pub` inside the invocation");
6686 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6687 -> DiagnosticBuilder<'a>
6689 let expected_kinds = if item_type == "extern" {
6690 "missing `fn`, `type`, or `static`"
6692 "missing `fn`, `type`, or `const`"
6695 // Given this code `path(`, it seems like this is not
6696 // setting the visibility of a macro invocation, but rather
6697 // a mistyped method declaration.
6698 // Create a diagnostic pointing out that `fn` is missing.
6700 // x | pub path(&self) {
6701 // | ^ missing `fn`, `type`, or `const`
6703 // ^^ `sp` below will point to this
6704 let sp = prev_span.between(self.prev_span);
6705 let mut err = self.diagnostic().struct_span_err(
6707 &format!("{} for {}-item declaration",
6708 expected_kinds, item_type));
6709 err.span_label(sp, expected_kinds);
6713 /// Parse a method or a macro invocation in a trait impl.
6714 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6715 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6716 ast::ImplItemKind)> {
6717 // code copied from parse_macro_use_or_failure... abstraction!
6718 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6720 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6721 ast::ImplItemKind::Macro(mac)))
6723 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6724 let ident = self.parse_ident()?;
6725 let mut generics = self.parse_generics()?;
6726 let mut decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6727 generics.where_clause = self.parse_where_clause()?;
6728 self.construct_async_arguments(&mut asyncness, &mut decl);
6730 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6731 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6732 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6733 ast::MethodSig { header, decl },
6739 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6740 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6741 let ident = self.parse_ident()?;
6742 let mut tps = self.parse_generics()?;
6744 // Parse optional colon and supertrait bounds.
6745 let bounds = if self.eat(&token::Colon) {
6746 self.parse_generic_bounds(Some(self.prev_span))?
6751 if self.eat(&token::Eq) {
6752 // it's a trait alias
6753 let bounds = self.parse_generic_bounds(None)?;
6754 tps.where_clause = self.parse_where_clause()?;
6755 self.expect(&token::Semi)?;
6756 if is_auto == IsAuto::Yes {
6757 let msg = "trait aliases cannot be `auto`";
6758 self.struct_span_err(self.prev_span, msg)
6759 .span_label(self.prev_span, msg)
6762 if unsafety != Unsafety::Normal {
6763 let msg = "trait aliases cannot be `unsafe`";
6764 self.struct_span_err(self.prev_span, msg)
6765 .span_label(self.prev_span, msg)
6768 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6770 // it's a normal trait
6771 tps.where_clause = self.parse_where_clause()?;
6772 self.expect(&token::OpenDelim(token::Brace))?;
6773 let mut trait_items = vec![];
6774 while !self.eat(&token::CloseDelim(token::Brace)) {
6775 if let token::DocComment(_) = self.token {
6776 if self.look_ahead(1,
6777 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6778 let mut err = self.diagnostic().struct_span_err_with_code(
6780 "found a documentation comment that doesn't document anything",
6781 DiagnosticId::Error("E0584".into()),
6783 err.help("doc comments must come before what they document, maybe a \
6784 comment was intended with `//`?",
6791 let mut at_end = false;
6792 match self.parse_trait_item(&mut at_end) {
6793 Ok(item) => trait_items.push(item),
6797 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6802 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6806 fn choose_generics_over_qpath(&self) -> bool {
6807 // There's an ambiguity between generic parameters and qualified paths in impls.
6808 // If we see `<` it may start both, so we have to inspect some following tokens.
6809 // The following combinations can only start generics,
6810 // but not qualified paths (with one exception):
6811 // `<` `>` - empty generic parameters
6812 // `<` `#` - generic parameters with attributes
6813 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6814 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6815 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6816 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6817 // `<` const - generic const parameter
6818 // The only truly ambiguous case is
6819 // `<` IDENT `>` `::` IDENT ...
6820 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6821 // because this is what almost always expected in practice, qualified paths in impls
6822 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6823 self.token == token::Lt &&
6824 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6825 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6826 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6827 t == &token::Colon || t == &token::Eq) ||
6828 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6831 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6832 self.expect(&token::OpenDelim(token::Brace))?;
6833 let attrs = self.parse_inner_attributes()?;
6835 let mut impl_items = Vec::new();
6836 while !self.eat(&token::CloseDelim(token::Brace)) {
6837 let mut at_end = false;
6838 match self.parse_impl_item(&mut at_end) {
6839 Ok(impl_item) => impl_items.push(impl_item),
6843 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6848 Ok((impl_items, attrs))
6851 /// Parses an implementation item, `impl` keyword is already parsed.
6853 /// impl<'a, T> TYPE { /* impl items */ }
6854 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6855 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6857 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6858 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6859 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6860 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6861 -> PResult<'a, ItemInfo> {
6862 // First, parse generic parameters if necessary.
6863 let mut generics = if self.choose_generics_over_qpath() {
6864 self.parse_generics()?
6866 ast::Generics::default()
6869 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6870 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6872 ast::ImplPolarity::Negative
6874 ast::ImplPolarity::Positive
6877 // Parse both types and traits as a type, then reinterpret if necessary.
6878 let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6879 let ty_first = if self.token.is_keyword(keywords::For) &&
6880 self.look_ahead(1, |t| t != &token::Lt) {
6881 let span = self.prev_span.between(self.span);
6882 self.struct_span_err(span, "missing trait in a trait impl").emit();
6883 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6888 // If `for` is missing we try to recover.
6889 let has_for = self.eat_keyword(keywords::For);
6890 let missing_for_span = self.prev_span.between(self.span);
6892 let ty_second = if self.token == token::DotDot {
6893 // We need to report this error after `cfg` expansion for compatibility reasons
6894 self.bump(); // `..`, do not add it to expected tokens
6895 Some(DummyResult::raw_ty(self.prev_span, true))
6896 } else if has_for || self.token.can_begin_type() {
6897 Some(self.parse_ty()?)
6902 generics.where_clause = self.parse_where_clause()?;
6904 let (impl_items, attrs) = self.parse_impl_body()?;
6906 let item_kind = match ty_second {
6907 Some(ty_second) => {
6908 // impl Trait for Type
6910 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6911 .span_suggestion_short(
6914 " for ".to_string(),
6915 Applicability::MachineApplicable,
6919 let ty_first = ty_first.into_inner();
6920 let path = match ty_first.node {
6921 // This notably includes paths passed through `ty` macro fragments (#46438).
6922 TyKind::Path(None, path) => path,
6924 self.span_err(ty_first.span, "expected a trait, found type");
6925 err_path(ty_first.span)
6928 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6930 ItemKind::Impl(unsafety, polarity, defaultness,
6931 generics, Some(trait_ref), ty_second, impl_items)
6935 ItemKind::Impl(unsafety, polarity, defaultness,
6936 generics, None, ty_first, impl_items)
6940 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6943 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6944 if self.eat_keyword(keywords::For) {
6946 let params = self.parse_generic_params()?;
6948 // We rely on AST validation to rule out invalid cases: There must not be type
6949 // parameters, and the lifetime parameters must not have bounds.
6956 /// Parses `struct Foo { ... }`.
6957 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6958 let class_name = self.parse_ident()?;
6960 let mut generics = self.parse_generics()?;
6962 // There is a special case worth noting here, as reported in issue #17904.
6963 // If we are parsing a tuple struct it is the case that the where clause
6964 // should follow the field list. Like so:
6966 // struct Foo<T>(T) where T: Copy;
6968 // If we are parsing a normal record-style struct it is the case
6969 // that the where clause comes before the body, and after the generics.
6970 // So if we look ahead and see a brace or a where-clause we begin
6971 // parsing a record style struct.
6973 // Otherwise if we look ahead and see a paren we parse a tuple-style
6976 let vdata = if self.token.is_keyword(keywords::Where) {
6977 generics.where_clause = self.parse_where_clause()?;
6978 if self.eat(&token::Semi) {
6979 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6980 VariantData::Unit(ast::DUMMY_NODE_ID)
6982 // If we see: `struct Foo<T> where T: Copy { ... }`
6983 let (fields, recovered) = self.parse_record_struct_body()?;
6984 VariantData::Struct(fields, recovered)
6986 // No `where` so: `struct Foo<T>;`
6987 } else if self.eat(&token::Semi) {
6988 VariantData::Unit(ast::DUMMY_NODE_ID)
6989 // Record-style struct definition
6990 } else if self.token == token::OpenDelim(token::Brace) {
6991 let (fields, recovered) = self.parse_record_struct_body()?;
6992 VariantData::Struct(fields, recovered)
6993 // Tuple-style struct definition with optional where-clause.
6994 } else if self.token == token::OpenDelim(token::Paren) {
6995 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6996 generics.where_clause = self.parse_where_clause()?;
6997 self.expect(&token::Semi)?;
7000 let token_str = self.this_token_descr();
7001 let mut err = self.fatal(&format!(
7002 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
7005 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
7009 Ok((class_name, ItemKind::Struct(vdata, generics), None))
7012 /// Parses `union Foo { ... }`.
7013 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
7014 let class_name = self.parse_ident()?;
7016 let mut generics = self.parse_generics()?;
7018 let vdata = if self.token.is_keyword(keywords::Where) {
7019 generics.where_clause = self.parse_where_clause()?;
7020 let (fields, recovered) = self.parse_record_struct_body()?;
7021 VariantData::Struct(fields, recovered)
7022 } else if self.token == token::OpenDelim(token::Brace) {
7023 let (fields, recovered) = self.parse_record_struct_body()?;
7024 VariantData::Struct(fields, recovered)
7026 let token_str = self.this_token_descr();
7027 let mut err = self.fatal(&format!(
7028 "expected `where` or `{{` after union name, found {}", token_str));
7029 err.span_label(self.span, "expected `where` or `{` after union name");
7033 Ok((class_name, ItemKind::Union(vdata, generics), None))
7036 fn consume_block(&mut self, delim: token::DelimToken) {
7037 let mut brace_depth = 0;
7039 if self.eat(&token::OpenDelim(delim)) {
7041 } else if self.eat(&token::CloseDelim(delim)) {
7042 if brace_depth == 0 {
7048 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
7056 fn parse_record_struct_body(
7058 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
7059 let mut fields = Vec::new();
7060 let mut recovered = false;
7061 if self.eat(&token::OpenDelim(token::Brace)) {
7062 while self.token != token::CloseDelim(token::Brace) {
7063 let field = self.parse_struct_decl_field().map_err(|e| {
7064 self.recover_stmt();
7069 Ok(field) => fields.push(field),
7075 self.eat(&token::CloseDelim(token::Brace));
7077 let token_str = self.this_token_descr();
7078 let mut err = self.fatal(&format!(
7079 "expected `where`, or `{{` after struct name, found {}", token_str));
7080 err.span_label(self.span, "expected `where`, or `{` after struct name");
7084 Ok((fields, recovered))
7087 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
7088 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
7089 // Unit like structs are handled in parse_item_struct function
7090 let fields = self.parse_unspanned_seq(
7091 &token::OpenDelim(token::Paren),
7092 &token::CloseDelim(token::Paren),
7093 SeqSep::trailing_allowed(token::Comma),
7095 let attrs = p.parse_outer_attributes()?;
7097 let vis = p.parse_visibility(true)?;
7098 let ty = p.parse_ty()?;
7100 span: lo.to(ty.span),
7103 id: ast::DUMMY_NODE_ID,
7112 /// Parses a structure field declaration.
7113 fn parse_single_struct_field(&mut self,
7116 attrs: Vec<Attribute> )
7117 -> PResult<'a, StructField> {
7118 let mut seen_comma: bool = false;
7119 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
7120 if self.token == token::Comma {
7127 token::CloseDelim(token::Brace) => {}
7128 token::DocComment(_) => {
7129 let previous_span = self.prev_span;
7130 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
7131 self.bump(); // consume the doc comment
7132 let comma_after_doc_seen = self.eat(&token::Comma);
7133 // `seen_comma` is always false, because we are inside doc block
7134 // condition is here to make code more readable
7135 if seen_comma == false && comma_after_doc_seen == true {
7138 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7141 if seen_comma == false {
7142 let sp = self.sess.source_map().next_point(previous_span);
7143 err.span_suggestion(
7145 "missing comma here",
7147 Applicability::MachineApplicable
7154 let sp = self.sess.source_map().next_point(self.prev_span);
7155 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7156 self.this_token_descr()));
7157 if self.token.is_ident() {
7158 // This is likely another field; emit the diagnostic and keep going
7159 err.span_suggestion(
7161 "try adding a comma",
7163 Applicability::MachineApplicable,
7174 /// Parses an element of a struct declaration.
7175 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7176 let attrs = self.parse_outer_attributes()?;
7178 let vis = self.parse_visibility(false)?;
7179 self.parse_single_struct_field(lo, vis, attrs)
7182 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7183 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7184 /// If the following element can't be a tuple (i.e., it's a function definition), then
7185 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7186 /// so emit a proper diagnostic.
7187 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7188 maybe_whole!(self, NtVis, |x| x);
7190 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7191 if self.is_crate_vis() {
7192 self.bump(); // `crate`
7193 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7196 if !self.eat_keyword(keywords::Pub) {
7197 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7198 // keyword to grab a span from for inherited visibility; an empty span at the
7199 // beginning of the current token would seem to be the "Schelling span".
7200 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7202 let lo = self.prev_span;
7204 if self.check(&token::OpenDelim(token::Paren)) {
7205 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7206 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7207 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7208 // by the following tokens.
7209 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) &&
7210 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
7214 self.bump(); // `crate`
7215 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7217 lo.to(self.prev_span),
7218 VisibilityKind::Crate(CrateSugar::PubCrate),
7221 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7224 self.bump(); // `in`
7225 let path = self.parse_path(PathStyle::Mod)?; // `path`
7226 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7227 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7229 id: ast::DUMMY_NODE_ID,
7232 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7233 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7234 t.is_keyword(keywords::SelfLower))
7236 // `pub(self)` or `pub(super)`
7238 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7239 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7240 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7242 id: ast::DUMMY_NODE_ID,
7245 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7246 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7248 let msg = "incorrect visibility restriction";
7249 let suggestion = r##"some possible visibility restrictions are:
7250 `pub(crate)`: visible only on the current crate
7251 `pub(super)`: visible only in the current module's parent
7252 `pub(in path::to::module)`: visible only on the specified path"##;
7253 let path = self.parse_path(PathStyle::Mod)?;
7255 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7256 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7257 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7258 err.help(suggestion);
7259 err.span_suggestion(
7260 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7262 err.emit(); // emit diagnostic, but continue with public visibility
7266 Ok(respan(lo, VisibilityKind::Public))
7269 /// Parses defaultness (i.e., `default` or nothing).
7270 fn parse_defaultness(&mut self) -> Defaultness {
7271 // `pub` is included for better error messages
7272 if self.check_keyword(keywords::Default) &&
7273 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7274 t.is_keyword(keywords::Const) ||
7275 t.is_keyword(keywords::Fn) ||
7276 t.is_keyword(keywords::Unsafe) ||
7277 t.is_keyword(keywords::Extern) ||
7278 t.is_keyword(keywords::Type) ||
7279 t.is_keyword(keywords::Pub)) {
7280 self.bump(); // `default`
7281 Defaultness::Default
7287 /// Given a termination token, parses all of the items in a module.
7288 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7289 let mut items = vec![];
7290 while let Some(item) = self.parse_item()? {
7292 self.maybe_consume_incorrect_semicolon(&items);
7295 if !self.eat(term) {
7296 let token_str = self.this_token_descr();
7297 if !self.maybe_consume_incorrect_semicolon(&items) {
7298 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7299 err.span_label(self.span, "expected item");
7304 let hi = if self.span.is_dummy() {
7311 inner: inner_lo.to(hi),
7317 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7318 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7319 self.expect(&token::Colon)?;
7320 let ty = self.parse_ty()?;
7321 self.expect(&token::Eq)?;
7322 let e = self.parse_expr()?;
7323 self.expect(&token::Semi)?;
7324 let item = match m {
7325 Some(m) => ItemKind::Static(ty, m, e),
7326 None => ItemKind::Const(ty, e),
7328 Ok((id, item, None))
7331 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7332 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7333 let (in_cfg, outer_attrs) = {
7334 let mut strip_unconfigured = crate::config::StripUnconfigured {
7336 features: None, // don't perform gated feature checking
7338 let mut outer_attrs = outer_attrs.to_owned();
7339 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7340 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7343 let id_span = self.span;
7344 let id = self.parse_ident()?;
7345 if self.eat(&token::Semi) {
7346 if in_cfg && self.recurse_into_file_modules {
7347 // This mod is in an external file. Let's go get it!
7348 let ModulePathSuccess { path, directory_ownership, warn } =
7349 self.submod_path(id, &outer_attrs, id_span)?;
7350 let (module, mut attrs) =
7351 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7352 // Record that we fetched the mod from an external file
7354 let attr = Attribute {
7355 id: attr::mk_attr_id(),
7356 style: ast::AttrStyle::Outer,
7357 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7358 tokens: TokenStream::empty(),
7359 is_sugared_doc: false,
7360 span: syntax_pos::DUMMY_SP,
7362 attr::mark_known(&attr);
7365 Ok((id, ItemKind::Mod(module), Some(attrs)))
7367 let placeholder = ast::Mod {
7368 inner: syntax_pos::DUMMY_SP,
7372 Ok((id, ItemKind::Mod(placeholder), None))
7375 let old_directory = self.directory.clone();
7376 self.push_directory(id, &outer_attrs);
7378 self.expect(&token::OpenDelim(token::Brace))?;
7379 let mod_inner_lo = self.span;
7380 let attrs = self.parse_inner_attributes()?;
7381 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7383 self.directory = old_directory;
7384 Ok((id, ItemKind::Mod(module), Some(attrs)))
7388 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7389 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7390 self.directory.path.to_mut().push(&path.as_str());
7391 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7393 // We have to push on the current module name in the case of relative
7394 // paths in order to ensure that any additional module paths from inline
7395 // `mod x { ... }` come after the relative extension.
7397 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7398 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7399 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7400 if let Some(ident) = relative.take() { // remove the relative offset
7401 self.directory.path.to_mut().push(ident.as_str());
7404 self.directory.path.to_mut().push(&id.as_str());
7408 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7409 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7412 // On windows, the base path might have the form
7413 // `\\?\foo\bar` in which case it does not tolerate
7414 // mixed `/` and `\` separators, so canonicalize
7417 let s = s.replace("/", "\\");
7418 Some(dir_path.join(s))
7424 /// Returns a path to a module.
7425 pub fn default_submod_path(
7427 relative: Option<ast::Ident>,
7429 source_map: &SourceMap) -> ModulePath
7431 // If we're in a foo.rs file instead of a mod.rs file,
7432 // we need to look for submodules in
7433 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7434 // `./<id>.rs` and `./<id>/mod.rs`.
7435 let relative_prefix_string;
7436 let relative_prefix = if let Some(ident) = relative {
7437 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7438 &relative_prefix_string
7443 let mod_name = id.to_string();
7444 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7445 let secondary_path_str = format!("{}{}{}mod.rs",
7446 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7447 let default_path = dir_path.join(&default_path_str);
7448 let secondary_path = dir_path.join(&secondary_path_str);
7449 let default_exists = source_map.file_exists(&default_path);
7450 let secondary_exists = source_map.file_exists(&secondary_path);
7452 let result = match (default_exists, secondary_exists) {
7453 (true, false) => Ok(ModulePathSuccess {
7455 directory_ownership: DirectoryOwnership::Owned {
7460 (false, true) => Ok(ModulePathSuccess {
7461 path: secondary_path,
7462 directory_ownership: DirectoryOwnership::Owned {
7467 (false, false) => Err(Error::FileNotFoundForModule {
7468 mod_name: mod_name.clone(),
7469 default_path: default_path_str,
7470 secondary_path: secondary_path_str,
7471 dir_path: dir_path.display().to_string(),
7473 (true, true) => Err(Error::DuplicatePaths {
7474 mod_name: mod_name.clone(),
7475 default_path: default_path_str,
7476 secondary_path: secondary_path_str,
7482 path_exists: default_exists || secondary_exists,
7487 fn submod_path(&mut self,
7489 outer_attrs: &[Attribute],
7491 -> PResult<'a, ModulePathSuccess> {
7492 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7493 return Ok(ModulePathSuccess {
7494 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7495 // All `#[path]` files are treated as though they are a `mod.rs` file.
7496 // This means that `mod foo;` declarations inside `#[path]`-included
7497 // files are siblings,
7499 // Note that this will produce weirdness when a file named `foo.rs` is
7500 // `#[path]` included and contains a `mod foo;` declaration.
7501 // If you encounter this, it's your own darn fault :P
7502 Some(_) => DirectoryOwnership::Owned { relative: None },
7503 _ => DirectoryOwnership::UnownedViaMod(true),
7510 let relative = match self.directory.ownership {
7511 DirectoryOwnership::Owned { relative } => relative,
7512 DirectoryOwnership::UnownedViaBlock |
7513 DirectoryOwnership::UnownedViaMod(_) => None,
7515 let paths = Parser::default_submod_path(
7516 id, relative, &self.directory.path, self.sess.source_map());
7518 match self.directory.ownership {
7519 DirectoryOwnership::Owned { .. } => {
7520 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7522 DirectoryOwnership::UnownedViaBlock => {
7524 "Cannot declare a non-inline module inside a block \
7525 unless it has a path attribute";
7526 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7527 if paths.path_exists {
7528 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7530 err.span_note(id_sp, &msg);
7534 DirectoryOwnership::UnownedViaMod(warn) => {
7536 if let Ok(result) = paths.result {
7537 return Ok(ModulePathSuccess { warn: true, ..result });
7540 let mut err = self.diagnostic().struct_span_err(id_sp,
7541 "cannot declare a new module at this location");
7542 if !id_sp.is_dummy() {
7543 let src_path = self.sess.source_map().span_to_filename(id_sp);
7544 if let FileName::Real(src_path) = src_path {
7545 if let Some(stem) = src_path.file_stem() {
7546 let mut dest_path = src_path.clone();
7547 dest_path.set_file_name(stem);
7548 dest_path.push("mod.rs");
7549 err.span_note(id_sp,
7550 &format!("maybe move this module `{}` to its own \
7551 directory via `{}`", src_path.display(),
7552 dest_path.display()));
7556 if paths.path_exists {
7557 err.span_note(id_sp,
7558 &format!("... or maybe `use` the module `{}` instead \
7559 of possibly redeclaring it",
7567 /// Reads a module from a source file.
7568 fn eval_src_mod(&mut self,
7570 directory_ownership: DirectoryOwnership,
7573 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7574 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7575 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7576 let mut err = String::from("circular modules: ");
7577 let len = included_mod_stack.len();
7578 for p in &included_mod_stack[i.. len] {
7579 err.push_str(&p.to_string_lossy());
7580 err.push_str(" -> ");
7582 err.push_str(&path.to_string_lossy());
7583 return Err(self.span_fatal(id_sp, &err[..]));
7585 included_mod_stack.push(path.clone());
7586 drop(included_mod_stack);
7589 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7590 p0.cfg_mods = self.cfg_mods;
7591 let mod_inner_lo = p0.span;
7592 let mod_attrs = p0.parse_inner_attributes()?;
7593 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7595 self.sess.included_mod_stack.borrow_mut().pop();
7599 /// Parses a function declaration from a foreign module.
7600 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7601 -> PResult<'a, ForeignItem> {
7602 self.expect_keyword(keywords::Fn)?;
7604 let (ident, mut generics) = self.parse_fn_header()?;
7605 let decl = self.parse_fn_decl(true)?;
7606 generics.where_clause = self.parse_where_clause()?;
7608 self.expect(&token::Semi)?;
7609 Ok(ast::ForeignItem {
7612 node: ForeignItemKind::Fn(decl, generics),
7613 id: ast::DUMMY_NODE_ID,
7619 /// Parses a static item from a foreign module.
7620 /// Assumes that the `static` keyword is already parsed.
7621 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7622 -> PResult<'a, ForeignItem> {
7623 let mutbl = self.parse_mutability();
7624 let ident = self.parse_ident()?;
7625 self.expect(&token::Colon)?;
7626 let ty = self.parse_ty()?;
7628 self.expect(&token::Semi)?;
7632 node: ForeignItemKind::Static(ty, mutbl),
7633 id: ast::DUMMY_NODE_ID,
7639 /// Parses a type from a foreign module.
7640 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7641 -> PResult<'a, ForeignItem> {
7642 self.expect_keyword(keywords::Type)?;
7644 let ident = self.parse_ident()?;
7646 self.expect(&token::Semi)?;
7647 Ok(ast::ForeignItem {
7650 node: ForeignItemKind::Ty,
7651 id: ast::DUMMY_NODE_ID,
7657 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7658 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7659 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7661 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7662 self.parse_path_segment_ident()
7666 let mut idents = vec![];
7667 let mut replacement = vec![];
7668 let mut fixed_crate_name = false;
7669 // Accept `extern crate name-like-this` for better diagnostics
7670 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7671 if self.token == dash { // Do not include `-` as part of the expected tokens list
7672 while self.eat(&dash) {
7673 fixed_crate_name = true;
7674 replacement.push((self.prev_span, "_".to_string()));
7675 idents.push(self.parse_ident()?);
7678 if fixed_crate_name {
7679 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7680 let mut fixed_name = format!("{}", ident.name);
7681 for part in idents {
7682 fixed_name.push_str(&format!("_{}", part.name));
7684 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7686 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7687 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7688 err.multipart_suggestion(
7691 Applicability::MachineApplicable,
7698 /// Parses `extern crate` links.
7703 /// extern crate foo;
7704 /// extern crate bar as foo;
7706 fn parse_item_extern_crate(&mut self,
7708 visibility: Visibility,
7709 attrs: Vec<Attribute>)
7710 -> PResult<'a, P<Item>> {
7711 // Accept `extern crate name-like-this` for better diagnostics
7712 let orig_name = self.parse_crate_name_with_dashes()?;
7713 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7714 (rename, Some(orig_name.name))
7718 self.expect(&token::Semi)?;
7720 let span = lo.to(self.prev_span);
7721 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7724 /// Parses `extern` for foreign ABIs modules.
7726 /// `extern` is expected to have been
7727 /// consumed before calling this method.
7731 /// ```ignore (only-for-syntax-highlight)
7735 fn parse_item_foreign_mod(&mut self,
7737 opt_abi: Option<Abi>,
7738 visibility: Visibility,
7739 mut attrs: Vec<Attribute>)
7740 -> PResult<'a, P<Item>> {
7741 self.expect(&token::OpenDelim(token::Brace))?;
7743 let abi = opt_abi.unwrap_or(Abi::C);
7745 attrs.extend(self.parse_inner_attributes()?);
7747 let mut foreign_items = vec![];
7748 while !self.eat(&token::CloseDelim(token::Brace)) {
7749 foreign_items.push(self.parse_foreign_item()?);
7752 let prev_span = self.prev_span;
7753 let m = ast::ForeignMod {
7755 items: foreign_items
7757 let invalid = keywords::Invalid.ident();
7758 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7761 /// Parses `type Foo = Bar;`
7763 /// `existential type Foo: Bar;`
7766 /// without modifying the parser state.
7767 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7768 // This parses the grammar:
7769 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7770 if self.check_keyword(keywords::Type) ||
7771 self.check_keyword(keywords::Existential) &&
7772 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7773 let existential = self.eat_keyword(keywords::Existential);
7774 assert!(self.eat_keyword(keywords::Type));
7775 Some(self.parse_existential_or_alias(existential))
7781 /// Parses a type alias or existential type.
7782 fn parse_existential_or_alias(
7785 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7786 let ident = self.parse_ident()?;
7787 let mut tps = self.parse_generics()?;
7788 tps.where_clause = self.parse_where_clause()?;
7789 let alias = if existential {
7790 self.expect(&token::Colon)?;
7791 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7792 AliasKind::Existential(bounds)
7794 self.expect(&token::Eq)?;
7795 let ty = self.parse_ty()?;
7798 self.expect(&token::Semi)?;
7799 Ok((ident, alias, tps))
7802 /// Parses the part of an enum declaration following the `{`.
7803 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7804 let mut variants = Vec::new();
7805 let mut all_nullary = true;
7806 let mut any_disr = vec![];
7807 while self.token != token::CloseDelim(token::Brace) {
7808 let variant_attrs = self.parse_outer_attributes()?;
7809 let vlo = self.span;
7812 let mut disr_expr = None;
7814 let ident = self.parse_ident()?;
7815 if self.check(&token::OpenDelim(token::Brace)) {
7816 // Parse a struct variant.
7817 all_nullary = false;
7818 let (fields, recovered) = self.parse_record_struct_body()?;
7819 struct_def = VariantData::Struct(fields, recovered);
7820 } else if self.check(&token::OpenDelim(token::Paren)) {
7821 all_nullary = false;
7822 struct_def = VariantData::Tuple(
7823 self.parse_tuple_struct_body()?,
7826 } else if self.eat(&token::Eq) {
7827 disr_expr = Some(AnonConst {
7828 id: ast::DUMMY_NODE_ID,
7829 value: self.parse_expr()?,
7831 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7834 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7836 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7839 let vr = ast::Variant_ {
7841 id: ast::DUMMY_NODE_ID,
7842 attrs: variant_attrs,
7846 variants.push(respan(vlo.to(self.prev_span), vr));
7848 if !self.eat(&token::Comma) {
7849 if self.token.is_ident() && !self.token.is_reserved_ident() {
7850 let sp = self.sess.source_map().next_point(self.prev_span);
7851 let mut err = self.struct_span_err(sp, "missing comma");
7852 err.span_suggestion_short(
7856 Applicability::MaybeIncorrect,
7864 self.expect(&token::CloseDelim(token::Brace))?;
7865 if !any_disr.is_empty() && !all_nullary {
7866 let mut err = self.struct_span_err(
7868 "discriminator values can only be used with a field-less enum",
7870 for sp in any_disr {
7871 err.span_label(sp, "only valid in field-less enums");
7876 Ok(ast::EnumDef { variants })
7879 /// Parses an enum declaration.
7880 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7881 let id = self.parse_ident()?;
7882 let mut generics = self.parse_generics()?;
7883 generics.where_clause = self.parse_where_clause()?;
7884 self.expect(&token::OpenDelim(token::Brace))?;
7886 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7887 self.recover_stmt();
7888 self.eat(&token::CloseDelim(token::Brace));
7891 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7894 /// Parses a string as an ABI spec on an extern type or module. Consumes
7895 /// the `extern` keyword, if one is found.
7896 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7898 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7900 self.expect_no_suffix(sp, "an ABI spec", suf);
7902 match abi::lookup(&s.as_str()) {
7903 Some(abi) => Ok(Some(abi)),
7905 let prev_span = self.prev_span;
7906 let mut err = struct_span_err!(
7907 self.sess.span_diagnostic,
7910 "invalid ABI: found `{}`",
7912 err.span_label(prev_span, "invalid ABI");
7913 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7924 fn is_static_global(&mut self) -> bool {
7925 if self.check_keyword(keywords::Static) {
7926 // Check if this could be a closure
7927 !self.look_ahead(1, |token| {
7928 if token.is_keyword(keywords::Move) {
7932 token::BinOp(token::Or) | token::OrOr => true,
7943 attrs: Vec<Attribute>,
7944 macros_allowed: bool,
7945 attributes_allowed: bool,
7946 ) -> PResult<'a, Option<P<Item>>> {
7947 let mut unclosed_delims = vec![];
7948 let (ret, tokens) = self.collect_tokens(|this| {
7949 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7950 unclosed_delims.append(&mut this.unclosed_delims);
7953 self.unclosed_delims.append(&mut unclosed_delims);
7955 // Once we've parsed an item and recorded the tokens we got while
7956 // parsing we may want to store `tokens` into the item we're about to
7957 // return. Note, though, that we specifically didn't capture tokens
7958 // related to outer attributes. The `tokens` field here may later be
7959 // used with procedural macros to convert this item back into a token
7960 // stream, but during expansion we may be removing attributes as we go
7963 // If we've got inner attributes then the `tokens` we've got above holds
7964 // these inner attributes. If an inner attribute is expanded we won't
7965 // actually remove it from the token stream, so we'll just keep yielding
7966 // it (bad!). To work around this case for now we just avoid recording
7967 // `tokens` if we detect any inner attributes. This should help keep
7968 // expansion correct, but we should fix this bug one day!
7971 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7972 i.tokens = Some(tokens);
7979 /// Parses one of the items allowed by the flags.
7980 fn parse_item_implementation(
7982 attrs: Vec<Attribute>,
7983 macros_allowed: bool,
7984 attributes_allowed: bool,
7985 ) -> PResult<'a, Option<P<Item>>> {
7986 maybe_whole!(self, NtItem, |item| {
7987 let mut item = item.into_inner();
7988 let mut attrs = attrs;
7989 mem::swap(&mut item.attrs, &mut attrs);
7990 item.attrs.extend(attrs);
7996 let visibility = self.parse_visibility(false)?;
7998 if self.eat_keyword(keywords::Use) {
8000 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
8001 self.expect(&token::Semi)?;
8003 let span = lo.to(self.prev_span);
8004 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
8005 return Ok(Some(item));
8008 if self.eat_keyword(keywords::Extern) {
8009 if self.eat_keyword(keywords::Crate) {
8010 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
8013 let opt_abi = self.parse_opt_abi()?;
8015 if self.eat_keyword(keywords::Fn) {
8016 // EXTERN FUNCTION ITEM
8017 let fn_span = self.prev_span;
8018 let abi = opt_abi.unwrap_or(Abi::C);
8019 let (ident, item_, extra_attrs) =
8020 self.parse_item_fn(Unsafety::Normal,
8021 respan(fn_span, IsAsync::NotAsync),
8022 respan(fn_span, Constness::NotConst),
8024 let prev_span = self.prev_span;
8025 let item = self.mk_item(lo.to(prev_span),
8029 maybe_append(attrs, extra_attrs));
8030 return Ok(Some(item));
8031 } else if self.check(&token::OpenDelim(token::Brace)) {
8032 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
8038 if self.is_static_global() {
8041 let m = if self.eat_keyword(keywords::Mut) {
8044 Mutability::Immutable
8046 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
8047 let prev_span = self.prev_span;
8048 let item = self.mk_item(lo.to(prev_span),
8052 maybe_append(attrs, extra_attrs));
8053 return Ok(Some(item));
8055 if self.eat_keyword(keywords::Const) {
8056 let const_span = self.prev_span;
8057 if self.check_keyword(keywords::Fn)
8058 || (self.check_keyword(keywords::Unsafe)
8059 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
8060 // CONST FUNCTION ITEM
8061 let unsafety = self.parse_unsafety();
8063 let (ident, item_, extra_attrs) =
8064 self.parse_item_fn(unsafety,
8065 respan(const_span, IsAsync::NotAsync),
8066 respan(const_span, Constness::Const),
8068 let prev_span = self.prev_span;
8069 let item = self.mk_item(lo.to(prev_span),
8073 maybe_append(attrs, extra_attrs));
8074 return Ok(Some(item));
8078 if self.eat_keyword(keywords::Mut) {
8079 let prev_span = self.prev_span;
8080 let mut err = self.diagnostic()
8081 .struct_span_err(prev_span, "const globals cannot be mutable");
8082 err.span_label(prev_span, "cannot be mutable");
8083 err.span_suggestion(
8085 "you might want to declare a static instead",
8086 "static".to_owned(),
8087 Applicability::MaybeIncorrect,
8091 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
8092 let prev_span = self.prev_span;
8093 let item = self.mk_item(lo.to(prev_span),
8097 maybe_append(attrs, extra_attrs));
8098 return Ok(Some(item));
8101 // `unsafe async fn` or `async fn`
8103 self.check_keyword(keywords::Unsafe) &&
8104 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
8106 self.check_keyword(keywords::Async) &&
8107 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
8110 // ASYNC FUNCTION ITEM
8111 let unsafety = self.parse_unsafety();
8112 self.expect_keyword(keywords::Async)?;
8113 let async_span = self.prev_span;
8114 self.expect_keyword(keywords::Fn)?;
8115 let fn_span = self.prev_span;
8116 let (ident, item_, extra_attrs) =
8117 self.parse_item_fn(unsafety,
8118 respan(async_span, IsAsync::Async {
8119 closure_id: ast::DUMMY_NODE_ID,
8120 return_impl_trait_id: ast::DUMMY_NODE_ID,
8121 arguments: Vec::new(),
8123 respan(fn_span, Constness::NotConst),
8125 let prev_span = self.prev_span;
8126 let item = self.mk_item(lo.to(prev_span),
8130 maybe_append(attrs, extra_attrs));
8131 if self.span.rust_2015() {
8132 self.diagnostic().struct_span_err_with_code(
8134 "`async fn` is not permitted in the 2015 edition",
8135 DiagnosticId::Error("E0670".into())
8138 return Ok(Some(item));
8140 if self.check_keyword(keywords::Unsafe) &&
8141 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8142 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8144 // UNSAFE TRAIT ITEM
8145 self.bump(); // `unsafe`
8146 let is_auto = if self.eat_keyword(keywords::Trait) {
8149 self.expect_keyword(keywords::Auto)?;
8150 self.expect_keyword(keywords::Trait)?;
8153 let (ident, item_, extra_attrs) =
8154 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8155 let prev_span = self.prev_span;
8156 let item = self.mk_item(lo.to(prev_span),
8160 maybe_append(attrs, extra_attrs));
8161 return Ok(Some(item));
8163 if self.check_keyword(keywords::Impl) ||
8164 self.check_keyword(keywords::Unsafe) &&
8165 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8166 self.check_keyword(keywords::Default) &&
8167 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8168 self.check_keyword(keywords::Default) &&
8169 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8171 let defaultness = self.parse_defaultness();
8172 let unsafety = self.parse_unsafety();
8173 self.expect_keyword(keywords::Impl)?;
8174 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8175 let span = lo.to(self.prev_span);
8176 return Ok(Some(self.mk_item(span, ident, item, visibility,
8177 maybe_append(attrs, extra_attrs))));
8179 if self.check_keyword(keywords::Fn) {
8182 let fn_span = self.prev_span;
8183 let (ident, item_, extra_attrs) =
8184 self.parse_item_fn(Unsafety::Normal,
8185 respan(fn_span, IsAsync::NotAsync),
8186 respan(fn_span, Constness::NotConst),
8188 let prev_span = self.prev_span;
8189 let item = self.mk_item(lo.to(prev_span),
8193 maybe_append(attrs, extra_attrs));
8194 return Ok(Some(item));
8196 if self.check_keyword(keywords::Unsafe)
8197 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8198 // UNSAFE FUNCTION ITEM
8199 self.bump(); // `unsafe`
8200 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8201 self.check(&token::OpenDelim(token::Brace));
8202 let abi = if self.eat_keyword(keywords::Extern) {
8203 self.parse_opt_abi()?.unwrap_or(Abi::C)
8207 self.expect_keyword(keywords::Fn)?;
8208 let fn_span = self.prev_span;
8209 let (ident, item_, extra_attrs) =
8210 self.parse_item_fn(Unsafety::Unsafe,
8211 respan(fn_span, IsAsync::NotAsync),
8212 respan(fn_span, Constness::NotConst),
8214 let prev_span = self.prev_span;
8215 let item = self.mk_item(lo.to(prev_span),
8219 maybe_append(attrs, extra_attrs));
8220 return Ok(Some(item));
8222 if self.eat_keyword(keywords::Mod) {
8224 let (ident, item_, extra_attrs) =
8225 self.parse_item_mod(&attrs[..])?;
8226 let prev_span = self.prev_span;
8227 let item = self.mk_item(lo.to(prev_span),
8231 maybe_append(attrs, extra_attrs));
8232 return Ok(Some(item));
8234 if let Some(type_) = self.eat_type() {
8235 let (ident, alias, generics) = type_?;
8237 let item_ = match alias {
8238 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8239 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8241 let prev_span = self.prev_span;
8242 let item = self.mk_item(lo.to(prev_span),
8247 return Ok(Some(item));
8249 if self.eat_keyword(keywords::Enum) {
8251 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8252 let prev_span = self.prev_span;
8253 let item = self.mk_item(lo.to(prev_span),
8257 maybe_append(attrs, extra_attrs));
8258 return Ok(Some(item));
8260 if self.check_keyword(keywords::Trait)
8261 || (self.check_keyword(keywords::Auto)
8262 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8264 let is_auto = if self.eat_keyword(keywords::Trait) {
8267 self.expect_keyword(keywords::Auto)?;
8268 self.expect_keyword(keywords::Trait)?;
8272 let (ident, item_, extra_attrs) =
8273 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8274 let prev_span = self.prev_span;
8275 let item = self.mk_item(lo.to(prev_span),
8279 maybe_append(attrs, extra_attrs));
8280 return Ok(Some(item));
8282 if self.eat_keyword(keywords::Struct) {
8284 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8285 let prev_span = self.prev_span;
8286 let item = self.mk_item(lo.to(prev_span),
8290 maybe_append(attrs, extra_attrs));
8291 return Ok(Some(item));
8293 if self.is_union_item() {
8296 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8297 let prev_span = self.prev_span;
8298 let item = self.mk_item(lo.to(prev_span),
8302 maybe_append(attrs, extra_attrs));
8303 return Ok(Some(item));
8305 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8306 return Ok(Some(macro_def));
8309 // Verify whether we have encountered a struct or method definition where the user forgot to
8310 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8311 if visibility.node.is_pub() &&
8312 self.check_ident() &&
8313 self.look_ahead(1, |t| *t != token::Not)
8315 // Space between `pub` keyword and the identifier
8318 // ^^^ `sp` points here
8319 let sp = self.prev_span.between(self.span);
8320 let full_sp = self.prev_span.to(self.span);
8321 let ident_sp = self.span;
8322 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8323 // possible public struct definition where `struct` was forgotten
8324 let ident = self.parse_ident().unwrap();
8325 let msg = format!("add `struct` here to parse `{}` as a public struct",
8327 let mut err = self.diagnostic()
8328 .struct_span_err(sp, "missing `struct` for struct definition");
8329 err.span_suggestion_short(
8330 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8333 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8334 let ident = self.parse_ident().unwrap();
8336 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8341 self.consume_block(token::Paren);
8342 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8343 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8345 ("fn", kw_name, false)
8346 } else if self.check(&token::OpenDelim(token::Brace)) {
8348 ("fn", kw_name, false)
8349 } else if self.check(&token::Colon) {
8353 ("fn` or `struct", "function or struct", true)
8356 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8357 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8359 self.consume_block(token::Brace);
8360 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8364 err.span_suggestion_short(
8365 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8368 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8369 err.span_suggestion(
8371 "if you meant to call a macro, try",
8372 format!("{}!", snippet),
8373 // this is the `ambiguous` conditional branch
8374 Applicability::MaybeIncorrect
8377 err.help("if you meant to call a macro, remove the `pub` \
8378 and add a trailing `!` after the identifier");
8382 } else if self.look_ahead(1, |t| *t == token::Lt) {
8383 let ident = self.parse_ident().unwrap();
8384 self.eat_to_tokens(&[&token::Gt]);
8386 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8387 if let Ok(Some(_)) = self.parse_self_arg() {
8388 ("fn", "method", false)
8390 ("fn", "function", false)
8392 } else if self.check(&token::OpenDelim(token::Brace)) {
8393 ("struct", "struct", false)
8395 ("fn` or `struct", "function or struct", true)
8397 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8398 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8400 err.span_suggestion_short(
8402 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8403 format!(" {} ", kw),
8404 Applicability::MachineApplicable,
8410 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8413 /// Parses a foreign item.
8414 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8415 maybe_whole!(self, NtForeignItem, |ni| ni);
8417 let attrs = self.parse_outer_attributes()?;
8419 let visibility = self.parse_visibility(false)?;
8421 // FOREIGN STATIC ITEM
8422 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8423 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8424 if self.token.is_keyword(keywords::Const) {
8426 .struct_span_err(self.span, "extern items cannot be `const`")
8429 "try using a static value",
8430 "static".to_owned(),
8431 Applicability::MachineApplicable
8434 self.bump(); // `static` or `const`
8435 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8437 // FOREIGN FUNCTION ITEM
8438 if self.check_keyword(keywords::Fn) {
8439 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8441 // FOREIGN TYPE ITEM
8442 if self.check_keyword(keywords::Type) {
8443 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8446 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8450 ident: keywords::Invalid.ident(),
8451 span: lo.to(self.prev_span),
8452 id: ast::DUMMY_NODE_ID,
8455 node: ForeignItemKind::Macro(mac),
8460 if !attrs.is_empty() {
8461 self.expected_item_err(&attrs)?;
8469 /// This is the fall-through for parsing items.
8470 fn parse_macro_use_or_failure(
8472 attrs: Vec<Attribute> ,
8473 macros_allowed: bool,
8474 attributes_allowed: bool,
8476 visibility: Visibility
8477 ) -> PResult<'a, Option<P<Item>>> {
8478 if macros_allowed && self.token.is_path_start() &&
8479 !(self.is_async_fn() && self.span.rust_2015()) {
8480 // MACRO INVOCATION ITEM
8482 let prev_span = self.prev_span;
8483 self.complain_if_pub_macro(&visibility.node, prev_span);
8485 let mac_lo = self.span;
8488 let pth = self.parse_path(PathStyle::Mod)?;
8489 self.expect(&token::Not)?;
8491 // a 'special' identifier (like what `macro_rules!` uses)
8492 // is optional. We should eventually unify invoc syntax
8494 let id = if self.token.is_ident() {
8497 keywords::Invalid.ident() // no special identifier
8499 // eat a matched-delimiter token tree:
8500 let (delim, tts) = self.expect_delimited_token_tree()?;
8501 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8502 self.report_invalid_macro_expansion_item();
8505 let hi = self.prev_span;
8506 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8507 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8508 return Ok(Some(item));
8511 // FAILURE TO PARSE ITEM
8512 match visibility.node {
8513 VisibilityKind::Inherited => {}
8515 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8519 if !attributes_allowed && !attrs.is_empty() {
8520 self.expected_item_err(&attrs)?;
8525 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8526 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8527 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8529 if self.token.is_path_start() &&
8530 !(self.is_async_fn() && self.span.rust_2015()) {
8531 let prev_span = self.prev_span;
8533 let pth = self.parse_path(PathStyle::Mod)?;
8535 if pth.segments.len() == 1 {
8536 if !self.eat(&token::Not) {
8537 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8540 self.expect(&token::Not)?;
8543 if let Some(vis) = vis {
8544 self.complain_if_pub_macro(&vis.node, prev_span);
8549 // eat a matched-delimiter token tree:
8550 let (delim, tts) = self.expect_delimited_token_tree()?;
8551 if delim != MacDelimiter::Brace {
8552 self.expect(&token::Semi)?;
8555 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8561 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8562 where F: FnOnce(&mut Self) -> PResult<'a, R>
8564 // Record all tokens we parse when parsing this item.
8565 let mut tokens = Vec::new();
8566 let prev_collecting = match self.token_cursor.frame.last_token {
8567 LastToken::Collecting(ref mut list) => {
8568 Some(mem::replace(list, Vec::new()))
8570 LastToken::Was(ref mut last) => {
8571 tokens.extend(last.take());
8575 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8576 let prev = self.token_cursor.stack.len();
8578 let last_token = if self.token_cursor.stack.len() == prev {
8579 &mut self.token_cursor.frame.last_token
8581 &mut self.token_cursor.stack[prev].last_token
8584 // Pull out the tokens that we've collected from the call to `f` above.
8585 let mut collected_tokens = match *last_token {
8586 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8587 LastToken::Was(_) => panic!("our vector went away?"),
8590 // If we're not at EOF our current token wasn't actually consumed by
8591 // `f`, but it'll still be in our list that we pulled out. In that case
8593 let extra_token = if self.token != token::Eof {
8594 collected_tokens.pop()
8599 // If we were previously collecting tokens, then this was a recursive
8600 // call. In that case we need to record all the tokens we collected in
8601 // our parent list as well. To do that we push a clone of our stream
8602 // onto the previous list.
8603 match prev_collecting {
8605 list.extend(collected_tokens.iter().cloned());
8606 list.extend(extra_token);
8607 *last_token = LastToken::Collecting(list);
8610 *last_token = LastToken::Was(extra_token);
8614 Ok((ret?, TokenStream::new(collected_tokens)))
8617 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8618 let attrs = self.parse_outer_attributes()?;
8619 self.parse_item_(attrs, true, false)
8623 fn is_import_coupler(&mut self) -> bool {
8624 self.check(&token::ModSep) &&
8625 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8626 *t == token::BinOp(token::Star))
8629 /// Parses a `UseTree`.
8632 /// USE_TREE = [`::`] `*` |
8633 /// [`::`] `{` USE_TREE_LIST `}` |
8635 /// PATH `::` `{` USE_TREE_LIST `}` |
8636 /// PATH [`as` IDENT]
8638 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8641 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8642 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8643 self.check(&token::BinOp(token::Star)) ||
8644 self.is_import_coupler() {
8645 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8646 let mod_sep_ctxt = self.span.ctxt();
8647 if self.eat(&token::ModSep) {
8648 prefix.segments.push(
8649 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8653 if self.eat(&token::BinOp(token::Star)) {
8656 UseTreeKind::Nested(self.parse_use_tree_list()?)
8659 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8660 prefix = self.parse_path(PathStyle::Mod)?;
8662 if self.eat(&token::ModSep) {
8663 if self.eat(&token::BinOp(token::Star)) {
8666 UseTreeKind::Nested(self.parse_use_tree_list()?)
8669 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8673 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8676 /// Parses a `UseTreeKind::Nested(list)`.
8679 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8681 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8682 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8683 &token::CloseDelim(token::Brace),
8684 SeqSep::trailing_allowed(token::Comma), |this| {
8685 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8689 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8690 if self.eat_keyword(keywords::As) {
8691 self.parse_ident_or_underscore().map(Some)
8697 /// Parses a source module as a crate. This is the main entry point for the parser.
8698 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8700 let krate = Ok(ast::Crate {
8701 attrs: self.parse_inner_attributes()?,
8702 module: self.parse_mod_items(&token::Eof, lo)?,
8703 span: lo.to(self.span),
8708 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8709 let ret = match self.token {
8710 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8711 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8718 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8719 match self.parse_optional_str() {
8720 Some((s, style, suf)) => {
8721 let sp = self.prev_span;
8722 self.expect_no_suffix(sp, "a string literal", suf);
8726 let msg = "expected string literal";
8727 let mut err = self.fatal(msg);
8728 err.span_label(self.span, msg);
8734 fn report_invalid_macro_expansion_item(&self) {
8735 self.struct_span_err(
8737 "macros that expand to items must be delimited with braces or followed by a semicolon",
8738 ).multipart_suggestion(
8739 "change the delimiters to curly braces",
8741 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8742 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8744 Applicability::MaybeIncorrect,
8746 self.sess.source_map.next_point(self.prev_span),
8749 Applicability::MaybeIncorrect,
8753 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8754 fn eat_bad_pub(&mut self) {
8755 if self.token.is_keyword(keywords::Pub) {
8756 match self.parse_visibility(false) {
8758 let mut err = self.diagnostic()
8759 .struct_span_err(vis.span, "unnecessary visibility qualifier");
8760 err.span_label(vis.span, "`pub` not permitted here");
8763 Err(mut err) => err.emit(),
8768 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8769 /// into the generated closure so that they are dropped when the future is polled and not when
8772 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8773 /// this function and the statements created here are inserted at the top of the closure body.
8774 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &mut FnDecl) {
8775 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8776 for (index, input) in decl.inputs.iter_mut().enumerate() {
8777 let id = ast::DUMMY_NODE_ID;
8778 let span = input.pat.span;
8780 // Construct a name for our temporary argument.
8781 let name = format!("__arg{}", index);
8782 let ident = Ident::from_str(&name).gensym();
8784 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
8785 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
8787 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
8788 PatKind::Ident(binding_mode @ BindingMode::ByValue(_), ident, _) => {
8789 (binding_mode, ident, true)
8791 _ => (BindingMode::ByValue(Mutability::Mutable), ident, false),
8794 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8795 // async function if it isn't a simple pattern.
8796 let arg = if is_simple_pattern {
8800 ty: input.ty.clone(),
8804 node: PatKind::Ident(
8805 BindingMode::ByValue(Mutability::Immutable), ident, None,
8809 source: ArgSource::AsyncFn(input.pat.clone()),
8813 // Construct a `let __argN = __argN;` statement to insert at the top of the
8814 // async closure. This makes sure that the argument is captured by the closure and
8815 // that the drop order is correct.
8816 let move_local = Local {
8819 node: PatKind::Ident(binding_mode, ident, None),
8822 // We explicitly do not specify the type for this statement. When the user's
8823 // argument type is `impl Trait` then this would require the
8824 // `impl_trait_in_bindings` feature to also be present for that same type to
8825 // be valid in this binding. At the time of writing (13 Mar 19),
8826 // `impl_trait_in_bindings` is not stable.
8830 node: ExprKind::Path(None, ast::Path {
8832 segments: vec![PathSegment { ident, id, args: None }],
8835 attrs: ThinVec::new(),
8839 attrs: ThinVec::new(),
8840 source: LocalSource::AsyncFn,
8843 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8844 // async closure if this isn't a simple pattern.
8845 let pat_stmt = if is_simple_pattern {
8850 node: StmtKind::Local(P(Local {
8851 pat: input.pat.clone(),
8852 ..move_local.clone()
8858 // Remove mutability from arguments. If this is not a simple pattern,
8859 // those arguments are replaced by `__argN`, so there is no need to do this.
8860 if let PatKind::Ident(BindingMode::ByValue(mutability @ Mutability::Mutable), ..) =
8863 assert!(is_simple_pattern);
8864 *mutability = Mutability::Immutable;
8867 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
8868 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
8874 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8875 for unmatched in unclosed_delims.iter() {
8876 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8877 "incorrect close delimiter: `{}`",
8878 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8880 err.span_label(unmatched.found_span, "incorrect close delimiter");
8881 if let Some(sp) = unmatched.candidate_span {
8882 err.span_label(sp, "close delimiter possibly meant for this");
8884 if let Some(sp) = unmatched.unclosed_span {
8885 err.span_label(sp, "un-closed delimiter");
8889 unclosed_delims.clear();