1 use rustc_target::spec::abi::{self, Abi};
2 use ast::{AngleBracketedArgs, ParenthesisedArgs, AttrStyle, BareFnTy};
3 use ast::{GenericBound, TraitBoundModifier};
5 use ast::{Mod, AnonConst, Arg, Arm, Guard, Attribute, BindingMode, TraitItemKind};
7 use ast::{BlockCheckMode, CaptureBy, Movability};
8 use ast::{Constness, Crate};
11 use ast::{Expr, ExprKind, RangeLimits};
12 use ast::{Field, FnDecl, FnHeader};
13 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
14 use ast::{GenericParam, GenericParamKind};
16 use ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
17 use ast::{Label, Lifetime, Lit, LitKind};
19 use ast::MacStmtStyle;
20 use ast::{Mac, Mac_, MacDelimiter};
21 use ast::{MutTy, Mutability};
22 use ast::{Pat, PatKind, PathSegment};
23 use ast::{PolyTraitRef, QSelf};
24 use ast::{Stmt, StmtKind};
25 use ast::{VariantData, StructField};
28 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
29 use ast::{Ty, TyKind, TypeBinding, GenericBounds};
30 use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
31 use ast::{UseTree, UseTreeKind};
32 use ast::{BinOpKind, UnOp};
33 use ast::{RangeEnd, RangeSyntax};
35 use source_map::{self, SourceMap, Spanned, respan};
36 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName};
37 use errors::{self, Applicability, DiagnosticBuilder, DiagnosticId};
38 use parse::{self, SeqSep, classify, token};
39 use parse::lexer::TokenAndSpan;
40 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
41 use parse::token::DelimToken;
42 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
43 use util::parser::{AssocOp, Fixity};
48 use tokenstream::{self, DelimSpan, ThinTokenStream, TokenTree, TokenStream};
49 use symbol::{Symbol, keywords};
54 use std::path::{self, Path, PathBuf};
58 /// Whether the type alias or associated type is a concrete type or an existential type
60 /// Just a new name for the same type
62 /// Only trait impls of the type will be usable, not the actual type itself
63 Existential(GenericBounds),
67 struct Restrictions: u8 {
68 const STMT_EXPR = 1 << 0;
69 const NO_STRUCT_LITERAL = 1 << 1;
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
75 /// How to parse a path.
76 #[derive(Copy, Clone, PartialEq)]
78 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
79 /// with something else. For example, in expressions `segment < ....` can be interpreted
80 /// as a comparison and `segment ( ....` can be interpreted as a function call.
81 /// In all such contexts the non-path interpretation is preferred by default for practical
82 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
83 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
85 /// In other contexts, notably in types, no ambiguity exists and paths can be written
86 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
87 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
89 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
90 /// visibilities or attributes.
91 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
92 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
93 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
94 /// tokens when something goes wrong.
98 #[derive(Clone, Copy, PartialEq, Debug)]
104 #[derive(Clone, Copy, PartialEq, Debug)]
110 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
111 /// dropped into the token stream, which happens while parsing the result of
112 /// macro expansion). Placement of these is not as complex as I feared it would
113 /// be. The important thing is to make sure that lookahead doesn't balk at
114 /// `token::Interpolated` tokens.
115 macro_rules! maybe_whole_expr {
117 if let token::Interpolated(nt) = $p.token.clone() {
119 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
121 return Ok((*e).clone());
123 token::NtPath(ref path) => {
126 let kind = ExprKind::Path(None, (*path).clone());
127 return Ok($p.mk_expr(span, kind, ThinVec::new()));
129 token::NtBlock(ref block) => {
132 let kind = ExprKind::Block((*block).clone(), None);
133 return Ok($p.mk_expr(span, kind, ThinVec::new()));
141 /// As maybe_whole_expr, but for things other than expressions
142 macro_rules! maybe_whole {
143 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
144 if let token::Interpolated(nt) = $p.token.clone() {
145 if let token::$constructor($x) = nt.0.clone() {
153 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
154 if let Some(ref mut rhs) = rhs {
160 #[derive(Debug, Clone, Copy, PartialEq)]
171 trait RecoverQPath: Sized {
172 const PATH_STYLE: PathStyle = PathStyle::Expr;
173 fn to_ty(&self) -> Option<P<Ty>>;
174 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
175 fn to_string(&self) -> String;
178 impl RecoverQPath for Ty {
179 const PATH_STYLE: PathStyle = PathStyle::Type;
180 fn to_ty(&self) -> Option<P<Ty>> {
181 Some(P(self.clone()))
183 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
184 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
186 fn to_string(&self) -> String {
187 pprust::ty_to_string(self)
191 impl RecoverQPath for Pat {
192 fn to_ty(&self) -> Option<P<Ty>> {
195 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
196 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
198 fn to_string(&self) -> String {
199 pprust::pat_to_string(self)
203 impl RecoverQPath for Expr {
204 fn to_ty(&self) -> Option<P<Ty>> {
207 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
208 Self { span: path.span, node: ExprKind::Path(qself, path),
209 id: self.id, attrs: self.attrs.clone() }
211 fn to_string(&self) -> String {
212 pprust::expr_to_string(self)
216 /* ident is handled by common.rs */
219 pub struct Parser<'a> {
220 pub sess: &'a ParseSess,
221 /// the current token:
222 pub token: token::Token,
223 /// the span of the current token:
225 /// the span of the previous token:
226 meta_var_span: Option<Span>,
228 /// the previous token kind
229 prev_token_kind: PrevTokenKind,
230 restrictions: Restrictions,
231 /// Used to determine the path to externally loaded source files
232 crate directory: Directory<'a>,
233 /// Whether to parse sub-modules in other files.
234 pub recurse_into_file_modules: bool,
235 /// Name of the root module this parser originated from. If `None`, then the
236 /// name is not known. This does not change while the parser is descending
237 /// into modules, and sub-parsers have new values for this name.
238 pub root_module_name: Option<String>,
239 crate expected_tokens: Vec<TokenType>,
240 token_cursor: TokenCursor,
241 desugar_doc_comments: bool,
242 /// Whether we should configure out of line modules as we parse.
249 frame: TokenCursorFrame,
250 stack: Vec<TokenCursorFrame>,
254 struct TokenCursorFrame {
255 delim: token::DelimToken,
258 tree_cursor: tokenstream::Cursor,
260 last_token: LastToken,
263 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
264 /// by the parser, and then that's transitively used to record the tokens that
265 /// each parse AST item is created with.
267 /// Right now this has two states, either collecting tokens or not collecting
268 /// tokens. If we're collecting tokens we just save everything off into a local
269 /// `Vec`. This should eventually though likely save tokens from the original
270 /// token stream and just use slicing of token streams to avoid creation of a
271 /// whole new vector.
273 /// The second state is where we're passively not recording tokens, but the last
274 /// token is still tracked for when we want to start recording tokens. This
275 /// "last token" means that when we start recording tokens we'll want to ensure
276 /// that this, the first token, is included in the output.
278 /// You can find some more example usage of this in the `collect_tokens` method
282 Collecting(Vec<TokenStream>),
283 Was(Option<TokenStream>),
286 impl TokenCursorFrame {
287 fn new(sp: DelimSpan, delim: DelimToken, tts: &ThinTokenStream) -> Self {
291 open_delim: delim == token::NoDelim,
292 tree_cursor: tts.stream().into_trees(),
293 close_delim: delim == token::NoDelim,
294 last_token: LastToken::Was(None),
300 fn next(&mut self) -> TokenAndSpan {
302 let tree = if !self.frame.open_delim {
303 self.frame.open_delim = true;
304 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
305 } else if let Some(tree) = self.frame.tree_cursor.next() {
307 } else if !self.frame.close_delim {
308 self.frame.close_delim = true;
309 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
310 } else if let Some(frame) = self.stack.pop() {
314 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
317 match self.frame.last_token {
318 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
319 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
323 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
324 TokenTree::Delimited(sp, delim, tts) => {
325 let frame = TokenCursorFrame::new(sp, delim, &tts);
326 self.stack.push(mem::replace(&mut self.frame, frame));
332 fn next_desugared(&mut self) -> TokenAndSpan {
333 let (sp, name) = match self.next() {
334 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
338 let stripped = strip_doc_comment_decoration(&name.as_str());
340 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
341 // required to wrap the text.
342 let mut num_of_hashes = 0;
344 for ch in stripped.chars() {
347 '#' if count > 0 => count + 1,
350 num_of_hashes = cmp::max(num_of_hashes, count);
353 let delim_span = DelimSpan::from_single(sp);
354 let body = TokenTree::Delimited(
357 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
358 TokenTree::Token(sp, token::Eq),
359 TokenTree::Token(sp, token::Literal(
360 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
362 .iter().cloned().collect::<TokenStream>().into(),
365 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
368 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
369 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
370 .iter().cloned().collect::<TokenStream>().into()
372 [TokenTree::Token(sp, token::Pound), body]
373 .iter().cloned().collect::<TokenStream>().into()
381 #[derive(Clone, PartialEq)]
382 crate enum TokenType {
384 Keyword(keywords::Keyword),
393 fn to_string(&self) -> String {
395 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
396 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
397 TokenType::Operator => "an operator".to_string(),
398 TokenType::Lifetime => "lifetime".to_string(),
399 TokenType::Ident => "identifier".to_string(),
400 TokenType::Path => "path".to_string(),
401 TokenType::Type => "type".to_string(),
406 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
407 /// `IDENT<<u8 as Trait>::AssocTy>`.
409 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
410 /// that IDENT is not the ident of a fn trait
411 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
412 t == &token::ModSep || t == &token::Lt ||
413 t == &token::BinOp(token::Shl)
416 /// Information about the path to a module.
417 pub struct ModulePath {
420 pub result: Result<ModulePathSuccess, Error>,
423 pub struct ModulePathSuccess {
425 pub directory_ownership: DirectoryOwnership,
430 FileNotFoundForModule {
432 default_path: String,
433 secondary_path: String,
438 default_path: String,
439 secondary_path: String,
442 InclusiveRangeWithNoEnd,
446 fn span_err<S: Into<MultiSpan>>(self,
448 handler: &errors::Handler) -> DiagnosticBuilder {
450 Error::FileNotFoundForModule { ref mod_name,
454 let mut err = struct_span_err!(handler, sp, E0583,
455 "file not found for module `{}`", mod_name);
456 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
462 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
463 let mut err = struct_span_err!(handler, sp, E0584,
464 "file for module `{}` found at both {} and {}",
468 err.help("delete or rename one of them to remove the ambiguity");
471 Error::UselessDocComment => {
472 let mut err = struct_span_err!(handler, sp, E0585,
473 "found a documentation comment that doesn't document anything");
474 err.help("doc comments must come before what they document, maybe a comment was \
475 intended with `//`?");
478 Error::InclusiveRangeWithNoEnd => {
479 let mut err = struct_span_err!(handler, sp, E0586,
480 "inclusive range with no end");
481 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
491 AttributesParsed(ThinVec<Attribute>),
492 AlreadyParsed(P<Expr>),
495 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
496 fn from(o: Option<ThinVec<Attribute>>) -> Self {
497 if let Some(attrs) = o {
498 LhsExpr::AttributesParsed(attrs)
500 LhsExpr::NotYetParsed
505 impl From<P<Expr>> for LhsExpr {
506 fn from(expr: P<Expr>) -> Self {
507 LhsExpr::AlreadyParsed(expr)
511 /// Create a placeholder argument.
512 fn dummy_arg(span: Span) -> Arg {
513 let ident = Ident::new(keywords::Invalid.name(), span);
515 id: ast::DUMMY_NODE_ID,
516 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
522 id: ast::DUMMY_NODE_ID
524 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
527 #[derive(Copy, Clone, Debug)]
528 enum TokenExpectType {
533 impl<'a> Parser<'a> {
534 pub fn new(sess: &'a ParseSess,
536 directory: Option<Directory<'a>>,
537 recurse_into_file_modules: bool,
538 desugar_doc_comments: bool)
540 let mut parser = Parser {
542 token: token::Whitespace,
543 span: syntax_pos::DUMMY_SP,
544 prev_span: syntax_pos::DUMMY_SP,
546 prev_token_kind: PrevTokenKind::Other,
547 restrictions: Restrictions::empty(),
548 recurse_into_file_modules,
549 directory: Directory {
550 path: Cow::from(PathBuf::new()),
551 ownership: DirectoryOwnership::Owned { relative: None }
553 root_module_name: None,
554 expected_tokens: Vec::new(),
555 token_cursor: TokenCursor {
556 frame: TokenCursorFrame::new(
563 desugar_doc_comments,
567 let tok = parser.next_tok();
568 parser.token = tok.tok;
569 parser.span = tok.sp;
571 if let Some(directory) = directory {
572 parser.directory = directory;
573 } else if !parser.span.is_dummy() {
574 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
576 parser.directory.path = Cow::from(path);
580 parser.process_potential_macro_variable();
584 fn next_tok(&mut self) -> TokenAndSpan {
585 let mut next = if self.desugar_doc_comments {
586 self.token_cursor.next_desugared()
588 self.token_cursor.next()
590 if next.sp.is_dummy() {
591 // Tweak the location for better diagnostics, but keep syntactic context intact.
592 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
597 /// Convert the current token to a string using self's reader
598 pub fn this_token_to_string(&self) -> String {
599 pprust::token_to_string(&self.token)
602 fn token_descr(&self) -> Option<&'static str> {
603 Some(match &self.token {
604 t if t.is_special_ident() => "reserved identifier",
605 t if t.is_used_keyword() => "keyword",
606 t if t.is_unused_keyword() => "reserved keyword",
607 token::DocComment(..) => "doc comment",
612 fn this_token_descr(&self) -> String {
613 if let Some(prefix) = self.token_descr() {
614 format!("{} `{}`", prefix, self.this_token_to_string())
616 format!("`{}`", self.this_token_to_string())
620 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
621 let token_str = pprust::token_to_string(t);
622 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
625 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
626 match self.expect_one_of(&[], &[]) {
628 Ok(_) => unreachable!(),
632 /// Expect and consume the token t. Signal an error if
633 /// the next token is not t.
634 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
635 if self.expected_tokens.is_empty() {
636 if self.token == *t {
640 let token_str = pprust::token_to_string(t);
641 let this_token_str = self.this_token_descr();
642 let mut err = self.fatal(&format!("expected `{}`, found {}",
646 let sp = if self.token == token::Token::Eof {
647 // EOF, don't want to point at the following char, but rather the last token
650 self.sess.source_map().next_point(self.prev_span)
652 let label_exp = format!("expected `{}`", token_str);
653 let cm = self.sess.source_map();
654 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
655 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
656 // When the spans are in the same line, it means that the only content
657 // between them is whitespace, point only at the found token.
658 err.span_label(self.span, label_exp);
661 err.span_label(sp, label_exp);
662 err.span_label(self.span, "unexpected token");
668 self.expect_one_of(slice::from_ref(t), &[])
672 /// Expect next token to be edible or inedible token. If edible,
673 /// then consume it; if inedible, then return without consuming
674 /// anything. Signal a fatal error if next token is unexpected.
675 pub fn expect_one_of(&mut self,
676 edible: &[token::Token],
677 inedible: &[token::Token]) -> PResult<'a, ()>{
678 fn tokens_to_string(tokens: &[TokenType]) -> String {
679 let mut i = tokens.iter();
680 // This might be a sign we need a connect method on Iterator.
682 .map_or(String::new(), |t| t.to_string());
683 i.enumerate().fold(b, |mut b, (i, a)| {
684 if tokens.len() > 2 && i == tokens.len() - 2 {
686 } else if tokens.len() == 2 && i == tokens.len() - 2 {
691 b.push_str(&a.to_string());
695 if edible.contains(&self.token) {
698 } else if inedible.contains(&self.token) {
699 // leave it in the input
702 let mut expected = edible.iter()
703 .map(|x| TokenType::Token(x.clone()))
704 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
705 .chain(self.expected_tokens.iter().cloned())
706 .collect::<Vec<_>>();
707 expected.sort_by_cached_key(|x| x.to_string());
709 let expect = tokens_to_string(&expected[..]);
710 let actual = self.this_token_to_string();
711 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
712 let short_expect = if expected.len() > 6 {
713 format!("{} possible tokens", expected.len())
717 (format!("expected one of {}, found `{}`", expect, actual),
718 (self.sess.source_map().next_point(self.prev_span),
719 format!("expected one of {} here", short_expect)))
720 } else if expected.is_empty() {
721 (format!("unexpected token: `{}`", actual),
722 (self.prev_span, "unexpected token after this".to_string()))
724 (format!("expected {}, found `{}`", expect, actual),
725 (self.sess.source_map().next_point(self.prev_span),
726 format!("expected {} here", expect)))
728 let mut err = self.fatal(&msg_exp);
729 if self.token.is_ident_named("and") {
730 err.span_suggestion_short_with_applicability(
732 "use `&&` instead of `and` for the boolean operator",
734 Applicability::MaybeIncorrect,
737 if self.token.is_ident_named("or") {
738 err.span_suggestion_short_with_applicability(
740 "use `||` instead of `or` for the boolean operator",
742 Applicability::MaybeIncorrect,
745 let sp = if self.token == token::Token::Eof {
746 // This is EOF, don't want to point at the following char, but rather the last token
752 let cm = self.sess.source_map();
753 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
754 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
755 // When the spans are in the same line, it means that the only content between
756 // them is whitespace, point at the found token in that case:
758 // X | () => { syntax error };
759 // | ^^^^^ expected one of 8 possible tokens here
761 // instead of having:
763 // X | () => { syntax error };
764 // | -^^^^^ unexpected token
766 // | expected one of 8 possible tokens here
767 err.span_label(self.span, label_exp);
769 _ if self.prev_span == syntax_pos::DUMMY_SP => {
770 // Account for macro context where the previous span might not be
771 // available to avoid incorrect output (#54841).
772 err.span_label(self.span, "unexpected token");
775 err.span_label(sp, label_exp);
776 err.span_label(self.span, "unexpected token");
783 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
784 fn interpolated_or_expr_span(&self,
785 expr: PResult<'a, P<Expr>>)
786 -> PResult<'a, (Span, P<Expr>)> {
788 if self.prev_token_kind == PrevTokenKind::Interpolated {
796 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
797 let mut err = self.struct_span_err(self.span,
798 &format!("expected identifier, found {}",
799 self.this_token_descr()));
800 if let Some(token_descr) = self.token_descr() {
801 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
803 err.span_label(self.span, "expected identifier");
804 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
805 err.span_suggestion_with_applicability(
809 Applicability::MachineApplicable,
816 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
817 self.parse_ident_common(true)
820 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
822 token::Ident(ident, _) => {
823 if self.token.is_reserved_ident() {
824 let mut err = self.expected_ident_found();
831 let span = self.span;
833 Ok(Ident::new(ident.name, span))
836 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
837 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
839 self.expected_ident_found()
845 /// Check if the next token is `tok`, and return `true` if so.
847 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
849 crate fn check(&mut self, tok: &token::Token) -> bool {
850 let is_present = self.token == *tok;
851 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
855 /// Consume token 'tok' if it exists. Returns true if the given
856 /// token was present, false otherwise.
857 pub fn eat(&mut self, tok: &token::Token) -> bool {
858 let is_present = self.check(tok);
859 if is_present { self.bump() }
863 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
864 self.expected_tokens.push(TokenType::Keyword(kw));
865 self.token.is_keyword(kw)
868 /// If the next token is the given keyword, eat it and return
869 /// true. Otherwise, return false.
870 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
871 if self.check_keyword(kw) {
879 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
880 if self.token.is_keyword(kw) {
888 /// If the given word is not a keyword, signal an error.
889 /// If the next token is not the given word, signal an error.
890 /// Otherwise, eat it.
891 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
892 if !self.eat_keyword(kw) {
899 fn check_ident(&mut self) -> bool {
900 if self.token.is_ident() {
903 self.expected_tokens.push(TokenType::Ident);
908 fn check_path(&mut self) -> bool {
909 if self.token.is_path_start() {
912 self.expected_tokens.push(TokenType::Path);
917 fn check_type(&mut self) -> bool {
918 if self.token.can_begin_type() {
921 self.expected_tokens.push(TokenType::Type);
926 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
927 /// and continue. If a `+` is not seen, return false.
929 /// This is using when token splitting += into +.
930 /// See issue 47856 for an example of when this may occur.
931 fn eat_plus(&mut self) -> bool {
932 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
934 token::BinOp(token::Plus) => {
938 token::BinOpEq(token::Plus) => {
939 let span = self.span.with_lo(self.span.lo() + BytePos(1));
940 self.bump_with(token::Eq, span);
948 /// Checks to see if the next token is either `+` or `+=`.
949 /// Otherwise returns false.
950 fn check_plus(&mut self) -> bool {
951 if self.token.is_like_plus() {
955 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
960 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
961 /// `&` and continue. If an `&` is not seen, signal an error.
962 fn expect_and(&mut self) -> PResult<'a, ()> {
963 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
965 token::BinOp(token::And) => {
970 let span = self.span.with_lo(self.span.lo() + BytePos(1));
971 Ok(self.bump_with(token::BinOp(token::And), span))
973 _ => self.unexpected()
977 /// Expect and consume an `|`. If `||` is seen, replace it with a single
978 /// `|` and continue. If an `|` is not seen, signal an error.
979 fn expect_or(&mut self) -> PResult<'a, ()> {
980 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
982 token::BinOp(token::Or) => {
987 let span = self.span.with_lo(self.span.lo() + BytePos(1));
988 Ok(self.bump_with(token::BinOp(token::Or), span))
990 _ => self.unexpected()
994 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
996 None => {/* everything ok */}
998 let text = suf.as_str();
1000 self.span_bug(sp, "found empty literal suffix in Some")
1002 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
1007 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
1008 /// `<` and continue. If a `<` is not seen, return false.
1010 /// This is meant to be used when parsing generics on a path to get the
1012 fn eat_lt(&mut self) -> bool {
1013 self.expected_tokens.push(TokenType::Token(token::Lt));
1019 token::BinOp(token::Shl) => {
1020 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1021 self.bump_with(token::Lt, span);
1028 fn expect_lt(&mut self) -> PResult<'a, ()> {
1036 /// Expect and consume a GT. if a >> is seen, replace it
1037 /// with a single > and continue. If a GT is not seen,
1038 /// signal an error.
1039 fn expect_gt(&mut self) -> PResult<'a, ()> {
1040 self.expected_tokens.push(TokenType::Token(token::Gt));
1046 token::BinOp(token::Shr) => {
1047 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1048 Ok(self.bump_with(token::Gt, span))
1050 token::BinOpEq(token::Shr) => {
1051 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1052 Ok(self.bump_with(token::Ge, span))
1055 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1056 Ok(self.bump_with(token::Eq, span))
1058 _ => self.unexpected()
1062 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1063 /// passes through any errors encountered. Used for error recovery.
1064 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1065 let handler = self.diagnostic();
1067 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1069 TokenExpectType::Expect,
1070 |p| Ok(p.parse_token_tree())) {
1071 handler.cancel(err);
1075 /// Parse a sequence, including the closing delimiter. The function
1076 /// f must consume tokens until reaching the next separator or
1077 /// closing bracket.
1078 pub fn parse_seq_to_end<T, F>(&mut self,
1082 -> PResult<'a, Vec<T>> where
1083 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1085 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1090 /// Parse a sequence, not including the closing delimiter. The function
1091 /// f must consume tokens until reaching the next separator or
1092 /// closing bracket.
1093 pub fn parse_seq_to_before_end<T, F>(&mut self,
1097 -> PResult<'a, Vec<T>>
1098 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1100 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1103 fn parse_seq_to_before_tokens<T, F>(
1105 kets: &[&token::Token],
1107 expect: TokenExpectType,
1109 ) -> PResult<'a, Vec<T>>
1110 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1112 let mut first: bool = true;
1114 while !kets.iter().any(|k| {
1116 TokenExpectType::Expect => self.check(k),
1117 TokenExpectType::NoExpect => self.token == **k,
1121 token::CloseDelim(..) | token::Eof => break,
1124 if let Some(ref t) = sep.sep {
1128 if let Err(mut e) = self.expect(t) {
1129 // Attempt to keep parsing if it was a similar separator
1130 if let Some(ref tokens) = t.similar_tokens() {
1131 if tokens.contains(&self.token) {
1136 // Attempt to keep parsing if it was an omitted separator
1150 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1152 TokenExpectType::Expect => self.check(k),
1153 TokenExpectType::NoExpect => self.token == **k,
1166 /// Parse a sequence, including the closing delimiter. The function
1167 /// f must consume tokens until reaching the next separator or
1168 /// closing bracket.
1169 fn parse_unspanned_seq<T, F>(&mut self,
1174 -> PResult<'a, Vec<T>> where
1175 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1178 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1183 /// Advance the parser by one token
1184 pub fn bump(&mut self) {
1185 if self.prev_token_kind == PrevTokenKind::Eof {
1186 // Bumping after EOF is a bad sign, usually an infinite loop.
1187 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1190 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1192 // Record last token kind for possible error recovery.
1193 self.prev_token_kind = match self.token {
1194 token::DocComment(..) => PrevTokenKind::DocComment,
1195 token::Comma => PrevTokenKind::Comma,
1196 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1197 token::Interpolated(..) => PrevTokenKind::Interpolated,
1198 token::Eof => PrevTokenKind::Eof,
1199 token::Ident(..) => PrevTokenKind::Ident,
1200 _ => PrevTokenKind::Other,
1203 let next = self.next_tok();
1204 self.span = next.sp;
1205 self.token = next.tok;
1206 self.expected_tokens.clear();
1207 // check after each token
1208 self.process_potential_macro_variable();
1211 /// Advance the parser using provided token as a next one. Use this when
1212 /// consuming a part of a token. For example a single `<` from `<<`.
1213 fn bump_with(&mut self, next: token::Token, span: Span) {
1214 self.prev_span = self.span.with_hi(span.lo());
1215 // It would be incorrect to record the kind of the current token, but
1216 // fortunately for tokens currently using `bump_with`, the
1217 // prev_token_kind will be of no use anyway.
1218 self.prev_token_kind = PrevTokenKind::Other;
1221 self.expected_tokens.clear();
1224 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1225 F: FnOnce(&token::Token) -> R,
1228 return f(&self.token)
1231 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1232 Some(tree) => match tree {
1233 TokenTree::Token(_, tok) => tok,
1234 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1236 None => token::CloseDelim(self.token_cursor.frame.delim),
1240 fn look_ahead_span(&self, dist: usize) -> Span {
1245 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1246 Some(TokenTree::Token(span, _)) => span,
1247 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1248 None => self.look_ahead_span(dist - 1),
1251 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1252 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1254 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1255 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1257 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1258 err.span_err(sp, self.diagnostic())
1260 fn bug(&self, m: &str) -> ! {
1261 self.sess.span_diagnostic.span_bug(self.span, m)
1263 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1264 self.sess.span_diagnostic.span_err(sp, m)
1266 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1267 self.sess.span_diagnostic.struct_span_err(sp, m)
1269 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1270 self.sess.span_diagnostic.span_bug(sp, m)
1272 crate fn abort_if_errors(&self) {
1273 self.sess.span_diagnostic.abort_if_errors();
1276 fn cancel(&self, err: &mut DiagnosticBuilder) {
1277 self.sess.span_diagnostic.cancel(err)
1280 crate fn diagnostic(&self) -> &'a errors::Handler {
1281 &self.sess.span_diagnostic
1284 /// Is the current token one of the keywords that signals a bare function
1286 fn token_is_bare_fn_keyword(&mut self) -> bool {
1287 self.check_keyword(keywords::Fn) ||
1288 self.check_keyword(keywords::Unsafe) ||
1289 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1292 /// parse a `TyKind::BareFn` type:
1293 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1296 [unsafe] [extern "ABI"] fn (S) -> T
1306 let unsafety = self.parse_unsafety();
1307 let abi = if self.eat_keyword(keywords::Extern) {
1308 self.parse_opt_abi()?.unwrap_or(Abi::C)
1313 self.expect_keyword(keywords::Fn)?;
1314 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1315 let ret_ty = self.parse_ret_ty(false)?;
1316 let decl = P(FnDecl {
1321 Ok(TyKind::BareFn(P(BareFnTy {
1329 /// Parse asyncness: `async` or nothing
1330 fn parse_asyncness(&mut self) -> IsAsync {
1331 if self.eat_keyword(keywords::Async) {
1333 closure_id: ast::DUMMY_NODE_ID,
1334 return_impl_trait_id: ast::DUMMY_NODE_ID,
1341 /// Parse unsafety: `unsafe` or nothing.
1342 fn parse_unsafety(&mut self) -> Unsafety {
1343 if self.eat_keyword(keywords::Unsafe) {
1350 /// Parse the items in a trait declaration
1351 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1352 maybe_whole!(self, NtTraitItem, |x| x);
1353 let attrs = self.parse_outer_attributes()?;
1354 let (mut item, tokens) = self.collect_tokens(|this| {
1355 this.parse_trait_item_(at_end, attrs)
1357 // See `parse_item` for why this clause is here.
1358 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1359 item.tokens = Some(tokens);
1364 fn parse_trait_item_(&mut self,
1366 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1369 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1370 self.parse_trait_item_assoc_ty()?
1371 } else if self.is_const_item() {
1372 self.expect_keyword(keywords::Const)?;
1373 let ident = self.parse_ident()?;
1374 self.expect(&token::Colon)?;
1375 let ty = self.parse_ty()?;
1376 let default = if self.eat(&token::Eq) {
1377 let expr = self.parse_expr()?;
1378 self.expect(&token::Semi)?;
1381 self.expect(&token::Semi)?;
1384 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1385 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1386 // trait item macro.
1387 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1389 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1391 let ident = self.parse_ident()?;
1392 let mut generics = self.parse_generics()?;
1394 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1395 // This is somewhat dubious; We don't want to allow
1396 // argument names to be left off if there is a
1399 // We don't allow argument names to be left off in edition 2018.
1400 p.parse_arg_general(p.span.rust_2018(), true)
1402 generics.where_clause = self.parse_where_clause()?;
1404 let sig = ast::MethodSig {
1414 let body = match self.token {
1418 debug!("parse_trait_methods(): parsing required method");
1421 token::OpenDelim(token::Brace) => {
1422 debug!("parse_trait_methods(): parsing provided method");
1424 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1425 attrs.extend(inner_attrs.iter().cloned());
1428 token::Interpolated(ref nt) => {
1430 token::NtBlock(..) => {
1432 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1433 attrs.extend(inner_attrs.iter().cloned());
1437 let token_str = self.this_token_descr();
1438 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1440 err.span_label(self.span, "expected `;` or `{`");
1446 let token_str = self.this_token_descr();
1447 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1449 err.span_label(self.span, "expected `;` or `{`");
1453 (ident, ast::TraitItemKind::Method(sig, body), generics)
1457 id: ast::DUMMY_NODE_ID,
1462 span: lo.to(self.prev_span),
1467 /// Parse optional return type [ -> TY ] in function decl
1468 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1469 if self.eat(&token::RArrow) {
1470 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1472 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1477 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1478 self.parse_ty_common(true, true)
1481 /// Parse a type in restricted contexts where `+` is not permitted.
1482 /// Example 1: `&'a TYPE`
1483 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1484 /// Example 2: `value1 as TYPE + value2`
1485 /// `+` is prohibited to avoid interactions with expression grammar.
1486 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1487 self.parse_ty_common(false, true)
1490 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1491 -> PResult<'a, P<Ty>> {
1492 maybe_whole!(self, NtTy, |x| x);
1495 let mut impl_dyn_multi = false;
1496 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1497 // `(TYPE)` is a parenthesized type.
1498 // `(TYPE,)` is a tuple with a single field of type TYPE.
1499 let mut ts = vec![];
1500 let mut last_comma = false;
1501 while self.token != token::CloseDelim(token::Paren) {
1502 ts.push(self.parse_ty()?);
1503 if self.eat(&token::Comma) {
1510 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1511 self.expect(&token::CloseDelim(token::Paren))?;
1513 if ts.len() == 1 && !last_comma {
1514 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1515 let maybe_bounds = allow_plus && self.token.is_like_plus();
1517 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1518 TyKind::Path(None, ref path) if maybe_bounds => {
1519 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1521 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1522 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1523 let path = match bounds[0] {
1524 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1525 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1527 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1530 _ => TyKind::Paren(P(ty))
1535 } else if self.eat(&token::Not) {
1538 } else if self.eat(&token::BinOp(token::Star)) {
1540 TyKind::Ptr(self.parse_ptr()?)
1541 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1543 let t = self.parse_ty()?;
1544 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1545 let t = match self.maybe_parse_fixed_length_of_vec()? {
1546 None => TyKind::Slice(t),
1547 Some(length) => TyKind::Array(t, AnonConst {
1548 id: ast::DUMMY_NODE_ID,
1552 self.expect(&token::CloseDelim(token::Bracket))?;
1554 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1557 self.parse_borrowed_pointee()?
1558 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1560 // In order to not be ambiguous, the type must be surrounded by parens.
1561 self.expect(&token::OpenDelim(token::Paren))?;
1563 id: ast::DUMMY_NODE_ID,
1564 value: self.parse_expr()?,
1566 self.expect(&token::CloseDelim(token::Paren))?;
1568 } else if self.eat_keyword(keywords::Underscore) {
1569 // A type to be inferred `_`
1571 } else if self.token_is_bare_fn_keyword() {
1572 // Function pointer type
1573 self.parse_ty_bare_fn(Vec::new())?
1574 } else if self.check_keyword(keywords::For) {
1575 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1576 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1577 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1579 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1580 if self.token_is_bare_fn_keyword() {
1581 self.parse_ty_bare_fn(lifetime_defs)?
1583 let path = self.parse_path(PathStyle::Type)?;
1584 let parse_plus = allow_plus && self.check_plus();
1585 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1587 } else if self.eat_keyword(keywords::Impl) {
1588 // Always parse bounds greedily for better error recovery.
1589 let bounds = self.parse_generic_bounds()?;
1590 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1591 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1592 } else if self.check_keyword(keywords::Dyn) &&
1593 (self.span.rust_2018() ||
1594 self.look_ahead(1, |t| t.can_begin_bound() &&
1595 !can_continue_type_after_non_fn_ident(t))) {
1596 self.bump(); // `dyn`
1597 // Always parse bounds greedily for better error recovery.
1598 let bounds = self.parse_generic_bounds()?;
1599 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1600 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1601 } else if self.check(&token::Question) ||
1602 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1603 // Bound list (trait object type)
1604 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1605 TraitObjectSyntax::None)
1606 } else if self.eat_lt() {
1608 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1609 TyKind::Path(Some(qself), path)
1610 } else if self.token.is_path_start() {
1612 let path = self.parse_path(PathStyle::Type)?;
1613 if self.eat(&token::Not) {
1614 // Macro invocation in type position
1615 let (delim, tts) = self.expect_delimited_token_tree()?;
1616 let node = Mac_ { path, tts, delim };
1617 TyKind::Mac(respan(lo.to(self.prev_span), node))
1619 // Just a type path or bound list (trait object type) starting with a trait.
1621 // `Trait1 + Trait2 + 'a`
1622 if allow_plus && self.check_plus() {
1623 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1625 TyKind::Path(None, path)
1629 let msg = format!("expected type, found {}", self.this_token_descr());
1630 return Err(self.fatal(&msg));
1633 let span = lo.to(self.prev_span);
1634 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1636 // Try to recover from use of `+` with incorrect priority.
1637 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1638 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1639 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1644 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1645 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1646 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1647 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1649 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1650 bounds.append(&mut self.parse_generic_bounds()?);
1652 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1655 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1656 if !allow_plus && impl_dyn_multi {
1657 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1658 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1659 .span_suggestion_with_applicability(
1661 "use parentheses to disambiguate",
1663 Applicability::MachineApplicable
1668 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1669 // Do not add `+` to expected tokens.
1670 if !allow_plus || !self.token.is_like_plus() {
1675 let bounds = self.parse_generic_bounds()?;
1676 let sum_span = ty.span.to(self.prev_span);
1678 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1679 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1682 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1683 let sum_with_parens = pprust::to_string(|s| {
1684 use print::pprust::PrintState;
1687 s.print_opt_lifetime(lifetime)?;
1688 s.print_mutability(mut_ty.mutbl)?;
1690 s.print_type(&mut_ty.ty)?;
1691 s.print_type_bounds(" +", &bounds)?;
1694 err.span_suggestion_with_applicability(
1696 "try adding parentheses",
1698 Applicability::MachineApplicable
1701 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1702 err.span_label(sum_span, "perhaps you forgot parentheses?");
1705 err.span_label(sum_span, "expected a path");
1712 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1713 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1715 // Do not add `::` to expected tokens.
1716 if !allow_recovery || self.token != token::ModSep {
1719 let ty = match base.to_ty() {
1721 None => return Ok(base),
1724 self.bump(); // `::`
1725 let mut segments = Vec::new();
1726 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1728 let span = ty.span.to(self.prev_span);
1729 let path_span = span.to(span); // use an empty path since `position` == 0
1730 let recovered = base.to_recovered(
1731 Some(QSelf { ty, path_span, position: 0 }),
1732 ast::Path { segments, span },
1736 .struct_span_err(span, "missing angle brackets in associated item path")
1737 .span_suggestion_with_applicability( // this is a best-effort recovery
1738 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1744 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1745 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1746 let mutbl = self.parse_mutability();
1747 let ty = self.parse_ty_no_plus()?;
1748 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1751 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1752 let mutbl = if self.eat_keyword(keywords::Mut) {
1754 } else if self.eat_keyword(keywords::Const) {
1755 Mutability::Immutable
1757 let span = self.prev_span;
1759 "expected mut or const in raw pointer type (use \
1760 `*mut T` or `*const T` as appropriate)");
1761 Mutability::Immutable
1763 let t = self.parse_ty_no_plus()?;
1764 Ok(MutTy { ty: t, mutbl: mutbl })
1767 fn is_named_argument(&mut self) -> bool {
1768 let offset = match self.token {
1769 token::Interpolated(ref nt) => match nt.0 {
1770 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1773 token::BinOp(token::And) | token::AndAnd => 1,
1774 _ if self.token.is_keyword(keywords::Mut) => 1,
1778 self.look_ahead(offset, |t| t.is_ident()) &&
1779 self.look_ahead(offset + 1, |t| t == &token::Colon)
1782 /// Skip unexpected attributes and doc comments in this position and emit an appropriate error.
1783 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1784 if let token::DocComment(_) = self.token {
1785 let mut err = self.diagnostic().struct_span_err(
1787 &format!("documentation comments cannot be applied to {}", applied_to),
1789 err.span_label(self.span, "doc comments are not allowed here");
1792 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1793 *t == token::OpenDelim(token::Bracket)
1796 // Skip every token until next possible arg.
1797 while self.token != token::CloseDelim(token::Bracket) {
1800 let sp = lo.to(self.span);
1802 let mut err = self.diagnostic().struct_span_err(
1804 &format!("attributes cannot be applied to {}", applied_to),
1806 err.span_label(sp, "attributes are not allowed here");
1811 /// This version of parse arg doesn't necessarily require
1812 /// identifier names.
1813 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool) -> PResult<'a, Arg> {
1814 maybe_whole!(self, NtArg, |x| x);
1816 if let Ok(Some(_)) = self.parse_self_arg() {
1817 let mut err = self.struct_span_err(self.prev_span,
1818 "unexpected `self` argument in function");
1819 err.span_label(self.prev_span,
1820 "`self` is only valid as the first argument of an associated function");
1824 let (pat, ty) = if require_name || self.is_named_argument() {
1825 debug!("parse_arg_general parse_pat (require_name:{})",
1827 self.eat_incorrect_doc_comment("method arguments");
1828 let pat = self.parse_pat(Some("argument name"))?;
1830 if let Err(mut err) = self.expect(&token::Colon) {
1831 // If we find a pattern followed by an identifier, it could be an (incorrect)
1832 // C-style parameter declaration.
1833 if self.check_ident() && self.look_ahead(1, |t| {
1834 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1836 let ident = self.parse_ident().unwrap();
1837 let span = pat.span.with_hi(ident.span.hi());
1839 err.span_suggestion_with_applicability(
1841 "declare the type after the parameter binding",
1842 String::from("<identifier>: <type>"),
1843 Applicability::HasPlaceholders,
1845 } else if require_name && is_trait_item {
1846 if let PatKind::Ident(_, ident, _) = pat.node {
1847 err.span_suggestion_with_applicability(
1849 "explicitly ignore parameter",
1850 format!("_: {}", ident),
1851 Applicability::MachineApplicable,
1855 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1861 self.eat_incorrect_doc_comment("a method argument's type");
1862 (pat, self.parse_ty()?)
1864 debug!("parse_arg_general ident_to_pat");
1865 let parser_snapshot_before_ty = self.clone();
1866 self.eat_incorrect_doc_comment("a method argument's type");
1867 let mut ty = self.parse_ty();
1868 if ty.is_ok() && self.token == token::Colon {
1869 // This wasn't actually a type, but a pattern looking like a type,
1870 // so we are going to rollback and re-parse for recovery.
1871 ty = self.unexpected();
1875 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1877 id: ast::DUMMY_NODE_ID,
1878 node: PatKind::Ident(
1879 BindingMode::ByValue(Mutability::Immutable), ident, None),
1885 // Recover from attempting to parse the argument as a type without pattern.
1887 mem::replace(self, parser_snapshot_before_ty);
1888 let pat = self.parse_pat(Some("argument name"))?;
1889 self.expect(&token::Colon)?;
1890 let ty = self.parse_ty()?;
1892 let mut err = self.diagnostic().struct_span_err_with_code(
1894 "patterns aren't allowed in methods without bodies",
1895 DiagnosticId::Error("E0642".into()),
1897 err.span_suggestion_short_with_applicability(
1899 "give this argument a name or use an underscore to ignore it",
1901 Applicability::MachineApplicable,
1905 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1907 node: PatKind::Wild,
1909 id: ast::DUMMY_NODE_ID
1916 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1919 /// Parse a single function argument
1920 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1921 self.parse_arg_general(true, false)
1924 /// Parse an argument in a lambda header e.g., |arg, arg|
1925 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1926 let pat = self.parse_pat(Some("argument name"))?;
1927 let t = if self.eat(&token::Colon) {
1931 id: ast::DUMMY_NODE_ID,
1932 node: TyKind::Infer,
1933 span: self.prev_span,
1939 id: ast::DUMMY_NODE_ID
1943 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1944 if self.eat(&token::Semi) {
1945 Ok(Some(self.parse_expr()?))
1951 /// Matches token_lit = LIT_INTEGER | ...
1952 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1953 let out = match self.token {
1954 token::Interpolated(ref nt) => match nt.0 {
1955 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1956 ExprKind::Lit(ref lit) => { lit.node.clone() }
1957 _ => { return self.unexpected_last(&self.token); }
1959 _ => { return self.unexpected_last(&self.token); }
1961 token::Literal(lit, suf) => {
1962 let diag = Some((self.span, &self.sess.span_diagnostic));
1963 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1967 self.expect_no_suffix(sp, lit.literal_name(), suf)
1972 _ => { return self.unexpected_last(&self.token); }
1979 /// Matches lit = true | false | token_lit
1980 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1982 let lit = if self.eat_keyword(keywords::True) {
1984 } else if self.eat_keyword(keywords::False) {
1985 LitKind::Bool(false)
1987 let lit = self.parse_lit_token()?;
1990 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
1993 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1994 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1995 maybe_whole_expr!(self);
1997 let minus_lo = self.span;
1998 let minus_present = self.eat(&token::BinOp(token::Minus));
2000 let literal = self.parse_lit()?;
2001 let hi = self.prev_span;
2002 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2005 let minus_hi = self.prev_span;
2006 let unary = self.mk_unary(UnOp::Neg, expr);
2007 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2013 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2015 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2016 let span = self.span;
2018 Ok(Ident::new(ident.name, span))
2020 _ => self.parse_ident(),
2024 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2026 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2027 let span = self.span;
2029 Ok(Ident::new(ident.name, span))
2031 _ => self.parse_ident(),
2035 /// Parses qualified path.
2036 /// Assumes that the leading `<` has been parsed already.
2038 /// `qualified_path = <type [as trait_ref]>::path`
2043 /// `<T as U>::F::a<S>` (without disambiguator)
2044 /// `<T as U>::F::a::<S>` (with disambiguator)
2045 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2046 let lo = self.prev_span;
2047 let ty = self.parse_ty()?;
2049 // `path` will contain the prefix of the path up to the `>`,
2050 // if any (e.g., `U` in the `<T as U>::*` examples
2051 // above). `path_span` has the span of that path, or an empty
2052 // span in the case of something like `<T>::Bar`.
2053 let (mut path, path_span);
2054 if self.eat_keyword(keywords::As) {
2055 let path_lo = self.span;
2056 path = self.parse_path(PathStyle::Type)?;
2057 path_span = path_lo.to(self.prev_span);
2059 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2060 path_span = self.span.to(self.span);
2063 self.expect(&token::Gt)?;
2064 self.expect(&token::ModSep)?;
2066 let qself = QSelf { ty, path_span, position: path.segments.len() };
2067 self.parse_path_segments(&mut path.segments, style, true)?;
2069 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2072 /// Parses simple paths.
2074 /// `path = [::] segment+`
2075 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2078 /// `a::b::C<D>` (without disambiguator)
2079 /// `a::b::C::<D>` (with disambiguator)
2080 /// `Fn(Args)` (without disambiguator)
2081 /// `Fn::(Args)` (with disambiguator)
2082 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2083 self.parse_path_common(style, true)
2086 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2087 -> PResult<'a, ast::Path> {
2088 maybe_whole!(self, NtPath, |path| {
2089 if style == PathStyle::Mod &&
2090 path.segments.iter().any(|segment| segment.args.is_some()) {
2091 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2096 let lo = self.meta_var_span.unwrap_or(self.span);
2097 let mut segments = Vec::new();
2098 let mod_sep_ctxt = self.span.ctxt();
2099 if self.eat(&token::ModSep) {
2100 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2102 self.parse_path_segments(&mut segments, style, enable_warning)?;
2104 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2107 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2108 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2109 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2110 let meta_ident = match self.token {
2111 token::Interpolated(ref nt) => match nt.0 {
2112 token::NtMeta(ref meta) => match meta.node {
2113 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2120 if let Some(path) = meta_ident {
2124 self.parse_path(style)
2127 fn parse_path_segments(&mut self,
2128 segments: &mut Vec<PathSegment>,
2130 enable_warning: bool)
2131 -> PResult<'a, ()> {
2133 segments.push(self.parse_path_segment(style, enable_warning)?);
2135 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2141 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2142 -> PResult<'a, PathSegment> {
2143 let ident = self.parse_path_segment_ident()?;
2145 let is_args_start = |token: &token::Token| match *token {
2146 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2149 let check_args_start = |this: &mut Self| {
2150 this.expected_tokens.extend_from_slice(
2151 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2153 is_args_start(&this.token)
2156 Ok(if style == PathStyle::Type && check_args_start(self) ||
2157 style != PathStyle::Mod && self.check(&token::ModSep)
2158 && self.look_ahead(1, |t| is_args_start(t)) {
2159 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2161 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2162 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2163 .span_label(self.prev_span, "try removing `::`").emit();
2166 let args = if self.eat_lt() {
2168 let (args, bindings) = self.parse_generic_args()?;
2170 let span = lo.to(self.prev_span);
2171 AngleBracketedArgs { args, bindings, span }.into()
2175 let inputs = self.parse_seq_to_before_tokens(
2176 &[&token::CloseDelim(token::Paren)],
2177 SeqSep::trailing_allowed(token::Comma),
2178 TokenExpectType::Expect,
2181 let span = lo.to(self.prev_span);
2182 let output = if self.eat(&token::RArrow) {
2183 Some(self.parse_ty_common(false, false)?)
2187 ParenthesisedArgs { inputs, output, span }.into()
2190 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2192 // Generic arguments are not found.
2193 PathSegment::from_ident(ident)
2197 crate fn check_lifetime(&mut self) -> bool {
2198 self.expected_tokens.push(TokenType::Lifetime);
2199 self.token.is_lifetime()
2202 /// Parse single lifetime 'a or panic.
2203 crate fn expect_lifetime(&mut self) -> Lifetime {
2204 if let Some(ident) = self.token.lifetime() {
2205 let span = self.span;
2207 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2209 self.span_bug(self.span, "not a lifetime")
2213 fn eat_label(&mut self) -> Option<Label> {
2214 if let Some(ident) = self.token.lifetime() {
2215 let span = self.span;
2217 Some(Label { ident: Ident::new(ident.name, span) })
2223 /// Parse mutability (`mut` or nothing).
2224 fn parse_mutability(&mut self) -> Mutability {
2225 if self.eat_keyword(keywords::Mut) {
2228 Mutability::Immutable
2232 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2233 if let token::Literal(token::Integer(name), None) = self.token {
2235 Ok(Ident::new(name, self.prev_span))
2237 self.parse_ident_common(false)
2241 /// Parse ident (COLON expr)?
2242 fn parse_field(&mut self) -> PResult<'a, Field> {
2243 let attrs = self.parse_outer_attributes()?;
2246 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2247 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2248 let fieldname = self.parse_field_name()?;
2250 (fieldname, self.parse_expr()?, false)
2252 let fieldname = self.parse_ident_common(false)?;
2254 // Mimic `x: x` for the `x` field shorthand.
2255 let path = ast::Path::from_ident(fieldname);
2256 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2257 (fieldname, expr, true)
2261 span: lo.to(expr.span),
2264 attrs: attrs.into(),
2268 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2269 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2272 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2273 ExprKind::Unary(unop, expr)
2276 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2277 ExprKind::Binary(binop, lhs, rhs)
2280 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2281 ExprKind::Call(f, args)
2284 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2285 ExprKind::Index(expr, idx)
2288 fn mk_range(&mut self,
2289 start: Option<P<Expr>>,
2290 end: Option<P<Expr>>,
2291 limits: RangeLimits)
2292 -> PResult<'a, ast::ExprKind> {
2293 if end.is_none() && limits == RangeLimits::Closed {
2294 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2296 Ok(ExprKind::Range(start, end, limits))
2300 fn mk_assign_op(&mut self, binop: ast::BinOp,
2301 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2302 ExprKind::AssignOp(binop, lhs, rhs)
2305 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2307 id: ast::DUMMY_NODE_ID,
2308 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2314 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2315 let delim = match self.token {
2316 token::OpenDelim(delim) => delim,
2318 let msg = "expected open delimiter";
2319 let mut err = self.fatal(msg);
2320 err.span_label(self.span, msg);
2324 let tts = match self.parse_token_tree() {
2325 TokenTree::Delimited(_, _, tts) => tts,
2326 _ => unreachable!(),
2328 let delim = match delim {
2329 token::Paren => MacDelimiter::Parenthesis,
2330 token::Bracket => MacDelimiter::Bracket,
2331 token::Brace => MacDelimiter::Brace,
2332 token::NoDelim => self.bug("unexpected no delimiter"),
2334 Ok((delim, tts.stream().into()))
2337 /// At the bottom (top?) of the precedence hierarchy,
2338 /// parse things like parenthesized exprs,
2339 /// macros, return, etc.
2341 /// N.B., this does not parse outer attributes,
2342 /// and is private because it only works
2343 /// correctly if called from parse_dot_or_call_expr().
2344 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2345 maybe_whole_expr!(self);
2347 // Outer attributes are already parsed and will be
2348 // added to the return value after the fact.
2350 // Therefore, prevent sub-parser from parsing
2351 // attributes by giving them a empty "already parsed" list.
2352 let mut attrs = ThinVec::new();
2355 let mut hi = self.span;
2359 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2361 token::OpenDelim(token::Paren) => {
2364 attrs.extend(self.parse_inner_attributes()?);
2366 // (e) is parenthesized e
2367 // (e,) is a tuple with only one field, e
2368 let mut es = vec![];
2369 let mut trailing_comma = false;
2370 while self.token != token::CloseDelim(token::Paren) {
2371 es.push(self.parse_expr()?);
2372 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2373 if self.eat(&token::Comma) {
2374 trailing_comma = true;
2376 trailing_comma = false;
2382 hi = self.prev_span;
2383 ex = if es.len() == 1 && !trailing_comma {
2384 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2389 token::OpenDelim(token::Brace) => {
2390 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2392 token::BinOp(token::Or) | token::OrOr => {
2393 return self.parse_lambda_expr(attrs);
2395 token::OpenDelim(token::Bracket) => {
2398 attrs.extend(self.parse_inner_attributes()?);
2400 if self.eat(&token::CloseDelim(token::Bracket)) {
2402 ex = ExprKind::Array(Vec::new());
2405 let first_expr = self.parse_expr()?;
2406 if self.eat(&token::Semi) {
2407 // Repeating array syntax: [ 0; 512 ]
2408 let count = AnonConst {
2409 id: ast::DUMMY_NODE_ID,
2410 value: self.parse_expr()?,
2412 self.expect(&token::CloseDelim(token::Bracket))?;
2413 ex = ExprKind::Repeat(first_expr, count);
2414 } else if self.eat(&token::Comma) {
2415 // Vector with two or more elements.
2416 let remaining_exprs = self.parse_seq_to_end(
2417 &token::CloseDelim(token::Bracket),
2418 SeqSep::trailing_allowed(token::Comma),
2419 |p| Ok(p.parse_expr()?)
2421 let mut exprs = vec![first_expr];
2422 exprs.extend(remaining_exprs);
2423 ex = ExprKind::Array(exprs);
2425 // Vector with one element.
2426 self.expect(&token::CloseDelim(token::Bracket))?;
2427 ex = ExprKind::Array(vec![first_expr]);
2430 hi = self.prev_span;
2434 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2436 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2438 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2440 if self.is_async_block() { // check for `async {` and `async move {`
2441 return self.parse_async_block(attrs);
2443 return self.parse_lambda_expr(attrs);
2446 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2447 return self.parse_lambda_expr(attrs);
2449 if self.eat_keyword(keywords::If) {
2450 return self.parse_if_expr(attrs);
2452 if self.eat_keyword(keywords::For) {
2453 let lo = self.prev_span;
2454 return self.parse_for_expr(None, lo, attrs);
2456 if self.eat_keyword(keywords::While) {
2457 let lo = self.prev_span;
2458 return self.parse_while_expr(None, lo, attrs);
2460 if let Some(label) = self.eat_label() {
2461 let lo = label.ident.span;
2462 self.expect(&token::Colon)?;
2463 if self.eat_keyword(keywords::While) {
2464 return self.parse_while_expr(Some(label), lo, attrs)
2466 if self.eat_keyword(keywords::For) {
2467 return self.parse_for_expr(Some(label), lo, attrs)
2469 if self.eat_keyword(keywords::Loop) {
2470 return self.parse_loop_expr(Some(label), lo, attrs)
2472 if self.token == token::OpenDelim(token::Brace) {
2473 return self.parse_block_expr(Some(label),
2475 BlockCheckMode::Default,
2478 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2479 let mut err = self.fatal(msg);
2480 err.span_label(self.span, msg);
2483 if self.eat_keyword(keywords::Loop) {
2484 let lo = self.prev_span;
2485 return self.parse_loop_expr(None, lo, attrs);
2487 if self.eat_keyword(keywords::Continue) {
2488 let label = self.eat_label();
2489 let ex = ExprKind::Continue(label);
2490 let hi = self.prev_span;
2491 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2493 if self.eat_keyword(keywords::Match) {
2494 let match_sp = self.prev_span;
2495 return self.parse_match_expr(attrs).map_err(|mut err| {
2496 err.span_label(match_sp, "while parsing this match expression");
2500 if self.eat_keyword(keywords::Unsafe) {
2501 return self.parse_block_expr(
2504 BlockCheckMode::Unsafe(ast::UserProvided),
2507 if self.is_do_catch_block() {
2508 let mut db = self.fatal("found removed `do catch` syntax");
2509 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2512 if self.is_try_block() {
2514 assert!(self.eat_keyword(keywords::Try));
2515 return self.parse_try_block(lo, attrs);
2517 if self.eat_keyword(keywords::Return) {
2518 if self.token.can_begin_expr() {
2519 let e = self.parse_expr()?;
2521 ex = ExprKind::Ret(Some(e));
2523 ex = ExprKind::Ret(None);
2525 } else if self.eat_keyword(keywords::Break) {
2526 let label = self.eat_label();
2527 let e = if self.token.can_begin_expr()
2528 && !(self.token == token::OpenDelim(token::Brace)
2529 && self.restrictions.contains(
2530 Restrictions::NO_STRUCT_LITERAL)) {
2531 Some(self.parse_expr()?)
2535 ex = ExprKind::Break(label, e);
2536 hi = self.prev_span;
2537 } else if self.eat_keyword(keywords::Yield) {
2538 if self.token.can_begin_expr() {
2539 let e = self.parse_expr()?;
2541 ex = ExprKind::Yield(Some(e));
2543 ex = ExprKind::Yield(None);
2545 } else if self.token.is_keyword(keywords::Let) {
2546 // Catch this syntax error here, instead of in `parse_ident`, so
2547 // that we can explicitly mention that let is not to be used as an expression
2548 let mut db = self.fatal("expected expression, found statement (`let`)");
2549 db.span_label(self.span, "expected expression");
2550 db.note("variable declaration using `let` is a statement");
2552 } else if self.token.is_path_start() {
2553 let pth = self.parse_path(PathStyle::Expr)?;
2555 // `!`, as an operator, is prefix, so we know this isn't that
2556 if self.eat(&token::Not) {
2557 // MACRO INVOCATION expression
2558 let (delim, tts) = self.expect_delimited_token_tree()?;
2559 let hi = self.prev_span;
2560 let node = Mac_ { path: pth, tts, delim };
2561 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2563 if self.check(&token::OpenDelim(token::Brace)) {
2564 // This is a struct literal, unless we're prohibited
2565 // from parsing struct literals here.
2566 let prohibited = self.restrictions.contains(
2567 Restrictions::NO_STRUCT_LITERAL
2570 return self.parse_struct_expr(lo, pth, attrs);
2575 ex = ExprKind::Path(None, pth);
2577 match self.parse_literal_maybe_minus() {
2580 ex = expr.node.clone();
2583 self.cancel(&mut err);
2584 let msg = format!("expected expression, found {}",
2585 self.this_token_descr());
2586 let mut err = self.fatal(&msg);
2587 err.span_label(self.span, "expected expression");
2595 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2596 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2601 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2602 -> PResult<'a, P<Expr>> {
2603 let struct_sp = lo.to(self.prev_span);
2605 let mut fields = Vec::new();
2606 let mut base = None;
2608 attrs.extend(self.parse_inner_attributes()?);
2610 while self.token != token::CloseDelim(token::Brace) {
2611 if self.eat(&token::DotDot) {
2612 let exp_span = self.prev_span;
2613 match self.parse_expr() {
2619 self.recover_stmt();
2622 if self.token == token::Comma {
2623 let mut err = self.sess.span_diagnostic.mut_span_err(
2624 exp_span.to(self.prev_span),
2625 "cannot use a comma after the base struct",
2627 err.span_suggestion_short_with_applicability(
2629 "remove this comma",
2631 Applicability::MachineApplicable
2633 err.note("the base struct must always be the last field");
2635 self.recover_stmt();
2640 match self.parse_field() {
2641 Ok(f) => fields.push(f),
2643 e.span_label(struct_sp, "while parsing this struct");
2646 // If the next token is a comma, then try to parse
2647 // what comes next as additional fields, rather than
2648 // bailing out until next `}`.
2649 if self.token != token::Comma {
2650 self.recover_stmt();
2656 match self.expect_one_of(&[token::Comma],
2657 &[token::CloseDelim(token::Brace)]) {
2661 self.recover_stmt();
2667 let span = lo.to(self.span);
2668 self.expect(&token::CloseDelim(token::Brace))?;
2669 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2672 fn parse_or_use_outer_attributes(&mut self,
2673 already_parsed_attrs: Option<ThinVec<Attribute>>)
2674 -> PResult<'a, ThinVec<Attribute>> {
2675 if let Some(attrs) = already_parsed_attrs {
2678 self.parse_outer_attributes().map(|a| a.into())
2682 /// Parse a block or unsafe block
2683 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2684 lo: Span, blk_mode: BlockCheckMode,
2685 outer_attrs: ThinVec<Attribute>)
2686 -> PResult<'a, P<Expr>> {
2687 self.expect(&token::OpenDelim(token::Brace))?;
2689 let mut attrs = outer_attrs;
2690 attrs.extend(self.parse_inner_attributes()?);
2692 let blk = self.parse_block_tail(lo, blk_mode)?;
2693 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2696 /// parse a.b or a(13) or a[4] or just a
2697 fn parse_dot_or_call_expr(&mut self,
2698 already_parsed_attrs: Option<ThinVec<Attribute>>)
2699 -> PResult<'a, P<Expr>> {
2700 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2702 let b = self.parse_bottom_expr();
2703 let (span, b) = self.interpolated_or_expr_span(b)?;
2704 self.parse_dot_or_call_expr_with(b, span, attrs)
2707 fn parse_dot_or_call_expr_with(&mut self,
2710 mut attrs: ThinVec<Attribute>)
2711 -> PResult<'a, P<Expr>> {
2712 // Stitch the list of outer attributes onto the return value.
2713 // A little bit ugly, but the best way given the current code
2715 self.parse_dot_or_call_expr_with_(e0, lo)
2717 expr.map(|mut expr| {
2718 attrs.extend::<Vec<_>>(expr.attrs.into());
2721 ExprKind::If(..) | ExprKind::IfLet(..) => {
2722 if !expr.attrs.is_empty() {
2723 // Just point to the first attribute in there...
2724 let span = expr.attrs[0].span;
2727 "attributes are not yet allowed on `if` \
2738 // Assuming we have just parsed `.`, continue parsing into an expression.
2739 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2740 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2741 Ok(match self.token {
2742 token::OpenDelim(token::Paren) => {
2743 // Method call `expr.f()`
2744 let mut args = self.parse_unspanned_seq(
2745 &token::OpenDelim(token::Paren),
2746 &token::CloseDelim(token::Paren),
2747 SeqSep::trailing_allowed(token::Comma),
2748 |p| Ok(p.parse_expr()?)
2750 args.insert(0, self_arg);
2752 let span = lo.to(self.prev_span);
2753 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2756 // Field access `expr.f`
2757 if let Some(args) = segment.args {
2758 self.span_err(args.span(),
2759 "field expressions may not have generic arguments");
2762 let span = lo.to(self.prev_span);
2763 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2768 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2773 while self.eat(&token::Question) {
2774 let hi = self.prev_span;
2775 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2779 if self.eat(&token::Dot) {
2781 token::Ident(..) => {
2782 e = self.parse_dot_suffix(e, lo)?;
2784 token::Literal(token::Integer(name), _) => {
2785 let span = self.span;
2787 let field = ExprKind::Field(e, Ident::new(name, span));
2788 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2790 token::Literal(token::Float(n), _suf) => {
2792 let fstr = n.as_str();
2793 let mut err = self.diagnostic()
2794 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
2795 err.span_label(self.prev_span, "unexpected token");
2796 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2797 let float = match fstr.parse::<f64>().ok() {
2801 let sugg = pprust::to_string(|s| {
2802 use print::pprust::PrintState;
2806 s.print_usize(float.trunc() as usize)?;
2809 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2811 err.span_suggestion_with_applicability(
2812 lo.to(self.prev_span),
2813 "try parenthesizing the first index",
2815 Applicability::MachineApplicable
2822 // FIXME Could factor this out into non_fatal_unexpected or something.
2823 let actual = self.this_token_to_string();
2824 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2829 if self.expr_is_complete(&e) { break; }
2832 token::OpenDelim(token::Paren) => {
2833 let es = self.parse_unspanned_seq(
2834 &token::OpenDelim(token::Paren),
2835 &token::CloseDelim(token::Paren),
2836 SeqSep::trailing_allowed(token::Comma),
2837 |p| Ok(p.parse_expr()?)
2839 hi = self.prev_span;
2841 let nd = self.mk_call(e, es);
2842 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2846 // Could be either an index expression or a slicing expression.
2847 token::OpenDelim(token::Bracket) => {
2849 let ix = self.parse_expr()?;
2851 self.expect(&token::CloseDelim(token::Bracket))?;
2852 let index = self.mk_index(e, ix);
2853 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2861 crate fn process_potential_macro_variable(&mut self) {
2862 let (token, span) = match self.token {
2863 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2864 self.look_ahead(1, |t| t.is_ident()) => {
2866 let name = match self.token {
2867 token::Ident(ident, _) => ident,
2870 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2871 err.span_label(self.span, "unknown macro variable");
2875 token::Interpolated(ref nt) => {
2876 self.meta_var_span = Some(self.span);
2877 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2878 // and lifetime tokens, so the former are never encountered during normal parsing.
2880 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2881 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2891 /// parse a single token tree from the input.
2892 crate fn parse_token_tree(&mut self) -> TokenTree {
2894 token::OpenDelim(..) => {
2895 let frame = mem::replace(&mut self.token_cursor.frame,
2896 self.token_cursor.stack.pop().unwrap());
2897 self.span = frame.span.entire();
2899 TokenTree::Delimited(
2902 frame.tree_cursor.original_stream().into(),
2905 token::CloseDelim(_) | token::Eof => unreachable!(),
2907 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2909 TokenTree::Token(span, token)
2914 // parse a stream of tokens into a list of TokenTree's,
2916 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2917 let mut tts = Vec::new();
2918 while self.token != token::Eof {
2919 tts.push(self.parse_token_tree());
2924 pub fn parse_tokens(&mut self) -> TokenStream {
2925 let mut result = Vec::new();
2928 token::Eof | token::CloseDelim(..) => break,
2929 _ => result.push(self.parse_token_tree().into()),
2932 TokenStream::new(result)
2935 /// Parse a prefix-unary-operator expr
2936 fn parse_prefix_expr(&mut self,
2937 already_parsed_attrs: Option<ThinVec<Attribute>>)
2938 -> PResult<'a, P<Expr>> {
2939 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2941 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2942 let (hi, ex) = match self.token {
2945 let e = self.parse_prefix_expr(None);
2946 let (span, e) = self.interpolated_or_expr_span(e)?;
2947 (lo.to(span), self.mk_unary(UnOp::Not, e))
2949 // Suggest `!` for bitwise negation when encountering a `~`
2952 let e = self.parse_prefix_expr(None);
2953 let (span, e) = self.interpolated_or_expr_span(e)?;
2954 let span_of_tilde = lo;
2955 let mut err = self.diagnostic()
2956 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2957 err.span_suggestion_short_with_applicability(
2959 "use `!` to perform bitwise negation",
2961 Applicability::MachineApplicable
2964 (lo.to(span), self.mk_unary(UnOp::Not, e))
2966 token::BinOp(token::Minus) => {
2968 let e = self.parse_prefix_expr(None);
2969 let (span, e) = self.interpolated_or_expr_span(e)?;
2970 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2972 token::BinOp(token::Star) => {
2974 let e = self.parse_prefix_expr(None);
2975 let (span, e) = self.interpolated_or_expr_span(e)?;
2976 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2978 token::BinOp(token::And) | token::AndAnd => {
2980 let m = self.parse_mutability();
2981 let e = self.parse_prefix_expr(None);
2982 let (span, e) = self.interpolated_or_expr_span(e)?;
2983 (lo.to(span), ExprKind::AddrOf(m, e))
2985 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2987 let place = self.parse_expr_res(
2988 Restrictions::NO_STRUCT_LITERAL,
2991 let blk = self.parse_block()?;
2992 let span = blk.span;
2993 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2994 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2996 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2998 let e = self.parse_prefix_expr(None);
2999 let (span, e) = self.interpolated_or_expr_span(e)?;
3000 (lo.to(span), ExprKind::Box(e))
3002 token::Ident(..) if self.token.is_ident_named("not") => {
3003 // `not` is just an ordinary identifier in Rust-the-language,
3004 // but as `rustc`-the-compiler, we can issue clever diagnostics
3005 // for confused users who really want to say `!`
3006 let token_cannot_continue_expr = |t: &token::Token| match *t {
3007 // These tokens can start an expression after `!`, but
3008 // can't continue an expression after an ident
3009 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3010 token::Literal(..) | token::Pound => true,
3011 token::Interpolated(ref nt) => match nt.0 {
3012 token::NtIdent(..) | token::NtExpr(..) |
3013 token::NtBlock(..) | token::NtPath(..) => true,
3018 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3019 if cannot_continue_expr {
3021 // Emit the error ...
3022 let mut err = self.diagnostic()
3023 .struct_span_err(self.span,
3024 &format!("unexpected {} after identifier",
3025 self.this_token_descr()));
3026 // span the `not` plus trailing whitespace to avoid
3027 // trailing whitespace after the `!` in our suggestion
3028 let to_replace = self.sess.source_map()
3029 .span_until_non_whitespace(lo.to(self.span));
3030 err.span_suggestion_short_with_applicability(
3032 "use `!` to perform logical negation",
3034 Applicability::MachineApplicable
3037 // —and recover! (just as if we were in the block
3038 // for the `token::Not` arm)
3039 let e = self.parse_prefix_expr(None);
3040 let (span, e) = self.interpolated_or_expr_span(e)?;
3041 (lo.to(span), self.mk_unary(UnOp::Not, e))
3043 return self.parse_dot_or_call_expr(Some(attrs));
3046 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3048 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3051 /// Parse an associative expression
3053 /// This parses an expression accounting for associativity and precedence of the operators in
3056 fn parse_assoc_expr(&mut self,
3057 already_parsed_attrs: Option<ThinVec<Attribute>>)
3058 -> PResult<'a, P<Expr>> {
3059 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3062 /// Parse an associative expression with operators of at least `min_prec` precedence
3063 fn parse_assoc_expr_with(&mut self,
3066 -> PResult<'a, P<Expr>> {
3067 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3070 let attrs = match lhs {
3071 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3074 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3075 return self.parse_prefix_range_expr(attrs);
3077 self.parse_prefix_expr(attrs)?
3081 if self.expr_is_complete(&lhs) {
3082 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3085 self.expected_tokens.push(TokenType::Operator);
3086 while let Some(op) = AssocOp::from_token(&self.token) {
3088 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3089 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3090 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3091 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3092 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3093 (PrevTokenKind::Interpolated, _) => self.prev_span,
3094 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3095 if path.segments.len() == 1 => self.prev_span,
3099 let cur_op_span = self.span;
3100 let restrictions = if op.is_assign_like() {
3101 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3105 if op.precedence() < min_prec {
3108 // Check for deprecated `...` syntax
3109 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3110 self.err_dotdotdot_syntax(self.span);
3114 if op.is_comparison() {
3115 self.check_no_chained_comparison(&lhs, &op);
3118 if op == AssocOp::As {
3119 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3121 } else if op == AssocOp::Colon {
3122 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3125 err.span_label(self.span,
3126 "expecting a type here because of type ascription");
3127 let cm = self.sess.source_map();
3128 let cur_pos = cm.lookup_char_pos(self.span.lo());
3129 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3130 if cur_pos.line != op_pos.line {
3131 err.span_suggestion_with_applicability(
3133 "try using a semicolon",
3135 Applicability::MaybeIncorrect // speculative
3142 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3143 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3144 // generalise it to the Fixity::None code.
3146 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3147 // two variants are handled with `parse_prefix_range_expr` call above.
3148 let rhs = if self.is_at_start_of_range_notation_rhs() {
3149 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3150 LhsExpr::NotYetParsed)?)
3154 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3159 let limits = if op == AssocOp::DotDot {
3160 RangeLimits::HalfOpen
3165 let r = self.mk_range(Some(lhs), rhs, limits)?;
3166 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3170 let rhs = match op.fixity() {
3171 Fixity::Right => self.with_res(
3172 restrictions - Restrictions::STMT_EXPR,
3174 this.parse_assoc_expr_with(op.precedence(),
3175 LhsExpr::NotYetParsed)
3177 Fixity::Left => self.with_res(
3178 restrictions - Restrictions::STMT_EXPR,
3180 this.parse_assoc_expr_with(op.precedence() + 1,
3181 LhsExpr::NotYetParsed)
3183 // We currently have no non-associative operators that are not handled above by
3184 // the special cases. The code is here only for future convenience.
3185 Fixity::None => self.with_res(
3186 restrictions - Restrictions::STMT_EXPR,
3188 this.parse_assoc_expr_with(op.precedence() + 1,
3189 LhsExpr::NotYetParsed)
3193 let span = lhs_span.to(rhs.span);
3195 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3196 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3197 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3198 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3199 AssocOp::Greater | AssocOp::GreaterEqual => {
3200 let ast_op = op.to_ast_binop().unwrap();
3201 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3202 self.mk_expr(span, binary, ThinVec::new())
3205 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3206 AssocOp::ObsoleteInPlace =>
3207 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3208 AssocOp::AssignOp(k) => {
3210 token::Plus => BinOpKind::Add,
3211 token::Minus => BinOpKind::Sub,
3212 token::Star => BinOpKind::Mul,
3213 token::Slash => BinOpKind::Div,
3214 token::Percent => BinOpKind::Rem,
3215 token::Caret => BinOpKind::BitXor,
3216 token::And => BinOpKind::BitAnd,
3217 token::Or => BinOpKind::BitOr,
3218 token::Shl => BinOpKind::Shl,
3219 token::Shr => BinOpKind::Shr,
3221 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3222 self.mk_expr(span, aopexpr, ThinVec::new())
3224 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3225 self.bug("AssocOp should have been handled by special case")
3229 if op.fixity() == Fixity::None { break }
3234 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3235 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3236 -> PResult<'a, P<Expr>> {
3237 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3238 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3241 // Save the state of the parser before parsing type normally, in case there is a
3242 // LessThan comparison after this cast.
3243 let parser_snapshot_before_type = self.clone();
3244 match self.parse_ty_no_plus() {
3246 Ok(mk_expr(self, rhs))
3248 Err(mut type_err) => {
3249 // Rewind to before attempting to parse the type with generics, to recover
3250 // from situations like `x as usize < y` in which we first tried to parse
3251 // `usize < y` as a type with generic arguments.
3252 let parser_snapshot_after_type = self.clone();
3253 mem::replace(self, parser_snapshot_before_type);
3255 match self.parse_path(PathStyle::Expr) {
3257 let (op_noun, op_verb) = match self.token {
3258 token::Lt => ("comparison", "comparing"),
3259 token::BinOp(token::Shl) => ("shift", "shifting"),
3261 // We can end up here even without `<` being the next token, for
3262 // example because `parse_ty_no_plus` returns `Err` on keywords,
3263 // but `parse_path` returns `Ok` on them due to error recovery.
3264 // Return original error and parser state.
3265 mem::replace(self, parser_snapshot_after_type);
3266 return Err(type_err);
3270 // Successfully parsed the type path leaving a `<` yet to parse.
3273 // Report non-fatal diagnostics, keep `x as usize` as an expression
3274 // in AST and continue parsing.
3275 let msg = format!("`<` is interpreted as a start of generic \
3276 arguments for `{}`, not a {}", path, op_noun);
3277 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3278 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3279 "interpreted as generic arguments");
3280 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3282 let expr = mk_expr(self, P(Ty {
3284 node: TyKind::Path(None, path),
3285 id: ast::DUMMY_NODE_ID
3288 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3289 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3290 err.span_suggestion_with_applicability(
3292 &format!("try {} the cast value", op_verb),
3293 format!("({})", expr_str),
3294 Applicability::MachineApplicable
3300 Err(mut path_err) => {
3301 // Couldn't parse as a path, return original error and parser state.
3303 mem::replace(self, parser_snapshot_after_type);
3311 /// Produce an error if comparison operators are chained (RFC #558).
3312 /// We only need to check lhs, not rhs, because all comparison ops
3313 /// have same precedence and are left-associative
3314 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3315 debug_assert!(outer_op.is_comparison(),
3316 "check_no_chained_comparison: {:?} is not comparison",
3319 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3320 // respan to include both operators
3321 let op_span = op.span.to(self.span);
3322 let mut err = self.diagnostic().struct_span_err(op_span,
3323 "chained comparison operators require parentheses");
3324 if op.node == BinOpKind::Lt &&
3325 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3326 *outer_op == AssocOp::Greater // even in a case like the following:
3327 { // Foo<Bar<Baz<Qux, ()>>>
3329 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3330 err.help("or use `(...)` if you meant to specify fn arguments");
3338 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3339 fn parse_prefix_range_expr(&mut self,
3340 already_parsed_attrs: Option<ThinVec<Attribute>>)
3341 -> PResult<'a, P<Expr>> {
3342 // Check for deprecated `...` syntax
3343 if self.token == token::DotDotDot {
3344 self.err_dotdotdot_syntax(self.span);
3347 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3348 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3350 let tok = self.token.clone();
3351 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3353 let mut hi = self.span;
3355 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3356 // RHS must be parsed with more associativity than the dots.
3357 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3358 Some(self.parse_assoc_expr_with(next_prec,
3359 LhsExpr::NotYetParsed)
3367 let limits = if tok == token::DotDot {
3368 RangeLimits::HalfOpen
3373 let r = self.mk_range(None, opt_end, limits)?;
3374 Ok(self.mk_expr(lo.to(hi), r, attrs))
3377 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3378 if self.token.can_begin_expr() {
3379 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3380 if self.token == token::OpenDelim(token::Brace) {
3381 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3389 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3390 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3391 if self.check_keyword(keywords::Let) {
3392 return self.parse_if_let_expr(attrs);
3394 let lo = self.prev_span;
3395 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3397 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3398 // verify that the last statement is either an implicit return (no `;`) or an explicit
3399 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3400 // the dead code lint.
3401 if self.eat_keyword(keywords::Else) || !cond.returns() {
3402 let sp = self.sess.source_map().next_point(lo);
3403 let mut err = self.diagnostic()
3404 .struct_span_err(sp, "missing condition for `if` statemement");
3405 err.span_label(sp, "expected if condition here");
3408 let not_block = self.token != token::OpenDelim(token::Brace);
3409 let thn = self.parse_block().map_err(|mut err| {
3411 err.span_label(lo, "this `if` statement has a condition, but no block");
3415 let mut els: Option<P<Expr>> = None;
3416 let mut hi = thn.span;
3417 if self.eat_keyword(keywords::Else) {
3418 let elexpr = self.parse_else_expr()?;
3422 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3425 /// Parse an 'if let' expression ('if' token already eaten)
3426 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3427 -> PResult<'a, P<Expr>> {
3428 let lo = self.prev_span;
3429 self.expect_keyword(keywords::Let)?;
3430 let pats = self.parse_pats()?;
3431 self.expect(&token::Eq)?;
3432 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3433 let thn = self.parse_block()?;
3434 let (hi, els) = if self.eat_keyword(keywords::Else) {
3435 let expr = self.parse_else_expr()?;
3436 (expr.span, Some(expr))
3440 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3443 // `move |args| expr`
3444 fn parse_lambda_expr(&mut self,
3445 attrs: ThinVec<Attribute>)
3446 -> PResult<'a, P<Expr>>
3449 let movability = if self.eat_keyword(keywords::Static) {
3454 let asyncness = if self.span.rust_2018() {
3455 self.parse_asyncness()
3459 let capture_clause = if self.eat_keyword(keywords::Move) {
3464 let decl = self.parse_fn_block_decl()?;
3465 let decl_hi = self.prev_span;
3466 let body = match decl.output {
3467 FunctionRetTy::Default(_) => {
3468 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3469 self.parse_expr_res(restrictions, None)?
3472 // If an explicit return type is given, require a
3473 // block to appear (RFC 968).
3474 let body_lo = self.span;
3475 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3481 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3485 // `else` token already eaten
3486 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3487 if self.eat_keyword(keywords::If) {
3488 return self.parse_if_expr(ThinVec::new());
3490 let blk = self.parse_block()?;
3491 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3495 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3496 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3498 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3499 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3501 let pat = self.parse_top_level_pat()?;
3502 if !self.eat_keyword(keywords::In) {
3503 let in_span = self.prev_span.between(self.span);
3504 let mut err = self.sess.span_diagnostic
3505 .struct_span_err(in_span, "missing `in` in `for` loop");
3506 err.span_suggestion_short_with_applicability(
3507 in_span, "try adding `in` here", " in ".into(),
3508 // has been misleading, at least in the past (closed Issue #48492)
3509 Applicability::MaybeIncorrect
3513 let in_span = self.prev_span;
3514 if self.eat_keyword(keywords::In) {
3515 // a common typo: `for _ in in bar {}`
3516 let mut err = self.sess.span_diagnostic.struct_span_err(
3518 "expected iterable, found keyword `in`",
3520 err.span_suggestion_short_with_applicability(
3521 in_span.until(self.prev_span),
3522 "remove the duplicated `in`",
3524 Applicability::MachineApplicable,
3526 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3527 err.note("for more information on the status of emplacement syntax, see <\
3528 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3531 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3532 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3533 attrs.extend(iattrs);
3535 let hi = self.prev_span;
3536 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3539 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3540 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3542 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3543 if self.token.is_keyword(keywords::Let) {
3544 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3546 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3547 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3548 attrs.extend(iattrs);
3549 let span = span_lo.to(body.span);
3550 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3553 /// Parse a 'while let' expression ('while' token already eaten)
3554 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3556 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3557 self.expect_keyword(keywords::Let)?;
3558 let pats = self.parse_pats()?;
3559 self.expect(&token::Eq)?;
3560 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3561 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3562 attrs.extend(iattrs);
3563 let span = span_lo.to(body.span);
3564 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3567 // parse `loop {...}`, `loop` token already eaten
3568 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3570 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3571 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3572 attrs.extend(iattrs);
3573 let span = span_lo.to(body.span);
3574 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3577 /// Parse an `async move {...}` expression
3578 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3579 -> PResult<'a, P<Expr>>
3581 let span_lo = self.span;
3582 self.expect_keyword(keywords::Async)?;
3583 let capture_clause = if self.eat_keyword(keywords::Move) {
3588 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3589 attrs.extend(iattrs);
3591 span_lo.to(body.span),
3592 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3595 /// Parse a `try {...}` expression (`try` token already eaten)
3596 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3597 -> PResult<'a, P<Expr>>
3599 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3600 attrs.extend(iattrs);
3601 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3604 // `match` token already eaten
3605 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3606 let match_span = self.prev_span;
3607 let lo = self.prev_span;
3608 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3610 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3611 if self.token == token::Token::Semi {
3612 e.span_suggestion_short_with_applicability(
3614 "try removing this `match`",
3616 Applicability::MaybeIncorrect // speculative
3621 attrs.extend(self.parse_inner_attributes()?);
3623 let mut arms: Vec<Arm> = Vec::new();
3624 while self.token != token::CloseDelim(token::Brace) {
3625 match self.parse_arm() {
3626 Ok(arm) => arms.push(arm),
3628 // Recover by skipping to the end of the block.
3630 self.recover_stmt();
3631 let span = lo.to(self.span);
3632 if self.token == token::CloseDelim(token::Brace) {
3635 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3641 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3644 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3645 maybe_whole!(self, NtArm, |x| x);
3647 let attrs = self.parse_outer_attributes()?;
3648 // Allow a '|' before the pats (RFC 1925)
3649 self.eat(&token::BinOp(token::Or));
3650 let pats = self.parse_pats()?;
3651 let guard = if self.eat_keyword(keywords::If) {
3652 Some(Guard::If(self.parse_expr()?))
3656 let arrow_span = self.span;
3657 self.expect(&token::FatArrow)?;
3658 let arm_start_span = self.span;
3660 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3661 .map_err(|mut err| {
3662 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3666 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3667 && self.token != token::CloseDelim(token::Brace);
3670 let cm = self.sess.source_map();
3671 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3672 .map_err(|mut err| {
3673 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3674 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3675 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3676 && expr_lines.lines.len() == 2
3677 && self.token == token::FatArrow => {
3678 // We check whether there's any trailing code in the parse span,
3679 // if there isn't, we very likely have the following:
3682 // | -- - missing comma
3688 // | parsed until here as `"y" & X`
3689 err.span_suggestion_short_with_applicability(
3690 cm.next_point(arm_start_span),
3691 "missing a comma here to end this `match` arm",
3693 Applicability::MachineApplicable
3697 err.span_label(arrow_span,
3698 "while parsing the `match` arm starting here");
3704 self.eat(&token::Comma);
3715 /// Parse an expression
3717 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3718 self.parse_expr_res(Restrictions::empty(), None)
3721 /// Evaluate the closure with restrictions in place.
3723 /// After the closure is evaluated, restrictions are reset.
3724 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3725 where F: FnOnce(&mut Self) -> T
3727 let old = self.restrictions;
3728 self.restrictions = r;
3730 self.restrictions = old;
3735 /// Parse an expression, subject to the given restrictions
3737 fn parse_expr_res(&mut self, r: Restrictions,
3738 already_parsed_attrs: Option<ThinVec<Attribute>>)
3739 -> PResult<'a, P<Expr>> {
3740 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3743 /// Parse the RHS of a local variable declaration (e.g., '= 14;')
3744 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3745 if self.eat(&token::Eq) {
3746 Ok(Some(self.parse_expr()?))
3748 Ok(Some(self.parse_expr()?))
3754 /// Parse patterns, separated by '|' s
3755 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3756 let mut pats = Vec::new();
3758 pats.push(self.parse_top_level_pat()?);
3760 if self.token == token::OrOr {
3761 let mut err = self.struct_span_err(self.span,
3762 "unexpected token `||` after pattern");
3763 err.span_suggestion_with_applicability(
3765 "use a single `|` to specify multiple patterns",
3767 Applicability::MachineApplicable
3771 } else if self.eat(&token::BinOp(token::Or)) {
3779 // Parses a parenthesized list of patterns like
3780 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3781 // - a vector of the patterns that were parsed
3782 // - an option indicating the index of the `..` element
3783 // - a boolean indicating whether a trailing comma was present.
3784 // Trailing commas are significant because (p) and (p,) are different patterns.
3785 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3786 self.expect(&token::OpenDelim(token::Paren))?;
3787 let result = self.parse_pat_list()?;
3788 self.expect(&token::CloseDelim(token::Paren))?;
3792 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3793 let mut fields = Vec::new();
3794 let mut ddpos = None;
3795 let mut trailing_comma = false;
3797 if self.eat(&token::DotDot) {
3798 if ddpos.is_none() {
3799 ddpos = Some(fields.len());
3801 // Emit a friendly error, ignore `..` and continue parsing
3802 self.span_err(self.prev_span,
3803 "`..` can only be used once per tuple or tuple struct pattern");
3805 } else if !self.check(&token::CloseDelim(token::Paren)) {
3806 fields.push(self.parse_pat(None)?);
3811 trailing_comma = self.eat(&token::Comma);
3812 if !trailing_comma {
3817 if ddpos == Some(fields.len()) && trailing_comma {
3818 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3819 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3822 Ok((fields, ddpos, trailing_comma))
3825 fn parse_pat_vec_elements(
3827 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3828 let mut before = Vec::new();
3829 let mut slice = None;
3830 let mut after = Vec::new();
3831 let mut first = true;
3832 let mut before_slice = true;
3834 while self.token != token::CloseDelim(token::Bracket) {
3838 self.expect(&token::Comma)?;
3840 if self.token == token::CloseDelim(token::Bracket)
3841 && (before_slice || !after.is_empty()) {
3847 if self.eat(&token::DotDot) {
3849 if self.check(&token::Comma) ||
3850 self.check(&token::CloseDelim(token::Bracket)) {
3851 slice = Some(P(Pat {
3852 id: ast::DUMMY_NODE_ID,
3853 node: PatKind::Wild,
3854 span: self.prev_span,
3856 before_slice = false;
3862 let subpat = self.parse_pat(None)?;
3863 if before_slice && self.eat(&token::DotDot) {
3864 slice = Some(subpat);
3865 before_slice = false;
3866 } else if before_slice {
3867 before.push(subpat);
3873 Ok((before, slice, after))
3879 attrs: Vec<Attribute>
3880 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3881 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3883 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3884 // Parsing a pattern of the form "fieldname: pat"
3885 let fieldname = self.parse_field_name()?;
3887 let pat = self.parse_pat(None)?;
3889 (pat, fieldname, false)
3891 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3892 let is_box = self.eat_keyword(keywords::Box);
3893 let boxed_span = self.span;
3894 let is_ref = self.eat_keyword(keywords::Ref);
3895 let is_mut = self.eat_keyword(keywords::Mut);
3896 let fieldname = self.parse_ident()?;
3897 hi = self.prev_span;
3899 let bind_type = match (is_ref, is_mut) {
3900 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3901 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3902 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3903 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3905 let fieldpat = P(Pat {
3906 id: ast::DUMMY_NODE_ID,
3907 node: PatKind::Ident(bind_type, fieldname, None),
3908 span: boxed_span.to(hi),
3911 let subpat = if is_box {
3913 id: ast::DUMMY_NODE_ID,
3914 node: PatKind::Box(fieldpat),
3920 (subpat, fieldname, true)
3923 Ok(source_map::Spanned {
3925 node: ast::FieldPat {
3929 attrs: attrs.into(),
3934 /// Parse the fields of a struct-like pattern
3935 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3936 let mut fields = Vec::new();
3937 let mut etc = false;
3938 let mut ate_comma = true;
3939 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3940 let mut etc_span = None;
3942 while self.token != token::CloseDelim(token::Brace) {
3943 let attrs = self.parse_outer_attributes()?;
3946 // check that a comma comes after every field
3948 let err = self.struct_span_err(self.prev_span, "expected `,`");
3949 if let Some(mut delayed) = delayed_err {
3956 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3958 let mut etc_sp = self.span;
3960 if self.token == token::DotDotDot { // Issue #46718
3961 // Accept `...` as if it were `..` to avoid further errors
3962 let mut err = self.struct_span_err(self.span,
3963 "expected field pattern, found `...`");
3964 err.span_suggestion_with_applicability(
3966 "to omit remaining fields, use one fewer `.`",
3968 Applicability::MachineApplicable
3972 self.bump(); // `..` || `...`
3974 if self.token == token::CloseDelim(token::Brace) {
3975 etc_span = Some(etc_sp);
3978 let token_str = self.this_token_descr();
3979 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3981 err.span_label(self.span, "expected `}`");
3982 let mut comma_sp = None;
3983 if self.token == token::Comma { // Issue #49257
3984 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3985 err.span_label(etc_sp,
3986 "`..` must be at the end and cannot have a trailing comma");
3987 comma_sp = Some(self.span);
3992 etc_span = Some(etc_sp.until(self.span));
3993 if self.token == token::CloseDelim(token::Brace) {
3994 // If the struct looks otherwise well formed, recover and continue.
3995 if let Some(sp) = comma_sp {
3996 err.span_suggestion_short_with_applicability(
3998 "remove this comma",
4000 Applicability::MachineApplicable,
4005 } else if self.token.is_ident() && ate_comma {
4006 // Accept fields coming after `..,`.
4007 // This way we avoid "pattern missing fields" errors afterwards.
4008 // We delay this error until the end in order to have a span for a
4010 if let Some(mut delayed_err) = delayed_err {
4014 delayed_err = Some(err);
4017 if let Some(mut err) = delayed_err {
4024 fields.push(match self.parse_pat_field(lo, attrs) {
4027 if let Some(mut delayed_err) = delayed_err {
4033 ate_comma = self.eat(&token::Comma);
4036 if let Some(mut err) = delayed_err {
4037 if let Some(etc_span) = etc_span {
4038 err.multipart_suggestion(
4039 "move the `..` to the end of the field list",
4041 (etc_span, String::new()),
4042 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4048 return Ok((fields, etc));
4051 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4052 if self.token.is_path_start() {
4054 let (qself, path) = if self.eat_lt() {
4055 // Parse a qualified path
4056 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4059 // Parse an unqualified path
4060 (None, self.parse_path(PathStyle::Expr)?)
4062 let hi = self.prev_span;
4063 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4065 self.parse_literal_maybe_minus()
4069 // helper function to decide whether to parse as ident binding or to try to do
4070 // something more complex like range patterns
4071 fn parse_as_ident(&mut self) -> bool {
4072 self.look_ahead(1, |t| match *t {
4073 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4074 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4075 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4076 // range pattern branch
4077 token::DotDot => None,
4079 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4080 token::Comma | token::CloseDelim(token::Bracket) => true,
4085 /// A wrapper around `parse_pat` with some special error handling for the
4086 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4087 /// to subpatterns within such).
4088 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4089 let pat = self.parse_pat(None)?;
4090 if self.token == token::Comma {
4091 // An unexpected comma after a top-level pattern is a clue that the
4092 // user (perhaps more accustomed to some other language) forgot the
4093 // parentheses in what should have been a tuple pattern; return a
4094 // suggestion-enhanced error here rather than choking on the comma
4096 let comma_span = self.span;
4098 if let Err(mut err) = self.parse_pat_list() {
4099 // We didn't expect this to work anyway; we just wanted
4100 // to advance to the end of the comma-sequence so we know
4101 // the span to suggest parenthesizing
4104 let seq_span = pat.span.to(self.prev_span);
4105 let mut err = self.struct_span_err(comma_span,
4106 "unexpected `,` in pattern");
4107 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4108 err.span_suggestion_with_applicability(
4110 "try adding parentheses",
4111 format!("({})", seq_snippet),
4112 Applicability::MachineApplicable
4120 /// Parse a pattern.
4121 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4122 self.parse_pat_with_range_pat(true, expected)
4125 /// Parse a pattern, with a setting whether modern range patterns e.g., `a..=b`, `a..b` are
4127 fn parse_pat_with_range_pat(
4129 allow_range_pat: bool,
4130 expected: Option<&'static str>,
4131 ) -> PResult<'a, P<Pat>> {
4132 maybe_whole!(self, NtPat, |x| x);
4137 token::BinOp(token::And) | token::AndAnd => {
4138 // Parse &pat / &mut pat
4140 let mutbl = self.parse_mutability();
4141 if let token::Lifetime(ident) = self.token {
4142 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4144 err.span_label(self.span, "unexpected lifetime");
4147 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4148 pat = PatKind::Ref(subpat, mutbl);
4150 token::OpenDelim(token::Paren) => {
4151 // Parse (pat,pat,pat,...) as tuple pattern
4152 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4153 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4154 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4156 PatKind::Tuple(fields, ddpos)
4159 token::OpenDelim(token::Bracket) => {
4160 // Parse [pat,pat,...] as slice pattern
4162 let (before, slice, after) = self.parse_pat_vec_elements()?;
4163 self.expect(&token::CloseDelim(token::Bracket))?;
4164 pat = PatKind::Slice(before, slice, after);
4166 // At this point, token != &, &&, (, [
4167 _ => if self.eat_keyword(keywords::Underscore) {
4169 pat = PatKind::Wild;
4170 } else if self.eat_keyword(keywords::Mut) {
4171 // Parse mut ident @ pat / mut ref ident @ pat
4172 let mutref_span = self.prev_span.to(self.span);
4173 let binding_mode = if self.eat_keyword(keywords::Ref) {
4175 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4176 .span_suggestion_with_applicability(
4178 "try switching the order",
4180 Applicability::MachineApplicable
4182 BindingMode::ByRef(Mutability::Mutable)
4184 BindingMode::ByValue(Mutability::Mutable)
4186 pat = self.parse_pat_ident(binding_mode)?;
4187 } else if self.eat_keyword(keywords::Ref) {
4188 // Parse ref ident @ pat / ref mut ident @ pat
4189 let mutbl = self.parse_mutability();
4190 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4191 } else if self.eat_keyword(keywords::Box) {
4193 let subpat = self.parse_pat_with_range_pat(false, None)?;
4194 pat = PatKind::Box(subpat);
4195 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4196 self.parse_as_ident() {
4197 // Parse ident @ pat
4198 // This can give false positives and parse nullary enums,
4199 // they are dealt with later in resolve
4200 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4201 pat = self.parse_pat_ident(binding_mode)?;
4202 } else if self.token.is_path_start() {
4203 // Parse pattern starting with a path
4204 let (qself, path) = if self.eat_lt() {
4205 // Parse a qualified path
4206 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4209 // Parse an unqualified path
4210 (None, self.parse_path(PathStyle::Expr)?)
4213 token::Not if qself.is_none() => {
4214 // Parse macro invocation
4216 let (delim, tts) = self.expect_delimited_token_tree()?;
4217 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4218 pat = PatKind::Mac(mac);
4220 token::DotDotDot | token::DotDotEq | token::DotDot => {
4221 let end_kind = match self.token {
4222 token::DotDot => RangeEnd::Excluded,
4223 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4224 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4225 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4228 let op_span = self.span;
4230 let span = lo.to(self.prev_span);
4231 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4233 let end = self.parse_pat_range_end()?;
4234 let op = Spanned { span: op_span, node: end_kind };
4235 pat = PatKind::Range(begin, end, op);
4237 token::OpenDelim(token::Brace) => {
4238 if qself.is_some() {
4239 let msg = "unexpected `{` after qualified path";
4240 let mut err = self.fatal(msg);
4241 err.span_label(self.span, msg);
4244 // Parse struct pattern
4246 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4248 self.recover_stmt();
4252 pat = PatKind::Struct(path, fields, etc);
4254 token::OpenDelim(token::Paren) => {
4255 if qself.is_some() {
4256 let msg = "unexpected `(` after qualified path";
4257 let mut err = self.fatal(msg);
4258 err.span_label(self.span, msg);
4261 // Parse tuple struct or enum pattern
4262 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4263 pat = PatKind::TupleStruct(path, fields, ddpos)
4265 _ => pat = PatKind::Path(qself, path),
4268 // Try to parse everything else as literal with optional minus
4269 match self.parse_literal_maybe_minus() {
4271 let op_span = self.span;
4272 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4273 self.check(&token::DotDotDot) {
4274 let end_kind = if self.eat(&token::DotDotDot) {
4275 RangeEnd::Included(RangeSyntax::DotDotDot)
4276 } else if self.eat(&token::DotDotEq) {
4277 RangeEnd::Included(RangeSyntax::DotDotEq)
4278 } else if self.eat(&token::DotDot) {
4281 panic!("impossible case: we already matched \
4282 on a range-operator token")
4284 let end = self.parse_pat_range_end()?;
4285 let op = Spanned { span: op_span, node: end_kind };
4286 pat = PatKind::Range(begin, end, op);
4288 pat = PatKind::Lit(begin);
4292 self.cancel(&mut err);
4293 let expected = expected.unwrap_or("pattern");
4295 "expected {}, found {}",
4297 self.this_token_descr(),
4299 let mut err = self.fatal(&msg);
4300 err.span_label(self.span, format!("expected {}", expected));
4307 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4308 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4310 if !allow_range_pat {
4313 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4315 PatKind::Range(..) => {
4316 let mut err = self.struct_span_err(
4318 "the range pattern here has ambiguous interpretation",
4320 err.span_suggestion_with_applicability(
4322 "add parentheses to clarify the precedence",
4323 format!("({})", pprust::pat_to_string(&pat)),
4324 // "ambiguous interpretation" implies that we have to be guessing
4325 Applicability::MaybeIncorrect
4336 /// Parse ident or ident @ pat
4337 /// used by the copy foo and ref foo patterns to give a good
4338 /// error message when parsing mistakes like ref foo(a,b)
4339 fn parse_pat_ident(&mut self,
4340 binding_mode: ast::BindingMode)
4341 -> PResult<'a, PatKind> {
4342 let ident = self.parse_ident()?;
4343 let sub = if self.eat(&token::At) {
4344 Some(self.parse_pat(Some("binding pattern"))?)
4349 // just to be friendly, if they write something like
4351 // we end up here with ( as the current token. This shortly
4352 // leads to a parse error. Note that if there is no explicit
4353 // binding mode then we do not end up here, because the lookahead
4354 // will direct us over to parse_enum_variant()
4355 if self.token == token::OpenDelim(token::Paren) {
4356 return Err(self.span_fatal(
4358 "expected identifier, found enum pattern"))
4361 Ok(PatKind::Ident(binding_mode, ident, sub))
4364 /// Parse a local variable declaration
4365 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4366 let lo = self.prev_span;
4367 let pat = self.parse_top_level_pat()?;
4369 let (err, ty) = if self.eat(&token::Colon) {
4370 // Save the state of the parser before parsing type normally, in case there is a `:`
4371 // instead of an `=` typo.
4372 let parser_snapshot_before_type = self.clone();
4373 let colon_sp = self.prev_span;
4374 match self.parse_ty() {
4375 Ok(ty) => (None, Some(ty)),
4377 // Rewind to before attempting to parse the type and continue parsing
4378 let parser_snapshot_after_type = self.clone();
4379 mem::replace(self, parser_snapshot_before_type);
4381 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4382 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4383 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4389 let init = match (self.parse_initializer(err.is_some()), err) {
4390 (Ok(init), None) => { // init parsed, ty parsed
4393 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4394 // Could parse the type as if it were the initializer, it is likely there was a
4395 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4396 err.span_suggestion_short_with_applicability(
4398 "use `=` if you meant to assign",
4400 Applicability::MachineApplicable
4403 // As this was parsed successfully, continue as if the code has been fixed for the
4404 // rest of the file. It will still fail due to the emitted error, but we avoid
4408 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4410 // Couldn't parse the type nor the initializer, only raise the type error and
4411 // return to the parser state before parsing the type as the initializer.
4412 // let x: <parse_error>;
4413 mem::replace(self, snapshot);
4416 (Err(err), None) => { // init error, ty parsed
4417 // Couldn't parse the initializer and we're not attempting to recover a failed
4418 // parse of the type, return the error.
4422 let hi = if self.token == token::Semi {
4431 id: ast::DUMMY_NODE_ID,
4437 /// Parse a structure field
4438 fn parse_name_and_ty(&mut self,
4441 attrs: Vec<Attribute>)
4442 -> PResult<'a, StructField> {
4443 let name = self.parse_ident()?;
4444 self.expect(&token::Colon)?;
4445 let ty = self.parse_ty()?;
4447 span: lo.to(self.prev_span),
4450 id: ast::DUMMY_NODE_ID,
4456 /// Emit an expected item after attributes error.
4457 fn expected_item_err(&self, attrs: &[Attribute]) {
4458 let message = match attrs.last() {
4459 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4460 _ => "expected item after attributes",
4463 self.span_err(self.prev_span, message);
4466 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4467 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4468 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4469 Ok(self.parse_stmt_(true))
4472 // Eat tokens until we can be relatively sure we reached the end of the
4473 // statement. This is something of a best-effort heuristic.
4475 // We terminate when we find an unmatched `}` (without consuming it).
4476 fn recover_stmt(&mut self) {
4477 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4480 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4481 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4482 // approximate - it can mean we break too early due to macros, but that
4483 // should only lead to sub-optimal recovery, not inaccurate parsing).
4485 // If `break_on_block` is `Break`, then we will stop consuming tokens
4486 // after finding (and consuming) a brace-delimited block.
4487 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4488 let mut brace_depth = 0;
4489 let mut bracket_depth = 0;
4490 let mut in_block = false;
4491 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4492 break_on_semi, break_on_block);
4494 debug!("recover_stmt_ loop {:?}", self.token);
4496 token::OpenDelim(token::DelimToken::Brace) => {
4499 if break_on_block == BlockMode::Break &&
4501 bracket_depth == 0 {
4505 token::OpenDelim(token::DelimToken::Bracket) => {
4509 token::CloseDelim(token::DelimToken::Brace) => {
4510 if brace_depth == 0 {
4511 debug!("recover_stmt_ return - close delim {:?}", self.token);
4516 if in_block && bracket_depth == 0 && brace_depth == 0 {
4517 debug!("recover_stmt_ return - block end {:?}", self.token);
4521 token::CloseDelim(token::DelimToken::Bracket) => {
4523 if bracket_depth < 0 {
4529 debug!("recover_stmt_ return - Eof");
4534 if break_on_semi == SemiColonMode::Break &&
4536 bracket_depth == 0 {
4537 debug!("recover_stmt_ return - Semi");
4548 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4549 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4551 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4556 fn is_async_block(&mut self) -> bool {
4557 self.token.is_keyword(keywords::Async) &&
4560 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4561 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4563 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4568 fn is_do_catch_block(&mut self) -> bool {
4569 self.token.is_keyword(keywords::Do) &&
4570 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4571 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4572 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4575 fn is_try_block(&mut self) -> bool {
4576 self.token.is_keyword(keywords::Try) &&
4577 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4578 self.span.rust_2018() &&
4579 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4580 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4583 fn is_union_item(&self) -> bool {
4584 self.token.is_keyword(keywords::Union) &&
4585 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4588 fn is_crate_vis(&self) -> bool {
4589 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4592 fn is_extern_non_path(&self) -> bool {
4593 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4596 fn is_existential_type_decl(&self) -> bool {
4597 self.token.is_keyword(keywords::Existential) &&
4598 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4601 fn is_auto_trait_item(&mut self) -> bool {
4603 (self.token.is_keyword(keywords::Auto)
4604 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4605 || // unsafe auto trait
4606 (self.token.is_keyword(keywords::Unsafe) &&
4607 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4608 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4611 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4612 -> PResult<'a, Option<P<Item>>> {
4613 let token_lo = self.span;
4614 let (ident, def) = match self.token {
4615 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4617 let ident = self.parse_ident()?;
4618 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4619 match self.parse_token_tree() {
4620 TokenTree::Delimited(_, _, tts) => tts.stream(),
4621 _ => unreachable!(),
4623 } else if self.check(&token::OpenDelim(token::Paren)) {
4624 let args = self.parse_token_tree();
4625 let body = if self.check(&token::OpenDelim(token::Brace)) {
4626 self.parse_token_tree()
4631 TokenStream::new(vec![
4633 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4641 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4643 token::Ident(ident, _) if ident.name == "macro_rules" &&
4644 self.look_ahead(1, |t| *t == token::Not) => {
4645 let prev_span = self.prev_span;
4646 self.complain_if_pub_macro(&vis.node, prev_span);
4650 let ident = self.parse_ident()?;
4651 let (delim, tokens) = self.expect_delimited_token_tree()?;
4652 if delim != MacDelimiter::Brace {
4653 if !self.eat(&token::Semi) {
4654 let msg = "macros that expand to items must either \
4655 be surrounded with braces or followed by a semicolon";
4656 self.span_err(self.prev_span, msg);
4660 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4662 _ => return Ok(None),
4665 let span = lo.to(self.prev_span);
4666 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4669 fn parse_stmt_without_recovery(&mut self,
4670 macro_legacy_warnings: bool)
4671 -> PResult<'a, Option<Stmt>> {
4672 maybe_whole!(self, NtStmt, |x| Some(x));
4674 let attrs = self.parse_outer_attributes()?;
4677 Ok(Some(if self.eat_keyword(keywords::Let) {
4679 id: ast::DUMMY_NODE_ID,
4680 node: StmtKind::Local(self.parse_local(attrs.into())?),
4681 span: lo.to(self.prev_span),
4683 } else if let Some(macro_def) = self.eat_macro_def(
4685 &source_map::respan(lo, VisibilityKind::Inherited),
4689 id: ast::DUMMY_NODE_ID,
4690 node: StmtKind::Item(macro_def),
4691 span: lo.to(self.prev_span),
4693 // Starts like a simple path, being careful to avoid contextual keywords
4694 // such as a union items, item with `crate` visibility or auto trait items.
4695 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4696 // like a path (1 token), but it fact not a path.
4697 // `union::b::c` - path, `union U { ... }` - not a path.
4698 // `crate::b::c` - path, `crate struct S;` - not a path.
4699 // `extern::b::c` - path, `extern crate c;` - not a path.
4700 } else if self.token.is_path_start() &&
4701 !self.token.is_qpath_start() &&
4702 !self.is_union_item() &&
4703 !self.is_crate_vis() &&
4704 !self.is_extern_non_path() &&
4705 !self.is_existential_type_decl() &&
4706 !self.is_auto_trait_item() {
4707 let pth = self.parse_path(PathStyle::Expr)?;
4709 if !self.eat(&token::Not) {
4710 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4711 self.parse_struct_expr(lo, pth, ThinVec::new())?
4713 let hi = self.prev_span;
4714 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4717 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4718 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4719 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4722 return Ok(Some(Stmt {
4723 id: ast::DUMMY_NODE_ID,
4724 node: StmtKind::Expr(expr),
4725 span: lo.to(self.prev_span),
4729 // it's a macro invocation
4730 let id = match self.token {
4731 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4732 _ => self.parse_ident()?,
4735 // check that we're pointing at delimiters (need to check
4736 // again after the `if`, because of `parse_ident`
4737 // consuming more tokens).
4739 token::OpenDelim(_) => {}
4741 // we only expect an ident if we didn't parse one
4743 let ident_str = if id.name == keywords::Invalid.name() {
4748 let tok_str = self.this_token_descr();
4749 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4752 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4757 let (delim, tts) = self.expect_delimited_token_tree()?;
4758 let hi = self.prev_span;
4760 let style = if delim == MacDelimiter::Brace {
4761 MacStmtStyle::Braces
4763 MacStmtStyle::NoBraces
4766 if id.name == keywords::Invalid.name() {
4767 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4768 let node = if delim == MacDelimiter::Brace ||
4769 self.token == token::Semi || self.token == token::Eof {
4770 StmtKind::Mac(P((mac, style, attrs.into())))
4772 // We used to incorrectly stop parsing macro-expanded statements here.
4773 // If the next token will be an error anyway but could have parsed with the
4774 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4775 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4776 // These can continue an expression, so we can't stop parsing and warn.
4777 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4778 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4779 token::BinOp(token::And) | token::BinOp(token::Or) |
4780 token::AndAnd | token::OrOr |
4781 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4784 self.warn_missing_semicolon();
4785 StmtKind::Mac(P((mac, style, attrs.into())))
4787 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4788 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4789 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4793 id: ast::DUMMY_NODE_ID,
4798 // if it has a special ident, it's definitely an item
4800 // Require a semicolon or braces.
4801 if style != MacStmtStyle::Braces {
4802 if !self.eat(&token::Semi) {
4803 self.span_err(self.prev_span,
4804 "macros that expand to items must \
4805 either be surrounded with braces or \
4806 followed by a semicolon");
4809 let span = lo.to(hi);
4811 id: ast::DUMMY_NODE_ID,
4813 node: StmtKind::Item({
4815 span, id /*id is good here*/,
4816 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4817 respan(lo, VisibilityKind::Inherited),
4823 // FIXME: Bad copy of attrs
4824 let old_directory_ownership =
4825 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4826 let item = self.parse_item_(attrs.clone(), false, true)?;
4827 self.directory.ownership = old_directory_ownership;
4831 id: ast::DUMMY_NODE_ID,
4832 span: lo.to(i.span),
4833 node: StmtKind::Item(i),
4836 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4837 if !attrs.is_empty() {
4838 if s.prev_token_kind == PrevTokenKind::DocComment {
4839 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4840 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4841 s.span_err(s.span, "expected statement after outer attribute");
4846 // Do not attempt to parse an expression if we're done here.
4847 if self.token == token::Semi {
4848 unused_attrs(&attrs, self);
4853 if self.token == token::CloseDelim(token::Brace) {
4854 unused_attrs(&attrs, self);
4858 // Remainder are line-expr stmts.
4859 let e = self.parse_expr_res(
4860 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4862 id: ast::DUMMY_NODE_ID,
4863 span: lo.to(e.span),
4864 node: StmtKind::Expr(e),
4871 /// Is this expression a successfully-parsed statement?
4872 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4873 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4874 !classify::expr_requires_semi_to_be_stmt(e)
4877 /// Parse a block. No inner attrs are allowed.
4878 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4879 maybe_whole!(self, NtBlock, |x| x);
4883 if !self.eat(&token::OpenDelim(token::Brace)) {
4885 let tok = self.this_token_descr();
4886 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4887 let do_not_suggest_help =
4888 self.token.is_keyword(keywords::In) || self.token == token::Colon;
4890 if self.token.is_ident_named("and") {
4891 e.span_suggestion_short_with_applicability(
4893 "use `&&` instead of `and` for the boolean operator",
4895 Applicability::MaybeIncorrect,
4898 if self.token.is_ident_named("or") {
4899 e.span_suggestion_short_with_applicability(
4901 "use `||` instead of `or` for the boolean operator",
4903 Applicability::MaybeIncorrect,
4907 // Check to see if the user has written something like
4912 // Which is valid in other languages, but not Rust.
4913 match self.parse_stmt_without_recovery(false) {
4915 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4916 || do_not_suggest_help {
4917 // if the next token is an open brace (e.g., `if a b {`), the place-
4918 // inside-a-block suggestion would be more likely wrong than right
4919 e.span_label(sp, "expected `{`");
4922 let mut stmt_span = stmt.span;
4923 // expand the span to include the semicolon, if it exists
4924 if self.eat(&token::Semi) {
4925 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4927 let sugg = pprust::to_string(|s| {
4928 use print::pprust::{PrintState, INDENT_UNIT};
4929 s.ibox(INDENT_UNIT)?;
4931 s.print_stmt(&stmt)?;
4932 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4934 e.span_suggestion_with_applicability(
4936 "try placing this code inside a block",
4938 // speculative, has been misleading in the past (closed Issue #46836)
4939 Applicability::MaybeIncorrect
4943 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4944 self.cancel(&mut e);
4948 e.span_label(sp, "expected `{`");
4952 self.parse_block_tail(lo, BlockCheckMode::Default)
4955 /// Parse a block. Inner attrs are allowed.
4956 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4957 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4960 self.expect(&token::OpenDelim(token::Brace))?;
4961 Ok((self.parse_inner_attributes()?,
4962 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4965 /// Parse the rest of a block expression or function body
4966 /// Precondition: already parsed the '{'.
4967 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4968 let mut stmts = vec![];
4969 let mut recovered = false;
4971 while !self.eat(&token::CloseDelim(token::Brace)) {
4972 let stmt = match self.parse_full_stmt(false) {
4975 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4976 self.eat(&token::CloseDelim(token::Brace));
4982 if let Some(stmt) = stmt {
4984 } else if self.token == token::Eof {
4987 // Found only `;` or `}`.
4993 id: ast::DUMMY_NODE_ID,
4995 span: lo.to(self.prev_span),
5000 /// Parse a statement, including the trailing semicolon.
5001 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5002 // skip looking for a trailing semicolon when we have an interpolated statement
5003 maybe_whole!(self, NtStmt, |x| Some(x));
5005 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5007 None => return Ok(None),
5011 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5012 // expression without semicolon
5013 if classify::expr_requires_semi_to_be_stmt(expr) {
5014 // Just check for errors and recover; do not eat semicolon yet.
5016 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5019 self.recover_stmt();
5023 StmtKind::Local(..) => {
5024 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5025 if macro_legacy_warnings && self.token != token::Semi {
5026 self.warn_missing_semicolon();
5028 self.expect_one_of(&[], &[token::Semi])?;
5034 if self.eat(&token::Semi) {
5035 stmt = stmt.add_trailing_semicolon();
5038 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5042 fn warn_missing_semicolon(&self) {
5043 self.diagnostic().struct_span_warn(self.span, {
5044 &format!("expected `;`, found {}", self.this_token_descr())
5046 "This was erroneously allowed and will become a hard error in a future release"
5050 fn err_dotdotdot_syntax(&self, span: Span) {
5051 self.diagnostic().struct_span_err(span, {
5052 "unexpected token: `...`"
5053 }).span_suggestion_with_applicability(
5054 span, "use `..` for an exclusive range", "..".to_owned(),
5055 Applicability::MaybeIncorrect
5056 ).span_suggestion_with_applicability(
5057 span, "or `..=` for an inclusive range", "..=".to_owned(),
5058 Applicability::MaybeIncorrect
5062 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5063 // BOUND = TY_BOUND | LT_BOUND
5064 // LT_BOUND = LIFETIME (e.g., `'a`)
5065 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5066 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5067 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
5068 let mut bounds = Vec::new();
5070 // This needs to be synchronized with `Token::can_begin_bound`.
5071 let is_bound_start = self.check_path() || self.check_lifetime() ||
5072 self.check(&token::Question) ||
5073 self.check_keyword(keywords::For) ||
5074 self.check(&token::OpenDelim(token::Paren));
5077 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5078 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5079 if self.token.is_lifetime() {
5080 if let Some(question_span) = question {
5081 self.span_err(question_span,
5082 "`?` may only modify trait bounds, not lifetime bounds");
5084 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5086 self.expect(&token::CloseDelim(token::Paren))?;
5087 self.span_err(self.prev_span,
5088 "parenthesized lifetime bounds are not supported");
5091 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5092 let path = self.parse_path(PathStyle::Type)?;
5094 self.expect(&token::CloseDelim(token::Paren))?;
5096 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
5097 let modifier = if question.is_some() {
5098 TraitBoundModifier::Maybe
5100 TraitBoundModifier::None
5102 bounds.push(GenericBound::Trait(poly_trait, modifier));
5108 if !allow_plus || !self.eat_plus() {
5116 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
5117 self.parse_generic_bounds_common(true)
5120 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5121 // BOUND = LT_BOUND (e.g., `'a`)
5122 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5123 let mut lifetimes = Vec::new();
5124 while self.check_lifetime() {
5125 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5127 if !self.eat_plus() {
5134 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
5135 fn parse_ty_param(&mut self,
5136 preceding_attrs: Vec<Attribute>)
5137 -> PResult<'a, GenericParam> {
5138 let ident = self.parse_ident()?;
5140 // Parse optional colon and param bounds.
5141 let bounds = if self.eat(&token::Colon) {
5142 self.parse_generic_bounds()?
5147 let default = if self.eat(&token::Eq) {
5148 Some(self.parse_ty()?)
5155 id: ast::DUMMY_NODE_ID,
5156 attrs: preceding_attrs.into(),
5158 kind: GenericParamKind::Type {
5164 /// Parses the following grammar:
5165 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5166 fn parse_trait_item_assoc_ty(&mut self)
5167 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5168 let ident = self.parse_ident()?;
5169 let mut generics = self.parse_generics()?;
5171 // Parse optional colon and param bounds.
5172 let bounds = if self.eat(&token::Colon) {
5173 self.parse_generic_bounds()?
5177 generics.where_clause = self.parse_where_clause()?;
5179 let default = if self.eat(&token::Eq) {
5180 Some(self.parse_ty()?)
5184 self.expect(&token::Semi)?;
5186 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5189 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5190 /// trailing comma and erroneous trailing attributes.
5191 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5192 let mut lifetimes = Vec::new();
5193 let mut params = Vec::new();
5194 let mut seen_ty_param: Option<Span> = None;
5195 let mut last_comma_span = None;
5196 let mut bad_lifetime_pos = vec![];
5197 let mut suggestions = vec![];
5199 let attrs = self.parse_outer_attributes()?;
5200 if self.check_lifetime() {
5201 let lifetime = self.expect_lifetime();
5202 // Parse lifetime parameter.
5203 let bounds = if self.eat(&token::Colon) {
5204 self.parse_lt_param_bounds()
5208 lifetimes.push(ast::GenericParam {
5209 ident: lifetime.ident,
5211 attrs: attrs.into(),
5213 kind: ast::GenericParamKind::Lifetime,
5215 if let Some(sp) = seen_ty_param {
5216 let param_span = self.prev_span;
5217 let ate_comma = self.eat(&token::Comma);
5218 let remove_sp = if ate_comma {
5219 param_span.until(self.span)
5221 last_comma_span.unwrap_or(param_span).to(param_span)
5223 bad_lifetime_pos.push(param_span);
5225 if let Ok(snippet) = self.sess.source_map().span_to_snippet(param_span) {
5226 suggestions.push((remove_sp, String::new()));
5227 suggestions.push((sp.shrink_to_lo(), format!("{}, ", snippet)));
5230 last_comma_span = Some(self.prev_span);
5234 } else if self.check_ident() {
5235 // Parse type parameter.
5236 params.push(self.parse_ty_param(attrs)?);
5237 if seen_ty_param.is_none() {
5238 seen_ty_param = Some(self.prev_span);
5241 // Check for trailing attributes and stop parsing.
5242 if !attrs.is_empty() {
5243 let param_kind = if seen_ty_param.is_some() { "type" } else { "lifetime" };
5244 self.span_err(attrs[0].span,
5245 &format!("trailing attribute after {} parameters", param_kind));
5250 if !self.eat(&token::Comma) {
5253 last_comma_span = Some(self.prev_span);
5255 if !bad_lifetime_pos.is_empty() {
5256 let mut err = self.struct_span_err(
5258 "lifetime parameters must be declared prior to type parameters",
5260 if !suggestions.is_empty() {
5261 err.multipart_suggestion_with_applicability(
5262 "move the lifetime parameter prior to the first type parameter",
5264 Applicability::MachineApplicable,
5269 lifetimes.extend(params); // ensure the correct order of lifetimes and type params
5273 /// Parse a set of optional generic type parameter declarations. Where
5274 /// clauses are not parsed here, and must be added later via
5275 /// `parse_where_clause()`.
5277 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5278 /// | ( < lifetimes , typaramseq ( , )? > )
5279 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5280 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5281 maybe_whole!(self, NtGenerics, |x| x);
5283 let span_lo = self.span;
5285 let params = self.parse_generic_params()?;
5289 where_clause: WhereClause {
5290 id: ast::DUMMY_NODE_ID,
5291 predicates: Vec::new(),
5292 span: syntax_pos::DUMMY_SP,
5294 span: span_lo.to(self.prev_span),
5297 Ok(ast::Generics::default())
5301 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5302 /// possibly including trailing comma.
5303 fn parse_generic_args(&mut self)
5304 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5305 let mut args = Vec::new();
5306 let mut bindings = Vec::new();
5307 let mut seen_type = false;
5308 let mut seen_binding = false;
5310 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5311 // Parse lifetime argument.
5312 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5313 if seen_type || seen_binding {
5314 self.span_err(self.prev_span,
5315 "lifetime parameters must be declared prior to type parameters");
5317 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5318 // Parse associated type binding.
5320 let ident = self.parse_ident()?;
5322 let ty = self.parse_ty()?;
5323 bindings.push(TypeBinding {
5324 id: ast::DUMMY_NODE_ID,
5327 span: lo.to(self.prev_span),
5329 seen_binding = true;
5330 } else if self.check_type() {
5331 // Parse type argument.
5332 let ty_param = self.parse_ty()?;
5334 self.span_err(ty_param.span,
5335 "type parameters must be declared prior to associated type bindings");
5337 args.push(GenericArg::Type(ty_param));
5343 if !self.eat(&token::Comma) {
5347 Ok((args, bindings))
5350 /// Parses an optional `where` clause and places it in `generics`.
5352 /// ```ignore (only-for-syntax-highlight)
5353 /// where T : Trait<U, V> + 'b, 'a : 'b
5355 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5356 maybe_whole!(self, NtWhereClause, |x| x);
5358 let mut where_clause = WhereClause {
5359 id: ast::DUMMY_NODE_ID,
5360 predicates: Vec::new(),
5361 span: syntax_pos::DUMMY_SP,
5364 if !self.eat_keyword(keywords::Where) {
5365 return Ok(where_clause);
5367 let lo = self.prev_span;
5369 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5370 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5371 // change we parse those generics now, but report an error.
5372 if self.choose_generics_over_qpath() {
5373 let generics = self.parse_generics()?;
5374 self.span_err(generics.span,
5375 "generic parameters on `where` clauses are reserved for future use");
5380 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5381 let lifetime = self.expect_lifetime();
5382 // Bounds starting with a colon are mandatory, but possibly empty.
5383 self.expect(&token::Colon)?;
5384 let bounds = self.parse_lt_param_bounds();
5385 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5386 ast::WhereRegionPredicate {
5387 span: lo.to(self.prev_span),
5392 } else if self.check_type() {
5393 // Parse optional `for<'a, 'b>`.
5394 // This `for` is parsed greedily and applies to the whole predicate,
5395 // the bounded type can have its own `for` applying only to it.
5396 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5397 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5398 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5399 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5401 // Parse type with mandatory colon and (possibly empty) bounds,
5402 // or with mandatory equality sign and the second type.
5403 let ty = self.parse_ty()?;
5404 if self.eat(&token::Colon) {
5405 let bounds = self.parse_generic_bounds()?;
5406 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5407 ast::WhereBoundPredicate {
5408 span: lo.to(self.prev_span),
5409 bound_generic_params: lifetime_defs,
5414 // FIXME: Decide what should be used here, `=` or `==`.
5415 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5416 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5417 let rhs_ty = self.parse_ty()?;
5418 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5419 ast::WhereEqPredicate {
5420 span: lo.to(self.prev_span),
5423 id: ast::DUMMY_NODE_ID,
5427 return self.unexpected();
5433 if !self.eat(&token::Comma) {
5438 where_clause.span = lo.to(self.prev_span);
5442 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5443 -> PResult<'a, (Vec<Arg> , bool)> {
5444 self.expect(&token::OpenDelim(token::Paren))?;
5447 let mut variadic = false;
5448 let args: Vec<Option<Arg>> =
5449 self.parse_seq_to_before_end(
5450 &token::CloseDelim(token::Paren),
5451 SeqSep::trailing_allowed(token::Comma),
5453 if p.token == token::DotDotDot {
5457 if p.token != token::CloseDelim(token::Paren) {
5460 "`...` must be last in argument list for variadic function");
5464 let span = p.prev_span;
5465 if p.token == token::CloseDelim(token::Paren) {
5466 // continue parsing to present any further errors
5469 "only foreign functions are allowed to be variadic"
5471 Ok(Some(dummy_arg(span)))
5473 // this function definition looks beyond recovery, stop parsing
5475 "only foreign functions are allowed to be variadic");
5480 match p.parse_arg_general(named_args, false) {
5481 Ok(arg) => Ok(Some(arg)),
5484 let lo = p.prev_span;
5485 // Skip every token until next possible arg or end.
5486 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5487 // Create a placeholder argument for proper arg count (#34264).
5488 let span = lo.to(p.prev_span);
5489 Ok(Some(dummy_arg(span)))
5496 self.eat(&token::CloseDelim(token::Paren));
5498 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5500 if variadic && args.is_empty() {
5502 "variadic function must be declared with at least one named argument");
5505 Ok((args, variadic))
5508 /// Parse the argument list and result type of a function declaration
5509 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5511 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5512 let ret_ty = self.parse_ret_ty(true)?;
5521 /// Returns the parsed optional self argument and whether a self shortcut was used.
5522 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5523 let expect_ident = |this: &mut Self| match this.token {
5524 // Preserve hygienic context.
5525 token::Ident(ident, _) =>
5526 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5529 let isolated_self = |this: &mut Self, n| {
5530 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
5531 this.look_ahead(n + 1, |t| t != &token::ModSep)
5534 // Parse optional self parameter of a method.
5535 // Only a limited set of initial token sequences is considered self parameters, anything
5536 // else is parsed as a normal function parameter list, so some lookahead is required.
5537 let eself_lo = self.span;
5538 let (eself, eself_ident, eself_hi) = match self.token {
5539 token::BinOp(token::And) => {
5545 (if isolated_self(self, 1) {
5547 SelfKind::Region(None, Mutability::Immutable)
5548 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5549 isolated_self(self, 2) {
5552 SelfKind::Region(None, Mutability::Mutable)
5553 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5554 isolated_self(self, 2) {
5556 let lt = self.expect_lifetime();
5557 SelfKind::Region(Some(lt), Mutability::Immutable)
5558 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5559 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5560 isolated_self(self, 3) {
5562 let lt = self.expect_lifetime();
5564 SelfKind::Region(Some(lt), Mutability::Mutable)
5567 }, expect_ident(self), self.prev_span)
5569 token::BinOp(token::Star) => {
5574 // Emit special error for `self` cases.
5575 (if isolated_self(self, 1) {
5577 self.span_err(self.span, "cannot pass `self` by raw pointer");
5578 SelfKind::Value(Mutability::Immutable)
5579 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5580 isolated_self(self, 2) {
5583 self.span_err(self.span, "cannot pass `self` by raw pointer");
5584 SelfKind::Value(Mutability::Immutable)
5587 }, expect_ident(self), self.prev_span)
5589 token::Ident(..) => {
5590 if isolated_self(self, 0) {
5593 let eself_ident = expect_ident(self);
5594 let eself_hi = self.prev_span;
5595 (if self.eat(&token::Colon) {
5596 let ty = self.parse_ty()?;
5597 SelfKind::Explicit(ty, Mutability::Immutable)
5599 SelfKind::Value(Mutability::Immutable)
5600 }, eself_ident, eself_hi)
5601 } else if self.token.is_keyword(keywords::Mut) &&
5602 isolated_self(self, 1) {
5606 let eself_ident = expect_ident(self);
5607 let eself_hi = self.prev_span;
5608 (if self.eat(&token::Colon) {
5609 let ty = self.parse_ty()?;
5610 SelfKind::Explicit(ty, Mutability::Mutable)
5612 SelfKind::Value(Mutability::Mutable)
5613 }, eself_ident, eself_hi)
5618 _ => return Ok(None),
5621 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5622 Ok(Some(Arg::from_self(eself, eself_ident)))
5625 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5626 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5627 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5629 self.expect(&token::OpenDelim(token::Paren))?;
5631 // Parse optional self argument
5632 let self_arg = self.parse_self_arg()?;
5634 // Parse the rest of the function parameter list.
5635 let sep = SeqSep::trailing_allowed(token::Comma);
5636 let fn_inputs = if let Some(self_arg) = self_arg {
5637 if self.check(&token::CloseDelim(token::Paren)) {
5639 } else if self.eat(&token::Comma) {
5640 let mut fn_inputs = vec![self_arg];
5641 fn_inputs.append(&mut self.parse_seq_to_before_end(
5642 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5646 return self.unexpected();
5649 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5652 // Parse closing paren and return type.
5653 self.expect(&token::CloseDelim(token::Paren))?;
5656 output: self.parse_ret_ty(true)?,
5661 // parse the |arg, arg| header on a lambda
5662 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5663 let inputs_captures = {
5664 if self.eat(&token::OrOr) {
5667 self.expect(&token::BinOp(token::Or))?;
5668 let args = self.parse_seq_to_before_tokens(
5669 &[&token::BinOp(token::Or), &token::OrOr],
5670 SeqSep::trailing_allowed(token::Comma),
5671 TokenExpectType::NoExpect,
5672 |p| p.parse_fn_block_arg()
5678 let output = self.parse_ret_ty(true)?;
5681 inputs: inputs_captures,
5687 /// Parse the name and optional generic types of a function header.
5688 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5689 let id = self.parse_ident()?;
5690 let generics = self.parse_generics()?;
5694 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5695 attrs: Vec<Attribute>) -> P<Item> {
5699 id: ast::DUMMY_NODE_ID,
5707 /// Parse an item-position function declaration.
5708 fn parse_item_fn(&mut self,
5711 constness: Spanned<Constness>,
5713 -> PResult<'a, ItemInfo> {
5714 let (ident, mut generics) = self.parse_fn_header()?;
5715 let decl = self.parse_fn_decl(false)?;
5716 generics.where_clause = self.parse_where_clause()?;
5717 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5718 let header = FnHeader { unsafety, asyncness, constness, abi };
5719 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5722 /// true if we are looking at `const ID`, false for things like `const fn` etc
5723 fn is_const_item(&mut self) -> bool {
5724 self.token.is_keyword(keywords::Const) &&
5725 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5726 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5729 /// parses all the "front matter" for a `fn` declaration, up to
5730 /// and including the `fn` keyword:
5734 /// - `const unsafe fn`
5737 fn parse_fn_front_matter(&mut self)
5745 let is_const_fn = self.eat_keyword(keywords::Const);
5746 let const_span = self.prev_span;
5747 let unsafety = self.parse_unsafety();
5748 let asyncness = self.parse_asyncness();
5749 let (constness, unsafety, abi) = if is_const_fn {
5750 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5752 let abi = if self.eat_keyword(keywords::Extern) {
5753 self.parse_opt_abi()?.unwrap_or(Abi::C)
5757 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5759 self.expect_keyword(keywords::Fn)?;
5760 Ok((constness, unsafety, asyncness, abi))
5763 /// Parse an impl item.
5764 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5765 maybe_whole!(self, NtImplItem, |x| x);
5766 let attrs = self.parse_outer_attributes()?;
5767 let (mut item, tokens) = self.collect_tokens(|this| {
5768 this.parse_impl_item_(at_end, attrs)
5771 // See `parse_item` for why this clause is here.
5772 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5773 item.tokens = Some(tokens);
5778 fn parse_impl_item_(&mut self,
5780 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5782 let vis = self.parse_visibility(false)?;
5783 let defaultness = self.parse_defaultness();
5784 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5785 let (name, alias, generics) = type_?;
5786 let kind = match alias {
5787 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5788 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5790 (name, kind, generics)
5791 } else if self.is_const_item() {
5792 // This parses the grammar:
5793 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5794 self.expect_keyword(keywords::Const)?;
5795 let name = self.parse_ident()?;
5796 self.expect(&token::Colon)?;
5797 let typ = self.parse_ty()?;
5798 self.expect(&token::Eq)?;
5799 let expr = self.parse_expr()?;
5800 self.expect(&token::Semi)?;
5801 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5803 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5804 attrs.extend(inner_attrs);
5805 (name, node, generics)
5809 id: ast::DUMMY_NODE_ID,
5810 span: lo.to(self.prev_span),
5821 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5823 VisibilityKind::Inherited => {}
5825 let is_macro_rules: bool = match self.token {
5826 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5829 let mut err = if is_macro_rules {
5830 let mut err = self.diagnostic()
5831 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5832 err.span_suggestion_with_applicability(
5834 "try exporting the macro",
5835 "#[macro_export]".to_owned(),
5836 Applicability::MaybeIncorrect // speculative
5840 let mut err = self.diagnostic()
5841 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5842 err.help("try adjusting the macro to put `pub` inside the invocation");
5850 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5851 -> DiagnosticBuilder<'a>
5853 let expected_kinds = if item_type == "extern" {
5854 "missing `fn`, `type`, or `static`"
5856 "missing `fn`, `type`, or `const`"
5859 // Given this code `path(`, it seems like this is not
5860 // setting the visibility of a macro invocation, but rather
5861 // a mistyped method declaration.
5862 // Create a diagnostic pointing out that `fn` is missing.
5864 // x | pub path(&self) {
5865 // | ^ missing `fn`, `type`, or `const`
5867 // ^^ `sp` below will point to this
5868 let sp = prev_span.between(self.prev_span);
5869 let mut err = self.diagnostic().struct_span_err(
5871 &format!("{} for {}-item declaration",
5872 expected_kinds, item_type));
5873 err.span_label(sp, expected_kinds);
5877 /// Parse a method or a macro invocation in a trait impl.
5878 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5879 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5880 ast::ImplItemKind)> {
5881 // code copied from parse_macro_use_or_failure... abstraction!
5882 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5884 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5885 ast::ImplItemKind::Macro(mac)))
5887 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5888 let ident = self.parse_ident()?;
5889 let mut generics = self.parse_generics()?;
5890 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5891 generics.where_clause = self.parse_where_clause()?;
5893 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5894 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5895 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5896 ast::MethodSig { header, decl },
5902 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5903 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5904 let ident = self.parse_ident()?;
5905 let mut tps = self.parse_generics()?;
5907 // Parse optional colon and supertrait bounds.
5908 let bounds = if self.eat(&token::Colon) {
5909 self.parse_generic_bounds()?
5914 if self.eat(&token::Eq) {
5915 // it's a trait alias
5916 let bounds = self.parse_generic_bounds()?;
5917 tps.where_clause = self.parse_where_clause()?;
5918 self.expect(&token::Semi)?;
5919 if unsafety != Unsafety::Normal {
5920 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5922 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5924 // it's a normal trait
5925 tps.where_clause = self.parse_where_clause()?;
5926 self.expect(&token::OpenDelim(token::Brace))?;
5927 let mut trait_items = vec![];
5928 while !self.eat(&token::CloseDelim(token::Brace)) {
5929 let mut at_end = false;
5930 match self.parse_trait_item(&mut at_end) {
5931 Ok(item) => trait_items.push(item),
5935 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5940 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5944 fn choose_generics_over_qpath(&self) -> bool {
5945 // There's an ambiguity between generic parameters and qualified paths in impls.
5946 // If we see `<` it may start both, so we have to inspect some following tokens.
5947 // The following combinations can only start generics,
5948 // but not qualified paths (with one exception):
5949 // `<` `>` - empty generic parameters
5950 // `<` `#` - generic parameters with attributes
5951 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5952 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5953 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5954 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5955 // The only truly ambiguous case is
5956 // `<` IDENT `>` `::` IDENT ...
5957 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5958 // because this is what almost always expected in practice, qualified paths in impls
5959 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5960 self.token == token::Lt &&
5961 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5962 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5963 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5964 t == &token::Colon || t == &token::Eq))
5967 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5968 self.expect(&token::OpenDelim(token::Brace))?;
5969 let attrs = self.parse_inner_attributes()?;
5971 let mut impl_items = Vec::new();
5972 while !self.eat(&token::CloseDelim(token::Brace)) {
5973 let mut at_end = false;
5974 match self.parse_impl_item(&mut at_end) {
5975 Ok(impl_item) => impl_items.push(impl_item),
5979 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5984 Ok((impl_items, attrs))
5987 /// Parses an implementation item, `impl` keyword is already parsed.
5988 /// impl<'a, T> TYPE { /* impl items */ }
5989 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5990 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5991 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5992 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5993 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5994 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5995 -> PResult<'a, ItemInfo> {
5996 // First, parse generic parameters if necessary.
5997 let mut generics = if self.choose_generics_over_qpath() {
5998 self.parse_generics()?
6000 ast::Generics::default()
6003 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6004 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6006 ast::ImplPolarity::Negative
6008 ast::ImplPolarity::Positive
6011 // Parse both types and traits as a type, then reinterpret if necessary.
6012 let ty_first = self.parse_ty()?;
6014 // If `for` is missing we try to recover.
6015 let has_for = self.eat_keyword(keywords::For);
6016 let missing_for_span = self.prev_span.between(self.span);
6018 let ty_second = if self.token == token::DotDot {
6019 // We need to report this error after `cfg` expansion for compatibility reasons
6020 self.bump(); // `..`, do not add it to expected tokens
6021 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
6022 } else if has_for || self.token.can_begin_type() {
6023 Some(self.parse_ty()?)
6028 generics.where_clause = self.parse_where_clause()?;
6030 let (impl_items, attrs) = self.parse_impl_body()?;
6032 let item_kind = match ty_second {
6033 Some(ty_second) => {
6034 // impl Trait for Type
6036 self.span_err(missing_for_span, "missing `for` in a trait impl");
6039 let ty_first = ty_first.into_inner();
6040 let path = match ty_first.node {
6041 // This notably includes paths passed through `ty` macro fragments (#46438).
6042 TyKind::Path(None, path) => path,
6044 self.span_err(ty_first.span, "expected a trait, found type");
6045 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
6048 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6050 ItemKind::Impl(unsafety, polarity, defaultness,
6051 generics, Some(trait_ref), ty_second, impl_items)
6055 ItemKind::Impl(unsafety, polarity, defaultness,
6056 generics, None, ty_first, impl_items)
6060 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6063 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6064 if self.eat_keyword(keywords::For) {
6066 let params = self.parse_generic_params()?;
6068 // We rely on AST validation to rule out invalid cases: There must not be type
6069 // parameters, and the lifetime parameters must not have bounds.
6076 /// Parse struct Foo { ... }
6077 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6078 let class_name = self.parse_ident()?;
6080 let mut generics = self.parse_generics()?;
6082 // There is a special case worth noting here, as reported in issue #17904.
6083 // If we are parsing a tuple struct it is the case that the where clause
6084 // should follow the field list. Like so:
6086 // struct Foo<T>(T) where T: Copy;
6088 // If we are parsing a normal record-style struct it is the case
6089 // that the where clause comes before the body, and after the generics.
6090 // So if we look ahead and see a brace or a where-clause we begin
6091 // parsing a record style struct.
6093 // Otherwise if we look ahead and see a paren we parse a tuple-style
6096 let vdata = if self.token.is_keyword(keywords::Where) {
6097 generics.where_clause = self.parse_where_clause()?;
6098 if self.eat(&token::Semi) {
6099 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6100 VariantData::Unit(ast::DUMMY_NODE_ID)
6102 // If we see: `struct Foo<T> where T: Copy { ... }`
6103 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6105 // No `where` so: `struct Foo<T>;`
6106 } else if self.eat(&token::Semi) {
6107 VariantData::Unit(ast::DUMMY_NODE_ID)
6108 // Record-style struct definition
6109 } else if self.token == token::OpenDelim(token::Brace) {
6110 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6111 // Tuple-style struct definition with optional where-clause.
6112 } else if self.token == token::OpenDelim(token::Paren) {
6113 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6114 generics.where_clause = self.parse_where_clause()?;
6115 self.expect(&token::Semi)?;
6118 let token_str = self.this_token_descr();
6119 let mut err = self.fatal(&format!(
6120 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6123 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6127 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6130 /// Parse union Foo { ... }
6131 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6132 let class_name = self.parse_ident()?;
6134 let mut generics = self.parse_generics()?;
6136 let vdata = if self.token.is_keyword(keywords::Where) {
6137 generics.where_clause = self.parse_where_clause()?;
6138 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6139 } else if self.token == token::OpenDelim(token::Brace) {
6140 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6142 let token_str = self.this_token_descr();
6143 let mut err = self.fatal(&format!(
6144 "expected `where` or `{{` after union name, found {}", token_str));
6145 err.span_label(self.span, "expected `where` or `{` after union name");
6149 Ok((class_name, ItemKind::Union(vdata, generics), None))
6152 fn consume_block(&mut self, delim: token::DelimToken) {
6153 let mut brace_depth = 0;
6155 if self.eat(&token::OpenDelim(delim)) {
6157 } else if self.eat(&token::CloseDelim(delim)) {
6158 if brace_depth == 0 {
6164 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6172 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6173 let mut fields = Vec::new();
6174 if self.eat(&token::OpenDelim(token::Brace)) {
6175 while self.token != token::CloseDelim(token::Brace) {
6176 let field = self.parse_struct_decl_field().map_err(|e| {
6177 self.recover_stmt();
6181 Ok(field) => fields.push(field),
6187 self.eat(&token::CloseDelim(token::Brace));
6189 let token_str = self.this_token_descr();
6190 let mut err = self.fatal(&format!(
6191 "expected `where`, or `{{` after struct name, found {}", token_str));
6192 err.span_label(self.span, "expected `where`, or `{` after struct name");
6199 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6200 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6201 // Unit like structs are handled in parse_item_struct function
6202 let fields = self.parse_unspanned_seq(
6203 &token::OpenDelim(token::Paren),
6204 &token::CloseDelim(token::Paren),
6205 SeqSep::trailing_allowed(token::Comma),
6207 let attrs = p.parse_outer_attributes()?;
6209 let vis = p.parse_visibility(true)?;
6210 let ty = p.parse_ty()?;
6212 span: lo.to(ty.span),
6215 id: ast::DUMMY_NODE_ID,
6224 /// Parse a structure field declaration
6225 fn parse_single_struct_field(&mut self,
6228 attrs: Vec<Attribute> )
6229 -> PResult<'a, StructField> {
6230 let mut seen_comma: bool = false;
6231 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6232 if self.token == token::Comma {
6239 token::CloseDelim(token::Brace) => {}
6240 token::DocComment(_) => {
6241 let previous_span = self.prev_span;
6242 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6243 self.bump(); // consume the doc comment
6244 let comma_after_doc_seen = self.eat(&token::Comma);
6245 // `seen_comma` is always false, because we are inside doc block
6246 // condition is here to make code more readable
6247 if seen_comma == false && comma_after_doc_seen == true {
6250 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6253 if seen_comma == false {
6254 let sp = self.sess.source_map().next_point(previous_span);
6255 err.span_suggestion_with_applicability(
6257 "missing comma here",
6259 Applicability::MachineApplicable
6266 let sp = self.sess.source_map().next_point(self.prev_span);
6267 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6268 self.this_token_descr()));
6269 if self.token.is_ident() {
6270 // This is likely another field; emit the diagnostic and keep going
6271 err.span_suggestion_with_applicability(
6273 "try adding a comma",
6275 Applicability::MachineApplicable,
6286 /// Parse an element of a struct definition
6287 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6288 let attrs = self.parse_outer_attributes()?;
6290 let vis = self.parse_visibility(false)?;
6291 self.parse_single_struct_field(lo, vis, attrs)
6294 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6295 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6296 /// If the following element can't be a tuple (i.e., it's a function definition,
6297 /// it's not a tuple struct field) and the contents within the parens
6298 /// isn't valid, emit a proper diagnostic.
6299 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6300 maybe_whole!(self, NtVis, |x| x);
6302 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6303 if self.is_crate_vis() {
6304 self.bump(); // `crate`
6305 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6308 if !self.eat_keyword(keywords::Pub) {
6309 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6310 // keyword to grab a span from for inherited visibility; an empty span at the
6311 // beginning of the current token would seem to be the "Schelling span".
6312 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6314 let lo = self.prev_span;
6316 if self.check(&token::OpenDelim(token::Paren)) {
6317 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6318 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6319 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6320 // by the following tokens.
6321 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6324 self.bump(); // `crate`
6325 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6327 lo.to(self.prev_span),
6328 VisibilityKind::Crate(CrateSugar::PubCrate),
6331 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6334 self.bump(); // `in`
6335 let path = self.parse_path(PathStyle::Mod)?; // `path`
6336 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6337 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6339 id: ast::DUMMY_NODE_ID,
6342 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6343 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6344 t.is_keyword(keywords::SelfLower))
6346 // `pub(self)` or `pub(super)`
6348 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6349 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6350 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6352 id: ast::DUMMY_NODE_ID,
6355 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6356 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6358 let msg = "incorrect visibility restriction";
6359 let suggestion = r##"some possible visibility restrictions are:
6360 `pub(crate)`: visible only on the current crate
6361 `pub(super)`: visible only in the current module's parent
6362 `pub(in path::to::module)`: visible only on the specified path"##;
6363 let path = self.parse_path(PathStyle::Mod)?;
6364 let sp = self.prev_span;
6365 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6366 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6367 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6368 err.help(suggestion);
6369 err.span_suggestion_with_applicability(
6370 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6372 err.emit(); // emit diagnostic, but continue with public visibility
6376 Ok(respan(lo, VisibilityKind::Public))
6379 /// Parse defaultness: `default` or nothing.
6380 fn parse_defaultness(&mut self) -> Defaultness {
6381 // `pub` is included for better error messages
6382 if self.check_keyword(keywords::Default) &&
6383 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6384 t.is_keyword(keywords::Const) ||
6385 t.is_keyword(keywords::Fn) ||
6386 t.is_keyword(keywords::Unsafe) ||
6387 t.is_keyword(keywords::Extern) ||
6388 t.is_keyword(keywords::Type) ||
6389 t.is_keyword(keywords::Pub)) {
6390 self.bump(); // `default`
6391 Defaultness::Default
6397 /// Given a termination token, parse all of the items in a module
6398 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6399 let mut items = vec![];
6400 while let Some(item) = self.parse_item()? {
6404 if !self.eat(term) {
6405 let token_str = self.this_token_descr();
6406 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6407 if self.token == token::Semi {
6408 let msg = "consider removing this semicolon";
6409 err.span_suggestion_short_with_applicability(
6410 self.span, msg, String::new(), Applicability::MachineApplicable
6412 if !items.is_empty() { // Issue #51603
6413 let previous_item = &items[items.len()-1];
6414 let previous_item_kind_name = match previous_item.node {
6415 // say "braced struct" because tuple-structs and
6416 // braceless-empty-struct declarations do take a semicolon
6417 ItemKind::Struct(..) => Some("braced struct"),
6418 ItemKind::Enum(..) => Some("enum"),
6419 ItemKind::Trait(..) => Some("trait"),
6420 ItemKind::Union(..) => Some("union"),
6423 if let Some(name) = previous_item_kind_name {
6424 err.help(&format!("{} declarations are not followed by a semicolon",
6429 err.span_label(self.span, "expected item");
6434 let hi = if self.span.is_dummy() {
6441 inner: inner_lo.to(hi),
6447 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6448 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6449 self.expect(&token::Colon)?;
6450 let ty = self.parse_ty()?;
6451 self.expect(&token::Eq)?;
6452 let e = self.parse_expr()?;
6453 self.expect(&token::Semi)?;
6454 let item = match m {
6455 Some(m) => ItemKind::Static(ty, m, e),
6456 None => ItemKind::Const(ty, e),
6458 Ok((id, item, None))
6461 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6462 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6463 let (in_cfg, outer_attrs) = {
6464 let mut strip_unconfigured = ::config::StripUnconfigured {
6466 features: None, // don't perform gated feature checking
6468 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
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(Ident::from_str("warn_directory_ownership")),
6487 tokens: TokenStream::empty(),
6488 is_sugared_doc: false,
6489 span: syntax_pos::DUMMY_SP,
6491 attr::mark_known(&attr);
6494 Ok((id, ItemKind::Mod(module), Some(attrs)))
6496 let placeholder = ast::Mod {
6497 inner: syntax_pos::DUMMY_SP,
6501 Ok((id, ItemKind::Mod(placeholder), None))
6504 let old_directory = self.directory.clone();
6505 self.push_directory(id, &outer_attrs);
6507 self.expect(&token::OpenDelim(token::Brace))?;
6508 let mod_inner_lo = self.span;
6509 let attrs = self.parse_inner_attributes()?;
6510 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6512 self.directory = old_directory;
6513 Ok((id, ItemKind::Mod(module), Some(attrs)))
6517 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6518 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6519 self.directory.path.to_mut().push(&path.as_str());
6520 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6522 // We have to push on the current module name in the case of relative
6523 // paths in order to ensure that any additional module paths from inline
6524 // `mod x { ... }` come after the relative extension.
6526 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6527 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6528 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6529 if let Some(ident) = relative.take() { // remove the relative offset
6530 self.directory.path.to_mut().push(ident.as_str());
6533 self.directory.path.to_mut().push(&id.as_str());
6537 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6538 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6541 // On windows, the base path might have the form
6542 // `\\?\foo\bar` in which case it does not tolerate
6543 // mixed `/` and `\` separators, so canonicalize
6546 let s = s.replace("/", "\\");
6547 Some(dir_path.join(s))
6553 /// Returns either a path to a module, or .
6554 pub fn default_submod_path(
6556 relative: Option<ast::Ident>,
6558 source_map: &SourceMap) -> ModulePath
6560 // If we're in a foo.rs file instead of a mod.rs file,
6561 // we need to look for submodules in
6562 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6563 // `./<id>.rs` and `./<id>/mod.rs`.
6564 let relative_prefix_string;
6565 let relative_prefix = if let Some(ident) = relative {
6566 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6567 &relative_prefix_string
6572 let mod_name = id.to_string();
6573 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6574 let secondary_path_str = format!("{}{}{}mod.rs",
6575 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6576 let default_path = dir_path.join(&default_path_str);
6577 let secondary_path = dir_path.join(&secondary_path_str);
6578 let default_exists = source_map.file_exists(&default_path);
6579 let secondary_exists = source_map.file_exists(&secondary_path);
6581 let result = match (default_exists, secondary_exists) {
6582 (true, false) => Ok(ModulePathSuccess {
6584 directory_ownership: DirectoryOwnership::Owned {
6589 (false, true) => Ok(ModulePathSuccess {
6590 path: secondary_path,
6591 directory_ownership: DirectoryOwnership::Owned {
6596 (false, false) => Err(Error::FileNotFoundForModule {
6597 mod_name: mod_name.clone(),
6598 default_path: default_path_str,
6599 secondary_path: secondary_path_str,
6600 dir_path: dir_path.display().to_string(),
6602 (true, true) => Err(Error::DuplicatePaths {
6603 mod_name: mod_name.clone(),
6604 default_path: default_path_str,
6605 secondary_path: secondary_path_str,
6611 path_exists: default_exists || secondary_exists,
6616 fn submod_path(&mut self,
6618 outer_attrs: &[Attribute],
6620 -> PResult<'a, ModulePathSuccess> {
6621 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6622 return Ok(ModulePathSuccess {
6623 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6624 // All `#[path]` files are treated as though they are a `mod.rs` file.
6625 // This means that `mod foo;` declarations inside `#[path]`-included
6626 // files are siblings,
6628 // Note that this will produce weirdness when a file named `foo.rs` is
6629 // `#[path]` included and contains a `mod foo;` declaration.
6630 // If you encounter this, it's your own darn fault :P
6631 Some(_) => DirectoryOwnership::Owned { relative: None },
6632 _ => DirectoryOwnership::UnownedViaMod(true),
6639 let relative = match self.directory.ownership {
6640 DirectoryOwnership::Owned { relative } => relative,
6641 DirectoryOwnership::UnownedViaBlock |
6642 DirectoryOwnership::UnownedViaMod(_) => None,
6644 let paths = Parser::default_submod_path(
6645 id, relative, &self.directory.path, self.sess.source_map());
6647 match self.directory.ownership {
6648 DirectoryOwnership::Owned { .. } => {
6649 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6651 DirectoryOwnership::UnownedViaBlock => {
6653 "Cannot declare a non-inline module inside a block \
6654 unless it has a path attribute";
6655 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6656 if paths.path_exists {
6657 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6659 err.span_note(id_sp, &msg);
6663 DirectoryOwnership::UnownedViaMod(warn) => {
6665 if let Ok(result) = paths.result {
6666 return Ok(ModulePathSuccess { warn: true, ..result });
6669 let mut err = self.diagnostic().struct_span_err(id_sp,
6670 "cannot declare a new module at this location");
6671 if !id_sp.is_dummy() {
6672 let src_path = self.sess.source_map().span_to_filename(id_sp);
6673 if let FileName::Real(src_path) = src_path {
6674 if let Some(stem) = src_path.file_stem() {
6675 let mut dest_path = src_path.clone();
6676 dest_path.set_file_name(stem);
6677 dest_path.push("mod.rs");
6678 err.span_note(id_sp,
6679 &format!("maybe move this module `{}` to its own \
6680 directory via `{}`", src_path.display(),
6681 dest_path.display()));
6685 if paths.path_exists {
6686 err.span_note(id_sp,
6687 &format!("... or maybe `use` the module `{}` instead \
6688 of possibly redeclaring it",
6696 /// Read a module from a source file.
6697 fn eval_src_mod(&mut self,
6699 directory_ownership: DirectoryOwnership,
6702 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6703 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6704 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6705 let mut err = String::from("circular modules: ");
6706 let len = included_mod_stack.len();
6707 for p in &included_mod_stack[i.. len] {
6708 err.push_str(&p.to_string_lossy());
6709 err.push_str(" -> ");
6711 err.push_str(&path.to_string_lossy());
6712 return Err(self.span_fatal(id_sp, &err[..]));
6714 included_mod_stack.push(path.clone());
6715 drop(included_mod_stack);
6718 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6719 p0.cfg_mods = self.cfg_mods;
6720 let mod_inner_lo = p0.span;
6721 let mod_attrs = p0.parse_inner_attributes()?;
6722 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6724 self.sess.included_mod_stack.borrow_mut().pop();
6728 /// Parse a function declaration from a foreign module
6729 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6730 -> PResult<'a, ForeignItem> {
6731 self.expect_keyword(keywords::Fn)?;
6733 let (ident, mut generics) = self.parse_fn_header()?;
6734 let decl = self.parse_fn_decl(true)?;
6735 generics.where_clause = self.parse_where_clause()?;
6737 self.expect(&token::Semi)?;
6738 Ok(ast::ForeignItem {
6741 node: ForeignItemKind::Fn(decl, generics),
6742 id: ast::DUMMY_NODE_ID,
6748 /// Parse a static item from a foreign module.
6749 /// Assumes that the `static` keyword is already parsed.
6750 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6751 -> PResult<'a, ForeignItem> {
6752 let mutbl = self.eat_keyword(keywords::Mut);
6753 let ident = self.parse_ident()?;
6754 self.expect(&token::Colon)?;
6755 let ty = self.parse_ty()?;
6757 self.expect(&token::Semi)?;
6761 node: ForeignItemKind::Static(ty, mutbl),
6762 id: ast::DUMMY_NODE_ID,
6768 /// Parse a type from a foreign module
6769 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6770 -> PResult<'a, ForeignItem> {
6771 self.expect_keyword(keywords::Type)?;
6773 let ident = self.parse_ident()?;
6775 self.expect(&token::Semi)?;
6776 Ok(ast::ForeignItem {
6779 node: ForeignItemKind::Ty,
6780 id: ast::DUMMY_NODE_ID,
6786 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6787 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6788 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6790 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
6791 self.parse_path_segment_ident()
6795 let mut idents = vec![];
6796 let mut replacement = vec![];
6797 let mut fixed_crate_name = false;
6798 // Accept `extern crate name-like-this` for better diagnostics
6799 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6800 if self.token == dash { // Do not include `-` as part of the expected tokens list
6801 while self.eat(&dash) {
6802 fixed_crate_name = true;
6803 replacement.push((self.prev_span, "_".to_string()));
6804 idents.push(self.parse_ident()?);
6807 if fixed_crate_name {
6808 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6809 let mut fixed_name = format!("{}", ident.name);
6810 for part in idents {
6811 fixed_name.push_str(&format!("_{}", part.name));
6813 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6815 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6816 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6817 err.multipart_suggestion(suggestion_msg, replacement);
6823 /// Parse extern crate links
6827 /// extern crate foo;
6828 /// extern crate bar as foo;
6829 fn parse_item_extern_crate(&mut self,
6831 visibility: Visibility,
6832 attrs: Vec<Attribute>)
6833 -> PResult<'a, P<Item>> {
6834 // Accept `extern crate name-like-this` for better diagnostics
6835 let orig_name = self.parse_crate_name_with_dashes()?;
6836 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6837 (rename, Some(orig_name.name))
6841 self.expect(&token::Semi)?;
6843 let span = lo.to(self.prev_span);
6844 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6847 /// Parse `extern` for foreign ABIs
6850 /// `extern` is expected to have been
6851 /// consumed before calling this method
6857 fn parse_item_foreign_mod(&mut self,
6859 opt_abi: Option<Abi>,
6860 visibility: Visibility,
6861 mut attrs: Vec<Attribute>)
6862 -> PResult<'a, P<Item>> {
6863 self.expect(&token::OpenDelim(token::Brace))?;
6865 let abi = opt_abi.unwrap_or(Abi::C);
6867 attrs.extend(self.parse_inner_attributes()?);
6869 let mut foreign_items = vec![];
6870 while !self.eat(&token::CloseDelim(token::Brace)) {
6871 foreign_items.push(self.parse_foreign_item()?);
6874 let prev_span = self.prev_span;
6875 let m = ast::ForeignMod {
6877 items: foreign_items
6879 let invalid = keywords::Invalid.ident();
6880 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6883 /// Parse `type Foo = Bar;`
6885 /// `existential type Foo: Bar;`
6887 /// `return None` without modifying the parser state
6888 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6889 // This parses the grammar:
6890 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6891 if self.check_keyword(keywords::Type) ||
6892 self.check_keyword(keywords::Existential) &&
6893 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6894 let existential = self.eat_keyword(keywords::Existential);
6895 assert!(self.eat_keyword(keywords::Type));
6896 Some(self.parse_existential_or_alias(existential))
6902 /// Parse type alias or existential type
6903 fn parse_existential_or_alias(
6906 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6907 let ident = self.parse_ident()?;
6908 let mut tps = self.parse_generics()?;
6909 tps.where_clause = self.parse_where_clause()?;
6910 let alias = if existential {
6911 self.expect(&token::Colon)?;
6912 let bounds = self.parse_generic_bounds()?;
6913 AliasKind::Existential(bounds)
6915 self.expect(&token::Eq)?;
6916 let ty = self.parse_ty()?;
6919 self.expect(&token::Semi)?;
6920 Ok((ident, alias, tps))
6923 /// Parse the part of an "enum" decl following the '{'
6924 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6925 let mut variants = Vec::new();
6926 let mut all_nullary = true;
6927 let mut any_disr = None;
6928 while self.token != token::CloseDelim(token::Brace) {
6929 let variant_attrs = self.parse_outer_attributes()?;
6930 let vlo = self.span;
6933 let mut disr_expr = None;
6934 let ident = self.parse_ident()?;
6935 if self.check(&token::OpenDelim(token::Brace)) {
6936 // Parse a struct variant.
6937 all_nullary = false;
6938 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6939 ast::DUMMY_NODE_ID);
6940 } else if self.check(&token::OpenDelim(token::Paren)) {
6941 all_nullary = false;
6942 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6943 ast::DUMMY_NODE_ID);
6944 } else if self.eat(&token::Eq) {
6945 disr_expr = Some(AnonConst {
6946 id: ast::DUMMY_NODE_ID,
6947 value: self.parse_expr()?,
6949 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6950 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6952 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6955 let vr = ast::Variant_ {
6957 attrs: variant_attrs,
6961 variants.push(respan(vlo.to(self.prev_span), vr));
6963 if !self.eat(&token::Comma) { break; }
6965 self.expect(&token::CloseDelim(token::Brace))?;
6967 Some(disr_span) if !all_nullary =>
6968 self.span_err(disr_span,
6969 "discriminator values can only be used with a field-less enum"),
6973 Ok(ast::EnumDef { variants })
6976 /// Parse an "enum" declaration
6977 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6978 let id = self.parse_ident()?;
6979 let mut generics = self.parse_generics()?;
6980 generics.where_clause = self.parse_where_clause()?;
6981 self.expect(&token::OpenDelim(token::Brace))?;
6983 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6984 self.recover_stmt();
6985 self.eat(&token::CloseDelim(token::Brace));
6988 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6991 /// Parses a string as an ABI spec on an extern type or module. Consumes
6992 /// the `extern` keyword, if one is found.
6993 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6995 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6997 self.expect_no_suffix(sp, "ABI spec", suf);
6999 match abi::lookup(&s.as_str()) {
7000 Some(abi) => Ok(Some(abi)),
7002 let prev_span = self.prev_span;
7003 let mut err = struct_span_err!(
7004 self.sess.span_diagnostic,
7007 "invalid ABI: found `{}`",
7009 err.span_label(prev_span, "invalid ABI");
7010 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7021 fn is_static_global(&mut self) -> bool {
7022 if self.check_keyword(keywords::Static) {
7023 // Check if this could be a closure
7024 !self.look_ahead(1, |token| {
7025 if token.is_keyword(keywords::Move) {
7029 token::BinOp(token::Or) | token::OrOr => true,
7040 attrs: Vec<Attribute>,
7041 macros_allowed: bool,
7042 attributes_allowed: bool,
7043 ) -> PResult<'a, Option<P<Item>>> {
7044 let (ret, tokens) = self.collect_tokens(|this| {
7045 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
7048 // Once we've parsed an item and recorded the tokens we got while
7049 // parsing we may want to store `tokens` into the item we're about to
7050 // return. Note, though, that we specifically didn't capture tokens
7051 // related to outer attributes. The `tokens` field here may later be
7052 // used with procedural macros to convert this item back into a token
7053 // stream, but during expansion we may be removing attributes as we go
7056 // If we've got inner attributes then the `tokens` we've got above holds
7057 // these inner attributes. If an inner attribute is expanded we won't
7058 // actually remove it from the token stream, so we'll just keep yielding
7059 // it (bad!). To work around this case for now we just avoid recording
7060 // `tokens` if we detect any inner attributes. This should help keep
7061 // expansion correct, but we should fix this bug one day!
7064 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7065 i.tokens = Some(tokens);
7072 /// Parse one of the items allowed by the flags.
7073 fn parse_item_implementation(
7075 attrs: Vec<Attribute>,
7076 macros_allowed: bool,
7077 attributes_allowed: bool,
7078 ) -> PResult<'a, Option<P<Item>>> {
7079 maybe_whole!(self, NtItem, |item| {
7080 let mut item = item.into_inner();
7081 let mut attrs = attrs;
7082 mem::swap(&mut item.attrs, &mut attrs);
7083 item.attrs.extend(attrs);
7089 let visibility = self.parse_visibility(false)?;
7091 if self.eat_keyword(keywords::Use) {
7093 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7094 self.expect(&token::Semi)?;
7096 let span = lo.to(self.prev_span);
7097 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7098 return Ok(Some(item));
7101 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
7102 self.bump(); // `extern`
7103 if self.eat_keyword(keywords::Crate) {
7104 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7107 let opt_abi = self.parse_opt_abi()?;
7109 if self.eat_keyword(keywords::Fn) {
7110 // EXTERN FUNCTION ITEM
7111 let fn_span = self.prev_span;
7112 let abi = opt_abi.unwrap_or(Abi::C);
7113 let (ident, item_, extra_attrs) =
7114 self.parse_item_fn(Unsafety::Normal,
7116 respan(fn_span, Constness::NotConst),
7118 let prev_span = self.prev_span;
7119 let item = self.mk_item(lo.to(prev_span),
7123 maybe_append(attrs, extra_attrs));
7124 return Ok(Some(item));
7125 } else if self.check(&token::OpenDelim(token::Brace)) {
7126 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7132 if self.is_static_global() {
7135 let m = if self.eat_keyword(keywords::Mut) {
7138 Mutability::Immutable
7140 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7141 let prev_span = self.prev_span;
7142 let item = self.mk_item(lo.to(prev_span),
7146 maybe_append(attrs, extra_attrs));
7147 return Ok(Some(item));
7149 if self.eat_keyword(keywords::Const) {
7150 let const_span = self.prev_span;
7151 if self.check_keyword(keywords::Fn)
7152 || (self.check_keyword(keywords::Unsafe)
7153 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7154 // CONST FUNCTION ITEM
7155 let unsafety = self.parse_unsafety();
7157 let (ident, item_, extra_attrs) =
7158 self.parse_item_fn(unsafety,
7160 respan(const_span, Constness::Const),
7162 let prev_span = self.prev_span;
7163 let item = self.mk_item(lo.to(prev_span),
7167 maybe_append(attrs, extra_attrs));
7168 return Ok(Some(item));
7172 if self.eat_keyword(keywords::Mut) {
7173 let prev_span = self.prev_span;
7174 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
7175 .help("did you mean to declare a static?")
7178 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7179 let prev_span = self.prev_span;
7180 let item = self.mk_item(lo.to(prev_span),
7184 maybe_append(attrs, extra_attrs));
7185 return Ok(Some(item));
7188 // `unsafe async fn` or `async fn`
7190 self.check_keyword(keywords::Unsafe) &&
7191 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7193 self.check_keyword(keywords::Async) &&
7194 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7197 // ASYNC FUNCTION ITEM
7198 let unsafety = self.parse_unsafety();
7199 self.expect_keyword(keywords::Async)?;
7200 self.expect_keyword(keywords::Fn)?;
7201 let fn_span = self.prev_span;
7202 let (ident, item_, extra_attrs) =
7203 self.parse_item_fn(unsafety,
7205 closure_id: ast::DUMMY_NODE_ID,
7206 return_impl_trait_id: ast::DUMMY_NODE_ID,
7208 respan(fn_span, Constness::NotConst),
7210 let prev_span = self.prev_span;
7211 let item = self.mk_item(lo.to(prev_span),
7215 maybe_append(attrs, extra_attrs));
7216 return Ok(Some(item));
7218 if self.check_keyword(keywords::Unsafe) &&
7219 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7220 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7222 // UNSAFE TRAIT ITEM
7223 self.bump(); // `unsafe`
7224 let is_auto = if self.eat_keyword(keywords::Trait) {
7227 self.expect_keyword(keywords::Auto)?;
7228 self.expect_keyword(keywords::Trait)?;
7231 let (ident, item_, extra_attrs) =
7232 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7233 let prev_span = self.prev_span;
7234 let item = self.mk_item(lo.to(prev_span),
7238 maybe_append(attrs, extra_attrs));
7239 return Ok(Some(item));
7241 if self.check_keyword(keywords::Impl) ||
7242 self.check_keyword(keywords::Unsafe) &&
7243 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7244 self.check_keyword(keywords::Default) &&
7245 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7246 self.check_keyword(keywords::Default) &&
7247 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7249 let defaultness = self.parse_defaultness();
7250 let unsafety = self.parse_unsafety();
7251 self.expect_keyword(keywords::Impl)?;
7252 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7253 let span = lo.to(self.prev_span);
7254 return Ok(Some(self.mk_item(span, ident, item, visibility,
7255 maybe_append(attrs, extra_attrs))));
7257 if self.check_keyword(keywords::Fn) {
7260 let fn_span = self.prev_span;
7261 let (ident, item_, extra_attrs) =
7262 self.parse_item_fn(Unsafety::Normal,
7264 respan(fn_span, Constness::NotConst),
7266 let prev_span = self.prev_span;
7267 let item = self.mk_item(lo.to(prev_span),
7271 maybe_append(attrs, extra_attrs));
7272 return Ok(Some(item));
7274 if self.check_keyword(keywords::Unsafe)
7275 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7276 // UNSAFE FUNCTION ITEM
7277 self.bump(); // `unsafe`
7278 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7279 self.check(&token::OpenDelim(token::Brace));
7280 let abi = if self.eat_keyword(keywords::Extern) {
7281 self.parse_opt_abi()?.unwrap_or(Abi::C)
7285 self.expect_keyword(keywords::Fn)?;
7286 let fn_span = self.prev_span;
7287 let (ident, item_, extra_attrs) =
7288 self.parse_item_fn(Unsafety::Unsafe,
7290 respan(fn_span, Constness::NotConst),
7292 let prev_span = self.prev_span;
7293 let item = self.mk_item(lo.to(prev_span),
7297 maybe_append(attrs, extra_attrs));
7298 return Ok(Some(item));
7300 if self.eat_keyword(keywords::Mod) {
7302 let (ident, item_, extra_attrs) =
7303 self.parse_item_mod(&attrs[..])?;
7304 let prev_span = self.prev_span;
7305 let item = self.mk_item(lo.to(prev_span),
7309 maybe_append(attrs, extra_attrs));
7310 return Ok(Some(item));
7312 if let Some(type_) = self.eat_type() {
7313 let (ident, alias, generics) = type_?;
7315 let item_ = match alias {
7316 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7317 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7319 let prev_span = self.prev_span;
7320 let item = self.mk_item(lo.to(prev_span),
7325 return Ok(Some(item));
7327 if self.eat_keyword(keywords::Enum) {
7329 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7330 let prev_span = self.prev_span;
7331 let item = self.mk_item(lo.to(prev_span),
7335 maybe_append(attrs, extra_attrs));
7336 return Ok(Some(item));
7338 if self.check_keyword(keywords::Trait)
7339 || (self.check_keyword(keywords::Auto)
7340 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7342 let is_auto = if self.eat_keyword(keywords::Trait) {
7345 self.expect_keyword(keywords::Auto)?;
7346 self.expect_keyword(keywords::Trait)?;
7350 let (ident, item_, extra_attrs) =
7351 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7352 let prev_span = self.prev_span;
7353 let item = self.mk_item(lo.to(prev_span),
7357 maybe_append(attrs, extra_attrs));
7358 return Ok(Some(item));
7360 if self.eat_keyword(keywords::Struct) {
7362 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7363 let prev_span = self.prev_span;
7364 let item = self.mk_item(lo.to(prev_span),
7368 maybe_append(attrs, extra_attrs));
7369 return Ok(Some(item));
7371 if self.is_union_item() {
7374 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7375 let prev_span = self.prev_span;
7376 let item = self.mk_item(lo.to(prev_span),
7380 maybe_append(attrs, extra_attrs));
7381 return Ok(Some(item));
7383 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7384 return Ok(Some(macro_def));
7387 // Verify whether we have encountered a struct or method definition where the user forgot to
7388 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7389 if visibility.node.is_pub() &&
7390 self.check_ident() &&
7391 self.look_ahead(1, |t| *t != token::Not)
7393 // Space between `pub` keyword and the identifier
7396 // ^^^ `sp` points here
7397 let sp = self.prev_span.between(self.span);
7398 let full_sp = self.prev_span.to(self.span);
7399 let ident_sp = self.span;
7400 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7401 // possible public struct definition where `struct` was forgotten
7402 let ident = self.parse_ident().unwrap();
7403 let msg = format!("add `struct` here to parse `{}` as a public struct",
7405 let mut err = self.diagnostic()
7406 .struct_span_err(sp, "missing `struct` for struct definition");
7407 err.span_suggestion_short_with_applicability(
7408 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7411 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7412 let ident = self.parse_ident().unwrap();
7414 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
7419 self.consume_block(token::Paren);
7420 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7421 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7423 ("fn", kw_name, false)
7424 } else if self.check(&token::OpenDelim(token::Brace)) {
7426 ("fn", kw_name, false)
7427 } else if self.check(&token::Colon) {
7431 ("fn` or `struct", "function or struct", true)
7433 self.consume_block(token::Brace);
7435 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7436 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7438 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7442 err.span_suggestion_short_with_applicability(
7443 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7446 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7447 err.span_suggestion_with_applicability(
7449 "if you meant to call a macro, try",
7450 format!("{}!", snippet),
7451 // this is the `ambiguous` conditional branch
7452 Applicability::MaybeIncorrect
7455 err.help("if you meant to call a macro, remove the `pub` \
7456 and add a trailing `!` after the identifier");
7460 } else if self.look_ahead(1, |t| *t == token::Lt) {
7461 let ident = self.parse_ident().unwrap();
7462 self.eat_to_tokens(&[&token::Gt]);
7464 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7465 if let Ok(Some(_)) = self.parse_self_arg() {
7466 ("fn", "method", false)
7468 ("fn", "function", false)
7470 } else if self.check(&token::OpenDelim(token::Brace)) {
7471 ("struct", "struct", false)
7473 ("fn` or `struct", "function or struct", true)
7475 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7476 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7478 err.span_suggestion_short_with_applicability(
7480 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7481 format!(" {} ", kw),
7482 Applicability::MachineApplicable,
7488 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7491 /// Parse a foreign item.
7492 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7493 maybe_whole!(self, NtForeignItem, |ni| ni);
7495 let attrs = self.parse_outer_attributes()?;
7497 let visibility = self.parse_visibility(false)?;
7499 // FOREIGN STATIC ITEM
7500 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7501 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7502 if self.token.is_keyword(keywords::Const) {
7504 .struct_span_err(self.span, "extern items cannot be `const`")
7505 .span_suggestion_with_applicability(
7507 "try using a static value",
7508 "static".to_owned(),
7509 Applicability::MachineApplicable
7512 self.bump(); // `static` or `const`
7513 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7515 // FOREIGN FUNCTION ITEM
7516 if self.check_keyword(keywords::Fn) {
7517 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7519 // FOREIGN TYPE ITEM
7520 if self.check_keyword(keywords::Type) {
7521 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7524 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7528 ident: keywords::Invalid.ident(),
7529 span: lo.to(self.prev_span),
7530 id: ast::DUMMY_NODE_ID,
7533 node: ForeignItemKind::Macro(mac),
7538 if !attrs.is_empty() {
7539 self.expected_item_err(&attrs);
7547 /// This is the fall-through for parsing items.
7548 fn parse_macro_use_or_failure(
7550 attrs: Vec<Attribute> ,
7551 macros_allowed: bool,
7552 attributes_allowed: bool,
7554 visibility: Visibility
7555 ) -> PResult<'a, Option<P<Item>>> {
7556 if macros_allowed && self.token.is_path_start() {
7557 // MACRO INVOCATION ITEM
7559 let prev_span = self.prev_span;
7560 self.complain_if_pub_macro(&visibility.node, prev_span);
7562 let mac_lo = self.span;
7565 let pth = self.parse_path(PathStyle::Mod)?;
7566 self.expect(&token::Not)?;
7568 // a 'special' identifier (like what `macro_rules!` uses)
7569 // is optional. We should eventually unify invoc syntax
7571 let id = if self.token.is_ident() {
7574 keywords::Invalid.ident() // no special identifier
7576 // eat a matched-delimiter token tree:
7577 let (delim, tts) = self.expect_delimited_token_tree()?;
7578 if delim != MacDelimiter::Brace {
7579 if !self.eat(&token::Semi) {
7580 self.span_err(self.prev_span,
7581 "macros that expand to items must either \
7582 be surrounded with braces or followed by \
7587 let hi = self.prev_span;
7588 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7589 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7590 return Ok(Some(item));
7593 // FAILURE TO PARSE ITEM
7594 match visibility.node {
7595 VisibilityKind::Inherited => {}
7597 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7601 if !attributes_allowed && !attrs.is_empty() {
7602 self.expected_item_err(&attrs);
7607 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7608 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7609 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7611 if self.token.is_path_start() && !self.is_extern_non_path() {
7612 let prev_span = self.prev_span;
7614 let pth = self.parse_path(PathStyle::Mod)?;
7616 if pth.segments.len() == 1 {
7617 if !self.eat(&token::Not) {
7618 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7621 self.expect(&token::Not)?;
7624 if let Some(vis) = vis {
7625 self.complain_if_pub_macro(&vis.node, prev_span);
7630 // eat a matched-delimiter token tree:
7631 let (delim, tts) = self.expect_delimited_token_tree()?;
7632 if delim != MacDelimiter::Brace {
7633 self.expect(&token::Semi)?
7636 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7642 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7643 where F: FnOnce(&mut Self) -> PResult<'a, R>
7645 // Record all tokens we parse when parsing this item.
7646 let mut tokens = Vec::new();
7647 let prev_collecting = match self.token_cursor.frame.last_token {
7648 LastToken::Collecting(ref mut list) => {
7649 Some(mem::replace(list, Vec::new()))
7651 LastToken::Was(ref mut last) => {
7652 tokens.extend(last.take());
7656 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7657 let prev = self.token_cursor.stack.len();
7659 let last_token = if self.token_cursor.stack.len() == prev {
7660 &mut self.token_cursor.frame.last_token
7662 &mut self.token_cursor.stack[prev].last_token
7665 // Pull our the toekns that we've collected from the call to `f` above
7666 let mut collected_tokens = match *last_token {
7667 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7668 LastToken::Was(_) => panic!("our vector went away?"),
7671 // If we're not at EOF our current token wasn't actually consumed by
7672 // `f`, but it'll still be in our list that we pulled out. In that case
7674 let extra_token = if self.token != token::Eof {
7675 collected_tokens.pop()
7680 // If we were previously collecting tokens, then this was a recursive
7681 // call. In that case we need to record all the tokens we collected in
7682 // our parent list as well. To do that we push a clone of our stream
7683 // onto the previous list.
7684 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7685 match prev_collecting {
7687 list.push(stream.clone());
7688 list.extend(extra_token);
7689 *last_token = LastToken::Collecting(list);
7692 *last_token = LastToken::Was(extra_token);
7699 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7700 let attrs = self.parse_outer_attributes()?;
7701 self.parse_item_(attrs, true, false)
7705 fn is_import_coupler(&mut self) -> bool {
7706 self.check(&token::ModSep) &&
7707 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7708 *t == token::BinOp(token::Star))
7713 /// USE_TREE = [`::`] `*` |
7714 /// [`::`] `{` USE_TREE_LIST `}` |
7716 /// PATH `::` `{` USE_TREE_LIST `}` |
7717 /// PATH [`as` IDENT]
7718 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7721 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7722 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7723 self.check(&token::BinOp(token::Star)) ||
7724 self.is_import_coupler() {
7725 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7726 let mod_sep_ctxt = self.span.ctxt();
7727 if self.eat(&token::ModSep) {
7728 prefix.segments.push(
7729 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7733 if self.eat(&token::BinOp(token::Star)) {
7736 UseTreeKind::Nested(self.parse_use_tree_list()?)
7739 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7740 prefix = self.parse_path(PathStyle::Mod)?;
7742 if self.eat(&token::ModSep) {
7743 if self.eat(&token::BinOp(token::Star)) {
7746 UseTreeKind::Nested(self.parse_use_tree_list()?)
7749 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7753 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7756 /// Parse UseTreeKind::Nested(list)
7758 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7759 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7760 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7761 &token::CloseDelim(token::Brace),
7762 SeqSep::trailing_allowed(token::Comma), |this| {
7763 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7767 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7768 if self.eat_keyword(keywords::As) {
7769 self.parse_ident_or_underscore().map(Some)
7775 /// Parses a source module as a crate. This is the main
7776 /// entry point for the parser.
7777 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7780 attrs: self.parse_inner_attributes()?,
7781 module: self.parse_mod_items(&token::Eof, lo)?,
7782 span: lo.to(self.span),
7786 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7787 let ret = match self.token {
7788 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7789 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7796 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7797 match self.parse_optional_str() {
7798 Some((s, style, suf)) => {
7799 let sp = self.prev_span;
7800 self.expect_no_suffix(sp, "string literal", suf);
7804 let msg = "expected string literal";
7805 let mut err = self.fatal(msg);
7806 err.span_label(self.span, msg);