1 // ignore-tidy-filelength
3 use crate::ast::{AngleBracketedArgs, ParenthesizedArgs, AttrStyle, BareFnTy};
4 use crate::ast::{GenericBound, TraitBoundModifier};
5 use crate::ast::Unsafety;
6 use crate::ast::{Mod, AnonConst, Arg, 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};
19 use crate::ast::Local;
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, AssocTyConstraint, AssocTyConstraintKind, 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::{SeqSep, classify, literal, token};
39 use crate::parse::lexer::UnmatchedBrace;
40 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
41 use crate::parse::token::{Token, TokenKind, 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::{kw, sym, Symbol};
50 use crate::parse::diagnostics::{Error, dummy_arg};
52 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
53 use rustc_target::spec::abi::{self, Abi};
54 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
61 use std::path::{self, Path, PathBuf};
65 /// Whether the type alias or associated type is a concrete type or an existential type
67 /// Just a new name for the same type
69 /// Only trait impls of the type will be usable, not the actual type itself
70 Existential(GenericBounds),
74 struct Restrictions: u8 {
75 const STMT_EXPR = 1 << 0;
76 const NO_STRUCT_LITERAL = 1 << 1;
80 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
82 /// Specifies how to parse a path.
83 #[derive(Copy, Clone, PartialEq)]
85 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
86 /// with something else. For example, in expressions `segment < ....` can be interpreted
87 /// as a comparison and `segment ( ....` can be interpreted as a function call.
88 /// In all such contexts the non-path interpretation is preferred by default for practical
89 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
90 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
92 /// In other contexts, notably in types, no ambiguity exists and paths can be written
93 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
94 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
96 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
97 /// visibilities or attributes.
98 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
99 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
100 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
101 /// tokens when something goes wrong.
105 #[derive(Clone, Copy, PartialEq, Debug)]
106 crate enum SemiColonMode {
112 #[derive(Clone, Copy, PartialEq, Debug)]
113 crate enum BlockMode {
118 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
119 /// dropped into the token stream, which happens while parsing the result of
120 /// macro expansion). Placement of these is not as complex as I feared it would
121 /// be. The important thing is to make sure that lookahead doesn't balk at
122 /// `token::Interpolated` tokens.
123 macro_rules! maybe_whole_expr {
125 if let token::Interpolated(nt) = &$p.token.kind {
127 token::NtExpr(e) | token::NtLiteral(e) => {
132 token::NtPath(path) => {
133 let path = path.clone();
135 return Ok($p.mk_expr($p.span, ExprKind::Path(None, path), ThinVec::new()));
137 token::NtBlock(block) => {
138 let block = block.clone();
140 return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
148 /// As maybe_whole_expr, but for things other than expressions
149 macro_rules! maybe_whole {
150 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
151 if let token::Interpolated(nt) = &$p.token.kind {
152 if let token::$constructor(x) = &**nt {
161 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
162 macro_rules! maybe_recover_from_interpolated_ty_qpath {
163 ($self: expr, $allow_qpath_recovery: expr) => {
164 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
165 if let token::Interpolated(nt) = &$self.token.kind {
166 if let token::NtTy(ty) = &**nt {
169 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
176 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
177 if let Some(ref mut rhs) = rhs {
183 #[derive(Debug, Clone, Copy, PartialEq)]
195 // NOTE: `Ident`s are handled by `common.rs`.
198 pub struct Parser<'a> {
199 pub sess: &'a ParseSess,
200 /// The current token.
202 /// The span of the previous token.
203 meta_var_span: Option<Span>,
204 /// The span of the previous token.
206 /// The previous token kind.
207 prev_token_kind: PrevTokenKind,
208 restrictions: Restrictions,
209 /// Used to determine the path to externally loaded source files.
210 crate directory: Directory<'a>,
211 /// `true` to parse sub-modules in other files.
212 pub recurse_into_file_modules: bool,
213 /// Name of the root module this parser originated from. If `None`, then the
214 /// name is not known. This does not change while the parser is descending
215 /// into modules, and sub-parsers have new values for this name.
216 pub root_module_name: Option<String>,
217 crate expected_tokens: Vec<TokenType>,
218 crate token_cursor: TokenCursor,
219 desugar_doc_comments: bool,
220 /// `true` we should configure out of line modules as we parse.
222 /// This field is used to keep track of how many left angle brackets we have seen. This is
223 /// required in order to detect extra leading left angle brackets (`<` characters) and error
226 /// See the comments in the `parse_path_segment` function for more details.
227 crate unmatched_angle_bracket_count: u32,
228 crate max_angle_bracket_count: u32,
229 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
230 /// it gets removed from here. Every entry left at the end gets emitted as an independent
232 crate unclosed_delims: Vec<UnmatchedBrace>,
233 crate last_unexpected_token_span: Option<Span>,
234 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
235 crate subparser_name: Option<&'static str>,
238 impl<'a> Drop for Parser<'a> {
240 let diag = self.diagnostic();
241 emit_unclosed_delims(&mut self.unclosed_delims, diag);
245 // FIXME: Parser uses `self.span` all the time.
246 // Remove this impl if you think that using `self.token.span` instead is acceptable.
247 impl Deref for Parser<'_> {
249 fn deref(&self) -> &Self::Target {
255 crate struct TokenCursor {
256 crate frame: TokenCursorFrame,
257 crate stack: Vec<TokenCursorFrame>,
261 crate struct TokenCursorFrame {
262 crate delim: token::DelimToken,
263 crate span: DelimSpan,
264 crate open_delim: bool,
265 crate tree_cursor: tokenstream::Cursor,
266 crate close_delim: bool,
267 crate last_token: LastToken,
270 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
271 /// by the parser, and then that's transitively used to record the tokens that
272 /// each parse AST item is created with.
274 /// Right now this has two states, either collecting tokens or not collecting
275 /// tokens. If we're collecting tokens we just save everything off into a local
276 /// `Vec`. This should eventually though likely save tokens from the original
277 /// token stream and just use slicing of token streams to avoid creation of a
278 /// whole new vector.
280 /// The second state is where we're passively not recording tokens, but the last
281 /// token is still tracked for when we want to start recording tokens. This
282 /// "last token" means that when we start recording tokens we'll want to ensure
283 /// that this, the first token, is included in the output.
285 /// You can find some more example usage of this in the `collect_tokens` method
288 crate enum LastToken {
289 Collecting(Vec<TreeAndJoint>),
290 Was(Option<TreeAndJoint>),
293 impl TokenCursorFrame {
294 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
298 open_delim: delim == token::NoDelim,
299 tree_cursor: tts.clone().into_trees(),
300 close_delim: delim == token::NoDelim,
301 last_token: LastToken::Was(None),
307 fn next(&mut self) -> Token {
309 let tree = if !self.frame.open_delim {
310 self.frame.open_delim = true;
311 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
312 } else if let Some(tree) = self.frame.tree_cursor.next() {
314 } else if !self.frame.close_delim {
315 self.frame.close_delim = true;
316 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
317 } else if let Some(frame) = self.stack.pop() {
321 return Token::new(token::Eof, DUMMY_SP);
324 match self.frame.last_token {
325 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
326 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
330 TokenTree::Token(token) => return token,
331 TokenTree::Delimited(sp, delim, tts) => {
332 let frame = TokenCursorFrame::new(sp, delim, &tts);
333 self.stack.push(mem::replace(&mut self.frame, frame));
339 fn next_desugared(&mut self) -> Token {
340 let (name, sp) = match self.next() {
341 Token { kind: token::DocComment(name), span } => (name, span),
345 let stripped = strip_doc_comment_decoration(&name.as_str());
347 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
348 // required to wrap the text.
349 let mut num_of_hashes = 0;
351 for ch in stripped.chars() {
354 '#' if count > 0 => count + 1,
357 num_of_hashes = cmp::max(num_of_hashes, count);
360 let delim_span = DelimSpan::from_single(sp);
361 let body = TokenTree::Delimited(
365 TokenTree::token(token::Ident(sym::doc, false), sp),
366 TokenTree::token(token::Eq, sp),
367 TokenTree::token(TokenKind::lit(
368 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
371 .iter().cloned().collect::<TokenStream>().into(),
374 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
377 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
378 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
379 .iter().cloned().collect::<TokenStream>().into()
381 [TokenTree::token(token::Pound, sp), body]
382 .iter().cloned().collect::<TokenStream>().into()
390 #[derive(Clone, PartialEq)]
391 crate enum TokenType {
403 crate fn to_string(&self) -> String {
405 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
406 TokenType::Keyword(kw) => format!("`{}`", kw),
407 TokenType::Operator => "an operator".to_string(),
408 TokenType::Lifetime => "lifetime".to_string(),
409 TokenType::Ident => "identifier".to_string(),
410 TokenType::Path => "path".to_string(),
411 TokenType::Type => "type".to_string(),
412 TokenType::Const => "const".to_string(),
417 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
418 /// `IDENT<<u8 as Trait>::AssocTy>`.
420 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
421 /// that `IDENT` is not the ident of a fn trait.
422 fn can_continue_type_after_non_fn_ident(t: &TokenKind) -> bool {
423 t == &token::ModSep || t == &token::Lt ||
424 t == &token::BinOp(token::Shl)
427 /// Information about the path to a module.
428 pub struct ModulePath {
431 pub result: Result<ModulePathSuccess, Error>,
434 pub struct ModulePathSuccess {
436 pub directory_ownership: DirectoryOwnership,
443 AttributesParsed(ThinVec<Attribute>),
444 AlreadyParsed(P<Expr>),
447 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
448 fn from(o: Option<ThinVec<Attribute>>) -> Self {
449 if let Some(attrs) = o {
450 LhsExpr::AttributesParsed(attrs)
452 LhsExpr::NotYetParsed
457 impl From<P<Expr>> for LhsExpr {
458 fn from(expr: P<Expr>) -> Self {
459 LhsExpr::AlreadyParsed(expr)
463 #[derive(Copy, Clone, Debug)]
464 crate enum TokenExpectType {
469 impl<'a> Parser<'a> {
473 directory: Option<Directory<'a>>,
474 recurse_into_file_modules: bool,
475 desugar_doc_comments: bool,
476 subparser_name: Option<&'static str>,
478 let mut parser = Parser {
480 token: Token::dummy(),
483 prev_token_kind: PrevTokenKind::Other,
484 restrictions: Restrictions::empty(),
485 recurse_into_file_modules,
486 directory: Directory {
487 path: Cow::from(PathBuf::new()),
488 ownership: DirectoryOwnership::Owned { relative: None }
490 root_module_name: None,
491 expected_tokens: Vec::new(),
492 token_cursor: TokenCursor {
493 frame: TokenCursorFrame::new(
500 desugar_doc_comments,
502 unmatched_angle_bracket_count: 0,
503 max_angle_bracket_count: 0,
504 unclosed_delims: Vec::new(),
505 last_unexpected_token_span: None,
509 parser.token = parser.next_tok();
511 if let Some(directory) = directory {
512 parser.directory = directory;
513 } else if !parser.span.is_dummy() {
514 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
516 parser.directory.path = Cow::from(path);
520 parser.process_potential_macro_variable();
524 fn next_tok(&mut self) -> Token {
525 let mut next = if self.desugar_doc_comments {
526 self.token_cursor.next_desugared()
528 self.token_cursor.next()
530 if next.span.is_dummy() {
531 // Tweak the location for better diagnostics, but keep syntactic context intact.
532 next.span = self.prev_span.with_ctxt(next.span.ctxt());
537 /// Converts the current token to a string using `self`'s reader.
538 pub fn this_token_to_string(&self) -> String {
539 pprust::token_to_string(&self.token)
542 crate fn token_descr(&self) -> Option<&'static str> {
543 Some(match &self.token.kind {
544 _ if self.token.is_special_ident() => "reserved identifier",
545 _ if self.token.is_used_keyword() => "keyword",
546 _ if self.token.is_unused_keyword() => "reserved keyword",
547 token::DocComment(..) => "doc comment",
552 crate fn this_token_descr(&self) -> String {
553 if let Some(prefix) = self.token_descr() {
554 format!("{} `{}`", prefix, self.this_token_to_string())
556 format!("`{}`", self.this_token_to_string())
560 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
561 match self.expect_one_of(&[], &[]) {
563 Ok(_) => unreachable!(),
567 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
568 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
569 if self.expected_tokens.is_empty() {
570 if self.token == *t {
574 self.unexpected_try_recover(t)
577 self.expect_one_of(slice::from_ref(t), &[])
581 /// Expect next token to be edible or inedible token. If edible,
582 /// then consume it; if inedible, then return without consuming
583 /// anything. Signal a fatal error if next token is unexpected.
584 pub fn expect_one_of(
586 edible: &[TokenKind],
587 inedible: &[TokenKind],
588 ) -> PResult<'a, bool /* recovered */> {
589 if edible.contains(&self.token) {
592 } else if inedible.contains(&self.token) {
593 // leave it in the input
595 } else if self.last_unexpected_token_span == Some(self.span) {
598 self.expected_one_of_not_found(edible, inedible)
602 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
603 fn interpolated_or_expr_span(
605 expr: PResult<'a, P<Expr>>,
606 ) -> PResult<'a, (Span, P<Expr>)> {
608 if self.prev_token_kind == PrevTokenKind::Interpolated {
616 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
617 self.parse_ident_common(true)
620 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
621 match self.token.kind {
622 token::Ident(name, _) => {
623 if self.token.is_reserved_ident() {
624 let mut err = self.expected_ident_found();
631 let span = self.span;
633 Ok(Ident::new(name, span))
636 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
637 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
639 self.expected_ident_found()
645 /// Checks if the next token is `tok`, and returns `true` if so.
647 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
649 crate fn check(&mut self, tok: &TokenKind) -> bool {
650 let is_present = self.token == *tok;
651 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
655 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
656 pub fn eat(&mut self, tok: &TokenKind) -> bool {
657 let is_present = self.check(tok);
658 if is_present { self.bump() }
662 fn check_keyword(&mut self, kw: Symbol) -> bool {
663 self.expected_tokens.push(TokenType::Keyword(kw));
664 self.token.is_keyword(kw)
667 /// If the next token is the given keyword, eats it and returns
668 /// `true`. Otherwise, returns `false`.
669 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
670 if self.check_keyword(kw) {
678 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
679 if self.token.is_keyword(kw) {
687 /// If the given word is not a keyword, signals an error.
688 /// If the next token is not the given word, signals an error.
689 /// Otherwise, eats it.
690 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
691 if !self.eat_keyword(kw) {
698 crate fn check_ident(&mut self) -> bool {
699 if self.token.is_ident() {
702 self.expected_tokens.push(TokenType::Ident);
707 fn check_path(&mut self) -> bool {
708 if self.token.is_path_start() {
711 self.expected_tokens.push(TokenType::Path);
716 fn check_type(&mut self) -> bool {
717 if self.token.can_begin_type() {
720 self.expected_tokens.push(TokenType::Type);
725 fn check_const_arg(&mut self) -> bool {
726 if self.token.can_begin_const_arg() {
729 self.expected_tokens.push(TokenType::Const);
734 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
735 /// and continues. If a `+` is not seen, returns `false`.
737 /// This is used when token-splitting `+=` into `+`.
738 /// See issue #47856 for an example of when this may occur.
739 fn eat_plus(&mut self) -> bool {
740 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
741 match self.token.kind {
742 token::BinOp(token::Plus) => {
746 token::BinOpEq(token::Plus) => {
747 let span = self.span.with_lo(self.span.lo() + BytePos(1));
748 self.bump_with(token::Eq, span);
756 /// Checks to see if the next token is either `+` or `+=`.
757 /// Otherwise returns `false`.
758 fn check_plus(&mut self) -> bool {
759 if self.token.is_like_plus() {
763 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
768 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
769 /// `&` and continues. If an `&` is not seen, signals an error.
770 fn expect_and(&mut self) -> PResult<'a, ()> {
771 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
772 match self.token.kind {
773 token::BinOp(token::And) => {
778 let span = self.span.with_lo(self.span.lo() + BytePos(1));
779 Ok(self.bump_with(token::BinOp(token::And), span))
781 _ => self.unexpected()
785 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
786 /// `|` and continues. If an `|` is not seen, signals an error.
787 fn expect_or(&mut self) -> PResult<'a, ()> {
788 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
789 match self.token.kind {
790 token::BinOp(token::Or) => {
795 let span = self.span.with_lo(self.span.lo() + BytePos(1));
796 Ok(self.bump_with(token::BinOp(token::Or), span))
798 _ => self.unexpected()
802 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
803 literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
806 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
807 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
808 /// and continue. If a `<` is not seen, returns false.
810 /// This is meant to be used when parsing generics on a path to get the
812 fn eat_lt(&mut self) -> bool {
813 self.expected_tokens.push(TokenType::Token(token::Lt));
814 let ate = match self.token.kind {
819 token::BinOp(token::Shl) => {
820 let span = self.span.with_lo(self.span.lo() + BytePos(1));
821 self.bump_with(token::Lt, span);
825 let span = self.span.with_lo(self.span.lo() + BytePos(1));
826 self.bump_with(token::BinOp(token::Minus), span);
833 // See doc comment for `unmatched_angle_bracket_count`.
834 self.unmatched_angle_bracket_count += 1;
835 self.max_angle_bracket_count += 1;
836 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
842 fn expect_lt(&mut self) -> PResult<'a, ()> {
850 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
851 /// with a single `>` and continues. If a `>` is not seen, signals an error.
852 fn expect_gt(&mut self) -> PResult<'a, ()> {
853 self.expected_tokens.push(TokenType::Token(token::Gt));
854 let ate = match self.token.kind {
859 token::BinOp(token::Shr) => {
860 let span = self.span.with_lo(self.span.lo() + BytePos(1));
861 Some(self.bump_with(token::Gt, span))
863 token::BinOpEq(token::Shr) => {
864 let span = self.span.with_lo(self.span.lo() + BytePos(1));
865 Some(self.bump_with(token::Ge, span))
868 let span = self.span.with_lo(self.span.lo() + BytePos(1));
869 Some(self.bump_with(token::Eq, span))
876 // See doc comment for `unmatched_angle_bracket_count`.
877 if self.unmatched_angle_bracket_count > 0 {
878 self.unmatched_angle_bracket_count -= 1;
879 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
884 None => self.unexpected(),
888 /// Parses a sequence, including the closing delimiter. The function
889 /// `f` must consume tokens until reaching the next separator or
891 pub fn parse_seq_to_end<T, F>(&mut self,
895 -> PResult<'a, Vec<T>> where
896 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
898 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
905 /// Parses a sequence, not including the closing delimiter. The function
906 /// `f` must consume tokens until reaching the next separator or
908 pub fn parse_seq_to_before_end<T, F>(
913 ) -> PResult<'a, (Vec<T>, bool)>
914 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
916 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
919 crate fn parse_seq_to_before_tokens<T, F>(
923 expect: TokenExpectType,
925 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
926 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
928 let mut first = true;
929 let mut recovered = false;
931 while !kets.iter().any(|k| {
933 TokenExpectType::Expect => self.check(k),
934 TokenExpectType::NoExpect => self.token == **k,
937 match self.token.kind {
938 token::CloseDelim(..) | token::Eof => break,
941 if let Some(ref t) = sep.sep {
945 match self.expect(t) {
952 // Attempt to keep parsing if it was a similar separator
953 if let Some(ref tokens) = t.similar_tokens() {
954 if tokens.contains(&self.token) {
959 // Attempt to keep parsing if it was an omitted separator
974 if sep.trailing_sep_allowed && kets.iter().any(|k| {
976 TokenExpectType::Expect => self.check(k),
977 TokenExpectType::NoExpect => self.token == **k,
990 /// Parses a sequence, including the closing delimiter. The function
991 /// `f` must consume tokens until reaching the next separator or
993 fn parse_unspanned_seq<T, F>(
999 ) -> PResult<'a, Vec<T>> where
1000 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1003 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1010 /// Advance the parser by one token
1011 pub fn bump(&mut self) {
1012 if self.prev_token_kind == PrevTokenKind::Eof {
1013 // Bumping after EOF is a bad sign, usually an infinite loop.
1014 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1017 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1019 // Record last token kind for possible error recovery.
1020 self.prev_token_kind = match self.token.kind {
1021 token::DocComment(..) => PrevTokenKind::DocComment,
1022 token::Comma => PrevTokenKind::Comma,
1023 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1024 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1025 token::Interpolated(..) => PrevTokenKind::Interpolated,
1026 token::Eof => PrevTokenKind::Eof,
1027 token::Ident(..) => PrevTokenKind::Ident,
1028 _ => PrevTokenKind::Other,
1031 self.token = self.next_tok();
1032 self.expected_tokens.clear();
1033 // check after each token
1034 self.process_potential_macro_variable();
1037 /// Advance the parser using provided token as a next one. Use this when
1038 /// consuming a part of a token. For example a single `<` from `<<`.
1039 fn bump_with(&mut self, next: TokenKind, span: Span) {
1040 self.prev_span = self.span.with_hi(span.lo());
1041 // It would be incorrect to record the kind of the current token, but
1042 // fortunately for tokens currently using `bump_with`, the
1043 // prev_token_kind will be of no use anyway.
1044 self.prev_token_kind = PrevTokenKind::Other;
1045 self.token = Token::new(next, span);
1046 self.expected_tokens.clear();
1049 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1050 F: FnOnce(&Token) -> R,
1053 return f(&self.token);
1056 let frame = &self.token_cursor.frame;
1057 f(&match frame.tree_cursor.look_ahead(dist - 1) {
1058 Some(tree) => match tree {
1059 TokenTree::Token(token) => token,
1060 TokenTree::Delimited(dspan, delim, _) =>
1061 Token::new(token::OpenDelim(delim), dspan.open),
1063 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
1067 crate fn look_ahead_span(&self, dist: usize) -> Span {
1072 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1073 Some(TokenTree::Token(token)) => token.span,
1074 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1075 None => self.look_ahead_span(dist - 1),
1079 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1080 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1081 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1084 /// Is the current token one of the keywords that signals a bare function type?
1085 fn token_is_bare_fn_keyword(&mut self) -> bool {
1086 self.check_keyword(kw::Fn) ||
1087 self.check_keyword(kw::Unsafe) ||
1088 self.check_keyword(kw::Extern)
1091 /// Parses a `TyKind::BareFn` type.
1092 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1095 [unsafe] [extern "ABI"] fn (S) -> T
1105 let unsafety = self.parse_unsafety();
1106 let abi = if self.eat_keyword(kw::Extern) {
1107 self.parse_opt_abi()?.unwrap_or(Abi::C)
1112 self.expect_keyword(kw::Fn)?;
1113 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1114 let ret_ty = self.parse_ret_ty(false)?;
1115 let decl = P(FnDecl {
1120 Ok(TyKind::BareFn(P(BareFnTy {
1128 /// Parses asyncness: `async` or nothing.
1129 fn parse_asyncness(&mut self) -> IsAsync {
1130 if self.eat_keyword(kw::Async) {
1132 closure_id: ast::DUMMY_NODE_ID,
1133 return_impl_trait_id: ast::DUMMY_NODE_ID,
1140 /// Parses unsafety: `unsafe` or nothing.
1141 fn parse_unsafety(&mut self) -> Unsafety {
1142 if self.eat_keyword(kw::Unsafe) {
1149 /// Parses the items in a trait declaration.
1150 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1151 maybe_whole!(self, NtTraitItem, |x| x);
1152 let attrs = self.parse_outer_attributes()?;
1153 let mut unclosed_delims = vec![];
1154 let (mut item, tokens) = self.collect_tokens(|this| {
1155 let item = this.parse_trait_item_(at_end, attrs);
1156 unclosed_delims.append(&mut this.unclosed_delims);
1159 self.unclosed_delims.append(&mut unclosed_delims);
1160 // See `parse_item` for why this clause is here.
1161 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1162 item.tokens = Some(tokens);
1167 fn parse_trait_item_(&mut self,
1169 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1172 let (name, node, generics) = if self.eat_keyword(kw::Type) {
1173 self.parse_trait_item_assoc_ty()?
1174 } else if self.is_const_item() {
1175 self.expect_keyword(kw::Const)?;
1176 let ident = self.parse_ident()?;
1177 self.expect(&token::Colon)?;
1178 let ty = self.parse_ty()?;
1179 let default = if self.eat(&token::Eq) {
1180 let expr = self.parse_expr()?;
1181 self.expect(&token::Semi)?;
1184 self.expect(&token::Semi)?;
1187 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1188 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1189 // trait item macro.
1190 (Ident::invalid(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1192 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1194 let ident = self.parse_ident()?;
1195 let mut generics = self.parse_generics()?;
1197 let decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1198 // This is somewhat dubious; We don't want to allow
1199 // argument names to be left off if there is a
1202 // We don't allow argument names to be left off in edition 2018.
1203 p.parse_arg_general(p.span.rust_2018(), true, false)
1205 generics.where_clause = self.parse_where_clause()?;
1207 let sig = ast::MethodSig {
1217 let body = match self.token.kind {
1221 debug!("parse_trait_methods(): parsing required method");
1224 token::OpenDelim(token::Brace) => {
1225 debug!("parse_trait_methods(): parsing provided method");
1227 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1228 attrs.extend(inner_attrs.iter().cloned());
1231 token::Interpolated(ref nt) => {
1233 token::NtBlock(..) => {
1235 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1236 attrs.extend(inner_attrs.iter().cloned());
1240 return self.expected_semi_or_open_brace();
1245 return self.expected_semi_or_open_brace();
1248 (ident, ast::TraitItemKind::Method(sig, body), generics)
1252 id: ast::DUMMY_NODE_ID,
1257 span: lo.to(self.prev_span),
1262 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1263 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1264 if self.eat(&token::RArrow) {
1265 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1267 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1272 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1273 self.parse_ty_common(true, true, false)
1276 /// Parses a type in restricted contexts where `+` is not permitted.
1278 /// Example 1: `&'a TYPE`
1279 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1280 /// Example 2: `value1 as TYPE + value2`
1281 /// `+` is prohibited to avoid interactions with expression grammar.
1282 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1283 self.parse_ty_common(false, true, false)
1286 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1287 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1288 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1289 maybe_whole!(self, NtTy, |x| x);
1292 let mut impl_dyn_multi = false;
1293 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1294 // `(TYPE)` is a parenthesized type.
1295 // `(TYPE,)` is a tuple with a single field of type TYPE.
1296 let mut ts = vec![];
1297 let mut last_comma = false;
1298 while self.token != token::CloseDelim(token::Paren) {
1299 ts.push(self.parse_ty()?);
1300 if self.eat(&token::Comma) {
1307 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1308 self.expect(&token::CloseDelim(token::Paren))?;
1310 if ts.len() == 1 && !last_comma {
1311 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1312 let maybe_bounds = allow_plus && self.token.is_like_plus();
1314 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1315 TyKind::Path(None, ref path) if maybe_bounds => {
1316 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1318 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1319 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1320 let path = match bounds[0] {
1321 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1322 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1324 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1327 _ => TyKind::Paren(P(ty))
1332 } else if self.eat(&token::Not) {
1335 } else if self.eat(&token::BinOp(token::Star)) {
1337 TyKind::Ptr(self.parse_ptr()?)
1338 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1340 let t = self.parse_ty()?;
1341 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1342 let t = match self.maybe_parse_fixed_length_of_vec()? {
1343 None => TyKind::Slice(t),
1344 Some(length) => TyKind::Array(t, AnonConst {
1345 id: ast::DUMMY_NODE_ID,
1349 self.expect(&token::CloseDelim(token::Bracket))?;
1351 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1354 self.parse_borrowed_pointee()?
1355 } else if self.eat_keyword_noexpect(kw::Typeof) {
1357 // In order to not be ambiguous, the type must be surrounded by parens.
1358 self.expect(&token::OpenDelim(token::Paren))?;
1360 id: ast::DUMMY_NODE_ID,
1361 value: self.parse_expr()?,
1363 self.expect(&token::CloseDelim(token::Paren))?;
1365 } else if self.eat_keyword(kw::Underscore) {
1366 // A type to be inferred `_`
1368 } else if self.token_is_bare_fn_keyword() {
1369 // Function pointer type
1370 self.parse_ty_bare_fn(Vec::new())?
1371 } else if self.check_keyword(kw::For) {
1372 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1373 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1374 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1376 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1377 if self.token_is_bare_fn_keyword() {
1378 self.parse_ty_bare_fn(lifetime_defs)?
1380 let path = self.parse_path(PathStyle::Type)?;
1381 let parse_plus = allow_plus && self.check_plus();
1382 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1384 } else if self.eat_keyword(kw::Impl) {
1385 // Always parse bounds greedily for better error recovery.
1386 let bounds = self.parse_generic_bounds(None)?;
1387 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1388 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1389 } else if self.check_keyword(kw::Dyn) &&
1390 (self.span.rust_2018() ||
1391 self.look_ahead(1, |t| t.can_begin_bound() &&
1392 !can_continue_type_after_non_fn_ident(t))) {
1393 self.bump(); // `dyn`
1394 // Always parse bounds greedily for better error recovery.
1395 let bounds = self.parse_generic_bounds(None)?;
1396 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1397 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1398 } else if self.check(&token::Question) ||
1399 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1400 // Bound list (trait object type)
1401 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1402 TraitObjectSyntax::None)
1403 } else if self.eat_lt() {
1405 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1406 TyKind::Path(Some(qself), path)
1407 } else if self.token.is_path_start() {
1409 let path = self.parse_path(PathStyle::Type)?;
1410 if self.eat(&token::Not) {
1411 // Macro invocation in type position
1412 let (delim, tts) = self.expect_delimited_token_tree()?;
1413 let node = Mac_ { path, tts, delim };
1414 TyKind::Mac(respan(lo.to(self.prev_span), node))
1416 // Just a type path or bound list (trait object type) starting with a trait.
1418 // `Trait1 + Trait2 + 'a`
1419 if allow_plus && self.check_plus() {
1420 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1422 TyKind::Path(None, path)
1425 } else if self.check(&token::DotDotDot) {
1426 if allow_c_variadic {
1427 self.eat(&token::DotDotDot);
1430 return Err(self.fatal(
1431 "only foreign functions are allowed to be C-variadic"
1435 let msg = format!("expected type, found {}", self.this_token_descr());
1436 return Err(self.fatal(&msg));
1439 let span = lo.to(self.prev_span);
1440 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1442 // Try to recover from use of `+` with incorrect priority.
1443 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1444 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1445 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1448 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1449 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1450 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1451 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1453 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1454 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1456 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1459 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1460 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1461 let mutbl = self.parse_mutability();
1462 let ty = self.parse_ty_no_plus()?;
1463 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1466 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1467 let mutbl = if self.eat_keyword(kw::Mut) {
1469 } else if self.eat_keyword(kw::Const) {
1470 Mutability::Immutable
1472 let span = self.prev_span;
1473 let msg = "expected mut or const in raw pointer type";
1474 self.struct_span_err(span, msg)
1475 .span_label(span, msg)
1476 .help("use `*mut T` or `*const T` as appropriate")
1478 Mutability::Immutable
1480 let t = self.parse_ty_no_plus()?;
1481 Ok(MutTy { ty: t, mutbl: mutbl })
1484 fn is_named_argument(&self) -> bool {
1485 let offset = match self.token.kind {
1486 token::Interpolated(ref nt) => match **nt {
1487 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1490 token::BinOp(token::And) | token::AndAnd => 1,
1491 _ if self.token.is_keyword(kw::Mut) => 1,
1495 self.look_ahead(offset, |t| t.is_ident()) &&
1496 self.look_ahead(offset + 1, |t| t == &token::Colon)
1499 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1501 /// This version of parse arg doesn't necessarily require identifier names.
1502 fn parse_arg_general(
1505 is_trait_item: bool,
1506 allow_c_variadic: bool,
1507 ) -> PResult<'a, Arg> {
1508 if let Ok(Some(arg)) = self.parse_self_arg() {
1509 return self.recover_bad_self_arg(arg, is_trait_item);
1512 let (pat, ty) = if require_name || self.is_named_argument() {
1513 debug!("parse_arg_general parse_pat (require_name:{})", require_name);
1514 self.eat_incorrect_doc_comment("method arguments");
1515 let pat = self.parse_pat(Some("argument name"))?;
1517 if let Err(mut err) = self.expect(&token::Colon) {
1518 if let Some(ident) = self.argument_without_type(
1525 return Ok(dummy_arg(ident));
1531 self.eat_incorrect_doc_comment("a method argument's type");
1532 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1534 debug!("parse_arg_general ident_to_pat");
1535 let parser_snapshot_before_ty = self.clone();
1536 self.eat_incorrect_doc_comment("a method argument's type");
1537 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1538 if ty.is_ok() && self.token != token::Comma &&
1539 self.token != token::CloseDelim(token::Paren) {
1540 // This wasn't actually a type, but a pattern looking like a type,
1541 // so we are going to rollback and re-parse for recovery.
1542 ty = self.unexpected();
1546 let ident = Ident::new(kw::Invalid, self.prev_span);
1548 id: ast::DUMMY_NODE_ID,
1549 node: PatKind::Ident(
1550 BindingMode::ByValue(Mutability::Immutable), ident, None),
1556 // If this is a C-variadic argument and we hit an error, return the
1558 if self.token == token::DotDotDot {
1561 // Recover from attempting to parse the argument as a type without pattern.
1563 mem::replace(self, parser_snapshot_before_ty);
1564 self.recover_arg_parse()?
1569 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1572 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
1573 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1574 let pat = self.parse_pat(Some("argument name"))?;
1575 let t = if self.eat(&token::Colon) {
1579 id: ast::DUMMY_NODE_ID,
1580 node: TyKind::Infer,
1581 span: self.prev_span,
1587 id: ast::DUMMY_NODE_ID
1591 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1592 if self.eat(&token::Semi) {
1593 Ok(Some(self.parse_expr()?))
1599 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1600 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1601 maybe_whole_expr!(self);
1603 let minus_lo = self.span;
1604 let minus_present = self.eat(&token::BinOp(token::Minus));
1606 let literal = self.parse_lit()?;
1607 let hi = self.prev_span;
1608 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1611 let minus_hi = self.prev_span;
1612 let unary = self.mk_unary(UnOp::Neg, expr);
1613 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1619 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1620 match self.token.kind {
1621 token::Ident(name, _) if name.is_path_segment_keyword() => {
1622 let span = self.span;
1624 Ok(Ident::new(name, span))
1626 _ => self.parse_ident(),
1630 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
1631 match self.token.kind {
1632 token::Ident(name, false) if name == kw::Underscore => {
1633 let span = self.span;
1635 Ok(Ident::new(name, span))
1637 _ => self.parse_ident(),
1641 /// Parses a qualified path.
1642 /// Assumes that the leading `<` has been parsed already.
1644 /// `qualified_path = <type [as trait_ref]>::path`
1649 /// `<T as U>::F::a<S>` (without disambiguator)
1650 /// `<T as U>::F::a::<S>` (with disambiguator)
1651 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1652 let lo = self.prev_span;
1653 let ty = self.parse_ty()?;
1655 // `path` will contain the prefix of the path up to the `>`,
1656 // if any (e.g., `U` in the `<T as U>::*` examples
1657 // above). `path_span` has the span of that path, or an empty
1658 // span in the case of something like `<T>::Bar`.
1659 let (mut path, path_span);
1660 if self.eat_keyword(kw::As) {
1661 let path_lo = self.span;
1662 path = self.parse_path(PathStyle::Type)?;
1663 path_span = path_lo.to(self.prev_span);
1665 path_span = self.span.to(self.span);
1666 path = ast::Path { segments: Vec::new(), span: path_span };
1669 // See doc comment for `unmatched_angle_bracket_count`.
1670 self.expect(&token::Gt)?;
1671 if self.unmatched_angle_bracket_count > 0 {
1672 self.unmatched_angle_bracket_count -= 1;
1673 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1676 self.expect(&token::ModSep)?;
1678 let qself = QSelf { ty, path_span, position: path.segments.len() };
1679 self.parse_path_segments(&mut path.segments, style)?;
1681 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1684 /// Parses simple paths.
1686 /// `path = [::] segment+`
1687 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1690 /// `a::b::C<D>` (without disambiguator)
1691 /// `a::b::C::<D>` (with disambiguator)
1692 /// `Fn(Args)` (without disambiguator)
1693 /// `Fn::(Args)` (with disambiguator)
1694 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1695 maybe_whole!(self, NtPath, |path| {
1696 if style == PathStyle::Mod &&
1697 path.segments.iter().any(|segment| segment.args.is_some()) {
1698 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1703 let lo = self.meta_var_span.unwrap_or(self.span);
1704 let mut segments = Vec::new();
1705 let mod_sep_ctxt = self.span.ctxt();
1706 if self.eat(&token::ModSep) {
1707 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
1709 self.parse_path_segments(&mut segments, style)?;
1711 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1714 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
1715 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
1717 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1718 let meta_ident = match self.token.kind {
1719 token::Interpolated(ref nt) => match **nt {
1720 token::NtMeta(ref meta) => match meta.node {
1721 ast::MetaItemKind::Word => Some(meta.path.clone()),
1728 if let Some(path) = meta_ident {
1732 self.parse_path(style)
1735 crate fn parse_path_segments(&mut self,
1736 segments: &mut Vec<PathSegment>,
1738 -> PResult<'a, ()> {
1740 let segment = self.parse_path_segment(style)?;
1741 if style == PathStyle::Expr {
1742 // In order to check for trailing angle brackets, we must have finished
1743 // recursing (`parse_path_segment` can indirectly call this function),
1744 // that is, the next token must be the highlighted part of the below example:
1746 // `Foo::<Bar as Baz<T>>::Qux`
1749 // As opposed to the below highlight (if we had only finished the first
1752 // `Foo::<Bar as Baz<T>>::Qux`
1755 // `PathStyle::Expr` is only provided at the root invocation and never in
1756 // `parse_path_segment` to recurse and therefore can be checked to maintain
1758 self.check_trailing_angle_brackets(&segment, token::ModSep);
1760 segments.push(segment);
1762 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1768 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
1769 let ident = self.parse_path_segment_ident()?;
1771 let is_args_start = |token: &TokenKind| match *token {
1772 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
1773 | token::LArrow => true,
1776 let check_args_start = |this: &mut Self| {
1777 this.expected_tokens.extend_from_slice(
1778 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1780 is_args_start(&this.token)
1783 Ok(if style == PathStyle::Type && check_args_start(self) ||
1784 style != PathStyle::Mod && self.check(&token::ModSep)
1785 && self.look_ahead(1, |t| is_args_start(t)) {
1786 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
1787 // it isn't, then we reset the unmatched angle bracket count as we're about to start
1788 // parsing a new path.
1789 if style == PathStyle::Expr {
1790 self.unmatched_angle_bracket_count = 0;
1791 self.max_angle_bracket_count = 0;
1794 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1795 self.eat(&token::ModSep);
1797 let args = if self.eat_lt() {
1799 let (args, constraints) =
1800 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
1802 let span = lo.to(self.prev_span);
1803 AngleBracketedArgs { args, constraints, span }.into()
1807 let (inputs, recovered) = self.parse_seq_to_before_tokens(
1808 &[&token::CloseDelim(token::Paren)],
1809 SeqSep::trailing_allowed(token::Comma),
1810 TokenExpectType::Expect,
1815 let span = lo.to(self.prev_span);
1816 let output = if self.eat(&token::RArrow) {
1817 Some(self.parse_ty_common(false, false, false)?)
1821 ParenthesizedArgs { inputs, output, span }.into()
1824 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
1826 // Generic arguments are not found.
1827 PathSegment::from_ident(ident)
1831 crate fn check_lifetime(&mut self) -> bool {
1832 self.expected_tokens.push(TokenType::Lifetime);
1833 self.token.is_lifetime()
1836 /// Parses a single lifetime `'a` or panics.
1837 crate fn expect_lifetime(&mut self) -> Lifetime {
1838 if let Some(ident) = self.token.lifetime() {
1839 let span = self.span;
1841 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
1843 self.span_bug(self.span, "not a lifetime")
1847 fn eat_label(&mut self) -> Option<Label> {
1848 if let Some(ident) = self.token.lifetime() {
1849 let span = self.span;
1851 Some(Label { ident: Ident::new(ident.name, span) })
1857 /// Parses mutability (`mut` or nothing).
1858 fn parse_mutability(&mut self) -> Mutability {
1859 if self.eat_keyword(kw::Mut) {
1862 Mutability::Immutable
1866 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1867 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1869 self.expect_no_suffix(self.span, "a tuple index", suffix);
1871 Ok(Ident::new(symbol, self.prev_span))
1873 self.parse_ident_common(false)
1877 /// Parse ident (COLON expr)?
1878 fn parse_field(&mut self) -> PResult<'a, Field> {
1879 let attrs = self.parse_outer_attributes()?;
1882 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1883 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1884 t == &token::Colon || t == &token::Eq
1886 let fieldname = self.parse_field_name()?;
1888 // Check for an equals token. This means the source incorrectly attempts to
1889 // initialize a field with an eq rather than a colon.
1890 if self.token == token::Eq {
1892 .struct_span_err(self.span, "expected `:`, found `=`")
1894 fieldname.span.shrink_to_hi().to(self.span),
1895 "replace equals symbol with a colon",
1897 Applicability::MachineApplicable,
1902 (fieldname, self.parse_expr()?, false)
1904 let fieldname = self.parse_ident_common(false)?;
1906 // Mimic `x: x` for the `x` field shorthand.
1907 let path = ast::Path::from_ident(fieldname);
1908 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1909 (fieldname, expr, true)
1913 span: lo.to(expr.span),
1916 attrs: attrs.into(),
1920 crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1921 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
1924 fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1925 ExprKind::Unary(unop, expr)
1928 fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1929 ExprKind::Binary(binop, lhs, rhs)
1932 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1933 ExprKind::Call(f, args)
1936 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1937 ExprKind::Index(expr, idx)
1941 start: Option<P<Expr>>,
1942 end: Option<P<Expr>>,
1943 limits: RangeLimits)
1944 -> PResult<'a, ast::ExprKind> {
1945 if end.is_none() && limits == RangeLimits::Closed {
1946 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
1948 Ok(ExprKind::Range(start, end, limits))
1952 fn mk_assign_op(&self, binop: ast::BinOp,
1953 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1954 ExprKind::AssignOp(binop, lhs, rhs)
1957 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
1958 let delim = match self.token.kind {
1959 token::OpenDelim(delim) => delim,
1961 let msg = "expected open delimiter";
1962 let mut err = self.fatal(msg);
1963 err.span_label(self.span, msg);
1967 let tts = match self.parse_token_tree() {
1968 TokenTree::Delimited(_, _, tts) => tts,
1969 _ => unreachable!(),
1971 let delim = match delim {
1972 token::Paren => MacDelimiter::Parenthesis,
1973 token::Bracket => MacDelimiter::Bracket,
1974 token::Brace => MacDelimiter::Brace,
1975 token::NoDelim => self.bug("unexpected no delimiter"),
1977 Ok((delim, tts.into()))
1980 /// At the bottom (top?) of the precedence hierarchy,
1981 /// Parses things like parenthesized exprs, macros, `return`, etc.
1983 /// N.B., this does not parse outer attributes, and is private because it only works
1984 /// correctly if called from `parse_dot_or_call_expr()`.
1985 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1986 maybe_recover_from_interpolated_ty_qpath!(self, true);
1987 maybe_whole_expr!(self);
1989 // Outer attributes are already parsed and will be
1990 // added to the return value after the fact.
1992 // Therefore, prevent sub-parser from parsing
1993 // attributes by giving them a empty "already parsed" list.
1994 let mut attrs = ThinVec::new();
1997 let mut hi = self.span;
2001 // Note: when adding new syntax here, don't forget to adjust TokenKind::can_begin_expr().
2002 match self.token.kind {
2003 token::OpenDelim(token::Paren) => {
2006 attrs.extend(self.parse_inner_attributes()?);
2008 // (e) is parenthesized e
2009 // (e,) is a tuple with only one field, e
2010 let mut es = vec![];
2011 let mut trailing_comma = false;
2012 let mut recovered = false;
2013 while self.token != token::CloseDelim(token::Paren) {
2014 es.push(match self.parse_expr() {
2017 // recover from parse error in tuple list
2018 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2021 recovered = self.expect_one_of(
2023 &[token::Comma, token::CloseDelim(token::Paren)],
2025 if self.eat(&token::Comma) {
2026 trailing_comma = true;
2028 trailing_comma = false;
2036 hi = self.prev_span;
2037 ex = if es.len() == 1 && !trailing_comma {
2038 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2043 token::OpenDelim(token::Brace) => {
2044 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2046 token::BinOp(token::Or) | token::OrOr => {
2047 return self.parse_lambda_expr(attrs);
2049 token::OpenDelim(token::Bracket) => {
2052 attrs.extend(self.parse_inner_attributes()?);
2054 if self.eat(&token::CloseDelim(token::Bracket)) {
2056 ex = ExprKind::Array(Vec::new());
2059 let first_expr = self.parse_expr()?;
2060 if self.eat(&token::Semi) {
2061 // Repeating array syntax: [ 0; 512 ]
2062 let count = AnonConst {
2063 id: ast::DUMMY_NODE_ID,
2064 value: self.parse_expr()?,
2066 self.expect(&token::CloseDelim(token::Bracket))?;
2067 ex = ExprKind::Repeat(first_expr, count);
2068 } else if self.eat(&token::Comma) {
2069 // Vector with two or more elements.
2070 let remaining_exprs = self.parse_seq_to_end(
2071 &token::CloseDelim(token::Bracket),
2072 SeqSep::trailing_allowed(token::Comma),
2073 |p| Ok(p.parse_expr()?)
2075 let mut exprs = vec![first_expr];
2076 exprs.extend(remaining_exprs);
2077 ex = ExprKind::Array(exprs);
2079 // Vector with one element.
2080 self.expect(&token::CloseDelim(token::Bracket))?;
2081 ex = ExprKind::Array(vec![first_expr]);
2084 hi = self.prev_span;
2088 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2090 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2092 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
2093 return self.parse_lambda_expr(attrs);
2095 if self.eat_keyword(kw::If) {
2096 return self.parse_if_expr(attrs);
2098 if self.eat_keyword(kw::For) {
2099 let lo = self.prev_span;
2100 return self.parse_for_expr(None, lo, attrs);
2102 if self.eat_keyword(kw::While) {
2103 let lo = self.prev_span;
2104 return self.parse_while_expr(None, lo, attrs);
2106 if let Some(label) = self.eat_label() {
2107 let lo = label.ident.span;
2108 self.expect(&token::Colon)?;
2109 if self.eat_keyword(kw::While) {
2110 return self.parse_while_expr(Some(label), lo, attrs)
2112 if self.eat_keyword(kw::For) {
2113 return self.parse_for_expr(Some(label), lo, attrs)
2115 if self.eat_keyword(kw::Loop) {
2116 return self.parse_loop_expr(Some(label), lo, attrs)
2118 if self.token == token::OpenDelim(token::Brace) {
2119 return self.parse_block_expr(Some(label),
2121 BlockCheckMode::Default,
2124 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2125 let mut err = self.fatal(msg);
2126 err.span_label(self.span, msg);
2129 if self.eat_keyword(kw::Loop) {
2130 let lo = self.prev_span;
2131 return self.parse_loop_expr(None, lo, attrs);
2133 if self.eat_keyword(kw::Continue) {
2134 let label = self.eat_label();
2135 let ex = ExprKind::Continue(label);
2136 let hi = self.prev_span;
2137 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2139 if self.eat_keyword(kw::Match) {
2140 let match_sp = self.prev_span;
2141 return self.parse_match_expr(attrs).map_err(|mut err| {
2142 err.span_label(match_sp, "while parsing this match expression");
2146 if self.eat_keyword(kw::Unsafe) {
2147 return self.parse_block_expr(
2150 BlockCheckMode::Unsafe(ast::UserProvided),
2153 if self.is_do_catch_block() {
2154 let mut db = self.fatal("found removed `do catch` syntax");
2155 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2158 if self.is_try_block() {
2160 assert!(self.eat_keyword(kw::Try));
2161 return self.parse_try_block(lo, attrs);
2164 // Span::rust_2018() is somewhat expensive; don't get it repeatedly.
2165 let is_span_rust_2018 = self.span.rust_2018();
2166 if is_span_rust_2018 && self.check_keyword(kw::Async) {
2167 return if self.is_async_block() { // check for `async {` and `async move {`
2168 self.parse_async_block(attrs)
2170 self.parse_lambda_expr(attrs)
2173 if self.eat_keyword(kw::Return) {
2174 if self.token.can_begin_expr() {
2175 let e = self.parse_expr()?;
2177 ex = ExprKind::Ret(Some(e));
2179 ex = ExprKind::Ret(None);
2181 } else if self.eat_keyword(kw::Break) {
2182 let label = self.eat_label();
2183 let e = if self.token.can_begin_expr()
2184 && !(self.token == token::OpenDelim(token::Brace)
2185 && self.restrictions.contains(
2186 Restrictions::NO_STRUCT_LITERAL)) {
2187 Some(self.parse_expr()?)
2191 ex = ExprKind::Break(label, e);
2192 hi = self.prev_span;
2193 } else if self.eat_keyword(kw::Yield) {
2194 if self.token.can_begin_expr() {
2195 let e = self.parse_expr()?;
2197 ex = ExprKind::Yield(Some(e));
2199 ex = ExprKind::Yield(None);
2201 } else if self.token.is_keyword(kw::Let) {
2202 // Catch this syntax error here, instead of in `parse_ident`, so
2203 // that we can explicitly mention that let is not to be used as an expression
2204 let mut db = self.fatal("expected expression, found statement (`let`)");
2205 db.span_label(self.span, "expected expression");
2206 db.note("variable declaration using `let` is a statement");
2208 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
2209 let (await_hi, e_kind) = self.parse_await_macro_or_alt(lo, self.prev_span)?;
2212 } else if self.token.is_path_start() {
2213 let path = self.parse_path(PathStyle::Expr)?;
2215 // `!`, as an operator, is prefix, so we know this isn't that
2216 if self.eat(&token::Not) {
2217 // MACRO INVOCATION expression
2218 let (delim, tts) = self.expect_delimited_token_tree()?;
2219 hi = self.prev_span;
2220 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2221 } else if self.check(&token::OpenDelim(token::Brace)) {
2222 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2226 ex = ExprKind::Path(None, path);
2230 ex = ExprKind::Path(None, path);
2233 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2234 // Don't complain about bare semicolons after unclosed braces
2235 // recovery in order to keep the error count down. Fixing the
2236 // delimiters will possibly also fix the bare semicolon found in
2237 // expression context. For example, silence the following error:
2239 // error: expected expression, found `;`
2243 // | ^ expected expression
2246 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2248 match self.parse_literal_maybe_minus() {
2251 ex = expr.node.clone();
2254 self.cancel(&mut err);
2255 return Err(self.expected_expression_found());
2262 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2263 self.maybe_recover_from_bad_qpath(expr, true)
2266 /// Parse `await!(<expr>)` calls, or alternatively recover from incorrect but reasonable
2267 /// alternative syntaxes `await <expr>`, `await? <expr>`, `await(<expr>)` and
2268 /// `await { <expr> }`.
2269 fn parse_await_macro_or_alt(
2273 ) -> PResult<'a, (Span, ExprKind)> {
2274 if self.token == token::Not {
2275 // Handle correct `await!(<expr>)`.
2276 // FIXME: make this an error when `await!` is no longer supported
2277 // https://github.com/rust-lang/rust/issues/60610
2278 self.expect(&token::Not)?;
2279 self.expect(&token::OpenDelim(token::Paren))?;
2280 let expr = self.parse_expr().map_err(|mut err| {
2281 err.span_label(await_sp, "while parsing this await macro call");
2284 self.expect(&token::CloseDelim(token::Paren))?;
2285 Ok((self.prev_span, ExprKind::Await(ast::AwaitOrigin::MacroLike, expr)))
2286 } else { // Handle `await <expr>`.
2287 self.parse_incorrect_await_syntax(lo, await_sp)
2291 fn maybe_parse_struct_expr(
2295 attrs: &ThinVec<Attribute>,
2296 ) -> Option<PResult<'a, P<Expr>>> {
2297 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2298 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2299 // `{ ident, ` cannot start a block
2300 self.look_ahead(2, |t| t == &token::Comma) ||
2301 self.look_ahead(2, |t| t == &token::Colon) && (
2302 // `{ ident: token, ` cannot start a block
2303 self.look_ahead(4, |t| t == &token::Comma) ||
2304 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2305 self.look_ahead(3, |t| !t.can_begin_type())
2309 if struct_allowed || certainly_not_a_block() {
2310 // This is a struct literal, but we don't can't accept them here
2311 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2312 if let (Ok(expr), false) = (&expr, struct_allowed) {
2313 let mut err = self.diagnostic().struct_span_err(
2315 "struct literals are not allowed here",
2317 err.multipart_suggestion(
2318 "surround the struct literal with parentheses",
2320 (lo.shrink_to_lo(), "(".to_string()),
2321 (expr.span.shrink_to_hi(), ")".to_string()),
2323 Applicability::MachineApplicable,
2332 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2333 -> PResult<'a, P<Expr>> {
2334 let struct_sp = lo.to(self.prev_span);
2336 let mut fields = Vec::new();
2337 let mut base = None;
2339 attrs.extend(self.parse_inner_attributes()?);
2341 while self.token != token::CloseDelim(token::Brace) {
2342 if self.eat(&token::DotDot) {
2343 let exp_span = self.prev_span;
2344 match self.parse_expr() {
2350 self.recover_stmt();
2353 if self.token == token::Comma {
2354 let mut err = self.sess.span_diagnostic.mut_span_err(
2355 exp_span.to(self.prev_span),
2356 "cannot use a comma after the base struct",
2358 err.span_suggestion_short(
2360 "remove this comma",
2362 Applicability::MachineApplicable
2364 err.note("the base struct must always be the last field");
2366 self.recover_stmt();
2371 let mut recovery_field = None;
2372 if let token::Ident(name, _) = self.token.kind {
2373 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2374 // Use in case of error after field-looking code: `S { foo: () with a }`
2375 recovery_field = Some(ast::Field {
2376 ident: Ident::new(name, self.span),
2378 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2379 is_shorthand: false,
2380 attrs: ThinVec::new(),
2384 let mut parsed_field = None;
2385 match self.parse_field() {
2386 Ok(f) => parsed_field = Some(f),
2388 e.span_label(struct_sp, "while parsing this struct");
2391 // If the next token is a comma, then try to parse
2392 // what comes next as additional fields, rather than
2393 // bailing out until next `}`.
2394 if self.token != token::Comma {
2395 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2396 if self.token != token::Comma {
2403 match self.expect_one_of(&[token::Comma],
2404 &[token::CloseDelim(token::Brace)]) {
2405 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2406 // only include the field if there's no parse error for the field name
2410 if let Some(f) = recovery_field {
2413 e.span_label(struct_sp, "while parsing this struct");
2415 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2416 self.eat(&token::Comma);
2421 let span = lo.to(self.span);
2422 self.expect(&token::CloseDelim(token::Brace))?;
2423 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2426 fn parse_or_use_outer_attributes(&mut self,
2427 already_parsed_attrs: Option<ThinVec<Attribute>>)
2428 -> PResult<'a, ThinVec<Attribute>> {
2429 if let Some(attrs) = already_parsed_attrs {
2432 self.parse_outer_attributes().map(|a| a.into())
2436 /// Parses a block or unsafe block.
2437 crate fn parse_block_expr(
2439 opt_label: Option<Label>,
2441 blk_mode: BlockCheckMode,
2442 outer_attrs: ThinVec<Attribute>,
2443 ) -> PResult<'a, P<Expr>> {
2444 self.expect(&token::OpenDelim(token::Brace))?;
2446 let mut attrs = outer_attrs;
2447 attrs.extend(self.parse_inner_attributes()?);
2449 let blk = self.parse_block_tail(lo, blk_mode)?;
2450 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2453 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2454 fn parse_dot_or_call_expr(&mut self,
2455 already_parsed_attrs: Option<ThinVec<Attribute>>)
2456 -> PResult<'a, P<Expr>> {
2457 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2459 let b = self.parse_bottom_expr();
2460 let (span, b) = self.interpolated_or_expr_span(b)?;
2461 self.parse_dot_or_call_expr_with(b, span, attrs)
2464 fn parse_dot_or_call_expr_with(&mut self,
2467 mut attrs: ThinVec<Attribute>)
2468 -> PResult<'a, P<Expr>> {
2469 // Stitch the list of outer attributes onto the return value.
2470 // A little bit ugly, but the best way given the current code
2472 self.parse_dot_or_call_expr_with_(e0, lo)
2474 expr.map(|mut expr| {
2475 attrs.extend::<Vec<_>>(expr.attrs.into());
2478 ExprKind::If(..) | ExprKind::IfLet(..) => {
2479 if !expr.attrs.is_empty() {
2480 // Just point to the first attribute in there...
2481 let span = expr.attrs[0].span;
2484 "attributes are not yet allowed on `if` \
2495 // Assuming we have just parsed `.`, continue parsing into an expression.
2496 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2497 if self.span.rust_2018() && self.eat_keyword(kw::Await) {
2498 let span = lo.to(self.prev_span);
2499 let await_expr = self.mk_expr(
2501 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
2504 self.recover_from_await_method_call();
2505 return Ok(await_expr);
2507 let segment = self.parse_path_segment(PathStyle::Expr)?;
2508 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2510 Ok(match self.token.kind {
2511 token::OpenDelim(token::Paren) => {
2512 // Method call `expr.f()`
2513 let mut args = self.parse_unspanned_seq(
2514 &token::OpenDelim(token::Paren),
2515 &token::CloseDelim(token::Paren),
2516 SeqSep::trailing_allowed(token::Comma),
2517 |p| Ok(p.parse_expr()?)
2519 args.insert(0, self_arg);
2521 let span = lo.to(self.prev_span);
2522 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2525 // Field access `expr.f`
2526 if let Some(args) = segment.args {
2527 self.span_err(args.span(),
2528 "field expressions may not have generic arguments");
2531 let span = lo.to(self.prev_span);
2532 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2537 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2542 while self.eat(&token::Question) {
2543 let hi = self.prev_span;
2544 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2548 if self.eat(&token::Dot) {
2549 match self.token.kind {
2550 token::Ident(..) => {
2551 e = self.parse_dot_suffix(e, lo)?;
2553 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
2554 let span = self.span;
2556 let field = ExprKind::Field(e, Ident::new(symbol, span));
2557 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2559 self.expect_no_suffix(span, "a tuple index", suffix);
2561 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
2563 let fstr = symbol.as_str();
2564 let msg = format!("unexpected token: `{}`", symbol);
2565 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
2566 err.span_label(self.prev_span, "unexpected token");
2567 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2568 let float = match fstr.parse::<f64>().ok() {
2572 let sugg = pprust::to_string(|s| {
2573 use crate::print::pprust::PrintState;
2577 s.print_usize(float.trunc() as usize)?;
2580 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2582 err.span_suggestion(
2583 lo.to(self.prev_span),
2584 "try parenthesizing the first index",
2586 Applicability::MachineApplicable
2593 // FIXME Could factor this out into non_fatal_unexpected or something.
2594 let actual = self.this_token_to_string();
2595 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2600 if self.expr_is_complete(&e) { break; }
2601 match self.token.kind {
2603 token::OpenDelim(token::Paren) => {
2604 let seq = self.parse_unspanned_seq(
2605 &token::OpenDelim(token::Paren),
2606 &token::CloseDelim(token::Paren),
2607 SeqSep::trailing_allowed(token::Comma),
2608 |p| Ok(p.parse_expr()?)
2610 let nd = self.mk_call(e, es);
2611 let hi = self.prev_span;
2612 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2614 e = self.recover_seq_parse_error(token::Paren, lo, seq);
2618 // Could be either an index expression or a slicing expression.
2619 token::OpenDelim(token::Bracket) => {
2621 let ix = self.parse_expr()?;
2623 self.expect(&token::CloseDelim(token::Bracket))?;
2624 let index = self.mk_index(e, ix);
2625 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2633 crate fn process_potential_macro_variable(&mut self) {
2634 self.token = match self.token.kind {
2635 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2636 self.look_ahead(1, |t| t.is_ident()) => {
2638 let name = match self.token.kind {
2639 token::Ident(name, _) => name,
2642 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2643 err.span_label(self.span, "unknown macro variable");
2648 token::Interpolated(ref nt) => {
2649 self.meta_var_span = Some(self.span);
2650 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2651 // and lifetime tokens, so the former are never encountered during normal parsing.
2653 token::NtIdent(ident, is_raw) =>
2654 Token::new(token::Ident(ident.name, is_raw), ident.span),
2655 token::NtLifetime(ident) =>
2656 Token::new(token::Lifetime(ident.name), ident.span),
2664 /// Parses a single token tree from the input.
2665 crate fn parse_token_tree(&mut self) -> TokenTree {
2666 match self.token.kind {
2667 token::OpenDelim(..) => {
2668 let frame = mem::replace(&mut self.token_cursor.frame,
2669 self.token_cursor.stack.pop().unwrap());
2670 self.token.span = frame.span.entire();
2672 TokenTree::Delimited(
2675 frame.tree_cursor.stream.into(),
2678 token::CloseDelim(_) | token::Eof => unreachable!(),
2680 let token = self.token.take();
2682 TokenTree::Token(token)
2687 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
2688 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2689 let mut tts = Vec::new();
2690 while self.token != token::Eof {
2691 tts.push(self.parse_token_tree());
2696 pub fn parse_tokens(&mut self) -> TokenStream {
2697 let mut result = Vec::new();
2699 match self.token.kind {
2700 token::Eof | token::CloseDelim(..) => break,
2701 _ => result.push(self.parse_token_tree().into()),
2704 TokenStream::new(result)
2707 /// Parse a prefix-unary-operator expr
2708 fn parse_prefix_expr(&mut self,
2709 already_parsed_attrs: Option<ThinVec<Attribute>>)
2710 -> PResult<'a, P<Expr>> {
2711 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2713 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
2714 let (hi, ex) = match self.token.kind {
2717 let e = self.parse_prefix_expr(None);
2718 let (span, e) = self.interpolated_or_expr_span(e)?;
2719 (lo.to(span), self.mk_unary(UnOp::Not, e))
2721 // Suggest `!` for bitwise negation when encountering a `~`
2724 let e = self.parse_prefix_expr(None);
2725 let (span, e) = self.interpolated_or_expr_span(e)?;
2726 let span_of_tilde = lo;
2727 let mut err = self.diagnostic()
2728 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2729 err.span_suggestion_short(
2731 "use `!` to perform bitwise negation",
2733 Applicability::MachineApplicable
2736 (lo.to(span), self.mk_unary(UnOp::Not, e))
2738 token::BinOp(token::Minus) => {
2740 let e = self.parse_prefix_expr(None);
2741 let (span, e) = self.interpolated_or_expr_span(e)?;
2742 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2744 token::BinOp(token::Star) => {
2746 let e = self.parse_prefix_expr(None);
2747 let (span, e) = self.interpolated_or_expr_span(e)?;
2748 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2750 token::BinOp(token::And) | token::AndAnd => {
2752 let m = self.parse_mutability();
2753 let e = self.parse_prefix_expr(None);
2754 let (span, e) = self.interpolated_or_expr_span(e)?;
2755 (lo.to(span), ExprKind::AddrOf(m, e))
2757 token::Ident(..) if self.token.is_keyword(kw::Box) => {
2759 let e = self.parse_prefix_expr(None);
2760 let (span, e) = self.interpolated_or_expr_span(e)?;
2761 (lo.to(span), ExprKind::Box(e))
2763 token::Ident(..) if self.token.is_ident_named(sym::not) => {
2764 // `not` is just an ordinary identifier in Rust-the-language,
2765 // but as `rustc`-the-compiler, we can issue clever diagnostics
2766 // for confused users who really want to say `!`
2767 let token_cannot_continue_expr = |t: &Token| match t.kind {
2768 // These tokens can start an expression after `!`, but
2769 // can't continue an expression after an ident
2770 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
2771 token::Literal(..) | token::Pound => true,
2772 token::Interpolated(ref nt) => match **nt {
2773 token::NtIdent(..) | token::NtExpr(..) |
2774 token::NtBlock(..) | token::NtPath(..) => true,
2779 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2780 if cannot_continue_expr {
2782 // Emit the error ...
2783 let mut err = self.diagnostic()
2784 .struct_span_err(self.span,
2785 &format!("unexpected {} after identifier",
2786 self.this_token_descr()));
2787 // span the `not` plus trailing whitespace to avoid
2788 // trailing whitespace after the `!` in our suggestion
2789 let to_replace = self.sess.source_map()
2790 .span_until_non_whitespace(lo.to(self.span));
2791 err.span_suggestion_short(
2793 "use `!` to perform logical negation",
2795 Applicability::MachineApplicable
2798 // —and recover! (just as if we were in the block
2799 // for the `token::Not` arm)
2800 let e = self.parse_prefix_expr(None);
2801 let (span, e) = self.interpolated_or_expr_span(e)?;
2802 (lo.to(span), self.mk_unary(UnOp::Not, e))
2804 return self.parse_dot_or_call_expr(Some(attrs));
2807 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2809 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2812 /// Parses an associative expression.
2814 /// This parses an expression accounting for associativity and precedence of the operators in
2817 fn parse_assoc_expr(&mut self,
2818 already_parsed_attrs: Option<ThinVec<Attribute>>)
2819 -> PResult<'a, P<Expr>> {
2820 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2823 /// Parses an associative expression with operators of at least `min_prec` precedence.
2824 fn parse_assoc_expr_with(&mut self,
2827 -> PResult<'a, P<Expr>> {
2828 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2831 let attrs = match lhs {
2832 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2835 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2836 return self.parse_prefix_range_expr(attrs);
2838 self.parse_prefix_expr(attrs)?
2842 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
2844 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2847 (false, _) => {} // continue parsing the expression
2848 // An exhaustive check is done in the following block, but these are checked first
2849 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
2850 // want to keep their span info to improve diagnostics in these cases in a later stage.
2851 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
2852 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
2853 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
2854 (true, Some(AssocOp::Add)) // `{ 42 } + 42
2855 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
2856 // `if x { a } else { b } && if y { c } else { d }`
2857 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
2858 // These cases are ambiguous and can't be identified in the parser alone
2859 let sp = self.sess.source_map().start_point(self.span);
2860 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
2863 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
2866 (true, Some(_)) => {
2867 // We've found an expression that would be parsed as a statement, but the next
2868 // token implies this should be parsed as an expression.
2869 // For example: `if let Some(x) = x { x } else { 0 } / 2`
2870 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
2871 "expected expression, found `{}`",
2872 pprust::token_to_string(&self.token),
2874 err.span_label(self.span, "expected expression");
2875 self.sess.expr_parentheses_needed(
2878 Some(pprust::expr_to_string(&lhs),
2883 self.expected_tokens.push(TokenType::Operator);
2884 while let Some(op) = AssocOp::from_token(&self.token) {
2886 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2887 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2888 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2889 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2890 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2891 (PrevTokenKind::Interpolated, _) => self.prev_span,
2892 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2893 if path.segments.len() == 1 => self.prev_span,
2897 let cur_op_span = self.span;
2898 let restrictions = if op.is_assign_like() {
2899 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2903 let prec = op.precedence();
2904 if prec < min_prec {
2907 // Check for deprecated `...` syntax
2908 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2909 self.err_dotdotdot_syntax(self.span);
2913 if op.is_comparison() {
2914 self.check_no_chained_comparison(&lhs, &op);
2917 if op == AssocOp::As {
2918 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2920 } else if op == AssocOp::Colon {
2921 let maybe_path = self.could_ascription_be_path(&lhs.node);
2922 let next_sp = self.span;
2924 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2927 self.bad_type_ascription(
2938 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2939 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2940 // generalise it to the Fixity::None code.
2942 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2943 // two variants are handled with `parse_prefix_range_expr` call above.
2944 let rhs = if self.is_at_start_of_range_notation_rhs() {
2945 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
2949 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2954 let limits = if op == AssocOp::DotDot {
2955 RangeLimits::HalfOpen
2960 let r = self.mk_range(Some(lhs), rhs, limits)?;
2961 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2965 let fixity = op.fixity();
2966 let prec_adjustment = match fixity {
2969 // We currently have no non-associative operators that are not handled above by
2970 // the special cases. The code is here only for future convenience.
2973 let rhs = self.with_res(
2974 restrictions - Restrictions::STMT_EXPR,
2975 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
2978 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
2979 // including the attributes.
2983 .filter(|a| a.style == AttrStyle::Outer)
2985 .map_or(lhs_span, |a| a.span);
2986 let span = lhs_span.to(rhs.span);
2988 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2989 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2990 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2991 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2992 AssocOp::Greater | AssocOp::GreaterEqual => {
2993 let ast_op = op.to_ast_binop().unwrap();
2994 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
2995 self.mk_expr(span, binary, ThinVec::new())
2997 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2998 AssocOp::AssignOp(k) => {
3000 token::Plus => BinOpKind::Add,
3001 token::Minus => BinOpKind::Sub,
3002 token::Star => BinOpKind::Mul,
3003 token::Slash => BinOpKind::Div,
3004 token::Percent => BinOpKind::Rem,
3005 token::Caret => BinOpKind::BitXor,
3006 token::And => BinOpKind::BitAnd,
3007 token::Or => BinOpKind::BitOr,
3008 token::Shl => BinOpKind::Shl,
3009 token::Shr => BinOpKind::Shr,
3011 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3012 self.mk_expr(span, aopexpr, ThinVec::new())
3014 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3015 self.bug("AssocOp should have been handled by special case")
3019 if let Fixity::None = fixity { break }
3024 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3025 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3026 -> PResult<'a, P<Expr>> {
3027 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3028 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3031 // Save the state of the parser before parsing type normally, in case there is a
3032 // LessThan comparison after this cast.
3033 let parser_snapshot_before_type = self.clone();
3034 match self.parse_ty_no_plus() {
3036 Ok(mk_expr(self, rhs))
3038 Err(mut type_err) => {
3039 // Rewind to before attempting to parse the type with generics, to recover
3040 // from situations like `x as usize < y` in which we first tried to parse
3041 // `usize < y` as a type with generic arguments.
3042 let parser_snapshot_after_type = self.clone();
3043 mem::replace(self, parser_snapshot_before_type);
3045 match self.parse_path(PathStyle::Expr) {
3047 let (op_noun, op_verb) = match self.token.kind {
3048 token::Lt => ("comparison", "comparing"),
3049 token::BinOp(token::Shl) => ("shift", "shifting"),
3051 // We can end up here even without `<` being the next token, for
3052 // example because `parse_ty_no_plus` returns `Err` on keywords,
3053 // but `parse_path` returns `Ok` on them due to error recovery.
3054 // Return original error and parser state.
3055 mem::replace(self, parser_snapshot_after_type);
3056 return Err(type_err);
3060 // Successfully parsed the type path leaving a `<` yet to parse.
3063 // Report non-fatal diagnostics, keep `x as usize` as an expression
3064 // in AST and continue parsing.
3065 let msg = format!("`<` is interpreted as a start of generic \
3066 arguments for `{}`, not a {}", path, op_noun);
3067 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3068 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3069 "interpreted as generic arguments");
3070 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3072 let expr = mk_expr(self, P(Ty {
3074 node: TyKind::Path(None, path),
3075 id: ast::DUMMY_NODE_ID
3078 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3079 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3080 err.span_suggestion(
3082 &format!("try {} the cast value", op_verb),
3083 format!("({})", expr_str),
3084 Applicability::MachineApplicable
3090 Err(mut path_err) => {
3091 // Couldn't parse as a path, return original error and parser state.
3093 mem::replace(self, parser_snapshot_after_type);
3101 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3102 fn parse_prefix_range_expr(&mut self,
3103 already_parsed_attrs: Option<ThinVec<Attribute>>)
3104 -> PResult<'a, P<Expr>> {
3105 // Check for deprecated `...` syntax
3106 if self.token == token::DotDotDot {
3107 self.err_dotdotdot_syntax(self.span);
3110 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3111 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3113 let tok = self.token.clone();
3114 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3116 let mut hi = self.span;
3118 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3119 // RHS must be parsed with more associativity than the dots.
3120 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3121 Some(self.parse_assoc_expr_with(next_prec,
3122 LhsExpr::NotYetParsed)
3130 let limits = if tok == token::DotDot {
3131 RangeLimits::HalfOpen
3136 let r = self.mk_range(None, opt_end, limits)?;
3137 Ok(self.mk_expr(lo.to(hi), r, attrs))
3140 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3141 if self.token.can_begin_expr() {
3142 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3143 if self.token == token::OpenDelim(token::Brace) {
3144 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3152 /// Parses an `if` or `if let` expression (`if` token already eaten).
3153 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3154 if self.check_keyword(kw::Let) {
3155 return self.parse_if_let_expr(attrs);
3157 let lo = self.prev_span;
3158 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3160 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3161 // verify that the last statement is either an implicit return (no `;`) or an explicit
3162 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3163 // the dead code lint.
3164 if self.eat_keyword(kw::Else) || !cond.returns() {
3165 let sp = self.sess.source_map().next_point(lo);
3166 let mut err = self.diagnostic()
3167 .struct_span_err(sp, "missing condition for `if` statemement");
3168 err.span_label(sp, "expected if condition here");
3171 let not_block = self.token != token::OpenDelim(token::Brace);
3172 let thn = self.parse_block().map_err(|mut err| {
3174 err.span_label(lo, "this `if` statement has a condition, but no block");
3178 let mut els: Option<P<Expr>> = None;
3179 let mut hi = thn.span;
3180 if self.eat_keyword(kw::Else) {
3181 let elexpr = self.parse_else_expr()?;
3185 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3188 /// Parses an `if let` expression (`if` token already eaten).
3189 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3190 -> PResult<'a, P<Expr>> {
3191 let lo = self.prev_span;
3192 self.expect_keyword(kw::Let)?;
3193 let pats = self.parse_pats()?;
3194 self.expect(&token::Eq)?;
3195 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3196 let thn = self.parse_block()?;
3197 let (hi, els) = if self.eat_keyword(kw::Else) {
3198 let expr = self.parse_else_expr()?;
3199 (expr.span, Some(expr))
3203 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3206 /// Parses `move |args| expr`.
3207 fn parse_lambda_expr(&mut self,
3208 attrs: ThinVec<Attribute>)
3209 -> PResult<'a, P<Expr>>
3212 let movability = if self.eat_keyword(kw::Static) {
3217 let asyncness = if self.span.rust_2018() {
3218 self.parse_asyncness()
3222 let capture_clause = if self.eat_keyword(kw::Move) {
3227 let decl = self.parse_fn_block_decl()?;
3228 let decl_hi = self.prev_span;
3229 let body = match decl.output {
3230 FunctionRetTy::Default(_) => {
3231 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3232 self.parse_expr_res(restrictions, None)?
3235 // If an explicit return type is given, require a
3236 // block to appear (RFC 968).
3237 let body_lo = self.span;
3238 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3244 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3248 // `else` token already eaten
3249 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3250 if self.eat_keyword(kw::If) {
3251 return self.parse_if_expr(ThinVec::new());
3253 let blk = self.parse_block()?;
3254 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3258 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3259 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3261 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3262 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3264 let pat = self.parse_top_level_pat()?;
3265 if !self.eat_keyword(kw::In) {
3266 let in_span = self.prev_span.between(self.span);
3267 let mut err = self.sess.span_diagnostic
3268 .struct_span_err(in_span, "missing `in` in `for` loop");
3269 err.span_suggestion_short(
3270 in_span, "try adding `in` here", " in ".into(),
3271 // has been misleading, at least in the past (closed Issue #48492)
3272 Applicability::MaybeIncorrect
3276 let in_span = self.prev_span;
3277 self.check_for_for_in_in_typo(in_span);
3278 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3279 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3280 attrs.extend(iattrs);
3282 let hi = self.prev_span;
3283 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3286 /// Parses a `while` or `while let` expression (`while` token already eaten).
3287 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3289 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3290 if self.token.is_keyword(kw::Let) {
3291 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3293 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3294 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3295 attrs.extend(iattrs);
3296 let span = span_lo.to(body.span);
3297 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3300 /// Parses a `while let` expression (`while` token already eaten).
3301 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3303 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3304 self.expect_keyword(kw::Let)?;
3305 let pats = self.parse_pats()?;
3306 self.expect(&token::Eq)?;
3307 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3308 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3309 attrs.extend(iattrs);
3310 let span = span_lo.to(body.span);
3311 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3314 // parse `loop {...}`, `loop` token already eaten
3315 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3317 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3318 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3319 attrs.extend(iattrs);
3320 let span = span_lo.to(body.span);
3321 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3324 /// Parses an `async move {...}` expression.
3325 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3326 -> PResult<'a, P<Expr>>
3328 let span_lo = self.span;
3329 self.expect_keyword(kw::Async)?;
3330 let capture_clause = if self.eat_keyword(kw::Move) {
3335 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3336 attrs.extend(iattrs);
3338 span_lo.to(body.span),
3339 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3342 /// Parses a `try {...}` expression (`try` token already eaten).
3343 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3344 -> PResult<'a, P<Expr>>
3346 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3347 attrs.extend(iattrs);
3348 if self.eat_keyword(kw::Catch) {
3349 let mut error = self.struct_span_err(self.prev_span,
3350 "keyword `catch` cannot follow a `try` block");
3351 error.help("try using `match` on the result of the `try` block instead");
3355 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3359 // `match` token already eaten
3360 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3361 let match_span = self.prev_span;
3362 let lo = self.prev_span;
3363 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3365 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3366 if self.token == token::Semi {
3367 e.span_suggestion_short(
3369 "try removing this `match`",
3371 Applicability::MaybeIncorrect // speculative
3376 attrs.extend(self.parse_inner_attributes()?);
3378 let mut arms: Vec<Arm> = Vec::new();
3379 while self.token != token::CloseDelim(token::Brace) {
3380 match self.parse_arm() {
3381 Ok(arm) => arms.push(arm),
3383 // Recover by skipping to the end of the block.
3385 self.recover_stmt();
3386 let span = lo.to(self.span);
3387 if self.token == token::CloseDelim(token::Brace) {
3390 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3396 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3399 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3400 let attrs = self.parse_outer_attributes()?;
3402 let pats = self.parse_pats()?;
3403 let guard = if self.eat_keyword(kw::If) {
3404 Some(Guard::If(self.parse_expr()?))
3408 let arrow_span = self.span;
3409 self.expect(&token::FatArrow)?;
3410 let arm_start_span = self.span;
3412 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3413 .map_err(|mut err| {
3414 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3418 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3419 && self.token != token::CloseDelim(token::Brace);
3424 let cm = self.sess.source_map();
3425 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3426 .map_err(|mut err| {
3427 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3428 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3429 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3430 && expr_lines.lines.len() == 2
3431 && self.token == token::FatArrow => {
3432 // We check whether there's any trailing code in the parse span,
3433 // if there isn't, we very likely have the following:
3436 // | -- - missing comma
3442 // | parsed until here as `"y" & X`
3443 err.span_suggestion_short(
3444 cm.next_point(arm_start_span),
3445 "missing a comma here to end this `match` arm",
3447 Applicability::MachineApplicable
3451 err.span_label(arrow_span,
3452 "while parsing the `match` arm starting here");
3458 self.eat(&token::Comma);
3470 /// Parses an expression.
3472 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3473 self.parse_expr_res(Restrictions::empty(), None)
3476 /// Evaluates the closure with restrictions in place.
3478 /// Afters the closure is evaluated, restrictions are reset.
3479 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3480 where F: FnOnce(&mut Self) -> T
3482 let old = self.restrictions;
3483 self.restrictions = r;
3485 self.restrictions = old;
3490 /// Parses an expression, subject to the given restrictions.
3492 fn parse_expr_res(&mut self, r: Restrictions,
3493 already_parsed_attrs: Option<ThinVec<Attribute>>)
3494 -> PResult<'a, P<Expr>> {
3495 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3498 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
3499 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3500 if self.eat(&token::Eq) {
3501 Ok(Some(self.parse_expr()?))
3503 Ok(Some(self.parse_expr()?))
3509 /// Parses patterns, separated by '|' s.
3510 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3511 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
3512 self.eat(&token::BinOp(token::Or));
3514 let mut pats = Vec::new();
3516 pats.push(self.parse_top_level_pat()?);
3518 if self.token == token::OrOr {
3519 let mut err = self.struct_span_err(self.span,
3520 "unexpected token `||` after pattern");
3521 err.span_suggestion(
3523 "use a single `|` to specify multiple patterns",
3525 Applicability::MachineApplicable
3529 } else if self.eat(&token::BinOp(token::Or)) {
3530 // This is a No-op. Continue the loop to parse the next
3538 // Parses a parenthesized list of patterns like
3539 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3540 // - a vector of the patterns that were parsed
3541 // - an option indicating the index of the `..` element
3542 // - a boolean indicating whether a trailing comma was present.
3543 // Trailing commas are significant because (p) and (p,) are different patterns.
3544 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3545 self.expect(&token::OpenDelim(token::Paren))?;
3546 let result = match self.parse_pat_list() {
3547 Ok(result) => result,
3548 Err(mut err) => { // recover from parse error in tuple pattern list
3550 self.consume_block(token::Paren);
3551 return Ok((vec![], Some(0), false));
3554 self.expect(&token::CloseDelim(token::Paren))?;
3558 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3559 let mut fields = Vec::new();
3560 let mut ddpos = None;
3561 let mut prev_dd_sp = None;
3562 let mut trailing_comma = false;
3564 if self.eat(&token::DotDot) {
3565 if ddpos.is_none() {
3566 ddpos = Some(fields.len());
3567 prev_dd_sp = Some(self.prev_span);
3569 // Emit a friendly error, ignore `..` and continue parsing
3570 let mut err = self.struct_span_err(
3572 "`..` can only be used once per tuple or tuple struct pattern",
3574 err.span_label(self.prev_span, "can only be used once per pattern");
3575 if let Some(sp) = prev_dd_sp {
3576 err.span_label(sp, "previously present here");
3580 } else if !self.check(&token::CloseDelim(token::Paren)) {
3581 fields.push(self.parse_pat(None)?);
3586 trailing_comma = self.eat(&token::Comma);
3587 if !trailing_comma {
3592 if ddpos == Some(fields.len()) && trailing_comma {
3593 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3594 let msg = "trailing comma is not permitted after `..`";
3595 self.struct_span_err(self.prev_span, msg)
3596 .span_label(self.prev_span, msg)
3600 Ok((fields, ddpos, trailing_comma))
3603 fn parse_pat_vec_elements(
3605 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3606 let mut before = Vec::new();
3607 let mut slice = None;
3608 let mut after = Vec::new();
3609 let mut first = true;
3610 let mut before_slice = true;
3612 while self.token != token::CloseDelim(token::Bracket) {
3616 self.expect(&token::Comma)?;
3618 if self.token == token::CloseDelim(token::Bracket)
3619 && (before_slice || !after.is_empty()) {
3625 if self.eat(&token::DotDot) {
3627 if self.check(&token::Comma) ||
3628 self.check(&token::CloseDelim(token::Bracket)) {
3629 slice = Some(P(Pat {
3630 id: ast::DUMMY_NODE_ID,
3631 node: PatKind::Wild,
3632 span: self.prev_span,
3634 before_slice = false;
3640 let subpat = self.parse_pat(None)?;
3641 if before_slice && self.eat(&token::DotDot) {
3642 slice = Some(subpat);
3643 before_slice = false;
3644 } else if before_slice {
3645 before.push(subpat);
3651 Ok((before, slice, after))
3657 attrs: Vec<Attribute>
3658 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3659 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3661 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3662 // Parsing a pattern of the form "fieldname: pat"
3663 let fieldname = self.parse_field_name()?;
3665 let pat = self.parse_pat(None)?;
3667 (pat, fieldname, false)
3669 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3670 let is_box = self.eat_keyword(kw::Box);
3671 let boxed_span = self.span;
3672 let is_ref = self.eat_keyword(kw::Ref);
3673 let is_mut = self.eat_keyword(kw::Mut);
3674 let fieldname = self.parse_ident()?;
3675 hi = self.prev_span;
3677 let bind_type = match (is_ref, is_mut) {
3678 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3679 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3680 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3681 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3683 let fieldpat = P(Pat {
3684 id: ast::DUMMY_NODE_ID,
3685 node: PatKind::Ident(bind_type, fieldname, None),
3686 span: boxed_span.to(hi),
3689 let subpat = if is_box {
3691 id: ast::DUMMY_NODE_ID,
3692 node: PatKind::Box(fieldpat),
3698 (subpat, fieldname, true)
3701 Ok(source_map::Spanned {
3703 node: ast::FieldPat {
3707 attrs: attrs.into(),
3712 /// Parses the fields of a struct-like pattern.
3713 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3714 let mut fields = Vec::new();
3715 let mut etc = false;
3716 let mut ate_comma = true;
3717 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3718 let mut etc_span = None;
3720 while self.token != token::CloseDelim(token::Brace) {
3721 let attrs = self.parse_outer_attributes()?;
3724 // check that a comma comes after every field
3726 let err = self.struct_span_err(self.prev_span, "expected `,`");
3727 if let Some(mut delayed) = delayed_err {
3734 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3736 let mut etc_sp = self.span;
3738 if self.token == token::DotDotDot { // Issue #46718
3739 // Accept `...` as if it were `..` to avoid further errors
3740 let mut err = self.struct_span_err(self.span,
3741 "expected field pattern, found `...`");
3742 err.span_suggestion(
3744 "to omit remaining fields, use one fewer `.`",
3746 Applicability::MachineApplicable
3750 self.bump(); // `..` || `...`
3752 if self.token == token::CloseDelim(token::Brace) {
3753 etc_span = Some(etc_sp);
3756 let token_str = self.this_token_descr();
3757 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3759 err.span_label(self.span, "expected `}`");
3760 let mut comma_sp = None;
3761 if self.token == token::Comma { // Issue #49257
3762 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3763 err.span_label(etc_sp,
3764 "`..` must be at the end and cannot have a trailing comma");
3765 comma_sp = Some(self.span);
3770 etc_span = Some(etc_sp.until(self.span));
3771 if self.token == token::CloseDelim(token::Brace) {
3772 // If the struct looks otherwise well formed, recover and continue.
3773 if let Some(sp) = comma_sp {
3774 err.span_suggestion_short(
3776 "remove this comma",
3778 Applicability::MachineApplicable,
3783 } else if self.token.is_ident() && ate_comma {
3784 // Accept fields coming after `..,`.
3785 // This way we avoid "pattern missing fields" errors afterwards.
3786 // We delay this error until the end in order to have a span for a
3788 if let Some(mut delayed_err) = delayed_err {
3792 delayed_err = Some(err);
3795 if let Some(mut err) = delayed_err {
3802 fields.push(match self.parse_pat_field(lo, attrs) {
3805 if let Some(mut delayed_err) = delayed_err {
3811 ate_comma = self.eat(&token::Comma);
3814 if let Some(mut err) = delayed_err {
3815 if let Some(etc_span) = etc_span {
3816 err.multipart_suggestion(
3817 "move the `..` to the end of the field list",
3819 (etc_span, String::new()),
3820 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3822 Applicability::MachineApplicable,
3827 return Ok((fields, etc));
3830 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3831 if self.token.is_path_start() {
3833 let (qself, path) = if self.eat_lt() {
3834 // Parse a qualified path
3835 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3838 // Parse an unqualified path
3839 (None, self.parse_path(PathStyle::Expr)?)
3841 let hi = self.prev_span;
3842 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3844 self.parse_literal_maybe_minus()
3848 // helper function to decide whether to parse as ident binding or to try to do
3849 // something more complex like range patterns
3850 fn parse_as_ident(&mut self) -> bool {
3851 self.look_ahead(1, |t| match t.kind {
3852 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3853 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3854 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3855 // range pattern branch
3856 token::DotDot => None,
3858 }).unwrap_or_else(|| self.look_ahead(2, |t| match t.kind {
3859 token::Comma | token::CloseDelim(token::Bracket) => true,
3864 /// A wrapper around `parse_pat` with some special error handling for the
3865 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3866 /// to subpatterns within such).
3867 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3868 let pat = self.parse_pat(None)?;
3869 if self.token == token::Comma {
3870 // An unexpected comma after a top-level pattern is a clue that the
3871 // user (perhaps more accustomed to some other language) forgot the
3872 // parentheses in what should have been a tuple pattern; return a
3873 // suggestion-enhanced error here rather than choking on the comma
3875 let comma_span = self.span;
3877 if let Err(mut err) = self.parse_pat_list() {
3878 // We didn't expect this to work anyway; we just wanted
3879 // to advance to the end of the comma-sequence so we know
3880 // the span to suggest parenthesizing
3883 let seq_span = pat.span.to(self.prev_span);
3884 let mut err = self.struct_span_err(comma_span,
3885 "unexpected `,` in pattern");
3886 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3887 err.span_suggestion(
3889 "try adding parentheses to match on a tuple..",
3890 format!("({})", seq_snippet),
3891 Applicability::MachineApplicable
3894 "..or a vertical bar to match on multiple alternatives",
3895 format!("{}", seq_snippet.replace(",", " |")),
3896 Applicability::MachineApplicable
3904 /// Parses a pattern.
3905 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
3906 self.parse_pat_with_range_pat(true, expected)
3909 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
3911 fn parse_pat_with_range_pat(
3913 allow_range_pat: bool,
3914 expected: Option<&'static str>,
3915 ) -> PResult<'a, P<Pat>> {
3916 maybe_recover_from_interpolated_ty_qpath!(self, true);
3917 maybe_whole!(self, NtPat, |x| x);
3921 match self.token.kind {
3922 token::BinOp(token::And) | token::AndAnd => {
3923 // Parse &pat / &mut pat
3925 let mutbl = self.parse_mutability();
3926 if let token::Lifetime(name) = self.token.kind {
3927 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
3928 err.span_label(self.span, "unexpected lifetime");
3931 let subpat = self.parse_pat_with_range_pat(false, expected)?;
3932 pat = PatKind::Ref(subpat, mutbl);
3934 token::OpenDelim(token::Paren) => {
3935 // Parse (pat,pat,pat,...) as tuple pattern
3936 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3937 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3938 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3940 PatKind::Tuple(fields, ddpos)
3943 token::OpenDelim(token::Bracket) => {
3944 // Parse [pat,pat,...] as slice pattern
3946 let (before, slice, after) = self.parse_pat_vec_elements()?;
3947 self.expect(&token::CloseDelim(token::Bracket))?;
3948 pat = PatKind::Slice(before, slice, after);
3950 // At this point, token != &, &&, (, [
3951 _ => if self.eat_keyword(kw::Underscore) {
3953 pat = PatKind::Wild;
3954 } else if self.eat_keyword(kw::Mut) {
3955 // Parse mut ident @ pat / mut ref ident @ pat
3956 let mutref_span = self.prev_span.to(self.span);
3957 let binding_mode = if self.eat_keyword(kw::Ref) {
3959 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3962 "try switching the order",
3964 Applicability::MachineApplicable
3966 BindingMode::ByRef(Mutability::Mutable)
3968 BindingMode::ByValue(Mutability::Mutable)
3970 pat = self.parse_pat_ident(binding_mode)?;
3971 } else if self.eat_keyword(kw::Ref) {
3972 // Parse ref ident @ pat / ref mut ident @ pat
3973 let mutbl = self.parse_mutability();
3974 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3975 } else if self.eat_keyword(kw::Box) {
3977 let subpat = self.parse_pat_with_range_pat(false, None)?;
3978 pat = PatKind::Box(subpat);
3979 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3980 self.parse_as_ident() {
3981 // Parse ident @ pat
3982 // This can give false positives and parse nullary enums,
3983 // they are dealt with later in resolve
3984 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3985 pat = self.parse_pat_ident(binding_mode)?;
3986 } else if self.token.is_path_start() {
3987 // Parse pattern starting with a path
3988 let (qself, path) = if self.eat_lt() {
3989 // Parse a qualified path
3990 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3993 // Parse an unqualified path
3994 (None, self.parse_path(PathStyle::Expr)?)
3996 match self.token.kind {
3997 token::Not if qself.is_none() => {
3998 // Parse macro invocation
4000 let (delim, tts) = self.expect_delimited_token_tree()?;
4001 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4002 pat = PatKind::Mac(mac);
4004 token::DotDotDot | token::DotDotEq | token::DotDot => {
4005 let end_kind = match self.token.kind {
4006 token::DotDot => RangeEnd::Excluded,
4007 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4008 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4009 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4012 let op_span = self.span;
4014 let span = lo.to(self.prev_span);
4015 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4017 let end = self.parse_pat_range_end()?;
4018 let op = Spanned { span: op_span, node: end_kind };
4019 pat = PatKind::Range(begin, end, op);
4021 token::OpenDelim(token::Brace) => {
4022 if qself.is_some() {
4023 let msg = "unexpected `{` after qualified path";
4024 let mut err = self.fatal(msg);
4025 err.span_label(self.span, msg);
4028 // Parse struct pattern
4030 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4032 self.recover_stmt();
4036 pat = PatKind::Struct(path, fields, etc);
4038 token::OpenDelim(token::Paren) => {
4039 if qself.is_some() {
4040 let msg = "unexpected `(` after qualified path";
4041 let mut err = self.fatal(msg);
4042 err.span_label(self.span, msg);
4045 // Parse tuple struct or enum pattern
4046 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4047 pat = PatKind::TupleStruct(path, fields, ddpos)
4049 _ => pat = PatKind::Path(qself, path),
4052 // Try to parse everything else as literal with optional minus
4053 match self.parse_literal_maybe_minus() {
4055 let op_span = self.span;
4056 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4057 self.check(&token::DotDotDot) {
4058 let end_kind = if self.eat(&token::DotDotDot) {
4059 RangeEnd::Included(RangeSyntax::DotDotDot)
4060 } else if self.eat(&token::DotDotEq) {
4061 RangeEnd::Included(RangeSyntax::DotDotEq)
4062 } else if self.eat(&token::DotDot) {
4065 panic!("impossible case: we already matched \
4066 on a range-operator token")
4068 let end = self.parse_pat_range_end()?;
4069 let op = Spanned { span: op_span, node: end_kind };
4070 pat = PatKind::Range(begin, end, op);
4072 pat = PatKind::Lit(begin);
4076 self.cancel(&mut err);
4077 let expected = expected.unwrap_or("pattern");
4079 "expected {}, found {}",
4081 self.this_token_descr(),
4083 let mut err = self.fatal(&msg);
4084 err.span_label(self.span, format!("expected {}", expected));
4085 let sp = self.sess.source_map().start_point(self.span);
4086 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4087 self.sess.expr_parentheses_needed(&mut err, *sp, None);
4095 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4096 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4098 if !allow_range_pat {
4101 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4103 PatKind::Range(..) => {
4104 let mut err = self.struct_span_err(
4106 "the range pattern here has ambiguous interpretation",
4108 err.span_suggestion(
4110 "add parentheses to clarify the precedence",
4111 format!("({})", pprust::pat_to_string(&pat)),
4112 // "ambiguous interpretation" implies that we have to be guessing
4113 Applicability::MaybeIncorrect
4124 /// Parses `ident` or `ident @ pat`.
4125 /// used by the copy foo and ref foo patterns to give a good
4126 /// error message when parsing mistakes like `ref foo(a, b)`.
4127 fn parse_pat_ident(&mut self,
4128 binding_mode: ast::BindingMode)
4129 -> PResult<'a, PatKind> {
4130 let ident = self.parse_ident()?;
4131 let sub = if self.eat(&token::At) {
4132 Some(self.parse_pat(Some("binding pattern"))?)
4137 // just to be friendly, if they write something like
4139 // we end up here with ( as the current token. This shortly
4140 // leads to a parse error. Note that if there is no explicit
4141 // binding mode then we do not end up here, because the lookahead
4142 // will direct us over to parse_enum_variant()
4143 if self.token == token::OpenDelim(token::Paren) {
4144 return Err(self.span_fatal(
4146 "expected identifier, found enum pattern"))
4149 Ok(PatKind::Ident(binding_mode, ident, sub))
4152 /// Parses a local variable declaration.
4153 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4154 let lo = self.prev_span;
4155 let pat = self.parse_top_level_pat()?;
4157 let (err, ty) = if self.eat(&token::Colon) {
4158 // Save the state of the parser before parsing type normally, in case there is a `:`
4159 // instead of an `=` typo.
4160 let parser_snapshot_before_type = self.clone();
4161 let colon_sp = self.prev_span;
4162 match self.parse_ty() {
4163 Ok(ty) => (None, Some(ty)),
4165 // Rewind to before attempting to parse the type and continue parsing
4166 let parser_snapshot_after_type = self.clone();
4167 mem::replace(self, parser_snapshot_before_type);
4169 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4170 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4171 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4177 let init = match (self.parse_initializer(err.is_some()), err) {
4178 (Ok(init), None) => { // init parsed, ty parsed
4181 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4182 // Could parse the type as if it were the initializer, it is likely there was a
4183 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4184 err.span_suggestion_short(
4186 "use `=` if you meant to assign",
4188 Applicability::MachineApplicable
4191 // As this was parsed successfully, continue as if the code has been fixed for the
4192 // rest of the file. It will still fail due to the emitted error, but we avoid
4196 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4198 // Couldn't parse the type nor the initializer, only raise the type error and
4199 // return to the parser state before parsing the type as the initializer.
4200 // let x: <parse_error>;
4201 mem::replace(self, snapshot);
4204 (Err(err), None) => { // init error, ty parsed
4205 // Couldn't parse the initializer and we're not attempting to recover a failed
4206 // parse of the type, return the error.
4210 let hi = if self.token == token::Semi {
4219 id: ast::DUMMY_NODE_ID,
4225 /// Parses a structure field.
4226 fn parse_name_and_ty(&mut self,
4229 attrs: Vec<Attribute>)
4230 -> PResult<'a, StructField> {
4231 let name = self.parse_ident()?;
4232 self.expect(&token::Colon)?;
4233 let ty = self.parse_ty()?;
4235 span: lo.to(self.prev_span),
4238 id: ast::DUMMY_NODE_ID,
4244 /// Emits an expected-item-after-attributes error.
4245 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4246 let message = match attrs.last() {
4247 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4248 _ => "expected item after attributes",
4251 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4252 if attrs.last().unwrap().is_sugared_doc {
4253 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4258 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4259 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4260 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4261 Ok(self.parse_stmt_(true))
4264 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4265 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4267 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4272 fn is_async_block(&self) -> bool {
4273 self.token.is_keyword(kw::Async) &&
4276 self.is_keyword_ahead(1, &[kw::Move]) &&
4277 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4279 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4284 fn is_async_fn(&self) -> bool {
4285 self.token.is_keyword(kw::Async) &&
4286 self.is_keyword_ahead(1, &[kw::Fn])
4289 fn is_do_catch_block(&self) -> bool {
4290 self.token.is_keyword(kw::Do) &&
4291 self.is_keyword_ahead(1, &[kw::Catch]) &&
4292 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4293 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4296 fn is_try_block(&self) -> bool {
4297 self.token.is_keyword(kw::Try) &&
4298 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4299 self.span.rust_2018() &&
4300 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4301 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4304 fn is_union_item(&self) -> bool {
4305 self.token.is_keyword(kw::Union) &&
4306 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4309 fn is_crate_vis(&self) -> bool {
4310 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4313 fn is_existential_type_decl(&self) -> bool {
4314 self.token.is_keyword(kw::Existential) &&
4315 self.is_keyword_ahead(1, &[kw::Type])
4318 fn is_auto_trait_item(&self) -> bool {
4320 (self.token.is_keyword(kw::Auto) &&
4321 self.is_keyword_ahead(1, &[kw::Trait]))
4322 || // unsafe auto trait
4323 (self.token.is_keyword(kw::Unsafe) &&
4324 self.is_keyword_ahead(1, &[kw::Auto]) &&
4325 self.is_keyword_ahead(2, &[kw::Trait]))
4328 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4329 -> PResult<'a, Option<P<Item>>> {
4330 let token_lo = self.span;
4331 let (ident, def) = match self.token.kind {
4332 token::Ident(name, false) if name == kw::Macro => {
4334 let ident = self.parse_ident()?;
4335 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4336 match self.parse_token_tree() {
4337 TokenTree::Delimited(_, _, tts) => tts,
4338 _ => unreachable!(),
4340 } else if self.check(&token::OpenDelim(token::Paren)) {
4341 let args = self.parse_token_tree();
4342 let body = if self.check(&token::OpenDelim(token::Brace)) {
4343 self.parse_token_tree()
4348 TokenStream::new(vec![
4350 TokenTree::token(token::FatArrow, token_lo.to(self.prev_span)).into(),
4358 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4360 token::Ident(name, _) if name == sym::macro_rules &&
4361 self.look_ahead(1, |t| *t == token::Not) => {
4362 let prev_span = self.prev_span;
4363 self.complain_if_pub_macro(&vis.node, prev_span);
4367 let ident = self.parse_ident()?;
4368 let (delim, tokens) = self.expect_delimited_token_tree()?;
4369 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
4370 self.report_invalid_macro_expansion_item();
4373 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4375 _ => return Ok(None),
4378 let span = lo.to(self.prev_span);
4379 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4382 fn parse_stmt_without_recovery(&mut self,
4383 macro_legacy_warnings: bool)
4384 -> PResult<'a, Option<Stmt>> {
4385 maybe_whole!(self, NtStmt, |x| Some(x));
4387 let attrs = self.parse_outer_attributes()?;
4390 Ok(Some(if self.eat_keyword(kw::Let) {
4392 id: ast::DUMMY_NODE_ID,
4393 node: StmtKind::Local(self.parse_local(attrs.into())?),
4394 span: lo.to(self.prev_span),
4396 } else if let Some(macro_def) = self.eat_macro_def(
4398 &source_map::respan(lo, VisibilityKind::Inherited),
4402 id: ast::DUMMY_NODE_ID,
4403 node: StmtKind::Item(macro_def),
4404 span: lo.to(self.prev_span),
4406 // Starts like a simple path, being careful to avoid contextual keywords
4407 // such as a union items, item with `crate` visibility or auto trait items.
4408 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4409 // like a path (1 token), but it fact not a path.
4410 // `union::b::c` - path, `union U { ... }` - not a path.
4411 // `crate::b::c` - path, `crate struct S;` - not a path.
4412 } else if self.token.is_path_start() &&
4413 !self.token.is_qpath_start() &&
4414 !self.is_union_item() &&
4415 !self.is_crate_vis() &&
4416 !self.is_existential_type_decl() &&
4417 !self.is_auto_trait_item() &&
4418 !self.is_async_fn() {
4419 let pth = self.parse_path(PathStyle::Expr)?;
4421 if !self.eat(&token::Not) {
4422 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4423 self.parse_struct_expr(lo, pth, ThinVec::new())?
4425 let hi = self.prev_span;
4426 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4429 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4430 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4431 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4434 return Ok(Some(Stmt {
4435 id: ast::DUMMY_NODE_ID,
4436 node: StmtKind::Expr(expr),
4437 span: lo.to(self.prev_span),
4441 // it's a macro invocation
4442 let id = match self.token.kind {
4443 token::OpenDelim(_) => Ident::invalid(), // no special identifier
4444 _ => self.parse_ident()?,
4447 // check that we're pointing at delimiters (need to check
4448 // again after the `if`, because of `parse_ident`
4449 // consuming more tokens).
4450 match self.token.kind {
4451 token::OpenDelim(_) => {}
4453 // we only expect an ident if we didn't parse one
4455 let ident_str = if id.name == kw::Invalid {
4460 let tok_str = self.this_token_descr();
4461 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4464 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4469 let (delim, tts) = self.expect_delimited_token_tree()?;
4470 let hi = self.prev_span;
4472 let style = if delim == MacDelimiter::Brace {
4473 MacStmtStyle::Braces
4475 MacStmtStyle::NoBraces
4478 if id.name == kw::Invalid {
4479 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4480 let node = if delim == MacDelimiter::Brace ||
4481 self.token == token::Semi || self.token == token::Eof {
4482 StmtKind::Mac(P((mac, style, attrs.into())))
4484 // We used to incorrectly stop parsing macro-expanded statements here.
4485 // If the next token will be an error anyway but could have parsed with the
4486 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4487 else if macro_legacy_warnings &&
4488 self.token.can_begin_expr() &&
4489 match self.token.kind {
4490 // These can continue an expression, so we can't stop parsing and warn.
4491 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4492 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4493 token::BinOp(token::And) | token::BinOp(token::Or) |
4494 token::AndAnd | token::OrOr |
4495 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4498 self.warn_missing_semicolon();
4499 StmtKind::Mac(P((mac, style, attrs.into())))
4501 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
4502 let e = self.maybe_recover_from_bad_qpath(e, true)?;
4503 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4504 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4508 id: ast::DUMMY_NODE_ID,
4513 // if it has a special ident, it's definitely an item
4515 // Require a semicolon or braces.
4516 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
4517 self.report_invalid_macro_expansion_item();
4519 let span = lo.to(hi);
4521 id: ast::DUMMY_NODE_ID,
4523 node: StmtKind::Item({
4525 span, id /*id is good here*/,
4526 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4527 respan(lo, VisibilityKind::Inherited),
4533 // FIXME: Bad copy of attrs
4534 let old_directory_ownership =
4535 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4536 let item = self.parse_item_(attrs.clone(), false, true)?;
4537 self.directory.ownership = old_directory_ownership;
4541 id: ast::DUMMY_NODE_ID,
4542 span: lo.to(i.span),
4543 node: StmtKind::Item(i),
4546 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4547 if !attrs.is_empty() {
4548 if s.prev_token_kind == PrevTokenKind::DocComment {
4549 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4550 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4551 s.span_err(s.span, "expected statement after outer attribute");
4556 // Do not attempt to parse an expression if we're done here.
4557 if self.token == token::Semi {
4558 unused_attrs(&attrs, self);
4563 if self.token == token::CloseDelim(token::Brace) {
4564 unused_attrs(&attrs, self);
4568 // Remainder are line-expr stmts.
4569 let e = self.parse_expr_res(
4570 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4572 id: ast::DUMMY_NODE_ID,
4573 span: lo.to(e.span),
4574 node: StmtKind::Expr(e),
4581 /// Checks if this expression is a successfully parsed statement.
4582 fn expr_is_complete(&self, e: &Expr) -> bool {
4583 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4584 !classify::expr_requires_semi_to_be_stmt(e)
4587 /// Parses a block. No inner attributes are allowed.
4588 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4589 maybe_whole!(self, NtBlock, |x| x);
4593 if !self.eat(&token::OpenDelim(token::Brace)) {
4595 let tok = self.this_token_descr();
4596 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4597 let do_not_suggest_help =
4598 self.token.is_keyword(kw::In) || self.token == token::Colon;
4600 if self.token.is_ident_named(sym::and) {
4601 e.span_suggestion_short(
4603 "use `&&` instead of `and` for the boolean operator",
4605 Applicability::MaybeIncorrect,
4608 if self.token.is_ident_named(sym::or) {
4609 e.span_suggestion_short(
4611 "use `||` instead of `or` for the boolean operator",
4613 Applicability::MaybeIncorrect,
4617 // Check to see if the user has written something like
4622 // Which is valid in other languages, but not Rust.
4623 match self.parse_stmt_without_recovery(false) {
4625 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4626 || do_not_suggest_help {
4627 // if the next token is an open brace (e.g., `if a b {`), the place-
4628 // inside-a-block suggestion would be more likely wrong than right
4629 e.span_label(sp, "expected `{`");
4632 let mut stmt_span = stmt.span;
4633 // expand the span to include the semicolon, if it exists
4634 if self.eat(&token::Semi) {
4635 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4637 let sugg = pprust::to_string(|s| {
4638 use crate::print::pprust::{PrintState, INDENT_UNIT};
4639 s.ibox(INDENT_UNIT)?;
4641 s.print_stmt(&stmt)?;
4642 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4646 "try placing this code inside a block",
4648 // speculative, has been misleading in the past (closed Issue #46836)
4649 Applicability::MaybeIncorrect
4653 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4654 self.cancel(&mut e);
4658 e.span_label(sp, "expected `{`");
4662 self.parse_block_tail(lo, BlockCheckMode::Default)
4665 /// Parses a block. Inner attributes are allowed.
4666 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4667 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4670 self.expect(&token::OpenDelim(token::Brace))?;
4671 Ok((self.parse_inner_attributes()?,
4672 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4675 /// Parses the rest of a block expression or function body.
4676 /// Precondition: already parsed the '{'.
4677 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4678 let mut stmts = vec![];
4679 while !self.eat(&token::CloseDelim(token::Brace)) {
4680 let stmt = match self.parse_full_stmt(false) {
4683 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4685 id: ast::DUMMY_NODE_ID,
4686 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
4692 if let Some(stmt) = stmt {
4694 } else if self.token == token::Eof {
4697 // Found only `;` or `}`.
4703 id: ast::DUMMY_NODE_ID,
4705 span: lo.to(self.prev_span),
4709 /// Parses a statement, including the trailing semicolon.
4710 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4711 // skip looking for a trailing semicolon when we have an interpolated statement
4712 maybe_whole!(self, NtStmt, |x| Some(x));
4714 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4716 None => return Ok(None),
4720 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4721 // expression without semicolon
4722 if classify::expr_requires_semi_to_be_stmt(expr) {
4723 // Just check for errors and recover; do not eat semicolon yet.
4725 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4728 self.recover_stmt();
4732 StmtKind::Local(..) => {
4733 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4734 if macro_legacy_warnings && self.token != token::Semi {
4735 self.warn_missing_semicolon();
4737 self.expect_one_of(&[], &[token::Semi])?;
4743 if self.eat(&token::Semi) {
4744 stmt = stmt.add_trailing_semicolon();
4747 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4751 fn warn_missing_semicolon(&self) {
4752 self.diagnostic().struct_span_warn(self.span, {
4753 &format!("expected `;`, found {}", self.this_token_descr())
4755 "This was erroneously allowed and will become a hard error in a future release"
4759 fn err_dotdotdot_syntax(&self, span: Span) {
4760 self.diagnostic().struct_span_err(span, {
4761 "unexpected token: `...`"
4763 span, "use `..` for an exclusive range", "..".to_owned(),
4764 Applicability::MaybeIncorrect
4766 span, "or `..=` for an inclusive range", "..=".to_owned(),
4767 Applicability::MaybeIncorrect
4771 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
4774 /// BOUND = TY_BOUND | LT_BOUND
4775 /// LT_BOUND = LIFETIME (e.g., `'a`)
4776 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4777 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
4779 fn parse_generic_bounds_common(&mut self,
4781 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4782 let mut bounds = Vec::new();
4783 let mut negative_bounds = Vec::new();
4784 let mut last_plus_span = None;
4785 let mut was_negative = false;
4787 // This needs to be synchronized with `TokenKind::can_begin_bound`.
4788 let is_bound_start = self.check_path() || self.check_lifetime() ||
4789 self.check(&token::Not) || // used for error reporting only
4790 self.check(&token::Question) ||
4791 self.check_keyword(kw::For) ||
4792 self.check(&token::OpenDelim(token::Paren));
4795 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4796 let inner_lo = self.span;
4797 let is_negative = self.eat(&token::Not);
4798 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4799 if self.token.is_lifetime() {
4800 if let Some(question_span) = question {
4801 self.span_err(question_span,
4802 "`?` may only modify trait bounds, not lifetime bounds");
4804 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4806 let inner_span = inner_lo.to(self.prev_span);
4807 self.expect(&token::CloseDelim(token::Paren))?;
4808 let mut err = self.struct_span_err(
4809 lo.to(self.prev_span),
4810 "parenthesized lifetime bounds are not supported"
4812 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
4813 err.span_suggestion_short(
4814 lo.to(self.prev_span),
4815 "remove the parentheses",
4817 Applicability::MachineApplicable
4823 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4824 let path = self.parse_path(PathStyle::Type)?;
4826 self.expect(&token::CloseDelim(token::Paren))?;
4828 let poly_span = lo.to(self.prev_span);
4830 was_negative = true;
4831 if let Some(sp) = last_plus_span.or(colon_span) {
4832 negative_bounds.push(sp.to(poly_span));
4835 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
4836 let modifier = if question.is_some() {
4837 TraitBoundModifier::Maybe
4839 TraitBoundModifier::None
4841 bounds.push(GenericBound::Trait(poly_trait, modifier));
4848 if !allow_plus || !self.eat_plus() {
4851 last_plus_span = Some(self.prev_span);
4855 if !negative_bounds.is_empty() || was_negative {
4856 let plural = negative_bounds.len() > 1;
4857 let last_span = negative_bounds.last().map(|sp| *sp);
4858 let mut err = self.struct_span_err(
4860 "negative trait bounds are not supported",
4862 if let Some(sp) = last_span {
4863 err.span_label(sp, "negative trait bounds are not supported");
4865 if let Some(bound_list) = colon_span {
4866 let bound_list = bound_list.to(self.prev_span);
4867 let mut new_bound_list = String::new();
4868 if !bounds.is_empty() {
4869 let mut snippets = bounds.iter().map(|bound| bound.span())
4870 .map(|span| self.sess.source_map().span_to_snippet(span));
4871 while let Some(Ok(snippet)) = snippets.next() {
4872 new_bound_list.push_str(" + ");
4873 new_bound_list.push_str(&snippet);
4875 new_bound_list = new_bound_list.replacen(" +", ":", 1);
4877 err.span_suggestion_hidden(
4879 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
4881 Applicability::MachineApplicable,
4890 crate fn parse_generic_bounds(&mut self,
4891 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4892 self.parse_generic_bounds_common(true, colon_span)
4895 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4898 /// BOUND = LT_BOUND (e.g., `'a`)
4900 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4901 let mut lifetimes = Vec::new();
4902 while self.check_lifetime() {
4903 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4905 if !self.eat_plus() {
4912 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
4913 fn parse_ty_param(&mut self,
4914 preceding_attrs: Vec<Attribute>)
4915 -> PResult<'a, GenericParam> {
4916 let ident = self.parse_ident()?;
4918 // Parse optional colon and param bounds.
4919 let bounds = if self.eat(&token::Colon) {
4920 self.parse_generic_bounds(Some(self.prev_span))?
4925 let default = if self.eat(&token::Eq) {
4926 Some(self.parse_ty()?)
4933 id: ast::DUMMY_NODE_ID,
4934 attrs: preceding_attrs.into(),
4936 kind: GenericParamKind::Type {
4942 /// Parses the following grammar:
4944 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4945 fn parse_trait_item_assoc_ty(&mut self)
4946 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4947 let ident = self.parse_ident()?;
4948 let mut generics = self.parse_generics()?;
4950 // Parse optional colon and param bounds.
4951 let bounds = if self.eat(&token::Colon) {
4952 self.parse_generic_bounds(None)?
4956 generics.where_clause = self.parse_where_clause()?;
4958 let default = if self.eat(&token::Eq) {
4959 Some(self.parse_ty()?)
4963 self.expect(&token::Semi)?;
4965 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4968 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
4969 self.expect_keyword(kw::Const)?;
4970 let ident = self.parse_ident()?;
4971 self.expect(&token::Colon)?;
4972 let ty = self.parse_ty()?;
4976 id: ast::DUMMY_NODE_ID,
4977 attrs: preceding_attrs.into(),
4979 kind: GenericParamKind::Const {
4985 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
4986 /// a trailing comma and erroneous trailing attributes.
4987 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4988 let mut params = Vec::new();
4990 let attrs = self.parse_outer_attributes()?;
4991 if self.check_lifetime() {
4992 let lifetime = self.expect_lifetime();
4993 // Parse lifetime parameter.
4994 let bounds = if self.eat(&token::Colon) {
4995 self.parse_lt_param_bounds()
4999 params.push(ast::GenericParam {
5000 ident: lifetime.ident,
5002 attrs: attrs.into(),
5004 kind: ast::GenericParamKind::Lifetime,
5006 } else if self.check_keyword(kw::Const) {
5007 // Parse const parameter.
5008 params.push(self.parse_const_param(attrs)?);
5009 } else if self.check_ident() {
5010 // Parse type parameter.
5011 params.push(self.parse_ty_param(attrs)?);
5013 // Check for trailing attributes and stop parsing.
5014 if !attrs.is_empty() {
5015 if !params.is_empty() {
5016 self.struct_span_err(
5018 &format!("trailing attribute after generic parameter"),
5020 .span_label(attrs[0].span, "attributes must go before parameters")
5023 self.struct_span_err(
5025 &format!("attribute without generic parameters"),
5029 "attributes are only permitted when preceding parameters",
5037 if !self.eat(&token::Comma) {
5044 /// Parses a set of optional generic type parameter declarations. Where
5045 /// clauses are not parsed here, and must be added later via
5046 /// `parse_where_clause()`.
5048 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5049 /// | ( < lifetimes , typaramseq ( , )? > )
5050 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5051 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5052 let span_lo = self.span;
5053 let (params, span) = if self.eat_lt() {
5054 let params = self.parse_generic_params()?;
5056 (params, span_lo.to(self.prev_span))
5058 (vec![], self.prev_span.between(self.span))
5062 where_clause: WhereClause {
5063 id: ast::DUMMY_NODE_ID,
5064 predicates: Vec::new(),
5071 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5072 /// For the purposes of understanding the parsing logic of generic arguments, this function
5073 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5074 /// had the correct amount of leading angle brackets.
5076 /// ```ignore (diagnostics)
5077 /// bar::<<<<T as Foo>::Output>();
5078 /// ^^ help: remove extra angle brackets
5080 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5084 ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5085 // We need to detect whether there are extra leading left angle brackets and produce an
5086 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5087 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5088 // then there won't be matching `>` tokens to find.
5090 // To explain how this detection works, consider the following example:
5092 // ```ignore (diagnostics)
5093 // bar::<<<<T as Foo>::Output>();
5094 // ^^ help: remove extra angle brackets
5097 // Parsing of the left angle brackets starts in this function. We start by parsing the
5098 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5101 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5102 // *Unmatched count:* 1
5103 // *`parse_path_segment` calls deep:* 0
5105 // This has the effect of recursing as this function is called if a `<` character
5106 // is found within the expected generic arguments:
5108 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5109 // *Unmatched count:* 2
5110 // *`parse_path_segment` calls deep:* 1
5112 // Eventually we will have recursed until having consumed all of the `<` tokens and
5113 // this will be reflected in the count:
5115 // *Upcoming tokens:* `T as Foo>::Output>;`
5116 // *Unmatched count:* 4
5117 // `parse_path_segment` calls deep:* 3
5119 // The parser will continue until reaching the first `>` - this will decrement the
5120 // unmatched angle bracket count and return to the parent invocation of this function
5121 // having succeeded in parsing:
5123 // *Upcoming tokens:* `::Output>;`
5124 // *Unmatched count:* 3
5125 // *`parse_path_segment` calls deep:* 2
5127 // This will continue until the next `>` character which will also return successfully
5128 // to the parent invocation of this function and decrement the count:
5130 // *Upcoming tokens:* `;`
5131 // *Unmatched count:* 2
5132 // *`parse_path_segment` calls deep:* 1
5134 // At this point, this function will expect to find another matching `>` character but
5135 // won't be able to and will return an error. This will continue all the way up the
5136 // call stack until the first invocation:
5138 // *Upcoming tokens:* `;`
5139 // *Unmatched count:* 2
5140 // *`parse_path_segment` calls deep:* 0
5142 // In doing this, we have managed to work out how many unmatched leading left angle
5143 // brackets there are, but we cannot recover as the unmatched angle brackets have
5144 // already been consumed. To remedy this, we keep a snapshot of the parser state
5145 // before we do the above. We can then inspect whether we ended up with a parsing error
5146 // and unmatched left angle brackets and if so, restore the parser state before we
5147 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5148 // recover by attempting to parse again.
5150 // In practice, the recursion of this function is indirect and there will be other
5151 // locations that consume some `<` characters - as long as we update the count when
5152 // this happens, it isn't an issue.
5154 let is_first_invocation = style == PathStyle::Expr;
5155 // Take a snapshot before attempting to parse - we can restore this later.
5156 let snapshot = if is_first_invocation {
5162 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5163 match self.parse_generic_args() {
5164 Ok(value) => Ok(value),
5165 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5166 // Cancel error from being unable to find `>`. We know the error
5167 // must have been this due to a non-zero unmatched angle bracket
5171 // Swap `self` with our backup of the parser state before attempting to parse
5172 // generic arguments.
5173 let snapshot = mem::replace(self, snapshot.unwrap());
5176 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5177 snapshot.count={:?}",
5178 snapshot.unmatched_angle_bracket_count,
5181 // Eat the unmatched angle brackets.
5182 for _ in 0..snapshot.unmatched_angle_bracket_count {
5186 // Make a span over ${unmatched angle bracket count} characters.
5187 let span = lo.with_hi(
5188 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5190 let plural = snapshot.unmatched_angle_bracket_count > 1;
5195 "unmatched angle bracket{}",
5196 if plural { "s" } else { "" }
5202 "remove extra angle bracket{}",
5203 if plural { "s" } else { "" }
5206 Applicability::MachineApplicable,
5210 // Try again without unmatched angle bracket characters.
5211 self.parse_generic_args()
5217 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5218 /// possibly including trailing comma.
5219 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
5220 let mut args = Vec::new();
5221 let mut constraints = Vec::new();
5222 let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new();
5223 let mut assoc_ty_constraints: Vec<Span> = Vec::new();
5225 let args_lo = self.span;
5228 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5229 // Parse lifetime argument.
5230 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5231 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5232 } else if self.check_ident() && self.look_ahead(1,
5233 |t| t == &token::Eq || t == &token::Colon) {
5234 // Parse associated type constraint.
5236 let ident = self.parse_ident()?;
5237 let kind = if self.eat(&token::Eq) {
5238 AssocTyConstraintKind::Equality {
5239 ty: self.parse_ty()?,
5241 } else if self.eat(&token::Colon) {
5242 AssocTyConstraintKind::Bound {
5243 bounds: self.parse_generic_bounds(Some(self.prev_span))?,
5248 let span = lo.to(self.prev_span);
5249 constraints.push(AssocTyConstraint {
5250 id: ast::DUMMY_NODE_ID,
5255 assoc_ty_constraints.push(span);
5256 } else if self.check_const_arg() {
5257 // Parse const argument.
5258 let expr = if let token::OpenDelim(token::Brace) = self.token.kind {
5259 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
5260 } else if self.token.is_ident() {
5261 // FIXME(const_generics): to distinguish between idents for types and consts,
5262 // we should introduce a GenericArg::Ident in the AST and distinguish when
5263 // lowering to the HIR. For now, idents for const args are not permitted.
5264 if self.token.is_keyword(kw::True) || self.token.is_keyword(kw::False) {
5265 self.parse_literal_maybe_minus()?
5268 self.fatal("identifiers may currently not be used for const generics")
5272 self.parse_literal_maybe_minus()?
5274 let value = AnonConst {
5275 id: ast::DUMMY_NODE_ID,
5278 args.push(GenericArg::Const(value));
5279 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5280 } else if self.check_type() {
5281 // Parse type argument.
5282 args.push(GenericArg::Type(self.parse_ty()?));
5283 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
5288 if !self.eat(&token::Comma) {
5293 // FIXME: we would like to report this in ast_validation instead, but we currently do not
5294 // preserve ordering of generic parameters with respect to associated type binding, so we
5295 // lose that information after parsing.
5296 if misplaced_assoc_ty_constraints.len() > 0 {
5297 let mut err = self.struct_span_err(
5298 args_lo.to(self.prev_span),
5299 "associated type bindings must be declared after generic parameters",
5301 for span in misplaced_assoc_ty_constraints {
5304 "this associated type binding should be moved after the generic parameters",
5310 Ok((args, constraints))
5313 /// Parses an optional where-clause and places it in `generics`.
5315 /// ```ignore (only-for-syntax-highlight)
5316 /// where T : Trait<U, V> + 'b, 'a : 'b
5318 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5319 let mut where_clause = WhereClause {
5320 id: ast::DUMMY_NODE_ID,
5321 predicates: Vec::new(),
5322 span: self.prev_span.to(self.prev_span),
5325 if !self.eat_keyword(kw::Where) {
5326 return Ok(where_clause);
5328 let lo = self.prev_span;
5330 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5331 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5332 // change we parse those generics now, but report an error.
5333 if self.choose_generics_over_qpath() {
5334 let generics = self.parse_generics()?;
5335 self.struct_span_err(
5337 "generic parameters on `where` clauses are reserved for future use",
5339 .span_label(generics.span, "currently unsupported")
5345 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5346 let lifetime = self.expect_lifetime();
5347 // Bounds starting with a colon are mandatory, but possibly empty.
5348 self.expect(&token::Colon)?;
5349 let bounds = self.parse_lt_param_bounds();
5350 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5351 ast::WhereRegionPredicate {
5352 span: lo.to(self.prev_span),
5357 } else if self.check_type() {
5358 // Parse optional `for<'a, 'b>`.
5359 // This `for` is parsed greedily and applies to the whole predicate,
5360 // the bounded type can have its own `for` applying only to it.
5362 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
5363 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
5364 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
5365 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5367 // Parse type with mandatory colon and (possibly empty) bounds,
5368 // or with mandatory equality sign and the second type.
5369 let ty = self.parse_ty()?;
5370 if self.eat(&token::Colon) {
5371 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
5372 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5373 ast::WhereBoundPredicate {
5374 span: lo.to(self.prev_span),
5375 bound_generic_params: lifetime_defs,
5380 // FIXME: Decide what should be used here, `=` or `==`.
5381 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5382 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5383 let rhs_ty = self.parse_ty()?;
5384 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5385 ast::WhereEqPredicate {
5386 span: lo.to(self.prev_span),
5389 id: ast::DUMMY_NODE_ID,
5393 return self.unexpected();
5399 if !self.eat(&token::Comma) {
5404 where_clause.span = lo.to(self.prev_span);
5408 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
5409 -> PResult<'a, (Vec<Arg> , bool)> {
5410 self.expect(&token::OpenDelim(token::Paren))?;
5413 let mut c_variadic = false;
5414 let (args, recovered): (Vec<Option<Arg>>, bool) =
5415 self.parse_seq_to_before_end(
5416 &token::CloseDelim(token::Paren),
5417 SeqSep::trailing_allowed(token::Comma),
5419 // If the argument is a C-variadic argument we should not
5420 // enforce named arguments.
5421 let enforce_named_args = if p.token == token::DotDotDot {
5426 match p.parse_arg_general(enforce_named_args, false,
5429 if let TyKind::CVarArgs = arg.ty.node {
5431 if p.token != token::CloseDelim(token::Paren) {
5434 "`...` must be the last argument of a C-variadic function");
5445 let lo = p.prev_span;
5446 // Skip every token until next possible arg or end.
5447 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5448 // Create a placeholder argument for proper arg count (issue #34264).
5449 let span = lo.to(p.prev_span);
5450 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
5457 self.eat(&token::CloseDelim(token::Paren));
5460 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5462 if c_variadic && args.is_empty() {
5464 "C-variadic function must be declared with at least one named argument");
5467 Ok((args, c_variadic))
5470 /// Parses the argument list and result type of a function declaration.
5471 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
5473 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
5474 let ret_ty = self.parse_ret_ty(true)?;
5483 /// Returns the parsed optional self argument and whether a self shortcut was used.
5484 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5485 let expect_ident = |this: &mut Self| match this.token.kind {
5486 // Preserve hygienic context.
5487 token::Ident(name, _) =>
5488 { let span = this.span; this.bump(); Ident::new(name, span) }
5491 let isolated_self = |this: &mut Self, n| {
5492 this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
5493 this.look_ahead(n + 1, |t| t != &token::ModSep)
5496 // Parse optional `self` parameter of a method.
5497 // Only a limited set of initial token sequences is considered `self` parameters; anything
5498 // else is parsed as a normal function parameter list, so some lookahead is required.
5499 let eself_lo = self.span;
5500 let (eself, eself_ident, eself_hi) = match self.token.kind {
5501 token::BinOp(token::And) => {
5507 (if isolated_self(self, 1) {
5509 SelfKind::Region(None, Mutability::Immutable)
5510 } else if self.is_keyword_ahead(1, &[kw::Mut]) &&
5511 isolated_self(self, 2) {
5514 SelfKind::Region(None, Mutability::Mutable)
5515 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5516 isolated_self(self, 2) {
5518 let lt = self.expect_lifetime();
5519 SelfKind::Region(Some(lt), Mutability::Immutable)
5520 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5521 self.is_keyword_ahead(2, &[kw::Mut]) &&
5522 isolated_self(self, 3) {
5524 let lt = self.expect_lifetime();
5526 SelfKind::Region(Some(lt), Mutability::Mutable)
5529 }, expect_ident(self), self.prev_span)
5531 token::BinOp(token::Star) => {
5536 // Emit special error for `self` cases.
5537 let msg = "cannot pass `self` by raw pointer";
5538 (if isolated_self(self, 1) {
5540 self.struct_span_err(self.span, msg)
5541 .span_label(self.span, msg)
5543 SelfKind::Value(Mutability::Immutable)
5544 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5545 isolated_self(self, 2) {
5548 self.struct_span_err(self.span, msg)
5549 .span_label(self.span, msg)
5551 SelfKind::Value(Mutability::Immutable)
5554 }, expect_ident(self), self.prev_span)
5556 token::Ident(..) => {
5557 if isolated_self(self, 0) {
5560 let eself_ident = expect_ident(self);
5561 let eself_hi = self.prev_span;
5562 (if self.eat(&token::Colon) {
5563 let ty = self.parse_ty()?;
5564 SelfKind::Explicit(ty, Mutability::Immutable)
5566 SelfKind::Value(Mutability::Immutable)
5567 }, eself_ident, eself_hi)
5568 } else if self.token.is_keyword(kw::Mut) &&
5569 isolated_self(self, 1) {
5573 let eself_ident = expect_ident(self);
5574 let eself_hi = self.prev_span;
5575 (if self.eat(&token::Colon) {
5576 let ty = self.parse_ty()?;
5577 SelfKind::Explicit(ty, Mutability::Mutable)
5579 SelfKind::Value(Mutability::Mutable)
5580 }, eself_ident, eself_hi)
5585 _ => return Ok(None),
5588 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5589 Ok(Some(Arg::from_self(eself, eself_ident)))
5592 /// Parses the parameter list and result type of a function that may have a `self` parameter.
5593 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5594 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5596 self.expect(&token::OpenDelim(token::Paren))?;
5598 // Parse optional self argument.
5599 let self_arg = self.parse_self_arg()?;
5601 // Parse the rest of the function parameter list.
5602 let sep = SeqSep::trailing_allowed(token::Comma);
5603 let (mut fn_inputs, recovered) = if let Some(self_arg) = self_arg {
5604 if self.check(&token::CloseDelim(token::Paren)) {
5605 (vec![self_arg], false)
5606 } else if self.eat(&token::Comma) {
5607 let mut fn_inputs = vec![self_arg];
5608 let (mut input, recovered) = self.parse_seq_to_before_end(
5609 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
5610 fn_inputs.append(&mut input);
5611 (fn_inputs, recovered)
5613 match self.expect_one_of(&[], &[]) {
5614 Err(err) => return Err(err),
5615 Ok(recovered) => (vec![self_arg], recovered),
5619 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5623 // Parse closing paren and return type.
5624 self.expect(&token::CloseDelim(token::Paren))?;
5626 // Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
5627 self.deduplicate_recovered_arg_names(&mut fn_inputs);
5631 output: self.parse_ret_ty(true)?,
5636 /// Parses the `|arg, arg|` header of a closure.
5637 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5638 let inputs_captures = {
5639 if self.eat(&token::OrOr) {
5642 self.expect(&token::BinOp(token::Or))?;
5643 let args = self.parse_seq_to_before_tokens(
5644 &[&token::BinOp(token::Or), &token::OrOr],
5645 SeqSep::trailing_allowed(token::Comma),
5646 TokenExpectType::NoExpect,
5647 |p| p.parse_fn_block_arg()
5653 let output = self.parse_ret_ty(true)?;
5656 inputs: inputs_captures,
5662 /// Parses the name and optional generic types of a function header.
5663 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5664 let id = self.parse_ident()?;
5665 let generics = self.parse_generics()?;
5669 fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5670 attrs: Vec<Attribute>) -> P<Item> {
5674 id: ast::DUMMY_NODE_ID,
5682 /// Parses an item-position function declaration.
5683 fn parse_item_fn(&mut self,
5685 asyncness: Spanned<IsAsync>,
5686 constness: Spanned<Constness>,
5688 -> PResult<'a, ItemInfo> {
5689 let (ident, mut generics) = self.parse_fn_header()?;
5690 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
5691 let decl = self.parse_fn_decl(allow_c_variadic)?;
5692 generics.where_clause = self.parse_where_clause()?;
5693 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5694 let header = FnHeader { unsafety, asyncness, constness, abi };
5695 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5698 /// Returns `true` if we are looking at `const ID`
5699 /// (returns `false` for things like `const fn`, etc.).
5700 fn is_const_item(&self) -> bool {
5701 self.token.is_keyword(kw::Const) &&
5702 !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
5705 /// Parses all the "front matter" for a `fn` declaration, up to
5706 /// and including the `fn` keyword:
5710 /// - `const unsafe fn`
5713 fn parse_fn_front_matter(&mut self)
5721 let is_const_fn = self.eat_keyword(kw::Const);
5722 let const_span = self.prev_span;
5723 let unsafety = self.parse_unsafety();
5724 let asyncness = self.parse_asyncness();
5725 let asyncness = respan(self.prev_span, asyncness);
5726 let (constness, unsafety, abi) = if is_const_fn {
5727 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5729 let abi = if self.eat_keyword(kw::Extern) {
5730 self.parse_opt_abi()?.unwrap_or(Abi::C)
5734 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5736 if !self.eat_keyword(kw::Fn) {
5737 // It is possible for `expect_one_of` to recover given the contents of
5738 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
5739 // account for this.
5740 if !self.expect_one_of(&[], &[])? { unreachable!() }
5742 Ok((constness, unsafety, asyncness, abi))
5745 /// Parses an impl item.
5746 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5747 maybe_whole!(self, NtImplItem, |x| x);
5748 let attrs = self.parse_outer_attributes()?;
5749 let mut unclosed_delims = vec![];
5750 let (mut item, tokens) = self.collect_tokens(|this| {
5751 let item = this.parse_impl_item_(at_end, attrs);
5752 unclosed_delims.append(&mut this.unclosed_delims);
5755 self.unclosed_delims.append(&mut unclosed_delims);
5757 // See `parse_item` for why this clause is here.
5758 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5759 item.tokens = Some(tokens);
5764 fn parse_impl_item_(&mut self,
5766 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5768 let vis = self.parse_visibility(false)?;
5769 let defaultness = self.parse_defaultness();
5770 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5771 let (name, alias, generics) = type_?;
5772 let kind = match alias {
5773 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5774 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5776 (name, kind, generics)
5777 } else if self.is_const_item() {
5778 // This parses the grammar:
5779 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5780 self.expect_keyword(kw::Const)?;
5781 let name = self.parse_ident()?;
5782 self.expect(&token::Colon)?;
5783 let typ = self.parse_ty()?;
5784 self.expect(&token::Eq)?;
5785 let expr = self.parse_expr()?;
5786 self.expect(&token::Semi)?;
5787 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5789 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5790 attrs.extend(inner_attrs);
5791 (name, node, generics)
5795 id: ast::DUMMY_NODE_ID,
5796 span: lo.to(self.prev_span),
5807 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
5809 VisibilityKind::Inherited => {}
5811 let mut err = if self.token.is_keyword(sym::macro_rules) {
5812 let mut err = self.diagnostic()
5813 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5814 err.span_suggestion(
5816 "try exporting the macro",
5817 "#[macro_export]".to_owned(),
5818 Applicability::MaybeIncorrect // speculative
5822 let mut err = self.diagnostic()
5823 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5824 err.help("try adjusting the macro to put `pub` inside the invocation");
5832 fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
5833 -> DiagnosticBuilder<'a>
5835 let expected_kinds = if item_type == "extern" {
5836 "missing `fn`, `type`, or `static`"
5838 "missing `fn`, `type`, or `const`"
5841 // Given this code `path(`, it seems like this is not
5842 // setting the visibility of a macro invocation, but rather
5843 // a mistyped method declaration.
5844 // Create a diagnostic pointing out that `fn` is missing.
5846 // x | pub path(&self) {
5847 // | ^ missing `fn`, `type`, or `const`
5849 // ^^ `sp` below will point to this
5850 let sp = prev_span.between(self.prev_span);
5851 let mut err = self.diagnostic().struct_span_err(
5853 &format!("{} for {}-item declaration",
5854 expected_kinds, item_type));
5855 err.span_label(sp, expected_kinds);
5859 /// Parse a method or a macro invocation in a trait impl.
5860 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5861 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5862 ast::ImplItemKind)> {
5863 // code copied from parse_macro_use_or_failure... abstraction!
5864 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5866 Ok((Ident::invalid(), vec![], ast::Generics::default(),
5867 ast::ImplItemKind::Macro(mac)))
5869 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5870 let ident = self.parse_ident()?;
5871 let mut generics = self.parse_generics()?;
5872 let decl = self.parse_fn_decl_with_self(|p| {
5873 p.parse_arg_general(true, true, false)
5875 generics.where_clause = self.parse_where_clause()?;
5877 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5878 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5879 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5880 ast::MethodSig { header, decl },
5886 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
5887 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5888 let ident = self.parse_ident()?;
5889 let mut tps = self.parse_generics()?;
5891 // Parse optional colon and supertrait bounds.
5892 let bounds = if self.eat(&token::Colon) {
5893 self.parse_generic_bounds(Some(self.prev_span))?
5898 if self.eat(&token::Eq) {
5899 // it's a trait alias
5900 let bounds = self.parse_generic_bounds(None)?;
5901 tps.where_clause = self.parse_where_clause()?;
5902 self.expect(&token::Semi)?;
5903 if is_auto == IsAuto::Yes {
5904 let msg = "trait aliases cannot be `auto`";
5905 self.struct_span_err(self.prev_span, msg)
5906 .span_label(self.prev_span, msg)
5909 if unsafety != Unsafety::Normal {
5910 let msg = "trait aliases cannot be `unsafe`";
5911 self.struct_span_err(self.prev_span, msg)
5912 .span_label(self.prev_span, msg)
5915 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5917 // it's a normal trait
5918 tps.where_clause = self.parse_where_clause()?;
5919 self.expect(&token::OpenDelim(token::Brace))?;
5920 let mut trait_items = vec![];
5921 while !self.eat(&token::CloseDelim(token::Brace)) {
5922 if let token::DocComment(_) = self.token.kind {
5923 if self.look_ahead(1,
5924 |tok| tok == &token::CloseDelim(token::Brace)) {
5925 let mut err = self.diagnostic().struct_span_err_with_code(
5927 "found a documentation comment that doesn't document anything",
5928 DiagnosticId::Error("E0584".into()),
5930 err.help("doc comments must come before what they document, maybe a \
5931 comment was intended with `//`?",
5938 let mut at_end = false;
5939 match self.parse_trait_item(&mut at_end) {
5940 Ok(item) => trait_items.push(item),
5944 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5949 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5953 fn choose_generics_over_qpath(&self) -> bool {
5954 // There's an ambiguity between generic parameters and qualified paths in impls.
5955 // If we see `<` it may start both, so we have to inspect some following tokens.
5956 // The following combinations can only start generics,
5957 // but not qualified paths (with one exception):
5958 // `<` `>` - empty generic parameters
5959 // `<` `#` - generic parameters with attributes
5960 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5961 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5962 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5963 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5964 // `<` const - generic const parameter
5965 // The only truly ambiguous case is
5966 // `<` IDENT `>` `::` IDENT ...
5967 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5968 // because this is what almost always expected in practice, qualified paths in impls
5969 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5970 self.token == token::Lt &&
5971 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5972 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5973 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5974 t == &token::Colon || t == &token::Eq) ||
5975 self.is_keyword_ahead(1, &[kw::Const]))
5978 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5979 self.expect(&token::OpenDelim(token::Brace))?;
5980 let attrs = self.parse_inner_attributes()?;
5982 let mut impl_items = Vec::new();
5983 while !self.eat(&token::CloseDelim(token::Brace)) {
5984 let mut at_end = false;
5985 match self.parse_impl_item(&mut at_end) {
5986 Ok(impl_item) => impl_items.push(impl_item),
5990 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5995 Ok((impl_items, attrs))
5998 /// Parses an implementation item, `impl` keyword is already parsed.
6000 /// impl<'a, T> TYPE { /* impl items */ }
6001 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6002 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6004 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6005 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6006 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6007 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6008 -> PResult<'a, ItemInfo> {
6009 // First, parse generic parameters if necessary.
6010 let mut generics = if self.choose_generics_over_qpath() {
6011 self.parse_generics()?
6013 ast::Generics::default()
6016 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6017 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6019 ast::ImplPolarity::Negative
6021 ast::ImplPolarity::Positive
6024 // Parse both types and traits as a type, then reinterpret if necessary.
6025 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
6026 let ty_first = if self.token.is_keyword(kw::For) &&
6027 self.look_ahead(1, |t| t != &token::Lt) {
6028 let span = self.prev_span.between(self.span);
6029 self.struct_span_err(span, "missing trait in a trait impl").emit();
6030 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6035 // If `for` is missing we try to recover.
6036 let has_for = self.eat_keyword(kw::For);
6037 let missing_for_span = self.prev_span.between(self.span);
6039 let ty_second = if self.token == token::DotDot {
6040 // We need to report this error after `cfg` expansion for compatibility reasons
6041 self.bump(); // `..`, do not add it to expected tokens
6042 Some(DummyResult::raw_ty(self.prev_span, true))
6043 } else if has_for || self.token.can_begin_type() {
6044 Some(self.parse_ty()?)
6049 generics.where_clause = self.parse_where_clause()?;
6051 let (impl_items, attrs) = self.parse_impl_body()?;
6053 let item_kind = match ty_second {
6054 Some(ty_second) => {
6055 // impl Trait for Type
6057 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6058 .span_suggestion_short(
6061 " for ".to_string(),
6062 Applicability::MachineApplicable,
6066 let ty_first = ty_first.into_inner();
6067 let path = match ty_first.node {
6068 // This notably includes paths passed through `ty` macro fragments (#46438).
6069 TyKind::Path(None, path) => path,
6071 self.span_err(ty_first.span, "expected a trait, found type");
6072 err_path(ty_first.span)
6075 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6077 ItemKind::Impl(unsafety, polarity, defaultness,
6078 generics, Some(trait_ref), ty_second, impl_items)
6082 ItemKind::Impl(unsafety, polarity, defaultness,
6083 generics, None, ty_first, impl_items)
6087 Ok((Ident::invalid(), item_kind, Some(attrs)))
6090 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6091 if self.eat_keyword(kw::For) {
6093 let params = self.parse_generic_params()?;
6095 // We rely on AST validation to rule out invalid cases: There must not be type
6096 // parameters, and the lifetime parameters must not have bounds.
6103 /// Parses `struct Foo { ... }`.
6104 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6105 let class_name = self.parse_ident()?;
6107 let mut generics = self.parse_generics()?;
6109 // There is a special case worth noting here, as reported in issue #17904.
6110 // If we are parsing a tuple struct it is the case that the where clause
6111 // should follow the field list. Like so:
6113 // struct Foo<T>(T) where T: Copy;
6115 // If we are parsing a normal record-style struct it is the case
6116 // that the where clause comes before the body, and after the generics.
6117 // So if we look ahead and see a brace or a where-clause we begin
6118 // parsing a record style struct.
6120 // Otherwise if we look ahead and see a paren we parse a tuple-style
6123 let vdata = if self.token.is_keyword(kw::Where) {
6124 generics.where_clause = self.parse_where_clause()?;
6125 if self.eat(&token::Semi) {
6126 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6127 VariantData::Unit(ast::DUMMY_NODE_ID)
6129 // If we see: `struct Foo<T> where T: Copy { ... }`
6130 let (fields, recovered) = self.parse_record_struct_body()?;
6131 VariantData::Struct(fields, recovered)
6133 // No `where` so: `struct Foo<T>;`
6134 } else if self.eat(&token::Semi) {
6135 VariantData::Unit(ast::DUMMY_NODE_ID)
6136 // Record-style struct definition
6137 } else if self.token == token::OpenDelim(token::Brace) {
6138 let (fields, recovered) = self.parse_record_struct_body()?;
6139 VariantData::Struct(fields, recovered)
6140 // Tuple-style struct definition with optional where-clause.
6141 } else if self.token == token::OpenDelim(token::Paren) {
6142 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6143 generics.where_clause = self.parse_where_clause()?;
6144 self.expect(&token::Semi)?;
6147 let token_str = self.this_token_descr();
6148 let mut err = self.fatal(&format!(
6149 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6152 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6156 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6159 /// Parses `union Foo { ... }`.
6160 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6161 let class_name = self.parse_ident()?;
6163 let mut generics = self.parse_generics()?;
6165 let vdata = if self.token.is_keyword(kw::Where) {
6166 generics.where_clause = self.parse_where_clause()?;
6167 let (fields, recovered) = self.parse_record_struct_body()?;
6168 VariantData::Struct(fields, recovered)
6169 } else if self.token == token::OpenDelim(token::Brace) {
6170 let (fields, recovered) = self.parse_record_struct_body()?;
6171 VariantData::Struct(fields, recovered)
6173 let token_str = self.this_token_descr();
6174 let mut err = self.fatal(&format!(
6175 "expected `where` or `{{` after union name, found {}", token_str));
6176 err.span_label(self.span, "expected `where` or `{` after union name");
6180 Ok((class_name, ItemKind::Union(vdata, generics), None))
6183 fn parse_record_struct_body(
6185 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6186 let mut fields = Vec::new();
6187 let mut recovered = false;
6188 if self.eat(&token::OpenDelim(token::Brace)) {
6189 while self.token != token::CloseDelim(token::Brace) {
6190 let field = self.parse_struct_decl_field().map_err(|e| {
6191 self.recover_stmt();
6196 Ok(field) => fields.push(field),
6202 self.eat(&token::CloseDelim(token::Brace));
6204 let token_str = self.this_token_descr();
6205 let mut err = self.fatal(&format!(
6206 "expected `where`, or `{{` after struct name, found {}", token_str));
6207 err.span_label(self.span, "expected `where`, or `{` after struct name");
6211 Ok((fields, recovered))
6214 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6215 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6216 // Unit like structs are handled in parse_item_struct function
6217 let fields = self.parse_unspanned_seq(
6218 &token::OpenDelim(token::Paren),
6219 &token::CloseDelim(token::Paren),
6220 SeqSep::trailing_allowed(token::Comma),
6222 let attrs = p.parse_outer_attributes()?;
6224 let vis = p.parse_visibility(true)?;
6225 let ty = p.parse_ty()?;
6227 span: lo.to(ty.span),
6230 id: ast::DUMMY_NODE_ID,
6239 /// Parses a structure field declaration.
6240 fn parse_single_struct_field(&mut self,
6243 attrs: Vec<Attribute> )
6244 -> PResult<'a, StructField> {
6245 let mut seen_comma: bool = false;
6246 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6247 if self.token == token::Comma {
6250 match self.token.kind {
6254 token::CloseDelim(token::Brace) => {}
6255 token::DocComment(_) => {
6256 let previous_span = self.prev_span;
6257 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6258 self.bump(); // consume the doc comment
6259 let comma_after_doc_seen = self.eat(&token::Comma);
6260 // `seen_comma` is always false, because we are inside doc block
6261 // condition is here to make code more readable
6262 if seen_comma == false && comma_after_doc_seen == true {
6265 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6268 if seen_comma == false {
6269 let sp = self.sess.source_map().next_point(previous_span);
6270 err.span_suggestion(
6272 "missing comma here",
6274 Applicability::MachineApplicable
6281 let sp = self.sess.source_map().next_point(self.prev_span);
6282 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6283 self.this_token_descr()));
6284 if self.token.is_ident() {
6285 // This is likely another field; emit the diagnostic and keep going
6286 err.span_suggestion(
6288 "try adding a comma",
6290 Applicability::MachineApplicable,
6301 /// Parses an element of a struct declaration.
6302 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6303 let attrs = self.parse_outer_attributes()?;
6305 let vis = self.parse_visibility(false)?;
6306 self.parse_single_struct_field(lo, vis, attrs)
6309 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6310 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6311 /// If the following element can't be a tuple (i.e., it's a function definition), then
6312 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6313 /// so emit a proper diagnostic.
6314 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6315 maybe_whole!(self, NtVis, |x| x);
6317 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
6318 if self.is_crate_vis() {
6319 self.bump(); // `crate`
6320 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6323 if !self.eat_keyword(kw::Pub) {
6324 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6325 // keyword to grab a span from for inherited visibility; an empty span at the
6326 // beginning of the current token would seem to be the "Schelling span".
6327 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6329 let lo = self.prev_span;
6331 if self.check(&token::OpenDelim(token::Paren)) {
6332 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6333 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6334 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6335 // by the following tokens.
6336 if self.is_keyword_ahead(1, &[kw::Crate]) &&
6337 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
6341 self.bump(); // `crate`
6342 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6344 lo.to(self.prev_span),
6345 VisibilityKind::Crate(CrateSugar::PubCrate),
6348 } else if self.is_keyword_ahead(1, &[kw::In]) {
6351 self.bump(); // `in`
6352 let path = self.parse_path(PathStyle::Mod)?; // `path`
6353 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6354 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6356 id: ast::DUMMY_NODE_ID,
6359 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6360 self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
6362 // `pub(self)` or `pub(super)`
6364 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6365 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6366 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6368 id: ast::DUMMY_NODE_ID,
6371 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6372 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6374 let msg = "incorrect visibility restriction";
6375 let suggestion = r##"some possible visibility restrictions are:
6376 `pub(crate)`: visible only on the current crate
6377 `pub(super)`: visible only in the current module's parent
6378 `pub(in path::to::module)`: visible only on the specified path"##;
6379 let path = self.parse_path(PathStyle::Mod)?;
6381 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6382 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6383 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6384 err.help(suggestion);
6385 err.span_suggestion(
6386 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6388 err.emit(); // emit diagnostic, but continue with public visibility
6392 Ok(respan(lo, VisibilityKind::Public))
6395 /// Parses defaultness (i.e., `default` or nothing).
6396 fn parse_defaultness(&mut self) -> Defaultness {
6397 // `pub` is included for better error messages
6398 if self.check_keyword(kw::Default) &&
6399 self.is_keyword_ahead(1, &[
6409 self.bump(); // `default`
6410 Defaultness::Default
6416 /// Given a termination token, parses all of the items in a module.
6417 fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
6418 let mut items = vec![];
6419 while let Some(item) = self.parse_item()? {
6421 self.maybe_consume_incorrect_semicolon(&items);
6424 if !self.eat(term) {
6425 let token_str = self.this_token_descr();
6426 if !self.maybe_consume_incorrect_semicolon(&items) {
6427 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6428 err.span_label(self.span, "expected item");
6433 let hi = if self.span.is_dummy() {
6440 inner: inner_lo.to(hi),
6446 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6447 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6448 self.expect(&token::Colon)?;
6449 let ty = self.parse_ty()?;
6450 self.expect(&token::Eq)?;
6451 let e = self.parse_expr()?;
6452 self.expect(&token::Semi)?;
6453 let item = match m {
6454 Some(m) => ItemKind::Static(ty, m, e),
6455 None => ItemKind::Const(ty, e),
6457 Ok((id, item, None))
6460 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6461 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6462 let (in_cfg, outer_attrs) = {
6463 let mut strip_unconfigured = crate::config::StripUnconfigured {
6465 features: None, // don't perform gated feature checking
6467 let mut outer_attrs = outer_attrs.to_owned();
6468 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
6469 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6472 let id_span = self.span;
6473 let id = self.parse_ident()?;
6474 if self.eat(&token::Semi) {
6475 if in_cfg && self.recurse_into_file_modules {
6476 // This mod is in an external file. Let's go get it!
6477 let ModulePathSuccess { path, directory_ownership, warn } =
6478 self.submod_path(id, &outer_attrs, id_span)?;
6479 let (module, mut attrs) =
6480 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6481 // Record that we fetched the mod from an external file
6483 let attr = Attribute {
6484 id: attr::mk_attr_id(),
6485 style: ast::AttrStyle::Outer,
6486 path: ast::Path::from_ident(
6487 Ident::with_empty_ctxt(sym::warn_directory_ownership)),
6488 tokens: TokenStream::empty(),
6489 is_sugared_doc: false,
6492 attr::mark_known(&attr);
6495 Ok((id, ItemKind::Mod(module), Some(attrs)))
6497 let placeholder = ast::Mod {
6502 Ok((id, ItemKind::Mod(placeholder), None))
6505 let old_directory = self.directory.clone();
6506 self.push_directory(id, &outer_attrs);
6508 self.expect(&token::OpenDelim(token::Brace))?;
6509 let mod_inner_lo = self.span;
6510 let attrs = self.parse_inner_attributes()?;
6511 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6513 self.directory = old_directory;
6514 Ok((id, ItemKind::Mod(module), Some(attrs)))
6518 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6519 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6520 self.directory.path.to_mut().push(&path.as_str());
6521 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6523 // We have to push on the current module name in the case of relative
6524 // paths in order to ensure that any additional module paths from inline
6525 // `mod x { ... }` come after the relative extension.
6527 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6528 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6529 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6530 if let Some(ident) = relative.take() { // remove the relative offset
6531 self.directory.path.to_mut().push(ident.as_str());
6534 self.directory.path.to_mut().push(&id.as_str());
6538 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6539 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6542 // On windows, the base path might have the form
6543 // `\\?\foo\bar` in which case it does not tolerate
6544 // mixed `/` and `\` separators, so canonicalize
6547 let s = s.replace("/", "\\");
6548 Some(dir_path.join(s))
6554 /// Returns a path to a module.
6555 pub fn default_submod_path(
6557 relative: Option<ast::Ident>,
6559 source_map: &SourceMap) -> ModulePath
6561 // If we're in a foo.rs file instead of a mod.rs file,
6562 // we need to look for submodules in
6563 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6564 // `./<id>.rs` and `./<id>/mod.rs`.
6565 let relative_prefix_string;
6566 let relative_prefix = if let Some(ident) = relative {
6567 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6568 &relative_prefix_string
6573 let mod_name = id.to_string();
6574 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6575 let secondary_path_str = format!("{}{}{}mod.rs",
6576 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6577 let default_path = dir_path.join(&default_path_str);
6578 let secondary_path = dir_path.join(&secondary_path_str);
6579 let default_exists = source_map.file_exists(&default_path);
6580 let secondary_exists = source_map.file_exists(&secondary_path);
6582 let result = match (default_exists, secondary_exists) {
6583 (true, false) => Ok(ModulePathSuccess {
6585 directory_ownership: DirectoryOwnership::Owned {
6590 (false, true) => Ok(ModulePathSuccess {
6591 path: secondary_path,
6592 directory_ownership: DirectoryOwnership::Owned {
6597 (false, false) => Err(Error::FileNotFoundForModule {
6598 mod_name: mod_name.clone(),
6599 default_path: default_path_str,
6600 secondary_path: secondary_path_str,
6601 dir_path: dir_path.display().to_string(),
6603 (true, true) => Err(Error::DuplicatePaths {
6604 mod_name: mod_name.clone(),
6605 default_path: default_path_str,
6606 secondary_path: secondary_path_str,
6612 path_exists: default_exists || secondary_exists,
6617 fn submod_path(&mut self,
6619 outer_attrs: &[Attribute],
6621 -> PResult<'a, ModulePathSuccess> {
6622 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6623 return Ok(ModulePathSuccess {
6624 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6625 // All `#[path]` files are treated as though they are a `mod.rs` file.
6626 // This means that `mod foo;` declarations inside `#[path]`-included
6627 // files are siblings,
6629 // Note that this will produce weirdness when a file named `foo.rs` is
6630 // `#[path]` included and contains a `mod foo;` declaration.
6631 // If you encounter this, it's your own darn fault :P
6632 Some(_) => DirectoryOwnership::Owned { relative: None },
6633 _ => DirectoryOwnership::UnownedViaMod(true),
6640 let relative = match self.directory.ownership {
6641 DirectoryOwnership::Owned { relative } => relative,
6642 DirectoryOwnership::UnownedViaBlock |
6643 DirectoryOwnership::UnownedViaMod(_) => None,
6645 let paths = Parser::default_submod_path(
6646 id, relative, &self.directory.path, self.sess.source_map());
6648 match self.directory.ownership {
6649 DirectoryOwnership::Owned { .. } => {
6650 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6652 DirectoryOwnership::UnownedViaBlock => {
6654 "Cannot declare a non-inline module inside a block \
6655 unless it has a path attribute";
6656 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6657 if paths.path_exists {
6658 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6660 err.span_note(id_sp, &msg);
6664 DirectoryOwnership::UnownedViaMod(warn) => {
6666 if let Ok(result) = paths.result {
6667 return Ok(ModulePathSuccess { warn: true, ..result });
6670 let mut err = self.diagnostic().struct_span_err(id_sp,
6671 "cannot declare a new module at this location");
6672 if !id_sp.is_dummy() {
6673 let src_path = self.sess.source_map().span_to_filename(id_sp);
6674 if let FileName::Real(src_path) = src_path {
6675 if let Some(stem) = src_path.file_stem() {
6676 let mut dest_path = src_path.clone();
6677 dest_path.set_file_name(stem);
6678 dest_path.push("mod.rs");
6679 err.span_note(id_sp,
6680 &format!("maybe move this module `{}` to its own \
6681 directory via `{}`", src_path.display(),
6682 dest_path.display()));
6686 if paths.path_exists {
6687 err.span_note(id_sp,
6688 &format!("... or maybe `use` the module `{}` instead \
6689 of possibly redeclaring it",
6697 /// Reads a module from a source file.
6698 fn eval_src_mod(&mut self,
6700 directory_ownership: DirectoryOwnership,
6703 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6704 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6705 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6706 let mut err = String::from("circular modules: ");
6707 let len = included_mod_stack.len();
6708 for p in &included_mod_stack[i.. len] {
6709 err.push_str(&p.to_string_lossy());
6710 err.push_str(" -> ");
6712 err.push_str(&path.to_string_lossy());
6713 return Err(self.span_fatal(id_sp, &err[..]));
6715 included_mod_stack.push(path.clone());
6716 drop(included_mod_stack);
6719 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6720 p0.cfg_mods = self.cfg_mods;
6721 let mod_inner_lo = p0.span;
6722 let mod_attrs = p0.parse_inner_attributes()?;
6723 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6725 self.sess.included_mod_stack.borrow_mut().pop();
6729 /// Parses a function declaration from a foreign module.
6730 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6731 -> PResult<'a, ForeignItem> {
6732 self.expect_keyword(kw::Fn)?;
6734 let (ident, mut generics) = self.parse_fn_header()?;
6735 let decl = self.parse_fn_decl(true)?;
6736 generics.where_clause = self.parse_where_clause()?;
6738 self.expect(&token::Semi)?;
6739 Ok(ast::ForeignItem {
6742 node: ForeignItemKind::Fn(decl, generics),
6743 id: ast::DUMMY_NODE_ID,
6749 /// Parses a static item from a foreign module.
6750 /// Assumes that the `static` keyword is already parsed.
6751 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6752 -> PResult<'a, ForeignItem> {
6753 let mutbl = self.parse_mutability();
6754 let ident = self.parse_ident()?;
6755 self.expect(&token::Colon)?;
6756 let ty = self.parse_ty()?;
6758 self.expect(&token::Semi)?;
6762 node: ForeignItemKind::Static(ty, mutbl),
6763 id: ast::DUMMY_NODE_ID,
6769 /// Parses a type from a foreign module.
6770 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6771 -> PResult<'a, ForeignItem> {
6772 self.expect_keyword(kw::Type)?;
6774 let ident = self.parse_ident()?;
6776 self.expect(&token::Semi)?;
6777 Ok(ast::ForeignItem {
6780 node: ForeignItemKind::Ty,
6781 id: ast::DUMMY_NODE_ID,
6787 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6788 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6789 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6791 let mut ident = if self.token.is_keyword(kw::SelfLower) {
6792 self.parse_path_segment_ident()
6796 let mut idents = vec![];
6797 let mut replacement = vec![];
6798 let mut fixed_crate_name = false;
6799 // Accept `extern crate name-like-this` for better diagnostics
6800 let dash = token::BinOp(token::BinOpToken::Minus);
6801 if self.token == dash { // Do not include `-` as part of the expected tokens list
6802 while self.eat(&dash) {
6803 fixed_crate_name = true;
6804 replacement.push((self.prev_span, "_".to_string()));
6805 idents.push(self.parse_ident()?);
6808 if fixed_crate_name {
6809 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6810 let mut fixed_name = format!("{}", ident.name);
6811 for part in idents {
6812 fixed_name.push_str(&format!("_{}", part.name));
6814 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6816 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6817 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6818 err.multipart_suggestion(
6821 Applicability::MachineApplicable,
6828 /// Parses `extern crate` links.
6833 /// extern crate foo;
6834 /// extern crate bar as foo;
6836 fn parse_item_extern_crate(&mut self,
6838 visibility: Visibility,
6839 attrs: Vec<Attribute>)
6840 -> PResult<'a, P<Item>> {
6841 // Accept `extern crate name-like-this` for better diagnostics
6842 let orig_name = self.parse_crate_name_with_dashes()?;
6843 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6844 (rename, Some(orig_name.name))
6848 self.expect(&token::Semi)?;
6850 let span = lo.to(self.prev_span);
6851 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6854 /// Parses `extern` for foreign ABIs modules.
6856 /// `extern` is expected to have been
6857 /// consumed before calling this method.
6861 /// ```ignore (only-for-syntax-highlight)
6865 fn parse_item_foreign_mod(&mut self,
6867 opt_abi: Option<Abi>,
6868 visibility: Visibility,
6869 mut attrs: Vec<Attribute>)
6870 -> PResult<'a, P<Item>> {
6871 self.expect(&token::OpenDelim(token::Brace))?;
6873 let abi = opt_abi.unwrap_or(Abi::C);
6875 attrs.extend(self.parse_inner_attributes()?);
6877 let mut foreign_items = vec![];
6878 while !self.eat(&token::CloseDelim(token::Brace)) {
6879 foreign_items.push(self.parse_foreign_item()?);
6882 let prev_span = self.prev_span;
6883 let m = ast::ForeignMod {
6885 items: foreign_items
6887 let invalid = Ident::invalid();
6888 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6891 /// Parses `type Foo = Bar;`
6893 /// `existential type Foo: Bar;`
6896 /// without modifying the parser state.
6897 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6898 // This parses the grammar:
6899 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6900 if self.check_keyword(kw::Type) ||
6901 self.check_keyword(kw::Existential) &&
6902 self.is_keyword_ahead(1, &[kw::Type]) {
6903 let existential = self.eat_keyword(kw::Existential);
6904 assert!(self.eat_keyword(kw::Type));
6905 Some(self.parse_existential_or_alias(existential))
6911 /// Parses a type alias or existential type.
6912 fn parse_existential_or_alias(
6915 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6916 let ident = self.parse_ident()?;
6917 let mut tps = self.parse_generics()?;
6918 tps.where_clause = self.parse_where_clause()?;
6919 let alias = if existential {
6920 self.expect(&token::Colon)?;
6921 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6922 AliasKind::Existential(bounds)
6924 self.expect(&token::Eq)?;
6925 let ty = self.parse_ty()?;
6928 self.expect(&token::Semi)?;
6929 Ok((ident, alias, tps))
6932 /// Parses the part of an enum declaration following the `{`.
6933 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6934 let mut variants = Vec::new();
6935 let mut any_disr = vec![];
6936 while self.token != token::CloseDelim(token::Brace) {
6937 let variant_attrs = self.parse_outer_attributes()?;
6938 let vlo = self.span;
6941 let mut disr_expr = None;
6943 let ident = self.parse_ident()?;
6944 if self.check(&token::OpenDelim(token::Brace)) {
6945 // Parse a struct variant.
6946 let (fields, recovered) = self.parse_record_struct_body()?;
6947 struct_def = VariantData::Struct(fields, recovered);
6948 } else if self.check(&token::OpenDelim(token::Paren)) {
6949 struct_def = VariantData::Tuple(
6950 self.parse_tuple_struct_body()?,
6953 } else if self.eat(&token::Eq) {
6954 disr_expr = Some(AnonConst {
6955 id: ast::DUMMY_NODE_ID,
6956 value: self.parse_expr()?,
6958 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
6961 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6963 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6966 let vr = ast::Variant_ {
6968 id: ast::DUMMY_NODE_ID,
6969 attrs: variant_attrs,
6973 variants.push(respan(vlo.to(self.prev_span), vr));
6975 if !self.eat(&token::Comma) {
6976 if self.token.is_ident() && !self.token.is_reserved_ident() {
6977 let sp = self.sess.source_map().next_point(self.prev_span);
6978 let mut err = self.struct_span_err(sp, "missing comma");
6979 err.span_suggestion_short(
6983 Applicability::MaybeIncorrect,
6991 self.expect(&token::CloseDelim(token::Brace))?;
6992 self.maybe_report_invalid_custom_discriminants(any_disr, &variants);
6994 Ok(ast::EnumDef { variants })
6997 /// Parses an enum declaration.
6998 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6999 let id = self.parse_ident()?;
7000 let mut generics = self.parse_generics()?;
7001 generics.where_clause = self.parse_where_clause()?;
7002 self.expect(&token::OpenDelim(token::Brace))?;
7004 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7005 self.recover_stmt();
7006 self.eat(&token::CloseDelim(token::Brace));
7009 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7012 /// Parses a string as an ABI spec on an extern type or module. Consumes
7013 /// the `extern` keyword, if one is found.
7014 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7015 match self.token.kind {
7016 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
7017 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
7019 self.expect_no_suffix(sp, "an ABI spec", suffix);
7021 match abi::lookup(&symbol.as_str()) {
7022 Some(abi) => Ok(Some(abi)),
7024 let prev_span = self.prev_span;
7025 let mut err = struct_span_err!(
7026 self.sess.span_diagnostic,
7029 "invalid ABI: found `{}`",
7031 err.span_label(prev_span, "invalid ABI");
7032 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7043 fn is_static_global(&mut self) -> bool {
7044 if self.check_keyword(kw::Static) {
7045 // Check if this could be a closure
7046 !self.look_ahead(1, |token| {
7047 if token.is_keyword(kw::Move) {
7051 token::BinOp(token::Or) | token::OrOr => true,
7062 attrs: Vec<Attribute>,
7063 macros_allowed: bool,
7064 attributes_allowed: bool,
7065 ) -> PResult<'a, Option<P<Item>>> {
7066 let mut unclosed_delims = vec![];
7067 let (ret, tokens) = self.collect_tokens(|this| {
7068 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7069 unclosed_delims.append(&mut this.unclosed_delims);
7072 self.unclosed_delims.append(&mut unclosed_delims);
7074 // Once we've parsed an item and recorded the tokens we got while
7075 // parsing we may want to store `tokens` into the item we're about to
7076 // return. Note, though, that we specifically didn't capture tokens
7077 // related to outer attributes. The `tokens` field here may later be
7078 // used with procedural macros to convert this item back into a token
7079 // stream, but during expansion we may be removing attributes as we go
7082 // If we've got inner attributes then the `tokens` we've got above holds
7083 // these inner attributes. If an inner attribute is expanded we won't
7084 // actually remove it from the token stream, so we'll just keep yielding
7085 // it (bad!). To work around this case for now we just avoid recording
7086 // `tokens` if we detect any inner attributes. This should help keep
7087 // expansion correct, but we should fix this bug one day!
7090 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7091 i.tokens = Some(tokens);
7098 /// Parses one of the items allowed by the flags.
7099 fn parse_item_implementation(
7101 attrs: Vec<Attribute>,
7102 macros_allowed: bool,
7103 attributes_allowed: bool,
7104 ) -> PResult<'a, Option<P<Item>>> {
7105 maybe_whole!(self, NtItem, |item| {
7106 let mut item = item.into_inner();
7107 let mut attrs = attrs;
7108 mem::swap(&mut item.attrs, &mut attrs);
7109 item.attrs.extend(attrs);
7115 let visibility = self.parse_visibility(false)?;
7117 if self.eat_keyword(kw::Use) {
7119 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7120 self.expect(&token::Semi)?;
7122 let span = lo.to(self.prev_span);
7124 self.mk_item(span, Ident::invalid(), item_, visibility, attrs);
7125 return Ok(Some(item));
7128 if self.eat_keyword(kw::Extern) {
7129 if self.eat_keyword(kw::Crate) {
7130 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7133 let opt_abi = self.parse_opt_abi()?;
7135 if self.eat_keyword(kw::Fn) {
7136 // EXTERN FUNCTION ITEM
7137 let fn_span = self.prev_span;
7138 let abi = opt_abi.unwrap_or(Abi::C);
7139 let (ident, item_, extra_attrs) =
7140 self.parse_item_fn(Unsafety::Normal,
7141 respan(fn_span, IsAsync::NotAsync),
7142 respan(fn_span, Constness::NotConst),
7144 let prev_span = self.prev_span;
7145 let item = self.mk_item(lo.to(prev_span),
7149 maybe_append(attrs, extra_attrs));
7150 return Ok(Some(item));
7151 } else if self.check(&token::OpenDelim(token::Brace)) {
7152 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7158 if self.is_static_global() {
7161 let m = if self.eat_keyword(kw::Mut) {
7164 Mutability::Immutable
7166 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7167 let prev_span = self.prev_span;
7168 let item = self.mk_item(lo.to(prev_span),
7172 maybe_append(attrs, extra_attrs));
7173 return Ok(Some(item));
7175 if self.eat_keyword(kw::Const) {
7176 let const_span = self.prev_span;
7177 if self.check_keyword(kw::Fn)
7178 || (self.check_keyword(kw::Unsafe)
7179 && self.is_keyword_ahead(1, &[kw::Fn])) {
7180 // CONST FUNCTION ITEM
7181 let unsafety = self.parse_unsafety();
7183 let (ident, item_, extra_attrs) =
7184 self.parse_item_fn(unsafety,
7185 respan(const_span, IsAsync::NotAsync),
7186 respan(const_span, Constness::Const),
7188 let prev_span = self.prev_span;
7189 let item = self.mk_item(lo.to(prev_span),
7193 maybe_append(attrs, extra_attrs));
7194 return Ok(Some(item));
7198 if self.eat_keyword(kw::Mut) {
7199 let prev_span = self.prev_span;
7200 let mut err = self.diagnostic()
7201 .struct_span_err(prev_span, "const globals cannot be mutable");
7202 err.span_label(prev_span, "cannot be mutable");
7203 err.span_suggestion(
7205 "you might want to declare a static instead",
7206 "static".to_owned(),
7207 Applicability::MaybeIncorrect,
7211 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7212 let prev_span = self.prev_span;
7213 let item = self.mk_item(lo.to(prev_span),
7217 maybe_append(attrs, extra_attrs));
7218 return Ok(Some(item));
7221 // Parse `async unsafe? fn`.
7222 if self.check_keyword(kw::Async) {
7223 let async_span = self.span;
7224 if self.is_keyword_ahead(1, &[kw::Fn])
7225 || self.is_keyword_ahead(2, &[kw::Fn])
7227 // ASYNC FUNCTION ITEM
7228 self.bump(); // `async`
7229 let unsafety = self.parse_unsafety(); // `unsafe`?
7230 self.expect_keyword(kw::Fn)?; // `fn`
7231 let fn_span = self.prev_span;
7232 let (ident, item_, extra_attrs) =
7233 self.parse_item_fn(unsafety,
7234 respan(async_span, IsAsync::Async {
7235 closure_id: ast::DUMMY_NODE_ID,
7236 return_impl_trait_id: ast::DUMMY_NODE_ID,
7238 respan(fn_span, Constness::NotConst),
7240 let prev_span = self.prev_span;
7241 let item = self.mk_item(lo.to(prev_span),
7245 maybe_append(attrs, extra_attrs));
7246 if self.span.rust_2015() {
7247 self.diagnostic().struct_span_err_with_code(
7249 "`async fn` is not permitted in the 2015 edition",
7250 DiagnosticId::Error("E0670".into())
7253 return Ok(Some(item));
7256 if self.check_keyword(kw::Unsafe) &&
7257 self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
7259 // UNSAFE TRAIT ITEM
7260 self.bump(); // `unsafe`
7261 let is_auto = if self.eat_keyword(kw::Trait) {
7264 self.expect_keyword(kw::Auto)?;
7265 self.expect_keyword(kw::Trait)?;
7268 let (ident, item_, extra_attrs) =
7269 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7270 let prev_span = self.prev_span;
7271 let item = self.mk_item(lo.to(prev_span),
7275 maybe_append(attrs, extra_attrs));
7276 return Ok(Some(item));
7278 if self.check_keyword(kw::Impl) ||
7279 self.check_keyword(kw::Unsafe) &&
7280 self.is_keyword_ahead(1, &[kw::Impl]) ||
7281 self.check_keyword(kw::Default) &&
7282 self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) {
7284 let defaultness = self.parse_defaultness();
7285 let unsafety = self.parse_unsafety();
7286 self.expect_keyword(kw::Impl)?;
7287 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7288 let span = lo.to(self.prev_span);
7289 return Ok(Some(self.mk_item(span, ident, item, visibility,
7290 maybe_append(attrs, extra_attrs))));
7292 if self.check_keyword(kw::Fn) {
7295 let fn_span = self.prev_span;
7296 let (ident, item_, extra_attrs) =
7297 self.parse_item_fn(Unsafety::Normal,
7298 respan(fn_span, IsAsync::NotAsync),
7299 respan(fn_span, Constness::NotConst),
7301 let prev_span = self.prev_span;
7302 let item = self.mk_item(lo.to(prev_span),
7306 maybe_append(attrs, extra_attrs));
7307 return Ok(Some(item));
7309 if self.check_keyword(kw::Unsafe)
7310 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7311 // UNSAFE FUNCTION ITEM
7312 self.bump(); // `unsafe`
7313 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7314 self.check(&token::OpenDelim(token::Brace));
7315 let abi = if self.eat_keyword(kw::Extern) {
7316 self.parse_opt_abi()?.unwrap_or(Abi::C)
7320 self.expect_keyword(kw::Fn)?;
7321 let fn_span = self.prev_span;
7322 let (ident, item_, extra_attrs) =
7323 self.parse_item_fn(Unsafety::Unsafe,
7324 respan(fn_span, IsAsync::NotAsync),
7325 respan(fn_span, Constness::NotConst),
7327 let prev_span = self.prev_span;
7328 let item = self.mk_item(lo.to(prev_span),
7332 maybe_append(attrs, extra_attrs));
7333 return Ok(Some(item));
7335 if self.eat_keyword(kw::Mod) {
7337 let (ident, item_, extra_attrs) =
7338 self.parse_item_mod(&attrs[..])?;
7339 let prev_span = self.prev_span;
7340 let item = self.mk_item(lo.to(prev_span),
7344 maybe_append(attrs, extra_attrs));
7345 return Ok(Some(item));
7347 if let Some(type_) = self.eat_type() {
7348 let (ident, alias, generics) = type_?;
7350 let item_ = match alias {
7351 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7352 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7354 let prev_span = self.prev_span;
7355 let item = self.mk_item(lo.to(prev_span),
7360 return Ok(Some(item));
7362 if self.eat_keyword(kw::Enum) {
7364 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7365 let prev_span = self.prev_span;
7366 let item = self.mk_item(lo.to(prev_span),
7370 maybe_append(attrs, extra_attrs));
7371 return Ok(Some(item));
7373 if self.check_keyword(kw::Trait)
7374 || (self.check_keyword(kw::Auto)
7375 && self.is_keyword_ahead(1, &[kw::Trait]))
7377 let is_auto = if self.eat_keyword(kw::Trait) {
7380 self.expect_keyword(kw::Auto)?;
7381 self.expect_keyword(kw::Trait)?;
7385 let (ident, item_, extra_attrs) =
7386 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7387 let prev_span = self.prev_span;
7388 let item = self.mk_item(lo.to(prev_span),
7392 maybe_append(attrs, extra_attrs));
7393 return Ok(Some(item));
7395 if self.eat_keyword(kw::Struct) {
7397 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7398 let prev_span = self.prev_span;
7399 let item = self.mk_item(lo.to(prev_span),
7403 maybe_append(attrs, extra_attrs));
7404 return Ok(Some(item));
7406 if self.is_union_item() {
7409 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7410 let prev_span = self.prev_span;
7411 let item = self.mk_item(lo.to(prev_span),
7415 maybe_append(attrs, extra_attrs));
7416 return Ok(Some(item));
7418 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7419 return Ok(Some(macro_def));
7422 // Verify whether we have encountered a struct or method definition where the user forgot to
7423 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7424 if visibility.node.is_pub() &&
7425 self.check_ident() &&
7426 self.look_ahead(1, |t| *t != token::Not)
7428 // Space between `pub` keyword and the identifier
7431 // ^^^ `sp` points here
7432 let sp = self.prev_span.between(self.span);
7433 let full_sp = self.prev_span.to(self.span);
7434 let ident_sp = self.span;
7435 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7436 // possible public struct definition where `struct` was forgotten
7437 let ident = self.parse_ident().unwrap();
7438 let msg = format!("add `struct` here to parse `{}` as a public struct",
7440 let mut err = self.diagnostic()
7441 .struct_span_err(sp, "missing `struct` for struct definition");
7442 err.span_suggestion_short(
7443 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7446 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7447 let ident = self.parse_ident().unwrap();
7449 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
7454 self.consume_block(token::Paren);
7455 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7456 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7458 ("fn", kw_name, false)
7459 } else if self.check(&token::OpenDelim(token::Brace)) {
7461 ("fn", kw_name, false)
7462 } else if self.check(&token::Colon) {
7466 ("fn` or `struct", "function or struct", true)
7469 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7470 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7472 self.consume_block(token::Brace);
7473 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7477 err.span_suggestion_short(
7478 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7481 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7482 err.span_suggestion(
7484 "if you meant to call a macro, try",
7485 format!("{}!", snippet),
7486 // this is the `ambiguous` conditional branch
7487 Applicability::MaybeIncorrect
7490 err.help("if you meant to call a macro, remove the `pub` \
7491 and add a trailing `!` after the identifier");
7495 } else if self.look_ahead(1, |t| *t == token::Lt) {
7496 let ident = self.parse_ident().unwrap();
7497 self.eat_to_tokens(&[&token::Gt]);
7499 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7500 if let Ok(Some(_)) = self.parse_self_arg() {
7501 ("fn", "method", false)
7503 ("fn", "function", false)
7505 } else if self.check(&token::OpenDelim(token::Brace)) {
7506 ("struct", "struct", false)
7508 ("fn` or `struct", "function or struct", true)
7510 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7511 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7513 err.span_suggestion_short(
7515 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7516 format!(" {} ", kw),
7517 Applicability::MachineApplicable,
7523 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7526 /// Parses a foreign item.
7527 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7528 maybe_whole!(self, NtForeignItem, |ni| ni);
7530 let attrs = self.parse_outer_attributes()?;
7532 let visibility = self.parse_visibility(false)?;
7534 // FOREIGN STATIC ITEM
7535 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7536 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
7537 if self.token.is_keyword(kw::Const) {
7539 .struct_span_err(self.span, "extern items cannot be `const`")
7542 "try using a static value",
7543 "static".to_owned(),
7544 Applicability::MachineApplicable
7547 self.bump(); // `static` or `const`
7548 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7550 // FOREIGN FUNCTION ITEM
7551 if self.check_keyword(kw::Fn) {
7552 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7554 // FOREIGN TYPE ITEM
7555 if self.check_keyword(kw::Type) {
7556 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7559 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7563 ident: Ident::invalid(),
7564 span: lo.to(self.prev_span),
7565 id: ast::DUMMY_NODE_ID,
7568 node: ForeignItemKind::Macro(mac),
7573 if !attrs.is_empty() {
7574 self.expected_item_err(&attrs)?;
7582 /// This is the fall-through for parsing items.
7583 fn parse_macro_use_or_failure(
7585 attrs: Vec<Attribute> ,
7586 macros_allowed: bool,
7587 attributes_allowed: bool,
7589 visibility: Visibility
7590 ) -> PResult<'a, Option<P<Item>>> {
7591 if macros_allowed && self.token.is_path_start() &&
7592 !(self.is_async_fn() && self.span.rust_2015()) {
7593 // MACRO INVOCATION ITEM
7595 let prev_span = self.prev_span;
7596 self.complain_if_pub_macro(&visibility.node, prev_span);
7598 let mac_lo = self.span;
7601 let pth = self.parse_path(PathStyle::Mod)?;
7602 self.expect(&token::Not)?;
7604 // a 'special' identifier (like what `macro_rules!` uses)
7605 // is optional. We should eventually unify invoc syntax
7607 let id = if self.token.is_ident() {
7610 Ident::invalid() // no special identifier
7612 // eat a matched-delimiter token tree:
7613 let (delim, tts) = self.expect_delimited_token_tree()?;
7614 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
7615 self.report_invalid_macro_expansion_item();
7618 let hi = self.prev_span;
7619 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7620 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7621 return Ok(Some(item));
7624 // FAILURE TO PARSE ITEM
7625 match visibility.node {
7626 VisibilityKind::Inherited => {}
7628 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7632 if !attributes_allowed && !attrs.is_empty() {
7633 self.expected_item_err(&attrs)?;
7638 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
7639 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7640 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7642 if self.token.is_path_start() &&
7643 !(self.is_async_fn() && self.span.rust_2015()) {
7644 let prev_span = self.prev_span;
7646 let pth = self.parse_path(PathStyle::Mod)?;
7648 if pth.segments.len() == 1 {
7649 if !self.eat(&token::Not) {
7650 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7653 self.expect(&token::Not)?;
7656 if let Some(vis) = vis {
7657 self.complain_if_pub_macro(&vis.node, prev_span);
7662 // eat a matched-delimiter token tree:
7663 let (delim, tts) = self.expect_delimited_token_tree()?;
7664 if delim != MacDelimiter::Brace {
7665 self.expect(&token::Semi)?;
7668 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7674 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7675 where F: FnOnce(&mut Self) -> PResult<'a, R>
7677 // Record all tokens we parse when parsing this item.
7678 let mut tokens = Vec::new();
7679 let prev_collecting = match self.token_cursor.frame.last_token {
7680 LastToken::Collecting(ref mut list) => {
7681 Some(mem::replace(list, Vec::new()))
7683 LastToken::Was(ref mut last) => {
7684 tokens.extend(last.take());
7688 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7689 let prev = self.token_cursor.stack.len();
7691 let last_token = if self.token_cursor.stack.len() == prev {
7692 &mut self.token_cursor.frame.last_token
7694 &mut self.token_cursor.stack[prev].last_token
7697 // Pull out the tokens that we've collected from the call to `f` above.
7698 let mut collected_tokens = match *last_token {
7699 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7700 LastToken::Was(_) => panic!("our vector went away?"),
7703 // If we're not at EOF our current token wasn't actually consumed by
7704 // `f`, but it'll still be in our list that we pulled out. In that case
7706 let extra_token = if self.token != token::Eof {
7707 collected_tokens.pop()
7712 // If we were previously collecting tokens, then this was a recursive
7713 // call. In that case we need to record all the tokens we collected in
7714 // our parent list as well. To do that we push a clone of our stream
7715 // onto the previous list.
7716 match prev_collecting {
7718 list.extend(collected_tokens.iter().cloned());
7719 list.extend(extra_token);
7720 *last_token = LastToken::Collecting(list);
7723 *last_token = LastToken::Was(extra_token);
7727 Ok((ret?, TokenStream::new(collected_tokens)))
7730 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7731 let attrs = self.parse_outer_attributes()?;
7732 self.parse_item_(attrs, true, false)
7736 fn is_import_coupler(&mut self) -> bool {
7737 self.check(&token::ModSep) &&
7738 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7739 *t == token::BinOp(token::Star))
7742 /// Parses a `UseTree`.
7745 /// USE_TREE = [`::`] `*` |
7746 /// [`::`] `{` USE_TREE_LIST `}` |
7748 /// PATH `::` `{` USE_TREE_LIST `}` |
7749 /// PATH [`as` IDENT]
7751 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7754 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7755 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7756 self.check(&token::BinOp(token::Star)) ||
7757 self.is_import_coupler() {
7758 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7759 let mod_sep_ctxt = self.span.ctxt();
7760 if self.eat(&token::ModSep) {
7761 prefix.segments.push(
7762 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7766 if self.eat(&token::BinOp(token::Star)) {
7769 UseTreeKind::Nested(self.parse_use_tree_list()?)
7772 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7773 prefix = self.parse_path(PathStyle::Mod)?;
7775 if self.eat(&token::ModSep) {
7776 if self.eat(&token::BinOp(token::Star)) {
7779 UseTreeKind::Nested(self.parse_use_tree_list()?)
7782 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7786 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7789 /// Parses a `UseTreeKind::Nested(list)`.
7792 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7794 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7795 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7796 &token::CloseDelim(token::Brace),
7797 SeqSep::trailing_allowed(token::Comma), |this| {
7798 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7802 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7803 if self.eat_keyword(kw::As) {
7804 self.parse_ident_or_underscore().map(Some)
7810 /// Parses a source module as a crate. This is the main entry point for the parser.
7811 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7813 let krate = Ok(ast::Crate {
7814 attrs: self.parse_inner_attributes()?,
7815 module: self.parse_mod_items(&token::Eof, lo)?,
7816 span: lo.to(self.span),
7821 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7822 let ret = match self.token.kind {
7823 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
7824 (symbol, ast::StrStyle::Cooked, suffix),
7825 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
7826 (symbol, ast::StrStyle::Raw(n), suffix),
7833 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7834 match self.parse_optional_str() {
7835 Some((s, style, suf)) => {
7836 let sp = self.prev_span;
7837 self.expect_no_suffix(sp, "a string literal", suf);
7841 let msg = "expected string literal";
7842 let mut err = self.fatal(msg);
7843 err.span_label(self.span, msg);
7849 fn report_invalid_macro_expansion_item(&self) {
7850 self.struct_span_err(
7852 "macros that expand to items must be delimited with braces or followed by a semicolon",
7853 ).multipart_suggestion(
7854 "change the delimiters to curly braces",
7856 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
7857 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
7859 Applicability::MaybeIncorrect,
7861 self.sess.source_map.next_point(self.prev_span),
7864 Applicability::MaybeIncorrect,
7869 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
7870 for unmatched in unclosed_delims.iter() {
7871 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
7872 "incorrect close delimiter: `{}`",
7873 pprust::token_to_string(&token::CloseDelim(unmatched.found_delim)),
7875 err.span_label(unmatched.found_span, "incorrect close delimiter");
7876 if let Some(sp) = unmatched.candidate_span {
7877 err.span_label(sp, "close delimiter possibly meant for this");
7879 if let Some(sp) = unmatched.unclosed_span {
7880 err.span_label(sp, "un-closed delimiter");
7884 unclosed_delims.clear();