1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc_target::spec::abi::{self, Abi};
12 use ast::{AngleBracketedArgs, ParenthesisedArgs, AttrStyle, BareFnTy};
13 use ast::{GenericBound, TraitBoundModifier};
15 use ast::{Mod, AnonConst, Arg, Arm, Guard, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy, Movability};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl, FnHeader};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::{GenericParam, GenericParamKind};
26 use ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
27 use ast::{Label, Lifetime, Lit, LitKind};
29 use ast::MacStmtStyle;
30 use ast::{Mac, Mac_, MacDelimiter};
31 use ast::{MutTy, Mutability};
32 use ast::{Pat, PatKind, PathSegment};
33 use ast::{PolyTraitRef, QSelf};
34 use ast::{Stmt, StmtKind};
35 use ast::{VariantData, StructField};
38 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
39 use ast::{Ty, TyKind, TypeBinding, GenericBounds};
40 use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
41 use ast::{UseTree, UseTreeKind};
42 use ast::{BinOpKind, UnOp};
43 use ast::{RangeEnd, RangeSyntax};
45 use source_map::{self, SourceMap, Spanned, respan};
46 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName, edition::Edition};
47 use errors::{self, Applicability, DiagnosticBuilder, DiagnosticId};
48 use parse::{self, SeqSep, classify, token};
49 use parse::lexer::TokenAndSpan;
50 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
57 use tokenstream::{self, Delimited, DelimSpan, ThinTokenStream, TokenTree, TokenStream};
58 use symbol::{Symbol, keywords};
63 use std::path::{self, Path, PathBuf};
67 /// Whether the type alias or associated type is a concrete type or an existential type
69 /// Just a new name for the same type
71 /// Only trait impls of the type will be usable, not the actual type itself
72 Existential(GenericBounds),
76 struct Restrictions: u8 {
77 const STMT_EXPR = 1 << 0;
78 const NO_STRUCT_LITERAL = 1 << 1;
82 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
84 /// How to parse a path.
85 #[derive(Copy, Clone, PartialEq)]
87 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
88 /// with something else. For example, in expressions `segment < ....` can be interpreted
89 /// as a comparison and `segment ( ....` can be interpreted as a function call.
90 /// In all such contexts the non-path interpretation is preferred by default for practical
91 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
92 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
94 /// In other contexts, notably in types, no ambiguity exists and paths can be written
95 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
96 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
98 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
99 /// visibilities or attributes.
100 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
101 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
102 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
103 /// tokens when something goes wrong.
107 #[derive(Clone, Copy, PartialEq, Debug)]
113 #[derive(Clone, Copy, PartialEq, Debug)]
119 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
120 /// dropped into the token stream, which happens while parsing the result of
121 /// macro expansion). Placement of these is not as complex as I feared it would
122 /// be. The important thing is to make sure that lookahead doesn't balk at
123 /// `token::Interpolated` tokens.
124 macro_rules! maybe_whole_expr {
126 if let token::Interpolated(nt) = $p.token.clone() {
128 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
130 return Ok((*e).clone());
132 token::NtPath(ref path) => {
135 let kind = ExprKind::Path(None, (*path).clone());
136 return Ok($p.mk_expr(span, kind, ThinVec::new()));
138 token::NtBlock(ref block) => {
141 let kind = ExprKind::Block((*block).clone(), None);
142 return Ok($p.mk_expr(span, kind, ThinVec::new()));
150 /// As maybe_whole_expr, but for things other than expressions
151 macro_rules! maybe_whole {
152 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
153 if let token::Interpolated(nt) = $p.token.clone() {
154 if let token::$constructor($x) = nt.0.clone() {
162 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
163 if let Some(ref mut rhs) = rhs {
169 #[derive(Debug, Clone, Copy, PartialEq)]
180 trait RecoverQPath: Sized {
181 const PATH_STYLE: PathStyle = PathStyle::Expr;
182 fn to_ty(&self) -> Option<P<Ty>>;
183 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
184 fn to_string(&self) -> String;
187 impl RecoverQPath for Ty {
188 const PATH_STYLE: PathStyle = PathStyle::Type;
189 fn to_ty(&self) -> Option<P<Ty>> {
190 Some(P(self.clone()))
192 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
193 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
195 fn to_string(&self) -> String {
196 pprust::ty_to_string(self)
200 impl RecoverQPath for Pat {
201 fn to_ty(&self) -> Option<P<Ty>> {
204 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
205 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
207 fn to_string(&self) -> String {
208 pprust::pat_to_string(self)
212 impl RecoverQPath for Expr {
213 fn to_ty(&self) -> Option<P<Ty>> {
216 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
217 Self { span: path.span, node: ExprKind::Path(qself, path),
218 id: self.id, attrs: self.attrs.clone() }
220 fn to_string(&self) -> String {
221 pprust::expr_to_string(self)
225 /* ident is handled by common.rs */
228 pub struct Parser<'a> {
229 pub sess: &'a ParseSess,
230 /// the current token:
231 pub token: token::Token,
232 /// the span of the current token:
234 /// the span of the previous token:
235 meta_var_span: Option<Span>,
237 /// the previous token kind
238 prev_token_kind: PrevTokenKind,
239 restrictions: Restrictions,
240 /// Used to determine the path to externally loaded source files
241 crate directory: Directory<'a>,
242 /// Whether to parse sub-modules in other files.
243 pub recurse_into_file_modules: bool,
244 /// Name of the root module this parser originated from. If `None`, then the
245 /// name is not known. This does not change while the parser is descending
246 /// into modules, and sub-parsers have new values for this name.
247 pub root_module_name: Option<String>,
248 crate expected_tokens: Vec<TokenType>,
249 token_cursor: TokenCursor,
250 desugar_doc_comments: bool,
251 /// Whether we should configure out of line modules as we parse.
258 frame: TokenCursorFrame,
259 stack: Vec<TokenCursorFrame>,
263 struct TokenCursorFrame {
264 delim: token::DelimToken,
267 tree_cursor: tokenstream::Cursor,
269 last_token: LastToken,
272 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
273 /// by the parser, and then that's transitively used to record the tokens that
274 /// each parse AST item is created with.
276 /// Right now this has two states, either collecting tokens or not collecting
277 /// tokens. If we're collecting tokens we just save everything off into a local
278 /// `Vec`. This should eventually though likely save tokens from the original
279 /// token stream and just use slicing of token streams to avoid creation of a
280 /// whole new vector.
282 /// The second state is where we're passively not recording tokens, but the last
283 /// token is still tracked for when we want to start recording tokens. This
284 /// "last token" means that when we start recording tokens we'll want to ensure
285 /// that this, the first token, is included in the output.
287 /// You can find some more example usage of this in the `collect_tokens` method
291 Collecting(Vec<TokenStream>),
292 Was(Option<TokenStream>),
295 impl TokenCursorFrame {
296 fn new(sp: DelimSpan, delimited: &Delimited) -> Self {
298 delim: delimited.delim,
300 open_delim: delimited.delim == token::NoDelim,
301 tree_cursor: delimited.stream().into_trees(),
302 close_delim: delimited.delim == token::NoDelim,
303 last_token: LastToken::Was(None),
309 fn next(&mut self) -> TokenAndSpan {
311 let tree = if !self.frame.open_delim {
312 self.frame.open_delim = true;
313 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
314 .open_tt(self.frame.span.open)
315 } else if let Some(tree) = self.frame.tree_cursor.next() {
317 } else if !self.frame.close_delim {
318 self.frame.close_delim = true;
319 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
320 .close_tt(self.frame.span.close)
321 } else if let Some(frame) = self.stack.pop() {
325 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
328 match self.frame.last_token {
329 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
330 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
334 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
335 TokenTree::Delimited(sp, ref delimited) => {
336 let frame = TokenCursorFrame::new(sp, delimited);
337 self.stack.push(mem::replace(&mut self.frame, frame));
343 fn next_desugared(&mut self) -> TokenAndSpan {
344 let (sp, name) = match self.next() {
345 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
349 let stripped = strip_doc_comment_decoration(&name.as_str());
351 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
352 // required to wrap the text.
353 let mut num_of_hashes = 0;
355 for ch in stripped.chars() {
358 '#' if count > 0 => count + 1,
361 num_of_hashes = cmp::max(num_of_hashes, count);
364 let delim_span = DelimSpan::from_single(sp);
365 let body = TokenTree::Delimited(delim_span, Delimited {
366 delim: token::Bracket,
367 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
368 TokenTree::Token(sp, token::Eq),
369 TokenTree::Token(sp, token::Literal(
370 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
371 .iter().cloned().collect::<TokenStream>().into(),
374 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(delim_span, &Delimited {
375 delim: token::NoDelim,
376 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
377 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
378 .iter().cloned().collect::<TokenStream>().into()
380 [TokenTree::Token(sp, token::Pound), body]
381 .iter().cloned().collect::<TokenStream>().into()
389 #[derive(Clone, PartialEq)]
390 crate enum TokenType {
392 Keyword(keywords::Keyword),
401 fn to_string(&self) -> String {
403 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
404 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
405 TokenType::Operator => "an operator".to_string(),
406 TokenType::Lifetime => "lifetime".to_string(),
407 TokenType::Ident => "identifier".to_string(),
408 TokenType::Path => "path".to_string(),
409 TokenType::Type => "type".to_string(),
414 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
415 /// `IDENT<<u8 as Trait>::AssocTy>`.
417 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
418 /// that IDENT is not the ident of a fn trait
419 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
420 t == &token::ModSep || t == &token::Lt ||
421 t == &token::BinOp(token::Shl)
424 /// Information about the path to a module.
425 pub struct ModulePath {
428 pub result: Result<ModulePathSuccess, Error>,
431 pub struct ModulePathSuccess {
433 pub directory_ownership: DirectoryOwnership,
438 FileNotFoundForModule {
440 default_path: String,
441 secondary_path: String,
446 default_path: String,
447 secondary_path: String,
450 InclusiveRangeWithNoEnd,
454 fn span_err<S: Into<MultiSpan>>(self,
456 handler: &errors::Handler) -> DiagnosticBuilder {
458 Error::FileNotFoundForModule { ref mod_name,
462 let mut err = struct_span_err!(handler, sp, E0583,
463 "file not found for module `{}`", mod_name);
464 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
470 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
471 let mut err = struct_span_err!(handler, sp, E0584,
472 "file for module `{}` found at both {} and {}",
476 err.help("delete or rename one of them to remove the ambiguity");
479 Error::UselessDocComment => {
480 let mut err = struct_span_err!(handler, sp, E0585,
481 "found a documentation comment that doesn't document anything");
482 err.help("doc comments must come before what they document, maybe a comment was \
483 intended with `//`?");
486 Error::InclusiveRangeWithNoEnd => {
487 let mut err = struct_span_err!(handler, sp, E0586,
488 "inclusive range with no end");
489 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
499 AttributesParsed(ThinVec<Attribute>),
500 AlreadyParsed(P<Expr>),
503 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
504 fn from(o: Option<ThinVec<Attribute>>) -> Self {
505 if let Some(attrs) = o {
506 LhsExpr::AttributesParsed(attrs)
508 LhsExpr::NotYetParsed
513 impl From<P<Expr>> for LhsExpr {
514 fn from(expr: P<Expr>) -> Self {
515 LhsExpr::AlreadyParsed(expr)
519 /// Create a placeholder argument.
520 fn dummy_arg(span: Span) -> Arg {
521 let ident = Ident::new(keywords::Invalid.name(), span);
523 id: ast::DUMMY_NODE_ID,
524 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
530 id: ast::DUMMY_NODE_ID
532 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
535 #[derive(Copy, Clone, Debug)]
536 enum TokenExpectType {
541 impl<'a> Parser<'a> {
542 pub fn new(sess: &'a ParseSess,
544 directory: Option<Directory<'a>>,
545 recurse_into_file_modules: bool,
546 desugar_doc_comments: bool)
548 let mut parser = Parser {
550 token: token::Whitespace,
551 span: syntax_pos::DUMMY_SP,
552 prev_span: syntax_pos::DUMMY_SP,
554 prev_token_kind: PrevTokenKind::Other,
555 restrictions: Restrictions::empty(),
556 recurse_into_file_modules,
557 directory: Directory {
558 path: Cow::from(PathBuf::new()),
559 ownership: DirectoryOwnership::Owned { relative: None }
561 root_module_name: None,
562 expected_tokens: Vec::new(),
563 token_cursor: TokenCursor {
564 frame: TokenCursorFrame::new(DelimSpan::dummy(), &Delimited {
565 delim: token::NoDelim,
570 desugar_doc_comments,
574 let tok = parser.next_tok();
575 parser.token = tok.tok;
576 parser.span = tok.sp;
578 if let Some(directory) = directory {
579 parser.directory = directory;
580 } else if !parser.span.is_dummy() {
581 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
583 parser.directory.path = Cow::from(path);
587 parser.process_potential_macro_variable();
591 fn next_tok(&mut self) -> TokenAndSpan {
592 let mut next = if self.desugar_doc_comments {
593 self.token_cursor.next_desugared()
595 self.token_cursor.next()
597 if next.sp.is_dummy() {
598 // Tweak the location for better diagnostics, but keep syntactic context intact.
599 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
604 /// Convert the current token to a string using self's reader
605 pub fn this_token_to_string(&self) -> String {
606 pprust::token_to_string(&self.token)
609 fn token_descr(&self) -> Option<&'static str> {
610 Some(match &self.token {
611 t if t.is_special_ident() => "reserved identifier",
612 t if t.is_used_keyword() => "keyword",
613 t if t.is_unused_keyword() => "reserved keyword",
618 fn this_token_descr(&self) -> String {
619 if let Some(prefix) = self.token_descr() {
620 format!("{} `{}`", prefix, self.this_token_to_string())
622 format!("`{}`", self.this_token_to_string())
626 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
627 let token_str = pprust::token_to_string(t);
628 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
631 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
632 match self.expect_one_of(&[], &[]) {
634 Ok(_) => unreachable!(),
638 /// Expect and consume the token t. Signal an error if
639 /// the next token is not t.
640 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
641 if self.expected_tokens.is_empty() {
642 if self.token == *t {
646 let token_str = pprust::token_to_string(t);
647 let this_token_str = self.this_token_to_string();
648 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
652 let sp = if self.token == token::Token::Eof {
653 // EOF, don't want to point at the following char, but rather the last token
656 self.sess.source_map().next_point(self.prev_span)
658 let label_exp = format!("expected `{}`", token_str);
659 let cm = self.sess.source_map();
660 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
661 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
662 // When the spans are in the same line, it means that the only content
663 // between them is whitespace, point only at the found token.
664 err.span_label(self.span, label_exp);
667 err.span_label(sp, label_exp);
668 err.span_label(self.span, "unexpected token");
674 self.expect_one_of(slice::from_ref(t), &[])
678 /// Expect next token to be edible or inedible token. If edible,
679 /// then consume it; if inedible, then return without consuming
680 /// anything. Signal a fatal error if next token is unexpected.
681 fn expect_one_of(&mut self,
682 edible: &[token::Token],
683 inedible: &[token::Token]) -> PResult<'a, ()>{
684 fn tokens_to_string(tokens: &[TokenType]) -> String {
685 let mut i = tokens.iter();
686 // This might be a sign we need a connect method on Iterator.
688 .map_or(String::new(), |t| t.to_string());
689 i.enumerate().fold(b, |mut b, (i, a)| {
690 if tokens.len() > 2 && i == tokens.len() - 2 {
692 } else if tokens.len() == 2 && i == tokens.len() - 2 {
697 b.push_str(&a.to_string());
701 if edible.contains(&self.token) {
704 } else if inedible.contains(&self.token) {
705 // leave it in the input
708 let mut expected = edible.iter()
709 .map(|x| TokenType::Token(x.clone()))
710 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
711 .chain(self.expected_tokens.iter().cloned())
712 .collect::<Vec<_>>();
713 expected.sort_by_cached_key(|x| x.to_string());
715 let expect = tokens_to_string(&expected[..]);
716 let actual = self.this_token_to_string();
717 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
718 let short_expect = if expected.len() > 6 {
719 format!("{} possible tokens", expected.len())
723 (format!("expected one of {}, found `{}`", expect, actual),
724 (self.sess.source_map().next_point(self.prev_span),
725 format!("expected one of {} here", short_expect)))
726 } else if expected.is_empty() {
727 (format!("unexpected token: `{}`", actual),
728 (self.prev_span, "unexpected token after this".to_string()))
730 (format!("expected {}, found `{}`", expect, actual),
731 (self.sess.source_map().next_point(self.prev_span),
732 format!("expected {} here", expect)))
734 let mut err = self.fatal(&msg_exp);
735 let sp = if self.token == token::Token::Eof {
736 // This is EOF, don't want to point at the following char, but rather the last token
742 let cm = self.sess.source_map();
743 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
744 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
745 // When the spans are in the same line, it means that the only content between
746 // them is whitespace, point at the found token in that case:
748 // X | () => { syntax error };
749 // | ^^^^^ expected one of 8 possible tokens here
751 // instead of having:
753 // X | () => { syntax error };
754 // | -^^^^^ unexpected token
756 // | expected one of 8 possible tokens here
757 err.span_label(self.span, label_exp);
760 err.span_label(sp, label_exp);
761 err.span_label(self.span, "unexpected token");
768 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
769 fn interpolated_or_expr_span(&self,
770 expr: PResult<'a, P<Expr>>)
771 -> PResult<'a, (Span, P<Expr>)> {
773 if self.prev_token_kind == PrevTokenKind::Interpolated {
781 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
782 let mut err = self.struct_span_err(self.span,
783 &format!("expected identifier, found {}",
784 self.this_token_descr()));
785 if let Some(token_descr) = self.token_descr() {
786 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
788 err.span_label(self.span, "expected identifier");
789 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
790 err.span_suggestion_with_applicability(
794 Applicability::MachineApplicable,
801 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
802 self.parse_ident_common(true)
805 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
807 token::Ident(ident, _) => {
808 if self.token.is_reserved_ident() {
809 let mut err = self.expected_ident_found();
816 let span = self.span;
818 Ok(Ident::new(ident.name, span))
821 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
822 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
824 self.expected_ident_found()
830 /// Check if the next token is `tok`, and return `true` if so.
832 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
834 crate fn check(&mut self, tok: &token::Token) -> bool {
835 let is_present = self.token == *tok;
836 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
840 /// Consume token 'tok' if it exists. Returns true if the given
841 /// token was present, false otherwise.
842 pub fn eat(&mut self, tok: &token::Token) -> bool {
843 let is_present = self.check(tok);
844 if is_present { self.bump() }
848 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
849 self.expected_tokens.push(TokenType::Keyword(kw));
850 self.token.is_keyword(kw)
853 /// If the next token is the given keyword, eat it and return
854 /// true. Otherwise, return false.
855 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
856 if self.check_keyword(kw) {
864 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
865 if self.token.is_keyword(kw) {
873 /// If the given word is not a keyword, signal an error.
874 /// If the next token is not the given word, signal an error.
875 /// Otherwise, eat it.
876 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
877 if !self.eat_keyword(kw) {
884 fn check_ident(&mut self) -> bool {
885 if self.token.is_ident() {
888 self.expected_tokens.push(TokenType::Ident);
893 fn check_path(&mut self) -> bool {
894 if self.token.is_path_start() {
897 self.expected_tokens.push(TokenType::Path);
902 fn check_type(&mut self) -> bool {
903 if self.token.can_begin_type() {
906 self.expected_tokens.push(TokenType::Type);
911 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
912 /// and continue. If a `+` is not seen, return false.
914 /// This is using when token splitting += into +.
915 /// See issue 47856 for an example of when this may occur.
916 fn eat_plus(&mut self) -> bool {
917 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
919 token::BinOp(token::Plus) => {
923 token::BinOpEq(token::Plus) => {
924 let span = self.span.with_lo(self.span.lo() + BytePos(1));
925 self.bump_with(token::Eq, span);
933 /// Checks to see if the next token is either `+` or `+=`.
934 /// Otherwise returns false.
935 fn check_plus(&mut self) -> bool {
936 if self.token.is_like_plus() {
940 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
945 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
946 /// `&` and continue. If an `&` is not seen, signal an error.
947 fn expect_and(&mut self) -> PResult<'a, ()> {
948 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
950 token::BinOp(token::And) => {
955 let span = self.span.with_lo(self.span.lo() + BytePos(1));
956 Ok(self.bump_with(token::BinOp(token::And), span))
958 _ => self.unexpected()
962 /// Expect and consume an `|`. If `||` is seen, replace it with a single
963 /// `|` and continue. If an `|` is not seen, signal an error.
964 fn expect_or(&mut self) -> PResult<'a, ()> {
965 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
967 token::BinOp(token::Or) => {
972 let span = self.span.with_lo(self.span.lo() + BytePos(1));
973 Ok(self.bump_with(token::BinOp(token::Or), span))
975 _ => self.unexpected()
979 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
981 None => {/* everything ok */}
983 let text = suf.as_str();
985 self.span_bug(sp, "found empty literal suffix in Some")
987 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
992 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
993 /// `<` and continue. If a `<` is not seen, return false.
995 /// This is meant to be used when parsing generics on a path to get the
997 fn eat_lt(&mut self) -> bool {
998 self.expected_tokens.push(TokenType::Token(token::Lt));
1004 token::BinOp(token::Shl) => {
1005 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1006 self.bump_with(token::Lt, span);
1013 fn expect_lt(&mut self) -> PResult<'a, ()> {
1021 /// Expect and consume a GT. if a >> is seen, replace it
1022 /// with a single > and continue. If a GT is not seen,
1023 /// signal an error.
1024 fn expect_gt(&mut self) -> PResult<'a, ()> {
1025 self.expected_tokens.push(TokenType::Token(token::Gt));
1031 token::BinOp(token::Shr) => {
1032 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1033 Ok(self.bump_with(token::Gt, span))
1035 token::BinOpEq(token::Shr) => {
1036 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1037 Ok(self.bump_with(token::Ge, span))
1040 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1041 Ok(self.bump_with(token::Eq, span))
1043 _ => self.unexpected()
1047 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1048 /// passes through any errors encountered. Used for error recovery.
1049 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1050 let handler = self.diagnostic();
1052 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1054 TokenExpectType::Expect,
1055 |p| Ok(p.parse_token_tree())) {
1056 handler.cancel(err);
1060 /// Parse a sequence, including the closing delimiter. The function
1061 /// f must consume tokens until reaching the next separator or
1062 /// closing bracket.
1063 pub fn parse_seq_to_end<T, F>(&mut self,
1067 -> PResult<'a, Vec<T>> where
1068 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1070 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1075 /// Parse a sequence, not 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_before_end<T, F>(&mut self,
1082 -> PResult<'a, Vec<T>>
1083 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1085 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1088 fn parse_seq_to_before_tokens<T, F>(
1090 kets: &[&token::Token],
1092 expect: TokenExpectType,
1094 ) -> PResult<'a, Vec<T>>
1095 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1097 let mut first: bool = true;
1099 while !kets.iter().any(|k| {
1101 TokenExpectType::Expect => self.check(k),
1102 TokenExpectType::NoExpect => self.token == **k,
1106 token::CloseDelim(..) | token::Eof => break,
1109 if let Some(ref t) = sep.sep {
1113 if let Err(mut e) = self.expect(t) {
1114 // Attempt to keep parsing if it was a similar separator
1115 if let Some(ref tokens) = t.similar_tokens() {
1116 if tokens.contains(&self.token) {
1121 // Attempt to keep parsing if it was an omitted separator
1135 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1137 TokenExpectType::Expect => self.check(k),
1138 TokenExpectType::NoExpect => self.token == **k,
1151 /// Parse a sequence, including the closing delimiter. The function
1152 /// f must consume tokens until reaching the next separator or
1153 /// closing bracket.
1154 fn parse_unspanned_seq<T, F>(&mut self,
1159 -> PResult<'a, Vec<T>> where
1160 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1163 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1168 /// Advance the parser by one token
1169 pub fn bump(&mut self) {
1170 if self.prev_token_kind == PrevTokenKind::Eof {
1171 // Bumping after EOF is a bad sign, usually an infinite loop.
1172 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1175 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1177 // Record last token kind for possible error recovery.
1178 self.prev_token_kind = match self.token {
1179 token::DocComment(..) => PrevTokenKind::DocComment,
1180 token::Comma => PrevTokenKind::Comma,
1181 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1182 token::Interpolated(..) => PrevTokenKind::Interpolated,
1183 token::Eof => PrevTokenKind::Eof,
1184 token::Ident(..) => PrevTokenKind::Ident,
1185 _ => PrevTokenKind::Other,
1188 let next = self.next_tok();
1189 self.span = next.sp;
1190 self.token = next.tok;
1191 self.expected_tokens.clear();
1192 // check after each token
1193 self.process_potential_macro_variable();
1196 /// Advance the parser using provided token as a next one. Use this when
1197 /// consuming a part of a token. For example a single `<` from `<<`.
1198 fn bump_with(&mut self, next: token::Token, span: Span) {
1199 self.prev_span = self.span.with_hi(span.lo());
1200 // It would be incorrect to record the kind of the current token, but
1201 // fortunately for tokens currently using `bump_with`, the
1202 // prev_token_kind will be of no use anyway.
1203 self.prev_token_kind = PrevTokenKind::Other;
1206 self.expected_tokens.clear();
1209 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1210 F: FnOnce(&token::Token) -> R,
1213 return f(&self.token)
1216 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1217 Some(tree) => match tree {
1218 TokenTree::Token(_, tok) => tok,
1219 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1221 None => token::CloseDelim(self.token_cursor.frame.delim),
1225 fn look_ahead_span(&self, dist: usize) -> Span {
1230 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1231 Some(TokenTree::Token(span, _)) => span,
1232 Some(TokenTree::Delimited(span, _)) => span.entire(),
1233 None => self.look_ahead_span(dist - 1),
1236 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1237 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1239 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1240 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1242 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1243 err.span_err(sp, self.diagnostic())
1245 fn bug(&self, m: &str) -> ! {
1246 self.sess.span_diagnostic.span_bug(self.span, m)
1248 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1249 self.sess.span_diagnostic.span_err(sp, m)
1251 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1252 self.sess.span_diagnostic.struct_span_err(sp, m)
1254 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1255 self.sess.span_diagnostic.span_bug(sp, m)
1257 crate fn abort_if_errors(&self) {
1258 self.sess.span_diagnostic.abort_if_errors();
1261 fn cancel(&self, err: &mut DiagnosticBuilder) {
1262 self.sess.span_diagnostic.cancel(err)
1265 crate fn diagnostic(&self) -> &'a errors::Handler {
1266 &self.sess.span_diagnostic
1269 /// Is the current token one of the keywords that signals a bare function
1271 fn token_is_bare_fn_keyword(&mut self) -> bool {
1272 self.check_keyword(keywords::Fn) ||
1273 self.check_keyword(keywords::Unsafe) ||
1274 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1277 /// parse a TyKind::BareFn type:
1278 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1281 [unsafe] [extern "ABI"] fn (S) -> T
1291 let unsafety = self.parse_unsafety();
1292 let abi = if self.eat_keyword(keywords::Extern) {
1293 self.parse_opt_abi()?.unwrap_or(Abi::C)
1298 self.expect_keyword(keywords::Fn)?;
1299 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1300 let ret_ty = self.parse_ret_ty(false)?;
1301 let decl = P(FnDecl {
1306 Ok(TyKind::BareFn(P(BareFnTy {
1314 /// Parse asyncness: `async` or nothing
1315 fn parse_asyncness(&mut self) -> IsAsync {
1316 if self.eat_keyword(keywords::Async) {
1318 closure_id: ast::DUMMY_NODE_ID,
1319 return_impl_trait_id: ast::DUMMY_NODE_ID,
1326 /// Parse unsafety: `unsafe` or nothing.
1327 fn parse_unsafety(&mut self) -> Unsafety {
1328 if self.eat_keyword(keywords::Unsafe) {
1335 /// Parse the items in a trait declaration
1336 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1337 maybe_whole!(self, NtTraitItem, |x| x);
1338 let attrs = self.parse_outer_attributes()?;
1339 let (mut item, tokens) = self.collect_tokens(|this| {
1340 this.parse_trait_item_(at_end, attrs)
1342 // See `parse_item` for why this clause is here.
1343 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1344 item.tokens = Some(tokens);
1349 fn parse_trait_item_(&mut self,
1351 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1354 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1355 self.parse_trait_item_assoc_ty()?
1356 } else if self.is_const_item() {
1357 self.expect_keyword(keywords::Const)?;
1358 let ident = self.parse_ident()?;
1359 self.expect(&token::Colon)?;
1360 let ty = self.parse_ty()?;
1361 let default = if self.eat(&token::Eq) {
1362 let expr = self.parse_expr()?;
1363 self.expect(&token::Semi)?;
1366 self.expect(&token::Semi)?;
1369 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1370 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1371 // trait item macro.
1372 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1374 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1376 let ident = self.parse_ident()?;
1377 let mut generics = self.parse_generics()?;
1379 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1380 // This is somewhat dubious; We don't want to allow
1381 // argument names to be left off if there is a
1384 // We don't allow argument names to be left off in edition 2018.
1385 if p.span.edition() >= Edition::Edition2018 {
1386 p.parse_arg_general(true)
1388 p.parse_arg_general(false)
1391 generics.where_clause = self.parse_where_clause()?;
1393 let sig = ast::MethodSig {
1403 let body = match self.token {
1407 debug!("parse_trait_methods(): parsing required method");
1410 token::OpenDelim(token::Brace) => {
1411 debug!("parse_trait_methods(): parsing provided method");
1413 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1414 attrs.extend(inner_attrs.iter().cloned());
1418 let token_str = self.this_token_to_string();
1419 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1421 err.span_label(self.span, "expected `;` or `{`");
1425 (ident, ast::TraitItemKind::Method(sig, body), generics)
1429 id: ast::DUMMY_NODE_ID,
1434 span: lo.to(self.prev_span),
1439 /// Parse optional return type [ -> TY ] in function decl
1440 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1441 if self.eat(&token::RArrow) {
1442 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1444 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1449 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1450 self.parse_ty_common(true, true)
1453 /// Parse a type in restricted contexts where `+` is not permitted.
1454 /// Example 1: `&'a TYPE`
1455 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1456 /// Example 2: `value1 as TYPE + value2`
1457 /// `+` is prohibited to avoid interactions with expression grammar.
1458 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1459 self.parse_ty_common(false, true)
1462 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1463 -> PResult<'a, P<Ty>> {
1464 maybe_whole!(self, NtTy, |x| x);
1467 let mut impl_dyn_multi = false;
1468 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1469 // `(TYPE)` is a parenthesized type.
1470 // `(TYPE,)` is a tuple with a single field of type TYPE.
1471 let mut ts = vec![];
1472 let mut last_comma = false;
1473 while self.token != token::CloseDelim(token::Paren) {
1474 ts.push(self.parse_ty()?);
1475 if self.eat(&token::Comma) {
1482 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1483 self.expect(&token::CloseDelim(token::Paren))?;
1485 if ts.len() == 1 && !last_comma {
1486 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1487 let maybe_bounds = allow_plus && self.token.is_like_plus();
1489 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1490 TyKind::Path(None, ref path) if maybe_bounds => {
1491 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1493 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1494 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1495 let path = match bounds[0] {
1496 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1497 _ => self.bug("unexpected lifetime bound"),
1499 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1502 _ => TyKind::Paren(P(ty))
1507 } else if self.eat(&token::Not) {
1510 } else if self.eat(&token::BinOp(token::Star)) {
1512 TyKind::Ptr(self.parse_ptr()?)
1513 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1515 let t = self.parse_ty()?;
1516 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1517 let t = match self.maybe_parse_fixed_length_of_vec()? {
1518 None => TyKind::Slice(t),
1519 Some(length) => TyKind::Array(t, AnonConst {
1520 id: ast::DUMMY_NODE_ID,
1524 self.expect(&token::CloseDelim(token::Bracket))?;
1526 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1529 self.parse_borrowed_pointee()?
1530 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1532 // In order to not be ambiguous, the type must be surrounded by parens.
1533 self.expect(&token::OpenDelim(token::Paren))?;
1535 id: ast::DUMMY_NODE_ID,
1536 value: self.parse_expr()?,
1538 self.expect(&token::CloseDelim(token::Paren))?;
1540 } else if self.eat_keyword(keywords::Underscore) {
1541 // A type to be inferred `_`
1543 } else if self.token_is_bare_fn_keyword() {
1544 // Function pointer type
1545 self.parse_ty_bare_fn(Vec::new())?
1546 } else if self.check_keyword(keywords::For) {
1547 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1548 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1549 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1551 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1552 if self.token_is_bare_fn_keyword() {
1553 self.parse_ty_bare_fn(lifetime_defs)?
1555 let path = self.parse_path(PathStyle::Type)?;
1556 let parse_plus = allow_plus && self.check_plus();
1557 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1559 } else if self.eat_keyword(keywords::Impl) {
1560 // Always parse bounds greedily for better error recovery.
1561 let bounds = self.parse_generic_bounds()?;
1562 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1563 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1564 } else if self.check_keyword(keywords::Dyn) &&
1565 self.look_ahead(1, |t| t.can_begin_bound() &&
1566 !can_continue_type_after_non_fn_ident(t)) {
1567 self.bump(); // `dyn`
1568 // Always parse bounds greedily for better error recovery.
1569 let bounds = self.parse_generic_bounds()?;
1570 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1571 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1572 } else if self.check(&token::Question) ||
1573 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1574 // Bound list (trait object type)
1575 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1576 TraitObjectSyntax::None)
1577 } else if self.eat_lt() {
1579 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1580 TyKind::Path(Some(qself), path)
1581 } else if self.token.is_path_start() {
1583 let path = self.parse_path(PathStyle::Type)?;
1584 if self.eat(&token::Not) {
1585 // Macro invocation in type position
1586 let (delim, tts) = self.expect_delimited_token_tree()?;
1587 let node = Mac_ { path, tts, delim };
1588 TyKind::Mac(respan(lo.to(self.prev_span), node))
1590 // Just a type path or bound list (trait object type) starting with a trait.
1592 // `Trait1 + Trait2 + 'a`
1593 if allow_plus && self.check_plus() {
1594 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1596 TyKind::Path(None, path)
1600 let msg = format!("expected type, found {}", self.this_token_descr());
1601 return Err(self.fatal(&msg));
1604 let span = lo.to(self.prev_span);
1605 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1607 // Try to recover from use of `+` with incorrect priority.
1608 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1609 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1610 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1615 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1616 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1617 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1618 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1620 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1621 bounds.append(&mut self.parse_generic_bounds()?);
1623 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1626 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1627 if !allow_plus && impl_dyn_multi {
1628 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1629 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1630 .span_suggestion_with_applicability(
1632 "use parentheses to disambiguate",
1634 Applicability::MachineApplicable
1639 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1640 // Do not add `+` to expected tokens.
1641 if !allow_plus || !self.token.is_like_plus() {
1646 let bounds = self.parse_generic_bounds()?;
1647 let sum_span = ty.span.to(self.prev_span);
1649 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1650 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1653 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1654 let sum_with_parens = pprust::to_string(|s| {
1655 use print::pprust::PrintState;
1658 s.print_opt_lifetime(lifetime)?;
1659 s.print_mutability(mut_ty.mutbl)?;
1661 s.print_type(&mut_ty.ty)?;
1662 s.print_type_bounds(" +", &bounds)?;
1665 err.span_suggestion_with_applicability(
1667 "try adding parentheses",
1669 Applicability::MachineApplicable
1672 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1673 err.span_label(sum_span, "perhaps you forgot parentheses?");
1676 err.span_label(sum_span, "expected a path");
1683 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1684 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1686 // Do not add `::` to expected tokens.
1687 if !allow_recovery || self.token != token::ModSep {
1690 let ty = match base.to_ty() {
1692 None => return Ok(base),
1695 self.bump(); // `::`
1696 let mut segments = Vec::new();
1697 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1699 let span = ty.span.to(self.prev_span);
1700 let path_span = span.to(span); // use an empty path since `position` == 0
1701 let recovered = base.to_recovered(
1702 Some(QSelf { ty, path_span, position: 0 }),
1703 ast::Path { segments, span },
1707 .struct_span_err(span, "missing angle brackets in associated item path")
1708 .span_suggestion_with_applicability( // this is a best-effort recovery
1709 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1715 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1716 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1717 let mutbl = self.parse_mutability();
1718 let ty = self.parse_ty_no_plus()?;
1719 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1722 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1723 let mutbl = if self.eat_keyword(keywords::Mut) {
1725 } else if self.eat_keyword(keywords::Const) {
1726 Mutability::Immutable
1728 let span = self.prev_span;
1730 "expected mut or const in raw pointer type (use \
1731 `*mut T` or `*const T` as appropriate)");
1732 Mutability::Immutable
1734 let t = self.parse_ty_no_plus()?;
1735 Ok(MutTy { ty: t, mutbl: mutbl })
1738 fn is_named_argument(&mut self) -> bool {
1739 let offset = match self.token {
1740 token::Interpolated(ref nt) => match nt.0 {
1741 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1744 token::BinOp(token::And) | token::AndAnd => 1,
1745 _ if self.token.is_keyword(keywords::Mut) => 1,
1749 self.look_ahead(offset, |t| t.is_ident()) &&
1750 self.look_ahead(offset + 1, |t| t == &token::Colon)
1753 /// This version of parse arg doesn't necessarily require
1754 /// identifier names.
1755 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1756 maybe_whole!(self, NtArg, |x| x);
1758 let (pat, ty) = if require_name || self.is_named_argument() {
1759 debug!("parse_arg_general parse_pat (require_name:{})",
1761 let pat = self.parse_pat()?;
1763 self.expect(&token::Colon)?;
1764 (pat, self.parse_ty()?)
1766 debug!("parse_arg_general ident_to_pat");
1768 let parser_snapshot_before_pat = self.clone();
1770 // Once we can use edition 2018 in the compiler,
1771 // replace this with real try blocks.
1772 macro_rules! try_block {
1773 ($($inside:tt)*) => (
1774 (||{ ::std::ops::Try::from_ok({ $($inside)* }) })()
1778 // We're going to try parsing the argument as a pattern (even though it's not
1779 // allowed). This way we can provide better errors to the user.
1780 let pat_arg: PResult<'a, _> = try_block! {
1781 let pat = self.parse_pat()?;
1782 self.expect(&token::Colon)?;
1783 (pat, self.parse_ty()?)
1788 let mut err = self.diagnostic().struct_span_err_with_code(
1790 "patterns aren't allowed in methods without bodies",
1791 DiagnosticId::Error("E0642".into()),
1793 err.span_suggestion_short_with_applicability(
1795 "give this argument a name or use an underscore to ignore it",
1797 Applicability::MachineApplicable,
1800 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1802 node: PatKind::Wild,
1804 id: ast::DUMMY_NODE_ID
1810 // Recover from attempting to parse the argument as a pattern. This means
1811 // the type is alone, with no name, e.g. `fn foo(u32)`.
1812 mem::replace(self, parser_snapshot_before_pat);
1813 debug!("parse_arg_general ident_to_pat");
1814 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1815 let ty = self.parse_ty()?;
1817 id: ast::DUMMY_NODE_ID,
1818 node: PatKind::Ident(
1819 BindingMode::ByValue(Mutability::Immutable), ident, None),
1827 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1830 /// Parse a single function argument
1831 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1832 self.parse_arg_general(true)
1835 /// Parse an argument in a lambda header e.g. |arg, arg|
1836 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1837 let pat = self.parse_pat()?;
1838 let t = if self.eat(&token::Colon) {
1842 id: ast::DUMMY_NODE_ID,
1843 node: TyKind::Infer,
1850 id: ast::DUMMY_NODE_ID
1854 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1855 if self.eat(&token::Semi) {
1856 Ok(Some(self.parse_expr()?))
1862 /// Matches token_lit = LIT_INTEGER | ...
1863 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1864 let out = match self.token {
1865 token::Interpolated(ref nt) => match nt.0 {
1866 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1867 ExprKind::Lit(ref lit) => { lit.node.clone() }
1868 _ => { return self.unexpected_last(&self.token); }
1870 _ => { return self.unexpected_last(&self.token); }
1872 token::Literal(lit, suf) => {
1873 let diag = Some((self.span, &self.sess.span_diagnostic));
1874 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1878 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1883 _ => { return self.unexpected_last(&self.token); }
1890 /// Matches lit = true | false | token_lit
1891 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1893 let lit = if self.eat_keyword(keywords::True) {
1895 } else if self.eat_keyword(keywords::False) {
1896 LitKind::Bool(false)
1898 let lit = self.parse_lit_token()?;
1901 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
1904 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1905 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1906 maybe_whole_expr!(self);
1908 let minus_lo = self.span;
1909 let minus_present = self.eat(&token::BinOp(token::Minus));
1911 let literal = P(self.parse_lit()?);
1912 let hi = self.prev_span;
1913 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1916 let minus_hi = self.prev_span;
1917 let unary = self.mk_unary(UnOp::Neg, expr);
1918 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1924 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1926 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1927 let span = self.span;
1929 Ok(Ident::new(ident.name, span))
1931 _ => self.parse_ident(),
1935 /// Parses qualified path.
1936 /// Assumes that the leading `<` has been parsed already.
1938 /// `qualified_path = <type [as trait_ref]>::path`
1943 /// `<T as U>::F::a<S>` (without disambiguator)
1944 /// `<T as U>::F::a::<S>` (with disambiguator)
1945 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1946 let lo = self.prev_span;
1947 let ty = self.parse_ty()?;
1949 // `path` will contain the prefix of the path up to the `>`,
1950 // if any (e.g., `U` in the `<T as U>::*` examples
1951 // above). `path_span` has the span of that path, or an empty
1952 // span in the case of something like `<T>::Bar`.
1953 let (mut path, path_span);
1954 if self.eat_keyword(keywords::As) {
1955 let path_lo = self.span;
1956 path = self.parse_path(PathStyle::Type)?;
1957 path_span = path_lo.to(self.prev_span);
1959 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1960 path_span = self.span.to(self.span);
1963 self.expect(&token::Gt)?;
1964 self.expect(&token::ModSep)?;
1966 let qself = QSelf { ty, path_span, position: path.segments.len() };
1967 self.parse_path_segments(&mut path.segments, style, true)?;
1969 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1972 /// Parses simple paths.
1974 /// `path = [::] segment+`
1975 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1978 /// `a::b::C<D>` (without disambiguator)
1979 /// `a::b::C::<D>` (with disambiguator)
1980 /// `Fn(Args)` (without disambiguator)
1981 /// `Fn::(Args)` (with disambiguator)
1982 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1983 self.parse_path_common(style, true)
1986 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1987 -> PResult<'a, ast::Path> {
1988 maybe_whole!(self, NtPath, |path| {
1989 if style == PathStyle::Mod &&
1990 path.segments.iter().any(|segment| segment.args.is_some()) {
1991 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1996 let lo = self.meta_var_span.unwrap_or(self.span);
1997 let mut segments = Vec::new();
1998 if self.eat(&token::ModSep) {
1999 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
2001 self.parse_path_segments(&mut segments, style, enable_warning)?;
2003 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2006 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2007 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2008 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2009 let meta_ident = match self.token {
2010 token::Interpolated(ref nt) => match nt.0 {
2011 token::NtMeta(ref meta) => match meta.node {
2012 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2019 if let Some(path) = meta_ident {
2023 self.parse_path(style)
2026 fn parse_path_segments(&mut self,
2027 segments: &mut Vec<PathSegment>,
2029 enable_warning: bool)
2030 -> PResult<'a, ()> {
2032 segments.push(self.parse_path_segment(style, enable_warning)?);
2034 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2040 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2041 -> PResult<'a, PathSegment> {
2042 let ident = self.parse_path_segment_ident()?;
2044 let is_args_start = |token: &token::Token| match *token {
2045 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2048 let check_args_start = |this: &mut Self| {
2049 this.expected_tokens.extend_from_slice(
2050 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2052 is_args_start(&this.token)
2055 Ok(if style == PathStyle::Type && check_args_start(self) ||
2056 style != PathStyle::Mod && self.check(&token::ModSep)
2057 && self.look_ahead(1, |t| is_args_start(t)) {
2058 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2060 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2061 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2062 .span_label(self.prev_span, "try removing `::`").emit();
2065 let args = if self.eat_lt() {
2067 let (args, bindings) = self.parse_generic_args()?;
2069 let span = lo.to(self.prev_span);
2070 AngleBracketedArgs { args, bindings, span }.into()
2074 let inputs = self.parse_seq_to_before_tokens(
2075 &[&token::CloseDelim(token::Paren)],
2076 SeqSep::trailing_allowed(token::Comma),
2077 TokenExpectType::Expect,
2080 let span = lo.to(self.prev_span);
2081 let output = if self.eat(&token::RArrow) {
2082 Some(self.parse_ty_common(false, false)?)
2086 ParenthesisedArgs { inputs, output, span }.into()
2089 PathSegment { ident, args }
2091 // Generic arguments are not found.
2092 PathSegment::from_ident(ident)
2096 crate fn check_lifetime(&mut self) -> bool {
2097 self.expected_tokens.push(TokenType::Lifetime);
2098 self.token.is_lifetime()
2101 /// Parse single lifetime 'a or panic.
2102 crate fn expect_lifetime(&mut self) -> Lifetime {
2103 if let Some(ident) = self.token.lifetime() {
2104 let span = self.span;
2106 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2108 self.span_bug(self.span, "not a lifetime")
2112 fn eat_label(&mut self) -> Option<Label> {
2113 if let Some(ident) = self.token.lifetime() {
2114 let span = self.span;
2116 Some(Label { ident: Ident::new(ident.name, span) })
2122 /// Parse mutability (`mut` or nothing).
2123 fn parse_mutability(&mut self) -> Mutability {
2124 if self.eat_keyword(keywords::Mut) {
2127 Mutability::Immutable
2131 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2132 if let token::Literal(token::Integer(name), None) = self.token {
2134 Ok(Ident::new(name, self.prev_span))
2136 self.parse_ident_common(false)
2140 /// Parse ident (COLON expr)?
2141 fn parse_field(&mut self) -> PResult<'a, Field> {
2142 let attrs = self.parse_outer_attributes()?;
2145 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2146 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2147 let fieldname = self.parse_field_name()?;
2149 (fieldname, self.parse_expr()?, false)
2151 let fieldname = self.parse_ident_common(false)?;
2153 // Mimic `x: x` for the `x` field shorthand.
2154 let path = ast::Path::from_ident(fieldname);
2155 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2156 (fieldname, expr, true)
2160 span: lo.to(expr.span),
2163 attrs: attrs.into(),
2167 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2168 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2171 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2172 ExprKind::Unary(unop, expr)
2175 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2176 ExprKind::Binary(binop, lhs, rhs)
2179 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2180 ExprKind::Call(f, args)
2183 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2184 ExprKind::Index(expr, idx)
2187 fn mk_range(&mut self,
2188 start: Option<P<Expr>>,
2189 end: Option<P<Expr>>,
2190 limits: RangeLimits)
2191 -> PResult<'a, ast::ExprKind> {
2192 if end.is_none() && limits == RangeLimits::Closed {
2193 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2195 Ok(ExprKind::Range(start, end, limits))
2199 fn mk_assign_op(&mut self, binop: ast::BinOp,
2200 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2201 ExprKind::AssignOp(binop, lhs, rhs)
2204 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2206 id: ast::DUMMY_NODE_ID,
2207 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2213 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2214 let delim = match self.token {
2215 token::OpenDelim(delim) => delim,
2217 let msg = "expected open delimiter";
2218 let mut err = self.fatal(msg);
2219 err.span_label(self.span, msg);
2223 let delimited = match self.parse_token_tree() {
2224 TokenTree::Delimited(_, delimited) => delimited,
2225 _ => unreachable!(),
2227 let delim = match delim {
2228 token::Paren => MacDelimiter::Parenthesis,
2229 token::Bracket => MacDelimiter::Bracket,
2230 token::Brace => MacDelimiter::Brace,
2231 token::NoDelim => self.bug("unexpected no delimiter"),
2233 Ok((delim, delimited.stream().into()))
2236 /// At the bottom (top?) of the precedence hierarchy,
2237 /// parse things like parenthesized exprs,
2238 /// macros, return, etc.
2240 /// NB: This does not parse outer attributes,
2241 /// and is private because it only works
2242 /// correctly if called from parse_dot_or_call_expr().
2243 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2244 maybe_whole_expr!(self);
2246 // Outer attributes are already parsed and will be
2247 // added to the return value after the fact.
2249 // Therefore, prevent sub-parser from parsing
2250 // attributes by giving them a empty "already parsed" list.
2251 let mut attrs = ThinVec::new();
2254 let mut hi = self.span;
2258 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2260 token::OpenDelim(token::Paren) => {
2263 attrs.extend(self.parse_inner_attributes()?);
2265 // (e) is parenthesized e
2266 // (e,) is a tuple with only one field, e
2267 let mut es = vec![];
2268 let mut trailing_comma = false;
2269 while self.token != token::CloseDelim(token::Paren) {
2270 es.push(self.parse_expr()?);
2271 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2272 if self.eat(&token::Comma) {
2273 trailing_comma = true;
2275 trailing_comma = false;
2281 hi = self.prev_span;
2282 ex = if es.len() == 1 && !trailing_comma {
2283 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2288 token::OpenDelim(token::Brace) => {
2289 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2291 token::BinOp(token::Or) | token::OrOr => {
2292 return self.parse_lambda_expr(attrs);
2294 token::OpenDelim(token::Bracket) => {
2297 attrs.extend(self.parse_inner_attributes()?);
2299 if self.eat(&token::CloseDelim(token::Bracket)) {
2301 ex = ExprKind::Array(Vec::new());
2304 let first_expr = self.parse_expr()?;
2305 if self.eat(&token::Semi) {
2306 // Repeating array syntax: [ 0; 512 ]
2307 let count = AnonConst {
2308 id: ast::DUMMY_NODE_ID,
2309 value: self.parse_expr()?,
2311 self.expect(&token::CloseDelim(token::Bracket))?;
2312 ex = ExprKind::Repeat(first_expr, count);
2313 } else if self.eat(&token::Comma) {
2314 // Vector with two or more elements.
2315 let remaining_exprs = self.parse_seq_to_end(
2316 &token::CloseDelim(token::Bracket),
2317 SeqSep::trailing_allowed(token::Comma),
2318 |p| Ok(p.parse_expr()?)
2320 let mut exprs = vec![first_expr];
2321 exprs.extend(remaining_exprs);
2322 ex = ExprKind::Array(exprs);
2324 // Vector with one element.
2325 self.expect(&token::CloseDelim(token::Bracket))?;
2326 ex = ExprKind::Array(vec![first_expr]);
2329 hi = self.prev_span;
2333 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2335 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2337 if self.span.edition() >= Edition::Edition2018 &&
2338 self.check_keyword(keywords::Async)
2340 if self.is_async_block() { // check for `async {` and `async move {`
2341 return self.parse_async_block(attrs);
2343 return self.parse_lambda_expr(attrs);
2346 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2347 return self.parse_lambda_expr(attrs);
2349 if self.eat_keyword(keywords::If) {
2350 return self.parse_if_expr(attrs);
2352 if self.eat_keyword(keywords::For) {
2353 let lo = self.prev_span;
2354 return self.parse_for_expr(None, lo, attrs);
2356 if self.eat_keyword(keywords::While) {
2357 let lo = self.prev_span;
2358 return self.parse_while_expr(None, lo, attrs);
2360 if let Some(label) = self.eat_label() {
2361 let lo = label.ident.span;
2362 self.expect(&token::Colon)?;
2363 if self.eat_keyword(keywords::While) {
2364 return self.parse_while_expr(Some(label), lo, attrs)
2366 if self.eat_keyword(keywords::For) {
2367 return self.parse_for_expr(Some(label), lo, attrs)
2369 if self.eat_keyword(keywords::Loop) {
2370 return self.parse_loop_expr(Some(label), lo, attrs)
2372 if self.token == token::OpenDelim(token::Brace) {
2373 return self.parse_block_expr(Some(label),
2375 BlockCheckMode::Default,
2378 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2379 let mut err = self.fatal(msg);
2380 err.span_label(self.span, msg);
2383 if self.eat_keyword(keywords::Loop) {
2384 let lo = self.prev_span;
2385 return self.parse_loop_expr(None, lo, attrs);
2387 if self.eat_keyword(keywords::Continue) {
2388 let label = self.eat_label();
2389 let ex = ExprKind::Continue(label);
2390 let hi = self.prev_span;
2391 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2393 if self.eat_keyword(keywords::Match) {
2394 return self.parse_match_expr(attrs);
2396 if self.eat_keyword(keywords::Unsafe) {
2397 return self.parse_block_expr(
2400 BlockCheckMode::Unsafe(ast::UserProvided),
2403 if self.is_do_catch_block() {
2404 let mut db = self.fatal("found removed `do catch` syntax");
2405 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2408 if self.is_try_block() {
2410 assert!(self.eat_keyword(keywords::Try));
2411 return self.parse_try_block(lo, attrs);
2413 if self.eat_keyword(keywords::Return) {
2414 if self.token.can_begin_expr() {
2415 let e = self.parse_expr()?;
2417 ex = ExprKind::Ret(Some(e));
2419 ex = ExprKind::Ret(None);
2421 } else if self.eat_keyword(keywords::Break) {
2422 let label = self.eat_label();
2423 let e = if self.token.can_begin_expr()
2424 && !(self.token == token::OpenDelim(token::Brace)
2425 && self.restrictions.contains(
2426 Restrictions::NO_STRUCT_LITERAL)) {
2427 Some(self.parse_expr()?)
2431 ex = ExprKind::Break(label, e);
2432 hi = self.prev_span;
2433 } else if self.eat_keyword(keywords::Yield) {
2434 if self.token.can_begin_expr() {
2435 let e = self.parse_expr()?;
2437 ex = ExprKind::Yield(Some(e));
2439 ex = ExprKind::Yield(None);
2441 } else if self.token.is_keyword(keywords::Let) {
2442 // Catch this syntax error here, instead of in `parse_ident`, so
2443 // that we can explicitly mention that let is not to be used as an expression
2444 let mut db = self.fatal("expected expression, found statement (`let`)");
2445 db.span_label(self.span, "expected expression");
2446 db.note("variable declaration using `let` is a statement");
2448 } else if self.token.is_path_start() {
2449 let pth = self.parse_path(PathStyle::Expr)?;
2451 // `!`, as an operator, is prefix, so we know this isn't that
2452 if self.eat(&token::Not) {
2453 // MACRO INVOCATION expression
2454 let (delim, tts) = self.expect_delimited_token_tree()?;
2455 let hi = self.prev_span;
2456 let node = Mac_ { path: pth, tts, delim };
2457 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2459 if self.check(&token::OpenDelim(token::Brace)) {
2460 // This is a struct literal, unless we're prohibited
2461 // from parsing struct literals here.
2462 let prohibited = self.restrictions.contains(
2463 Restrictions::NO_STRUCT_LITERAL
2466 return self.parse_struct_expr(lo, pth, attrs);
2471 ex = ExprKind::Path(None, pth);
2473 match self.parse_literal_maybe_minus() {
2476 ex = expr.node.clone();
2479 self.cancel(&mut err);
2480 let msg = format!("expected expression, found {}",
2481 self.this_token_descr());
2482 let mut err = self.fatal(&msg);
2483 err.span_label(self.span, "expected expression");
2491 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2492 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2497 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2498 -> PResult<'a, P<Expr>> {
2499 let struct_sp = lo.to(self.prev_span);
2501 let mut fields = Vec::new();
2502 let mut base = None;
2504 attrs.extend(self.parse_inner_attributes()?);
2506 while self.token != token::CloseDelim(token::Brace) {
2507 if self.eat(&token::DotDot) {
2508 let exp_span = self.prev_span;
2509 match self.parse_expr() {
2515 self.recover_stmt();
2518 if self.token == token::Comma {
2519 let mut err = self.sess.span_diagnostic.mut_span_err(
2520 exp_span.to(self.prev_span),
2521 "cannot use a comma after the base struct",
2523 err.span_suggestion_short_with_applicability(
2525 "remove this comma",
2527 Applicability::MachineApplicable
2529 err.note("the base struct must always be the last field");
2531 self.recover_stmt();
2536 match self.parse_field() {
2537 Ok(f) => fields.push(f),
2539 e.span_label(struct_sp, "while parsing this struct");
2542 // If the next token is a comma, then try to parse
2543 // what comes next as additional fields, rather than
2544 // bailing out until next `}`.
2545 if self.token != token::Comma {
2546 self.recover_stmt();
2552 match self.expect_one_of(&[token::Comma],
2553 &[token::CloseDelim(token::Brace)]) {
2557 self.recover_stmt();
2563 let span = lo.to(self.span);
2564 self.expect(&token::CloseDelim(token::Brace))?;
2565 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2568 fn parse_or_use_outer_attributes(&mut self,
2569 already_parsed_attrs: Option<ThinVec<Attribute>>)
2570 -> PResult<'a, ThinVec<Attribute>> {
2571 if let Some(attrs) = already_parsed_attrs {
2574 self.parse_outer_attributes().map(|a| a.into())
2578 /// Parse a block or unsafe block
2579 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2580 lo: Span, blk_mode: BlockCheckMode,
2581 outer_attrs: ThinVec<Attribute>)
2582 -> PResult<'a, P<Expr>> {
2583 self.expect(&token::OpenDelim(token::Brace))?;
2585 let mut attrs = outer_attrs;
2586 attrs.extend(self.parse_inner_attributes()?);
2588 let blk = self.parse_block_tail(lo, blk_mode)?;
2589 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2592 /// parse a.b or a(13) or a[4] or just a
2593 fn parse_dot_or_call_expr(&mut self,
2594 already_parsed_attrs: Option<ThinVec<Attribute>>)
2595 -> PResult<'a, P<Expr>> {
2596 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2598 let b = self.parse_bottom_expr();
2599 let (span, b) = self.interpolated_or_expr_span(b)?;
2600 self.parse_dot_or_call_expr_with(b, span, attrs)
2603 fn parse_dot_or_call_expr_with(&mut self,
2606 mut attrs: ThinVec<Attribute>)
2607 -> PResult<'a, P<Expr>> {
2608 // Stitch the list of outer attributes onto the return value.
2609 // A little bit ugly, but the best way given the current code
2611 self.parse_dot_or_call_expr_with_(e0, lo)
2613 expr.map(|mut expr| {
2614 attrs.extend::<Vec<_>>(expr.attrs.into());
2617 ExprKind::If(..) | ExprKind::IfLet(..) => {
2618 if !expr.attrs.is_empty() {
2619 // Just point to the first attribute in there...
2620 let span = expr.attrs[0].span;
2623 "attributes are not yet allowed on `if` \
2634 // Assuming we have just parsed `.`, continue parsing into an expression.
2635 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2636 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2637 Ok(match self.token {
2638 token::OpenDelim(token::Paren) => {
2639 // Method call `expr.f()`
2640 let mut args = self.parse_unspanned_seq(
2641 &token::OpenDelim(token::Paren),
2642 &token::CloseDelim(token::Paren),
2643 SeqSep::trailing_allowed(token::Comma),
2644 |p| Ok(p.parse_expr()?)
2646 args.insert(0, self_arg);
2648 let span = lo.to(self.prev_span);
2649 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2652 // Field access `expr.f`
2653 if let Some(args) = segment.args {
2654 self.span_err(args.span(),
2655 "field expressions may not have generic arguments");
2658 let span = lo.to(self.prev_span);
2659 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2664 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2669 while self.eat(&token::Question) {
2670 let hi = self.prev_span;
2671 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2675 if self.eat(&token::Dot) {
2677 token::Ident(..) => {
2678 e = self.parse_dot_suffix(e, lo)?;
2680 token::Literal(token::Integer(name), _) => {
2681 let span = self.span;
2683 let field = ExprKind::Field(e, Ident::new(name, span));
2684 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2686 token::Literal(token::Float(n), _suf) => {
2688 let fstr = n.as_str();
2689 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2690 &format!("unexpected token: `{}`", n));
2691 err.span_label(self.prev_span, "unexpected token");
2692 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2693 let float = match fstr.parse::<f64>().ok() {
2697 let sugg = pprust::to_string(|s| {
2698 use print::pprust::PrintState;
2702 s.print_usize(float.trunc() as usize)?;
2705 s.s.word(fstr.splitn(2, ".").last().unwrap())
2707 err.span_suggestion_with_applicability(
2708 lo.to(self.prev_span),
2709 "try parenthesizing the first index",
2711 Applicability::MachineApplicable
2718 // FIXME Could factor this out into non_fatal_unexpected or something.
2719 let actual = self.this_token_to_string();
2720 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2725 if self.expr_is_complete(&e) { break; }
2728 token::OpenDelim(token::Paren) => {
2729 let es = self.parse_unspanned_seq(
2730 &token::OpenDelim(token::Paren),
2731 &token::CloseDelim(token::Paren),
2732 SeqSep::trailing_allowed(token::Comma),
2733 |p| Ok(p.parse_expr()?)
2735 hi = self.prev_span;
2737 let nd = self.mk_call(e, es);
2738 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2742 // Could be either an index expression or a slicing expression.
2743 token::OpenDelim(token::Bracket) => {
2745 let ix = self.parse_expr()?;
2747 self.expect(&token::CloseDelim(token::Bracket))?;
2748 let index = self.mk_index(e, ix);
2749 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2757 crate fn process_potential_macro_variable(&mut self) {
2758 let (token, span) = match self.token {
2759 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2760 self.look_ahead(1, |t| t.is_ident()) => {
2762 let name = match self.token {
2763 token::Ident(ident, _) => ident,
2766 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2767 err.span_label(self.span, "unknown macro variable");
2771 token::Interpolated(ref nt) => {
2772 self.meta_var_span = Some(self.span);
2773 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2774 // and lifetime tokens, so the former are never encountered during normal parsing.
2776 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2777 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2787 /// parse a single token tree from the input.
2788 crate fn parse_token_tree(&mut self) -> TokenTree {
2790 token::OpenDelim(..) => {
2791 let frame = mem::replace(&mut self.token_cursor.frame,
2792 self.token_cursor.stack.pop().unwrap());
2793 self.span = frame.span.entire();
2795 TokenTree::Delimited(frame.span, Delimited {
2797 tts: frame.tree_cursor.original_stream().into(),
2800 token::CloseDelim(_) | token::Eof => unreachable!(),
2802 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2804 TokenTree::Token(span, token)
2809 // parse a stream of tokens into a list of TokenTree's,
2811 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2812 let mut tts = Vec::new();
2813 while self.token != token::Eof {
2814 tts.push(self.parse_token_tree());
2819 pub fn parse_tokens(&mut self) -> TokenStream {
2820 let mut result = Vec::new();
2823 token::Eof | token::CloseDelim(..) => break,
2824 _ => result.push(self.parse_token_tree().into()),
2827 TokenStream::concat(result)
2830 /// Parse a prefix-unary-operator expr
2831 fn parse_prefix_expr(&mut self,
2832 already_parsed_attrs: Option<ThinVec<Attribute>>)
2833 -> PResult<'a, P<Expr>> {
2834 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2836 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2837 let (hi, ex) = match self.token {
2840 let e = self.parse_prefix_expr(None);
2841 let (span, e) = self.interpolated_or_expr_span(e)?;
2842 (lo.to(span), self.mk_unary(UnOp::Not, e))
2844 // Suggest `!` for bitwise negation when encountering a `~`
2847 let e = self.parse_prefix_expr(None);
2848 let (span, e) = self.interpolated_or_expr_span(e)?;
2849 let span_of_tilde = lo;
2850 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2851 "`~` cannot be used as a unary operator");
2852 err.span_suggestion_short_with_applicability(
2854 "use `!` to perform bitwise negation",
2856 Applicability::MachineApplicable
2859 (lo.to(span), self.mk_unary(UnOp::Not, e))
2861 token::BinOp(token::Minus) => {
2863 let e = self.parse_prefix_expr(None);
2864 let (span, e) = self.interpolated_or_expr_span(e)?;
2865 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2867 token::BinOp(token::Star) => {
2869 let e = self.parse_prefix_expr(None);
2870 let (span, e) = self.interpolated_or_expr_span(e)?;
2871 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2873 token::BinOp(token::And) | token::AndAnd => {
2875 let m = self.parse_mutability();
2876 let e = self.parse_prefix_expr(None);
2877 let (span, e) = self.interpolated_or_expr_span(e)?;
2878 (lo.to(span), ExprKind::AddrOf(m, e))
2880 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2882 let place = self.parse_expr_res(
2883 Restrictions::NO_STRUCT_LITERAL,
2886 let blk = self.parse_block()?;
2887 let span = blk.span;
2888 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2889 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2891 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2893 let e = self.parse_prefix_expr(None);
2894 let (span, e) = self.interpolated_or_expr_span(e)?;
2895 (lo.to(span), ExprKind::Box(e))
2897 token::Ident(..) if self.token.is_ident_named("not") => {
2898 // `not` is just an ordinary identifier in Rust-the-language,
2899 // but as `rustc`-the-compiler, we can issue clever diagnostics
2900 // for confused users who really want to say `!`
2901 let token_cannot_continue_expr = |t: &token::Token| match *t {
2902 // These tokens can start an expression after `!`, but
2903 // can't continue an expression after an ident
2904 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2905 token::Literal(..) | token::Pound => true,
2906 token::Interpolated(ref nt) => match nt.0 {
2907 token::NtIdent(..) | token::NtExpr(..) |
2908 token::NtBlock(..) | token::NtPath(..) => true,
2913 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2914 if cannot_continue_expr {
2916 // Emit the error ...
2917 let mut err = self.diagnostic()
2918 .struct_span_err(self.span,
2919 &format!("unexpected {} after identifier",
2920 self.this_token_descr()));
2921 // span the `not` plus trailing whitespace to avoid
2922 // trailing whitespace after the `!` in our suggestion
2923 let to_replace = self.sess.source_map()
2924 .span_until_non_whitespace(lo.to(self.span));
2925 err.span_suggestion_short_with_applicability(
2927 "use `!` to perform logical negation",
2929 Applicability::MachineApplicable
2932 // —and recover! (just as if we were in the block
2933 // for the `token::Not` arm)
2934 let e = self.parse_prefix_expr(None);
2935 let (span, e) = self.interpolated_or_expr_span(e)?;
2936 (lo.to(span), self.mk_unary(UnOp::Not, e))
2938 return self.parse_dot_or_call_expr(Some(attrs));
2941 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2943 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2946 /// Parse an associative expression
2948 /// This parses an expression accounting for associativity and precedence of the operators in
2950 fn parse_assoc_expr(&mut self,
2951 already_parsed_attrs: Option<ThinVec<Attribute>>)
2952 -> PResult<'a, P<Expr>> {
2953 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2956 /// Parse an associative expression with operators of at least `min_prec` precedence
2957 fn parse_assoc_expr_with(&mut self,
2960 -> PResult<'a, P<Expr>> {
2961 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2964 let attrs = match lhs {
2965 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2968 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2969 return self.parse_prefix_range_expr(attrs);
2971 self.parse_prefix_expr(attrs)?
2975 if self.expr_is_complete(&lhs) {
2976 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2979 self.expected_tokens.push(TokenType::Operator);
2980 while let Some(op) = AssocOp::from_token(&self.token) {
2982 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2983 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2984 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2985 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2986 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2987 (PrevTokenKind::Interpolated, _) => self.prev_span,
2988 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2989 if path.segments.len() == 1 => self.prev_span,
2993 let cur_op_span = self.span;
2994 let restrictions = if op.is_assign_like() {
2995 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2999 if op.precedence() < min_prec {
3002 // Check for deprecated `...` syntax
3003 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3004 self.err_dotdotdot_syntax(self.span);
3008 if op.is_comparison() {
3009 self.check_no_chained_comparison(&lhs, &op);
3012 if op == AssocOp::As {
3013 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3015 } else if op == AssocOp::Colon {
3016 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3019 err.span_label(self.span,
3020 "expecting a type here because of type ascription");
3021 let cm = self.sess.source_map();
3022 let cur_pos = cm.lookup_char_pos(self.span.lo());
3023 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3024 if cur_pos.line != op_pos.line {
3025 err.span_suggestion_with_applicability(
3027 "try using a semicolon",
3029 Applicability::MaybeIncorrect // speculative
3036 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3037 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3038 // generalise it to the Fixity::None code.
3040 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3041 // two variants are handled with `parse_prefix_range_expr` call above.
3042 let rhs = if self.is_at_start_of_range_notation_rhs() {
3043 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3044 LhsExpr::NotYetParsed)?)
3048 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3053 let limits = if op == AssocOp::DotDot {
3054 RangeLimits::HalfOpen
3059 let r = try!(self.mk_range(Some(lhs), rhs, limits));
3060 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3064 let rhs = match op.fixity() {
3065 Fixity::Right => self.with_res(
3066 restrictions - Restrictions::STMT_EXPR,
3068 this.parse_assoc_expr_with(op.precedence(),
3069 LhsExpr::NotYetParsed)
3071 Fixity::Left => self.with_res(
3072 restrictions - Restrictions::STMT_EXPR,
3074 this.parse_assoc_expr_with(op.precedence() + 1,
3075 LhsExpr::NotYetParsed)
3077 // We currently have no non-associative operators that are not handled above by
3078 // the special cases. The code is here only for future convenience.
3079 Fixity::None => self.with_res(
3080 restrictions - Restrictions::STMT_EXPR,
3082 this.parse_assoc_expr_with(op.precedence() + 1,
3083 LhsExpr::NotYetParsed)
3087 let span = lhs_span.to(rhs.span);
3089 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3090 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3091 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3092 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3093 AssocOp::Greater | AssocOp::GreaterEqual => {
3094 let ast_op = op.to_ast_binop().unwrap();
3095 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3096 self.mk_expr(span, binary, ThinVec::new())
3099 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3100 AssocOp::ObsoleteInPlace =>
3101 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3102 AssocOp::AssignOp(k) => {
3104 token::Plus => BinOpKind::Add,
3105 token::Minus => BinOpKind::Sub,
3106 token::Star => BinOpKind::Mul,
3107 token::Slash => BinOpKind::Div,
3108 token::Percent => BinOpKind::Rem,
3109 token::Caret => BinOpKind::BitXor,
3110 token::And => BinOpKind::BitAnd,
3111 token::Or => BinOpKind::BitOr,
3112 token::Shl => BinOpKind::Shl,
3113 token::Shr => BinOpKind::Shr,
3115 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3116 self.mk_expr(span, aopexpr, ThinVec::new())
3118 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3119 self.bug("AssocOp should have been handled by special case")
3123 if op.fixity() == Fixity::None { break }
3128 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3129 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3130 -> PResult<'a, P<Expr>> {
3131 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3132 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3135 // Save the state of the parser before parsing type normally, in case there is a
3136 // LessThan comparison after this cast.
3137 let parser_snapshot_before_type = self.clone();
3138 match self.parse_ty_no_plus() {
3140 Ok(mk_expr(self, rhs))
3142 Err(mut type_err) => {
3143 // Rewind to before attempting to parse the type with generics, to recover
3144 // from situations like `x as usize < y` in which we first tried to parse
3145 // `usize < y` as a type with generic arguments.
3146 let parser_snapshot_after_type = self.clone();
3147 mem::replace(self, parser_snapshot_before_type);
3149 match self.parse_path(PathStyle::Expr) {
3151 let (op_noun, op_verb) = match self.token {
3152 token::Lt => ("comparison", "comparing"),
3153 token::BinOp(token::Shl) => ("shift", "shifting"),
3155 // We can end up here even without `<` being the next token, for
3156 // example because `parse_ty_no_plus` returns `Err` on keywords,
3157 // but `parse_path` returns `Ok` on them due to error recovery.
3158 // Return original error and parser state.
3159 mem::replace(self, parser_snapshot_after_type);
3160 return Err(type_err);
3164 // Successfully parsed the type path leaving a `<` yet to parse.
3167 // Report non-fatal diagnostics, keep `x as usize` as an expression
3168 // in AST and continue parsing.
3169 let msg = format!("`<` is interpreted as a start of generic \
3170 arguments for `{}`, not a {}", path, op_noun);
3171 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3172 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3173 "interpreted as generic arguments");
3174 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3176 let expr = mk_expr(self, P(Ty {
3178 node: TyKind::Path(None, path),
3179 id: ast::DUMMY_NODE_ID
3182 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3183 .unwrap_or(pprust::expr_to_string(&expr));
3184 err.span_suggestion_with_applicability(
3186 &format!("try {} the cast value", op_verb),
3187 format!("({})", expr_str),
3188 Applicability::MachineApplicable
3194 Err(mut path_err) => {
3195 // Couldn't parse as a path, return original error and parser state.
3197 mem::replace(self, parser_snapshot_after_type);
3205 /// Produce an error if comparison operators are chained (RFC #558).
3206 /// We only need to check lhs, not rhs, because all comparison ops
3207 /// have same precedence and are left-associative
3208 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3209 debug_assert!(outer_op.is_comparison(),
3210 "check_no_chained_comparison: {:?} is not comparison",
3213 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3214 // respan to include both operators
3215 let op_span = op.span.to(self.span);
3216 let mut err = self.diagnostic().struct_span_err(op_span,
3217 "chained comparison operators require parentheses");
3218 if op.node == BinOpKind::Lt &&
3219 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3220 *outer_op == AssocOp::Greater // even in a case like the following:
3221 { // Foo<Bar<Baz<Qux, ()>>>
3223 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3224 err.help("or use `(...)` if you meant to specify fn arguments");
3232 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3233 fn parse_prefix_range_expr(&mut self,
3234 already_parsed_attrs: Option<ThinVec<Attribute>>)
3235 -> PResult<'a, P<Expr>> {
3236 // Check for deprecated `...` syntax
3237 if self.token == token::DotDotDot {
3238 self.err_dotdotdot_syntax(self.span);
3241 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3242 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3244 let tok = self.token.clone();
3245 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3247 let mut hi = self.span;
3249 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3250 // RHS must be parsed with more associativity than the dots.
3251 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3252 Some(self.parse_assoc_expr_with(next_prec,
3253 LhsExpr::NotYetParsed)
3261 let limits = if tok == token::DotDot {
3262 RangeLimits::HalfOpen
3267 let r = try!(self.mk_range(None,
3270 Ok(self.mk_expr(lo.to(hi), r, attrs))
3273 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3274 if self.token.can_begin_expr() {
3275 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3276 if self.token == token::OpenDelim(token::Brace) {
3277 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3285 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3286 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3287 if self.check_keyword(keywords::Let) {
3288 return self.parse_if_let_expr(attrs);
3290 let lo = self.prev_span;
3291 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3293 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3294 // verify that the last statement is either an implicit return (no `;`) or an explicit
3295 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3296 // the dead code lint.
3297 if self.eat_keyword(keywords::Else) || !cond.returns() {
3298 let sp = self.sess.source_map().next_point(lo);
3299 let mut err = self.diagnostic()
3300 .struct_span_err(sp, "missing condition for `if` statemement");
3301 err.span_label(sp, "expected if condition here");
3304 let not_block = self.token != token::OpenDelim(token::Brace);
3305 let thn = self.parse_block().map_err(|mut err| {
3307 err.span_label(lo, "this `if` statement has a condition, but no block");
3311 let mut els: Option<P<Expr>> = None;
3312 let mut hi = thn.span;
3313 if self.eat_keyword(keywords::Else) {
3314 let elexpr = self.parse_else_expr()?;
3318 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3321 /// Parse an 'if let' expression ('if' token already eaten)
3322 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3323 -> PResult<'a, P<Expr>> {
3324 let lo = self.prev_span;
3325 self.expect_keyword(keywords::Let)?;
3326 let pats = self.parse_pats()?;
3327 self.expect(&token::Eq)?;
3328 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3329 let thn = self.parse_block()?;
3330 let (hi, els) = if self.eat_keyword(keywords::Else) {
3331 let expr = self.parse_else_expr()?;
3332 (expr.span, Some(expr))
3336 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3339 // `move |args| expr`
3340 fn parse_lambda_expr(&mut self,
3341 attrs: ThinVec<Attribute>)
3342 -> PResult<'a, P<Expr>>
3345 let movability = if self.eat_keyword(keywords::Static) {
3350 let asyncness = if self.span.edition() >= Edition::Edition2018 {
3351 self.parse_asyncness()
3355 let capture_clause = if self.eat_keyword(keywords::Move) {
3360 let decl = self.parse_fn_block_decl()?;
3361 let decl_hi = self.prev_span;
3362 let body = match decl.output {
3363 FunctionRetTy::Default(_) => {
3364 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3365 self.parse_expr_res(restrictions, None)?
3368 // If an explicit return type is given, require a
3369 // block to appear (RFC 968).
3370 let body_lo = self.span;
3371 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3377 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3381 // `else` token already eaten
3382 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3383 if self.eat_keyword(keywords::If) {
3384 return self.parse_if_expr(ThinVec::new());
3386 let blk = self.parse_block()?;
3387 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3391 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3392 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3394 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3395 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3397 let pat = self.parse_top_level_pat()?;
3398 if !self.eat_keyword(keywords::In) {
3399 let in_span = self.prev_span.between(self.span);
3400 let mut err = self.sess.span_diagnostic
3401 .struct_span_err(in_span, "missing `in` in `for` loop");
3402 err.span_suggestion_short_with_applicability(
3403 in_span, "try adding `in` here", " in ".into(),
3404 // has been misleading, at least in the past (closed Issue #48492)
3405 Applicability::MaybeIncorrect
3409 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3410 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3411 attrs.extend(iattrs);
3413 let hi = self.prev_span;
3414 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3417 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3418 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3420 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3421 if self.token.is_keyword(keywords::Let) {
3422 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3424 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3425 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3426 attrs.extend(iattrs);
3427 let span = span_lo.to(body.span);
3428 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3431 /// Parse a 'while let' expression ('while' token already eaten)
3432 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3434 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3435 self.expect_keyword(keywords::Let)?;
3436 let pats = self.parse_pats()?;
3437 self.expect(&token::Eq)?;
3438 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3439 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3440 attrs.extend(iattrs);
3441 let span = span_lo.to(body.span);
3442 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3445 // parse `loop {...}`, `loop` token already eaten
3446 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3448 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3449 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3450 attrs.extend(iattrs);
3451 let span = span_lo.to(body.span);
3452 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3455 /// Parse an `async move {...}` expression
3456 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3457 -> PResult<'a, P<Expr>>
3459 let span_lo = self.span;
3460 self.expect_keyword(keywords::Async)?;
3461 let capture_clause = if self.eat_keyword(keywords::Move) {
3466 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3467 attrs.extend(iattrs);
3469 span_lo.to(body.span),
3470 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3473 /// Parse a `try {...}` expression (`try` token already eaten)
3474 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3475 -> PResult<'a, P<Expr>>
3477 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3478 attrs.extend(iattrs);
3479 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3482 // `match` token already eaten
3483 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3484 let match_span = self.prev_span;
3485 let lo = self.prev_span;
3486 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3488 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3489 if self.token == token::Token::Semi {
3490 e.span_suggestion_short_with_applicability(
3492 "try removing this `match`",
3494 Applicability::MaybeIncorrect // speculative
3499 attrs.extend(self.parse_inner_attributes()?);
3501 let mut arms: Vec<Arm> = Vec::new();
3502 while self.token != token::CloseDelim(token::Brace) {
3503 match self.parse_arm() {
3504 Ok(arm) => arms.push(arm),
3506 // Recover by skipping to the end of the block.
3508 self.recover_stmt();
3509 let span = lo.to(self.span);
3510 if self.token == token::CloseDelim(token::Brace) {
3513 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3519 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3522 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3523 maybe_whole!(self, NtArm, |x| x);
3525 let attrs = self.parse_outer_attributes()?;
3526 // Allow a '|' before the pats (RFC 1925)
3527 self.eat(&token::BinOp(token::Or));
3528 let pats = self.parse_pats()?;
3529 let guard = if self.eat_keyword(keywords::If) {
3530 Some(Guard::If(self.parse_expr()?))
3534 let arrow_span = self.span;
3535 self.expect(&token::FatArrow)?;
3536 let arm_start_span = self.span;
3538 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3539 .map_err(|mut err| {
3540 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3544 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3545 && self.token != token::CloseDelim(token::Brace);
3548 let cm = self.sess.source_map();
3549 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3550 .map_err(|mut err| {
3551 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3552 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3553 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3554 && expr_lines.lines.len() == 2
3555 && self.token == token::FatArrow => {
3556 // We check whether there's any trailing code in the parse span,
3557 // if there isn't, we very likely have the following:
3560 // | -- - missing comma
3566 // | parsed until here as `"y" & X`
3567 err.span_suggestion_short_with_applicability(
3568 cm.next_point(arm_start_span),
3569 "missing a comma here to end this `match` arm",
3571 Applicability::MachineApplicable
3575 err.span_label(arrow_span,
3576 "while parsing the `match` arm starting here");
3582 self.eat(&token::Comma);
3593 /// Parse an expression
3594 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3595 self.parse_expr_res(Restrictions::empty(), None)
3598 /// Evaluate the closure with restrictions in place.
3600 /// After the closure is evaluated, restrictions are reset.
3601 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3602 where F: FnOnce(&mut Self) -> T
3604 let old = self.restrictions;
3605 self.restrictions = r;
3607 self.restrictions = old;
3612 /// Parse an expression, subject to the given restrictions
3613 fn parse_expr_res(&mut self, r: Restrictions,
3614 already_parsed_attrs: Option<ThinVec<Attribute>>)
3615 -> PResult<'a, P<Expr>> {
3616 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3619 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3620 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3621 if self.eat(&token::Eq) {
3622 Ok(Some(self.parse_expr()?))
3624 Ok(Some(self.parse_expr()?))
3630 /// Parse patterns, separated by '|' s
3631 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3632 let mut pats = Vec::new();
3634 pats.push(self.parse_top_level_pat()?);
3636 if self.token == token::OrOr {
3637 let mut err = self.struct_span_err(self.span,
3638 "unexpected token `||` after pattern");
3639 err.span_suggestion_with_applicability(
3641 "use a single `|` to specify multiple patterns",
3643 Applicability::MachineApplicable
3647 } else if self.eat(&token::BinOp(token::Or)) {
3655 // Parses a parenthesized list of patterns like
3656 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3657 // - a vector of the patterns that were parsed
3658 // - an option indicating the index of the `..` element
3659 // - a boolean indicating whether a trailing comma was present.
3660 // Trailing commas are significant because (p) and (p,) are different patterns.
3661 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3662 self.expect(&token::OpenDelim(token::Paren))?;
3663 let result = self.parse_pat_list()?;
3664 self.expect(&token::CloseDelim(token::Paren))?;
3668 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3669 let mut fields = Vec::new();
3670 let mut ddpos = None;
3671 let mut trailing_comma = false;
3673 if self.eat(&token::DotDot) {
3674 if ddpos.is_none() {
3675 ddpos = Some(fields.len());
3677 // Emit a friendly error, ignore `..` and continue parsing
3678 self.span_err(self.prev_span,
3679 "`..` can only be used once per tuple or tuple struct pattern");
3681 } else if !self.check(&token::CloseDelim(token::Paren)) {
3682 fields.push(self.parse_pat()?);
3687 trailing_comma = self.eat(&token::Comma);
3688 if !trailing_comma {
3693 if ddpos == Some(fields.len()) && trailing_comma {
3694 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3695 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3698 Ok((fields, ddpos, trailing_comma))
3701 fn parse_pat_vec_elements(
3703 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3704 let mut before = Vec::new();
3705 let mut slice = None;
3706 let mut after = Vec::new();
3707 let mut first = true;
3708 let mut before_slice = true;
3710 while self.token != token::CloseDelim(token::Bracket) {
3714 self.expect(&token::Comma)?;
3716 if self.token == token::CloseDelim(token::Bracket)
3717 && (before_slice || !after.is_empty()) {
3723 if self.eat(&token::DotDot) {
3725 if self.check(&token::Comma) ||
3726 self.check(&token::CloseDelim(token::Bracket)) {
3727 slice = Some(P(Pat {
3728 id: ast::DUMMY_NODE_ID,
3729 node: PatKind::Wild,
3730 span: self.prev_span,
3732 before_slice = false;
3738 let subpat = self.parse_pat()?;
3739 if before_slice && self.eat(&token::DotDot) {
3740 slice = Some(subpat);
3741 before_slice = false;
3742 } else if before_slice {
3743 before.push(subpat);
3749 Ok((before, slice, after))
3755 attrs: Vec<Attribute>
3756 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3757 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3759 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3760 // Parsing a pattern of the form "fieldname: pat"
3761 let fieldname = self.parse_field_name()?;
3763 let pat = self.parse_pat()?;
3765 (pat, fieldname, false)
3767 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3768 let is_box = self.eat_keyword(keywords::Box);
3769 let boxed_span = self.span;
3770 let is_ref = self.eat_keyword(keywords::Ref);
3771 let is_mut = self.eat_keyword(keywords::Mut);
3772 let fieldname = self.parse_ident()?;
3773 hi = self.prev_span;
3775 let bind_type = match (is_ref, is_mut) {
3776 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3777 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3778 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3779 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3781 let fieldpat = P(Pat {
3782 id: ast::DUMMY_NODE_ID,
3783 node: PatKind::Ident(bind_type, fieldname, None),
3784 span: boxed_span.to(hi),
3787 let subpat = if is_box {
3789 id: ast::DUMMY_NODE_ID,
3790 node: PatKind::Box(fieldpat),
3796 (subpat, fieldname, true)
3799 Ok(source_map::Spanned {
3801 node: ast::FieldPat {
3805 attrs: attrs.into(),
3810 /// Parse the fields of a struct-like pattern
3811 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3812 let mut fields = Vec::new();
3813 let mut etc = false;
3814 let mut ate_comma = true;
3815 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3816 let mut etc_span = None;
3818 while self.token != token::CloseDelim(token::Brace) {
3819 let attrs = self.parse_outer_attributes()?;
3822 // check that a comma comes after every field
3824 let err = self.struct_span_err(self.prev_span, "expected `,`");
3829 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3831 let mut etc_sp = self.span;
3833 if self.token == token::DotDotDot { // Issue #46718
3834 // Accept `...` as if it were `..` to avoid further errors
3835 let mut err = self.struct_span_err(self.span,
3836 "expected field pattern, found `...`");
3837 err.span_suggestion_with_applicability(
3839 "to omit remaining fields, use one fewer `.`",
3841 Applicability::MachineApplicable
3845 self.bump(); // `..` || `...`:w
3847 if self.token == token::CloseDelim(token::Brace) {
3848 etc_span = Some(etc_sp);
3851 let token_str = self.this_token_to_string();
3852 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3854 err.span_label(self.span, "expected `}`");
3855 let mut comma_sp = None;
3856 if self.token == token::Comma { // Issue #49257
3857 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3858 err.span_label(etc_sp,
3859 "`..` must be at the end and cannot have a trailing comma");
3860 comma_sp = Some(self.span);
3865 etc_span = Some(etc_sp);
3866 if self.token == token::CloseDelim(token::Brace) {
3867 // If the struct looks otherwise well formed, recover and continue.
3868 if let Some(sp) = comma_sp {
3869 err.span_suggestion_short(sp, "remove this comma", String::new());
3873 } else if self.token.is_ident() && ate_comma {
3874 // Accept fields coming after `..,`.
3875 // This way we avoid "pattern missing fields" errors afterwards.
3876 // We delay this error until the end in order to have a span for a
3878 if let Some(mut delayed_err) = delayed_err {
3882 delayed_err = Some(err);
3885 if let Some(mut err) = delayed_err {
3892 fields.push(match self.parse_pat_field(lo, attrs) {
3895 if let Some(mut delayed_err) = delayed_err {
3901 ate_comma = self.eat(&token::Comma);
3904 if let Some(mut err) = delayed_err {
3905 if let Some(etc_span) = etc_span {
3906 err.multipart_suggestion(
3907 "move the `..` to the end of the field list",
3909 (etc_span, String::new()),
3910 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3916 return Ok((fields, etc));
3919 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3920 if self.token.is_path_start() {
3922 let (qself, path) = if self.eat_lt() {
3923 // Parse a qualified path
3924 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3927 // Parse an unqualified path
3928 (None, self.parse_path(PathStyle::Expr)?)
3930 let hi = self.prev_span;
3931 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3933 self.parse_literal_maybe_minus()
3937 // helper function to decide whether to parse as ident binding or to try to do
3938 // something more complex like range patterns
3939 fn parse_as_ident(&mut self) -> bool {
3940 self.look_ahead(1, |t| match *t {
3941 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3942 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3943 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3944 // range pattern branch
3945 token::DotDot => None,
3947 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3948 token::Comma | token::CloseDelim(token::Bracket) => true,
3953 /// A wrapper around `parse_pat` with some special error handling for the
3954 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3955 /// to subpatterns within such).
3956 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3957 let pat = self.parse_pat()?;
3958 if self.token == token::Comma {
3959 // An unexpected comma after a top-level pattern is a clue that the
3960 // user (perhaps more accustomed to some other language) forgot the
3961 // parentheses in what should have been a tuple pattern; return a
3962 // suggestion-enhanced error here rather than choking on the comma
3964 let comma_span = self.span;
3966 if let Err(mut err) = self.parse_pat_list() {
3967 // We didn't expect this to work anyway; we just wanted
3968 // to advance to the end of the comma-sequence so we know
3969 // the span to suggest parenthesizing
3972 let seq_span = pat.span.to(self.prev_span);
3973 let mut err = self.struct_span_err(comma_span,
3974 "unexpected `,` in pattern");
3975 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3976 err.span_suggestion_with_applicability(
3978 "try adding parentheses",
3979 format!("({})", seq_snippet),
3980 Applicability::MachineApplicable
3988 /// Parse a pattern.
3989 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3990 self.parse_pat_with_range_pat(true)
3993 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3995 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3996 maybe_whole!(self, NtPat, |x| x);
4001 token::BinOp(token::And) | token::AndAnd => {
4002 // Parse &pat / &mut pat
4004 let mutbl = self.parse_mutability();
4005 if let token::Lifetime(ident) = self.token {
4006 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4008 err.span_label(self.span, "unexpected lifetime");
4011 let subpat = self.parse_pat_with_range_pat(false)?;
4012 pat = PatKind::Ref(subpat, mutbl);
4014 token::OpenDelim(token::Paren) => {
4015 // Parse (pat,pat,pat,...) as tuple pattern
4016 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4017 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4018 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4020 PatKind::Tuple(fields, ddpos)
4023 token::OpenDelim(token::Bracket) => {
4024 // Parse [pat,pat,...] as slice pattern
4026 let (before, slice, after) = self.parse_pat_vec_elements()?;
4027 self.expect(&token::CloseDelim(token::Bracket))?;
4028 pat = PatKind::Slice(before, slice, after);
4030 // At this point, token != &, &&, (, [
4031 _ => if self.eat_keyword(keywords::Underscore) {
4033 pat = PatKind::Wild;
4034 } else if self.eat_keyword(keywords::Mut) {
4035 // Parse mut ident @ pat / mut ref ident @ pat
4036 let mutref_span = self.prev_span.to(self.span);
4037 let binding_mode = if self.eat_keyword(keywords::Ref) {
4039 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4040 .span_suggestion_with_applicability(
4042 "try switching the order",
4044 Applicability::MachineApplicable
4046 BindingMode::ByRef(Mutability::Mutable)
4048 BindingMode::ByValue(Mutability::Mutable)
4050 pat = self.parse_pat_ident(binding_mode)?;
4051 } else if self.eat_keyword(keywords::Ref) {
4052 // Parse ref ident @ pat / ref mut ident @ pat
4053 let mutbl = self.parse_mutability();
4054 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4055 } else if self.eat_keyword(keywords::Box) {
4057 let subpat = self.parse_pat_with_range_pat(false)?;
4058 pat = PatKind::Box(subpat);
4059 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4060 self.parse_as_ident() {
4061 // Parse ident @ pat
4062 // This can give false positives and parse nullary enums,
4063 // they are dealt with later in resolve
4064 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4065 pat = self.parse_pat_ident(binding_mode)?;
4066 } else if self.token.is_path_start() {
4067 // Parse pattern starting with a path
4068 let (qself, path) = if self.eat_lt() {
4069 // Parse a qualified path
4070 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4073 // Parse an unqualified path
4074 (None, self.parse_path(PathStyle::Expr)?)
4077 token::Not if qself.is_none() => {
4078 // Parse macro invocation
4080 let (delim, tts) = self.expect_delimited_token_tree()?;
4081 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4082 pat = PatKind::Mac(mac);
4084 token::DotDotDot | token::DotDotEq | token::DotDot => {
4085 let end_kind = match self.token {
4086 token::DotDot => RangeEnd::Excluded,
4087 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4088 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4089 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4092 let op_span = self.span;
4094 let span = lo.to(self.prev_span);
4095 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4097 let end = self.parse_pat_range_end()?;
4098 let op = Spanned { span: op_span, node: end_kind };
4099 pat = PatKind::Range(begin, end, op);
4101 token::OpenDelim(token::Brace) => {
4102 if qself.is_some() {
4103 let msg = "unexpected `{` after qualified path";
4104 let mut err = self.fatal(msg);
4105 err.span_label(self.span, msg);
4108 // Parse struct pattern
4110 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4112 self.recover_stmt();
4116 pat = PatKind::Struct(path, fields, etc);
4118 token::OpenDelim(token::Paren) => {
4119 if qself.is_some() {
4120 let msg = "unexpected `(` after qualified path";
4121 let mut err = self.fatal(msg);
4122 err.span_label(self.span, msg);
4125 // Parse tuple struct or enum pattern
4126 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4127 pat = PatKind::TupleStruct(path, fields, ddpos)
4129 _ => pat = PatKind::Path(qself, path),
4132 // Try to parse everything else as literal with optional minus
4133 match self.parse_literal_maybe_minus() {
4135 let op_span = self.span;
4136 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4137 self.check(&token::DotDotDot) {
4138 let end_kind = if self.eat(&token::DotDotDot) {
4139 RangeEnd::Included(RangeSyntax::DotDotDot)
4140 } else if self.eat(&token::DotDotEq) {
4141 RangeEnd::Included(RangeSyntax::DotDotEq)
4142 } else if self.eat(&token::DotDot) {
4145 panic!("impossible case: we already matched \
4146 on a range-operator token")
4148 let end = self.parse_pat_range_end()?;
4149 let op = Spanned { span: op_span, node: end_kind };
4150 pat = PatKind::Range(begin, end, op);
4152 pat = PatKind::Lit(begin);
4156 self.cancel(&mut err);
4157 let msg = format!("expected pattern, found {}", self.this_token_descr());
4158 let mut err = self.fatal(&msg);
4159 err.span_label(self.span, "expected pattern");
4166 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4167 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4169 if !allow_range_pat {
4172 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4174 PatKind::Range(..) => {
4175 let mut err = self.struct_span_err(
4177 "the range pattern here has ambiguous interpretation",
4179 err.span_suggestion_with_applicability(
4181 "add parentheses to clarify the precedence",
4182 format!("({})", pprust::pat_to_string(&pat)),
4183 // "ambiguous interpretation" implies that we have to be guessing
4184 Applicability::MaybeIncorrect
4195 /// Parse ident or ident @ pat
4196 /// used by the copy foo and ref foo patterns to give a good
4197 /// error message when parsing mistakes like ref foo(a,b)
4198 fn parse_pat_ident(&mut self,
4199 binding_mode: ast::BindingMode)
4200 -> PResult<'a, PatKind> {
4201 let ident = self.parse_ident()?;
4202 let sub = if self.eat(&token::At) {
4203 Some(self.parse_pat()?)
4208 // just to be friendly, if they write something like
4210 // we end up here with ( as the current token. This shortly
4211 // leads to a parse error. Note that if there is no explicit
4212 // binding mode then we do not end up here, because the lookahead
4213 // will direct us over to parse_enum_variant()
4214 if self.token == token::OpenDelim(token::Paren) {
4215 return Err(self.span_fatal(
4217 "expected identifier, found enum pattern"))
4220 Ok(PatKind::Ident(binding_mode, ident, sub))
4223 /// Parse a local variable declaration
4224 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4225 let lo = self.prev_span;
4226 let pat = self.parse_top_level_pat()?;
4228 let (err, ty) = if self.eat(&token::Colon) {
4229 // Save the state of the parser before parsing type normally, in case there is a `:`
4230 // instead of an `=` typo.
4231 let parser_snapshot_before_type = self.clone();
4232 let colon_sp = self.prev_span;
4233 match self.parse_ty() {
4234 Ok(ty) => (None, Some(ty)),
4236 // Rewind to before attempting to parse the type and continue parsing
4237 let parser_snapshot_after_type = self.clone();
4238 mem::replace(self, parser_snapshot_before_type);
4240 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4241 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4242 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4248 let init = match (self.parse_initializer(err.is_some()), err) {
4249 (Ok(init), None) => { // init parsed, ty parsed
4252 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4253 // Could parse the type as if it were the initializer, it is likely there was a
4254 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4255 err.span_suggestion_short_with_applicability(
4257 "use `=` if you meant to assign",
4259 Applicability::MachineApplicable
4262 // As this was parsed successfully, continue as if the code has been fixed for the
4263 // rest of the file. It will still fail due to the emitted error, but we avoid
4267 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4269 // Couldn't parse the type nor the initializer, only raise the type error and
4270 // return to the parser state before parsing the type as the initializer.
4271 // let x: <parse_error>;
4272 mem::replace(self, snapshot);
4275 (Err(err), None) => { // init error, ty parsed
4276 // Couldn't parse the initializer and we're not attempting to recover a failed
4277 // parse of the type, return the error.
4281 let hi = if self.token == token::Semi {
4290 id: ast::DUMMY_NODE_ID,
4296 /// Parse a structure field
4297 fn parse_name_and_ty(&mut self,
4300 attrs: Vec<Attribute>)
4301 -> PResult<'a, StructField> {
4302 let name = self.parse_ident()?;
4303 self.expect(&token::Colon)?;
4304 let ty = self.parse_ty()?;
4306 span: lo.to(self.prev_span),
4309 id: ast::DUMMY_NODE_ID,
4315 /// Emit an expected item after attributes error.
4316 fn expected_item_err(&self, attrs: &[Attribute]) {
4317 let message = match attrs.last() {
4318 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4319 _ => "expected item after attributes",
4322 self.span_err(self.prev_span, message);
4325 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4326 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4327 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4328 Ok(self.parse_stmt_(true))
4331 // Eat tokens until we can be relatively sure we reached the end of the
4332 // statement. This is something of a best-effort heuristic.
4334 // We terminate when we find an unmatched `}` (without consuming it).
4335 fn recover_stmt(&mut self) {
4336 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4339 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4340 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4341 // approximate - it can mean we break too early due to macros, but that
4342 // should only lead to sub-optimal recovery, not inaccurate parsing).
4344 // If `break_on_block` is `Break`, then we will stop consuming tokens
4345 // after finding (and consuming) a brace-delimited block.
4346 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4347 let mut brace_depth = 0;
4348 let mut bracket_depth = 0;
4349 let mut in_block = false;
4350 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4351 break_on_semi, break_on_block);
4353 debug!("recover_stmt_ loop {:?}", self.token);
4355 token::OpenDelim(token::DelimToken::Brace) => {
4358 if break_on_block == BlockMode::Break &&
4360 bracket_depth == 0 {
4364 token::OpenDelim(token::DelimToken::Bracket) => {
4368 token::CloseDelim(token::DelimToken::Brace) => {
4369 if brace_depth == 0 {
4370 debug!("recover_stmt_ return - close delim {:?}", self.token);
4375 if in_block && bracket_depth == 0 && brace_depth == 0 {
4376 debug!("recover_stmt_ return - block end {:?}", self.token);
4380 token::CloseDelim(token::DelimToken::Bracket) => {
4382 if bracket_depth < 0 {
4388 debug!("recover_stmt_ return - Eof");
4393 if break_on_semi == SemiColonMode::Break &&
4395 bracket_depth == 0 {
4396 debug!("recover_stmt_ return - Semi");
4407 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4408 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4410 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4415 fn is_async_block(&mut self) -> bool {
4416 self.token.is_keyword(keywords::Async) &&
4419 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4420 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4422 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4427 fn is_do_catch_block(&mut self) -> bool {
4428 self.token.is_keyword(keywords::Do) &&
4429 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4430 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4431 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4434 fn is_try_block(&mut self) -> bool {
4435 self.token.is_keyword(keywords::Try) &&
4436 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4438 self.span.edition() >= Edition::Edition2018 &&
4440 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4441 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4444 fn is_union_item(&self) -> bool {
4445 self.token.is_keyword(keywords::Union) &&
4446 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4449 fn is_crate_vis(&self) -> bool {
4450 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4453 fn is_extern_non_path(&self) -> bool {
4454 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4457 fn is_existential_type_decl(&self) -> bool {
4458 self.token.is_keyword(keywords::Existential) &&
4459 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4462 fn is_auto_trait_item(&mut self) -> bool {
4464 (self.token.is_keyword(keywords::Auto)
4465 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4466 || // unsafe auto trait
4467 (self.token.is_keyword(keywords::Unsafe) &&
4468 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4469 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4472 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4473 -> PResult<'a, Option<P<Item>>> {
4474 let token_lo = self.span;
4475 let (ident, def) = match self.token {
4476 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4478 let ident = self.parse_ident()?;
4479 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4480 match self.parse_token_tree() {
4481 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4482 _ => unreachable!(),
4484 } else if self.check(&token::OpenDelim(token::Paren)) {
4485 let args = self.parse_token_tree();
4486 let body = if self.check(&token::OpenDelim(token::Brace)) {
4487 self.parse_token_tree()
4492 TokenStream::concat(vec![
4494 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4502 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4504 token::Ident(ident, _) if ident.name == "macro_rules" &&
4505 self.look_ahead(1, |t| *t == token::Not) => {
4506 let prev_span = self.prev_span;
4507 self.complain_if_pub_macro(&vis.node, prev_span);
4511 let ident = self.parse_ident()?;
4512 let (delim, tokens) = self.expect_delimited_token_tree()?;
4513 if delim != MacDelimiter::Brace {
4514 if !self.eat(&token::Semi) {
4515 let msg = "macros that expand to items must either \
4516 be surrounded with braces or followed by a semicolon";
4517 self.span_err(self.prev_span, msg);
4521 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4523 _ => return Ok(None),
4526 let span = lo.to(self.prev_span);
4527 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4530 fn parse_stmt_without_recovery(&mut self,
4531 macro_legacy_warnings: bool)
4532 -> PResult<'a, Option<Stmt>> {
4533 maybe_whole!(self, NtStmt, |x| Some(x));
4535 let attrs = self.parse_outer_attributes()?;
4538 Ok(Some(if self.eat_keyword(keywords::Let) {
4540 id: ast::DUMMY_NODE_ID,
4541 node: StmtKind::Local(self.parse_local(attrs.into())?),
4542 span: lo.to(self.prev_span),
4544 } else if let Some(macro_def) = self.eat_macro_def(
4546 &source_map::respan(lo, VisibilityKind::Inherited),
4550 id: ast::DUMMY_NODE_ID,
4551 node: StmtKind::Item(macro_def),
4552 span: lo.to(self.prev_span),
4554 // Starts like a simple path, being careful to avoid contextual keywords
4555 // such as a union items, item with `crate` visibility or auto trait items.
4556 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4557 // like a path (1 token), but it fact not a path.
4558 // `union::b::c` - path, `union U { ... }` - not a path.
4559 // `crate::b::c` - path, `crate struct S;` - not a path.
4560 // `extern::b::c` - path, `extern crate c;` - not a path.
4561 } else if self.token.is_path_start() &&
4562 !self.token.is_qpath_start() &&
4563 !self.is_union_item() &&
4564 !self.is_crate_vis() &&
4565 !self.is_extern_non_path() &&
4566 !self.is_existential_type_decl() &&
4567 !self.is_auto_trait_item() {
4568 let pth = self.parse_path(PathStyle::Expr)?;
4570 if !self.eat(&token::Not) {
4571 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4572 self.parse_struct_expr(lo, pth, ThinVec::new())?
4574 let hi = self.prev_span;
4575 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4578 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4579 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4580 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4583 return Ok(Some(Stmt {
4584 id: ast::DUMMY_NODE_ID,
4585 node: StmtKind::Expr(expr),
4586 span: lo.to(self.prev_span),
4590 // it's a macro invocation
4591 let id = match self.token {
4592 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4593 _ => self.parse_ident()?,
4596 // check that we're pointing at delimiters (need to check
4597 // again after the `if`, because of `parse_ident`
4598 // consuming more tokens).
4600 token::OpenDelim(_) => {}
4602 // we only expect an ident if we didn't parse one
4604 let ident_str = if id.name == keywords::Invalid.name() {
4609 let tok_str = self.this_token_to_string();
4610 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4613 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4618 let (delim, tts) = self.expect_delimited_token_tree()?;
4619 let hi = self.prev_span;
4621 let style = if delim == MacDelimiter::Brace {
4622 MacStmtStyle::Braces
4624 MacStmtStyle::NoBraces
4627 if id.name == keywords::Invalid.name() {
4628 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4629 let node = if delim == MacDelimiter::Brace ||
4630 self.token == token::Semi || self.token == token::Eof {
4631 StmtKind::Mac(P((mac, style, attrs.into())))
4633 // We used to incorrectly stop parsing macro-expanded statements here.
4634 // If the next token will be an error anyway but could have parsed with the
4635 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4636 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4637 // These can continue an expression, so we can't stop parsing and warn.
4638 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4639 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4640 token::BinOp(token::And) | token::BinOp(token::Or) |
4641 token::AndAnd | token::OrOr |
4642 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4645 self.warn_missing_semicolon();
4646 StmtKind::Mac(P((mac, style, attrs.into())))
4648 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4649 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4650 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4654 id: ast::DUMMY_NODE_ID,
4659 // if it has a special ident, it's definitely an item
4661 // Require a semicolon or braces.
4662 if style != MacStmtStyle::Braces {
4663 if !self.eat(&token::Semi) {
4664 self.span_err(self.prev_span,
4665 "macros that expand to items must \
4666 either be surrounded with braces or \
4667 followed by a semicolon");
4670 let span = lo.to(hi);
4672 id: ast::DUMMY_NODE_ID,
4674 node: StmtKind::Item({
4676 span, id /*id is good here*/,
4677 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4678 respan(lo, VisibilityKind::Inherited),
4684 // FIXME: Bad copy of attrs
4685 let old_directory_ownership =
4686 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4687 let item = self.parse_item_(attrs.clone(), false, true)?;
4688 self.directory.ownership = old_directory_ownership;
4692 id: ast::DUMMY_NODE_ID,
4693 span: lo.to(i.span),
4694 node: StmtKind::Item(i),
4697 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4698 if !attrs.is_empty() {
4699 if s.prev_token_kind == PrevTokenKind::DocComment {
4700 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4701 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4702 s.span_err(s.span, "expected statement after outer attribute");
4707 // Do not attempt to parse an expression if we're done here.
4708 if self.token == token::Semi {
4709 unused_attrs(&attrs, self);
4714 if self.token == token::CloseDelim(token::Brace) {
4715 unused_attrs(&attrs, self);
4719 // Remainder are line-expr stmts.
4720 let e = self.parse_expr_res(
4721 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4723 id: ast::DUMMY_NODE_ID,
4724 span: lo.to(e.span),
4725 node: StmtKind::Expr(e),
4732 /// Is this expression a successfully-parsed statement?
4733 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4734 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4735 !classify::expr_requires_semi_to_be_stmt(e)
4738 /// Parse a block. No inner attrs are allowed.
4739 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4740 maybe_whole!(self, NtBlock, |x| x);
4744 if !self.eat(&token::OpenDelim(token::Brace)) {
4746 let tok = self.this_token_to_string();
4747 let mut do_not_suggest_help = false;
4748 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4749 if self.token.is_keyword(keywords::In) || self.token == token::Colon {
4750 do_not_suggest_help = true;
4751 e.span_label(sp, "expected `{`");
4754 // Check to see if the user has written something like
4759 // Which is valid in other languages, but not Rust.
4760 match self.parse_stmt_without_recovery(false) {
4762 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4763 || do_not_suggest_help {
4764 // if the next token is an open brace (e.g., `if a b {`), the place-
4765 // inside-a-block suggestion would be more likely wrong than right
4768 let mut stmt_span = stmt.span;
4769 // expand the span to include the semicolon, if it exists
4770 if self.eat(&token::Semi) {
4771 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4773 let sugg = pprust::to_string(|s| {
4774 use print::pprust::{PrintState, INDENT_UNIT};
4775 s.ibox(INDENT_UNIT)?;
4777 s.print_stmt(&stmt)?;
4778 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4780 e.span_suggestion_with_applicability(
4782 "try placing this code inside a block",
4784 // speculative, has been misleading in the past (closed Issue #46836)
4785 Applicability::MaybeIncorrect
4789 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4790 self.cancel(&mut e);
4797 self.parse_block_tail(lo, BlockCheckMode::Default)
4800 /// Parse a block. Inner attrs are allowed.
4801 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4802 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4805 self.expect(&token::OpenDelim(token::Brace))?;
4806 Ok((self.parse_inner_attributes()?,
4807 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4810 /// Parse the rest of a block expression or function body
4811 /// Precondition: already parsed the '{'.
4812 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4813 let mut stmts = vec![];
4814 let mut recovered = false;
4816 while !self.eat(&token::CloseDelim(token::Brace)) {
4817 let stmt = match self.parse_full_stmt(false) {
4820 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4821 self.eat(&token::CloseDelim(token::Brace));
4827 if let Some(stmt) = stmt {
4829 } else if self.token == token::Eof {
4832 // Found only `;` or `}`.
4838 id: ast::DUMMY_NODE_ID,
4840 span: lo.to(self.prev_span),
4845 /// Parse a statement, including the trailing semicolon.
4846 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4847 // skip looking for a trailing semicolon when we have an interpolated statement
4848 maybe_whole!(self, NtStmt, |x| Some(x));
4850 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4852 None => return Ok(None),
4856 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4857 // expression without semicolon
4858 if classify::expr_requires_semi_to_be_stmt(expr) {
4859 // Just check for errors and recover; do not eat semicolon yet.
4861 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4864 self.recover_stmt();
4868 StmtKind::Local(..) => {
4869 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4870 if macro_legacy_warnings && self.token != token::Semi {
4871 self.warn_missing_semicolon();
4873 self.expect_one_of(&[], &[token::Semi])?;
4879 if self.eat(&token::Semi) {
4880 stmt = stmt.add_trailing_semicolon();
4883 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4887 fn warn_missing_semicolon(&self) {
4888 self.diagnostic().struct_span_warn(self.span, {
4889 &format!("expected `;`, found `{}`", self.this_token_to_string())
4891 "This was erroneously allowed and will become a hard error in a future release"
4895 fn err_dotdotdot_syntax(&self, span: Span) {
4896 self.diagnostic().struct_span_err(span, {
4897 "unexpected token: `...`"
4898 }).span_suggestion_with_applicability(
4899 span, "use `..` for an exclusive range", "..".to_owned(),
4900 Applicability::MaybeIncorrect
4901 ).span_suggestion_with_applicability(
4902 span, "or `..=` for an inclusive range", "..=".to_owned(),
4903 Applicability::MaybeIncorrect
4907 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4908 // BOUND = TY_BOUND | LT_BOUND
4909 // LT_BOUND = LIFETIME (e.g. `'a`)
4910 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4911 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4912 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4913 let mut bounds = Vec::new();
4915 // This needs to be synchronized with `Token::can_begin_bound`.
4916 let is_bound_start = self.check_path() || self.check_lifetime() ||
4917 self.check(&token::Question) ||
4918 self.check_keyword(keywords::For) ||
4919 self.check(&token::OpenDelim(token::Paren));
4922 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4923 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4924 if self.token.is_lifetime() {
4925 if let Some(question_span) = question {
4926 self.span_err(question_span,
4927 "`?` may only modify trait bounds, not lifetime bounds");
4929 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4931 self.expect(&token::CloseDelim(token::Paren))?;
4932 self.span_err(self.prev_span,
4933 "parenthesized lifetime bounds are not supported");
4936 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4937 let path = self.parse_path(PathStyle::Type)?;
4939 self.expect(&token::CloseDelim(token::Paren))?;
4941 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4942 let modifier = if question.is_some() {
4943 TraitBoundModifier::Maybe
4945 TraitBoundModifier::None
4947 bounds.push(GenericBound::Trait(poly_trait, modifier));
4953 if !allow_plus || !self.eat_plus() {
4961 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
4962 self.parse_generic_bounds_common(true)
4965 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4966 // BOUND = LT_BOUND (e.g. `'a`)
4967 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4968 let mut lifetimes = Vec::new();
4969 while self.check_lifetime() {
4970 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4972 if !self.eat_plus() {
4979 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4980 fn parse_ty_param(&mut self,
4981 preceding_attrs: Vec<Attribute>)
4982 -> PResult<'a, GenericParam> {
4983 let ident = self.parse_ident()?;
4985 // Parse optional colon and param bounds.
4986 let bounds = if self.eat(&token::Colon) {
4987 self.parse_generic_bounds()?
4992 let default = if self.eat(&token::Eq) {
4993 Some(self.parse_ty()?)
5000 id: ast::DUMMY_NODE_ID,
5001 attrs: preceding_attrs.into(),
5003 kind: GenericParamKind::Type {
5009 /// Parses the following grammar:
5010 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5011 fn parse_trait_item_assoc_ty(&mut self)
5012 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5013 let ident = self.parse_ident()?;
5014 let mut generics = self.parse_generics()?;
5016 // Parse optional colon and param bounds.
5017 let bounds = if self.eat(&token::Colon) {
5018 self.parse_generic_bounds()?
5022 generics.where_clause = self.parse_where_clause()?;
5024 let default = if self.eat(&token::Eq) {
5025 Some(self.parse_ty()?)
5029 self.expect(&token::Semi)?;
5031 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5034 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5035 /// trailing comma and erroneous trailing attributes.
5036 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5037 let mut params = Vec::new();
5038 let mut seen_ty_param = false;
5040 let attrs = self.parse_outer_attributes()?;
5041 if self.check_lifetime() {
5042 let lifetime = self.expect_lifetime();
5043 // Parse lifetime parameter.
5044 let bounds = if self.eat(&token::Colon) {
5045 self.parse_lt_param_bounds()
5049 params.push(ast::GenericParam {
5050 ident: lifetime.ident,
5052 attrs: attrs.into(),
5054 kind: ast::GenericParamKind::Lifetime,
5057 self.span_err(self.prev_span,
5058 "lifetime parameters must be declared prior to type parameters");
5060 } else if self.check_ident() {
5061 // Parse type parameter.
5062 params.push(self.parse_ty_param(attrs)?);
5063 seen_ty_param = true;
5065 // Check for trailing attributes and stop parsing.
5066 if !attrs.is_empty() {
5067 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
5068 self.span_err(attrs[0].span,
5069 &format!("trailing attribute after {} parameters", param_kind));
5074 if !self.eat(&token::Comma) {
5081 /// Parse a set of optional generic type parameter declarations. Where
5082 /// clauses are not parsed here, and must be added later via
5083 /// `parse_where_clause()`.
5085 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5086 /// | ( < lifetimes , typaramseq ( , )? > )
5087 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5088 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5089 maybe_whole!(self, NtGenerics, |x| x);
5091 let span_lo = self.span;
5093 let params = self.parse_generic_params()?;
5097 where_clause: WhereClause {
5098 id: ast::DUMMY_NODE_ID,
5099 predicates: Vec::new(),
5100 span: syntax_pos::DUMMY_SP,
5102 span: span_lo.to(self.prev_span),
5105 Ok(ast::Generics::default())
5109 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5110 /// possibly including trailing comma.
5111 fn parse_generic_args(&mut self)
5112 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5113 let mut args = Vec::new();
5114 let mut bindings = Vec::new();
5115 let mut seen_type = false;
5116 let mut seen_binding = false;
5118 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5119 // Parse lifetime argument.
5120 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5121 if seen_type || seen_binding {
5122 self.span_err(self.prev_span,
5123 "lifetime parameters must be declared prior to type parameters");
5125 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5126 // Parse associated type binding.
5128 let ident = self.parse_ident()?;
5130 let ty = self.parse_ty()?;
5131 bindings.push(TypeBinding {
5132 id: ast::DUMMY_NODE_ID,
5135 span: lo.to(self.prev_span),
5137 seen_binding = true;
5138 } else if self.check_type() {
5139 // Parse type argument.
5140 let ty_param = self.parse_ty()?;
5142 self.span_err(ty_param.span,
5143 "type parameters must be declared prior to associated type bindings");
5145 args.push(GenericArg::Type(ty_param));
5151 if !self.eat(&token::Comma) {
5155 Ok((args, bindings))
5158 /// Parses an optional `where` clause and places it in `generics`.
5160 /// ```ignore (only-for-syntax-highlight)
5161 /// where T : Trait<U, V> + 'b, 'a : 'b
5163 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5164 maybe_whole!(self, NtWhereClause, |x| x);
5166 let mut where_clause = WhereClause {
5167 id: ast::DUMMY_NODE_ID,
5168 predicates: Vec::new(),
5169 span: syntax_pos::DUMMY_SP,
5172 if !self.eat_keyword(keywords::Where) {
5173 return Ok(where_clause);
5175 let lo = self.prev_span;
5177 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5178 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5179 // change we parse those generics now, but report an error.
5180 if self.choose_generics_over_qpath() {
5181 let generics = self.parse_generics()?;
5182 self.span_err(generics.span,
5183 "generic parameters on `where` clauses are reserved for future use");
5188 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5189 let lifetime = self.expect_lifetime();
5190 // Bounds starting with a colon are mandatory, but possibly empty.
5191 self.expect(&token::Colon)?;
5192 let bounds = self.parse_lt_param_bounds();
5193 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5194 ast::WhereRegionPredicate {
5195 span: lo.to(self.prev_span),
5200 } else if self.check_type() {
5201 // Parse optional `for<'a, 'b>`.
5202 // This `for` is parsed greedily and applies to the whole predicate,
5203 // the bounded type can have its own `for` applying only to it.
5204 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5205 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5206 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5207 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5209 // Parse type with mandatory colon and (possibly empty) bounds,
5210 // or with mandatory equality sign and the second type.
5211 let ty = self.parse_ty()?;
5212 if self.eat(&token::Colon) {
5213 let bounds = self.parse_generic_bounds()?;
5214 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5215 ast::WhereBoundPredicate {
5216 span: lo.to(self.prev_span),
5217 bound_generic_params: lifetime_defs,
5222 // FIXME: Decide what should be used here, `=` or `==`.
5223 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5224 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5225 let rhs_ty = self.parse_ty()?;
5226 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5227 ast::WhereEqPredicate {
5228 span: lo.to(self.prev_span),
5231 id: ast::DUMMY_NODE_ID,
5235 return self.unexpected();
5241 if !self.eat(&token::Comma) {
5246 where_clause.span = lo.to(self.prev_span);
5250 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5251 -> PResult<'a, (Vec<Arg> , bool)> {
5253 let mut variadic = false;
5254 let args: Vec<Option<Arg>> =
5255 self.parse_unspanned_seq(
5256 &token::OpenDelim(token::Paren),
5257 &token::CloseDelim(token::Paren),
5258 SeqSep::trailing_allowed(token::Comma),
5260 if p.token == token::DotDotDot {
5264 if p.token != token::CloseDelim(token::Paren) {
5267 "`...` must be last in argument list for variadic function");
5271 let span = p.prev_span;
5272 if p.token == token::CloseDelim(token::Paren) {
5273 // continue parsing to present any further errors
5276 "only foreign functions are allowed to be variadic"
5278 Ok(Some(dummy_arg(span)))
5280 // this function definition looks beyond recovery, stop parsing
5282 "only foreign functions are allowed to be variadic");
5287 match p.parse_arg_general(named_args) {
5288 Ok(arg) => Ok(Some(arg)),
5291 let lo = p.prev_span;
5292 // Skip every token until next possible arg or end.
5293 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5294 // Create a placeholder argument for proper arg count (#34264).
5295 let span = lo.to(p.prev_span);
5296 Ok(Some(dummy_arg(span)))
5303 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5305 if variadic && args.is_empty() {
5307 "variadic function must be declared with at least one named argument");
5310 Ok((args, variadic))
5313 /// Parse the argument list and result type of a function declaration
5314 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5316 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5317 let ret_ty = self.parse_ret_ty(true)?;
5326 /// Returns the parsed optional self argument and whether a self shortcut was used.
5327 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5328 let expect_ident = |this: &mut Self| match this.token {
5329 // Preserve hygienic context.
5330 token::Ident(ident, _) =>
5331 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5334 let isolated_self = |this: &mut Self, n| {
5335 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5336 this.look_ahead(n + 1, |t| t != &token::ModSep)
5339 // Parse optional self parameter of a method.
5340 // Only a limited set of initial token sequences is considered self parameters, anything
5341 // else is parsed as a normal function parameter list, so some lookahead is required.
5342 let eself_lo = self.span;
5343 let (eself, eself_ident, eself_hi) = match self.token {
5344 token::BinOp(token::And) => {
5350 (if isolated_self(self, 1) {
5352 SelfKind::Region(None, Mutability::Immutable)
5353 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5354 isolated_self(self, 2) {
5357 SelfKind::Region(None, Mutability::Mutable)
5358 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5359 isolated_self(self, 2) {
5361 let lt = self.expect_lifetime();
5362 SelfKind::Region(Some(lt), Mutability::Immutable)
5363 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5364 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5365 isolated_self(self, 3) {
5367 let lt = self.expect_lifetime();
5369 SelfKind::Region(Some(lt), Mutability::Mutable)
5372 }, expect_ident(self), self.prev_span)
5374 token::BinOp(token::Star) => {
5379 // Emit special error for `self` cases.
5380 (if isolated_self(self, 1) {
5382 self.span_err(self.span, "cannot pass `self` by raw pointer");
5383 SelfKind::Value(Mutability::Immutable)
5384 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5385 isolated_self(self, 2) {
5388 self.span_err(self.span, "cannot pass `self` by raw pointer");
5389 SelfKind::Value(Mutability::Immutable)
5392 }, expect_ident(self), self.prev_span)
5394 token::Ident(..) => {
5395 if isolated_self(self, 0) {
5398 let eself_ident = expect_ident(self);
5399 let eself_hi = self.prev_span;
5400 (if self.eat(&token::Colon) {
5401 let ty = self.parse_ty()?;
5402 SelfKind::Explicit(ty, Mutability::Immutable)
5404 SelfKind::Value(Mutability::Immutable)
5405 }, eself_ident, eself_hi)
5406 } else if self.token.is_keyword(keywords::Mut) &&
5407 isolated_self(self, 1) {
5411 let eself_ident = expect_ident(self);
5412 let eself_hi = self.prev_span;
5413 (if self.eat(&token::Colon) {
5414 let ty = self.parse_ty()?;
5415 SelfKind::Explicit(ty, Mutability::Mutable)
5417 SelfKind::Value(Mutability::Mutable)
5418 }, eself_ident, eself_hi)
5423 _ => return Ok(None),
5426 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5427 Ok(Some(Arg::from_self(eself, eself_ident)))
5430 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5431 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5432 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5434 self.expect(&token::OpenDelim(token::Paren))?;
5436 // Parse optional self argument
5437 let self_arg = self.parse_self_arg()?;
5439 // Parse the rest of the function parameter list.
5440 let sep = SeqSep::trailing_allowed(token::Comma);
5441 let fn_inputs = if let Some(self_arg) = self_arg {
5442 if self.check(&token::CloseDelim(token::Paren)) {
5444 } else if self.eat(&token::Comma) {
5445 let mut fn_inputs = vec![self_arg];
5446 fn_inputs.append(&mut self.parse_seq_to_before_end(
5447 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5451 return self.unexpected();
5454 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5457 // Parse closing paren and return type.
5458 self.expect(&token::CloseDelim(token::Paren))?;
5461 output: self.parse_ret_ty(true)?,
5466 // parse the |arg, arg| header on a lambda
5467 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5468 let inputs_captures = {
5469 if self.eat(&token::OrOr) {
5472 self.expect(&token::BinOp(token::Or))?;
5473 let args = self.parse_seq_to_before_tokens(
5474 &[&token::BinOp(token::Or), &token::OrOr],
5475 SeqSep::trailing_allowed(token::Comma),
5476 TokenExpectType::NoExpect,
5477 |p| p.parse_fn_block_arg()
5483 let output = self.parse_ret_ty(true)?;
5486 inputs: inputs_captures,
5492 /// Parse the name and optional generic types of a function header.
5493 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5494 let id = self.parse_ident()?;
5495 let generics = self.parse_generics()?;
5499 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5500 attrs: Vec<Attribute>) -> P<Item> {
5504 id: ast::DUMMY_NODE_ID,
5512 /// Parse an item-position function declaration.
5513 fn parse_item_fn(&mut self,
5516 constness: Spanned<Constness>,
5518 -> PResult<'a, ItemInfo> {
5519 let (ident, mut generics) = self.parse_fn_header()?;
5520 let decl = self.parse_fn_decl(false)?;
5521 generics.where_clause = self.parse_where_clause()?;
5522 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5523 let header = FnHeader { unsafety, asyncness, constness, abi };
5524 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5527 /// true if we are looking at `const ID`, false for things like `const fn` etc
5528 fn is_const_item(&mut self) -> bool {
5529 self.token.is_keyword(keywords::Const) &&
5530 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5531 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5534 /// parses all the "front matter" for a `fn` declaration, up to
5535 /// and including the `fn` keyword:
5539 /// - `const unsafe fn`
5542 fn parse_fn_front_matter(&mut self)
5550 let is_const_fn = self.eat_keyword(keywords::Const);
5551 let const_span = self.prev_span;
5552 let unsafety = self.parse_unsafety();
5553 let asyncness = self.parse_asyncness();
5554 let (constness, unsafety, abi) = if is_const_fn {
5555 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5557 let abi = if self.eat_keyword(keywords::Extern) {
5558 self.parse_opt_abi()?.unwrap_or(Abi::C)
5562 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5564 self.expect_keyword(keywords::Fn)?;
5565 Ok((constness, unsafety, asyncness, abi))
5568 /// Parse an impl item.
5569 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5570 maybe_whole!(self, NtImplItem, |x| x);
5571 let attrs = self.parse_outer_attributes()?;
5572 let (mut item, tokens) = self.collect_tokens(|this| {
5573 this.parse_impl_item_(at_end, attrs)
5576 // See `parse_item` for why this clause is here.
5577 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5578 item.tokens = Some(tokens);
5583 fn parse_impl_item_(&mut self,
5585 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5587 let vis = self.parse_visibility(false)?;
5588 let defaultness = self.parse_defaultness();
5589 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5590 let (name, alias, generics) = type_?;
5591 let kind = match alias {
5592 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5593 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5595 (name, kind, generics)
5596 } else if self.is_const_item() {
5597 // This parses the grammar:
5598 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5599 self.expect_keyword(keywords::Const)?;
5600 let name = self.parse_ident()?;
5601 self.expect(&token::Colon)?;
5602 let typ = self.parse_ty()?;
5603 self.expect(&token::Eq)?;
5604 let expr = self.parse_expr()?;
5605 self.expect(&token::Semi)?;
5606 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5608 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5609 attrs.extend(inner_attrs);
5610 (name, node, generics)
5614 id: ast::DUMMY_NODE_ID,
5615 span: lo.to(self.prev_span),
5626 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5627 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5632 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5634 VisibilityKind::Inherited => Ok(()),
5636 let is_macro_rules: bool = match self.token {
5637 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5641 let mut err = self.diagnostic()
5642 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5643 err.span_suggestion_with_applicability(
5645 "try exporting the macro",
5646 "#[macro_export]".to_owned(),
5647 Applicability::MaybeIncorrect // speculative
5651 let mut err = self.diagnostic()
5652 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5653 err.help("try adjusting the macro to put `pub` inside the invocation");
5660 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5661 -> DiagnosticBuilder<'a>
5663 let expected_kinds = if item_type == "extern" {
5664 "missing `fn`, `type`, or `static`"
5666 "missing `fn`, `type`, or `const`"
5669 // Given this code `path(`, it seems like this is not
5670 // setting the visibility of a macro invocation, but rather
5671 // a mistyped method declaration.
5672 // Create a diagnostic pointing out that `fn` is missing.
5674 // x | pub path(&self) {
5675 // | ^ missing `fn`, `type`, or `const`
5677 // ^^ `sp` below will point to this
5678 let sp = prev_span.between(self.prev_span);
5679 let mut err = self.diagnostic().struct_span_err(
5681 &format!("{} for {}-item declaration",
5682 expected_kinds, item_type));
5683 err.span_label(sp, expected_kinds);
5687 /// Parse a method or a macro invocation in a trait impl.
5688 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5689 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5690 ast::ImplItemKind)> {
5691 // code copied from parse_macro_use_or_failure... abstraction!
5692 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5694 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5695 ast::ImplItemKind::Macro(mac)))
5697 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5698 let ident = self.parse_ident()?;
5699 let mut generics = self.parse_generics()?;
5700 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5701 generics.where_clause = self.parse_where_clause()?;
5703 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5704 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5705 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5706 ast::MethodSig { header, decl },
5712 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5713 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5714 let ident = self.parse_ident()?;
5715 let mut tps = self.parse_generics()?;
5717 // Parse optional colon and supertrait bounds.
5718 let bounds = if self.eat(&token::Colon) {
5719 self.parse_generic_bounds()?
5724 if self.eat(&token::Eq) {
5725 // it's a trait alias
5726 let bounds = self.parse_generic_bounds()?;
5727 tps.where_clause = self.parse_where_clause()?;
5728 self.expect(&token::Semi)?;
5729 if unsafety != Unsafety::Normal {
5730 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5732 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5734 // it's a normal trait
5735 tps.where_clause = self.parse_where_clause()?;
5736 self.expect(&token::OpenDelim(token::Brace))?;
5737 let mut trait_items = vec![];
5738 while !self.eat(&token::CloseDelim(token::Brace)) {
5739 let mut at_end = false;
5740 match self.parse_trait_item(&mut at_end) {
5741 Ok(item) => trait_items.push(item),
5745 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5750 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5754 fn choose_generics_over_qpath(&self) -> bool {
5755 // There's an ambiguity between generic parameters and qualified paths in impls.
5756 // If we see `<` it may start both, so we have to inspect some following tokens.
5757 // The following combinations can only start generics,
5758 // but not qualified paths (with one exception):
5759 // `<` `>` - empty generic parameters
5760 // `<` `#` - generic parameters with attributes
5761 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5762 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5763 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5764 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5765 // The only truly ambiguous case is
5766 // `<` IDENT `>` `::` IDENT ...
5767 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5768 // because this is what almost always expected in practice, qualified paths in impls
5769 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5770 self.token == token::Lt &&
5771 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5772 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5773 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5774 t == &token::Colon || t == &token::Eq))
5777 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5778 self.expect(&token::OpenDelim(token::Brace))?;
5779 let attrs = self.parse_inner_attributes()?;
5781 let mut impl_items = Vec::new();
5782 while !self.eat(&token::CloseDelim(token::Brace)) {
5783 let mut at_end = false;
5784 match self.parse_impl_item(&mut at_end) {
5785 Ok(impl_item) => impl_items.push(impl_item),
5789 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5794 Ok((impl_items, attrs))
5797 /// Parses an implementation item, `impl` keyword is already parsed.
5798 /// impl<'a, T> TYPE { /* impl items */ }
5799 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5800 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5801 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5802 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5803 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5804 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5805 -> PResult<'a, ItemInfo> {
5806 // First, parse generic parameters if necessary.
5807 let mut generics = if self.choose_generics_over_qpath() {
5808 self.parse_generics()?
5810 ast::Generics::default()
5813 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5814 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5816 ast::ImplPolarity::Negative
5818 ast::ImplPolarity::Positive
5821 // Parse both types and traits as a type, then reinterpret if necessary.
5822 let ty_first = self.parse_ty()?;
5824 // If `for` is missing we try to recover.
5825 let has_for = self.eat_keyword(keywords::For);
5826 let missing_for_span = self.prev_span.between(self.span);
5828 let ty_second = if self.token == token::DotDot {
5829 // We need to report this error after `cfg` expansion for compatibility reasons
5830 self.bump(); // `..`, do not add it to expected tokens
5831 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5832 } else if has_for || self.token.can_begin_type() {
5833 Some(self.parse_ty()?)
5838 generics.where_clause = self.parse_where_clause()?;
5840 let (impl_items, attrs) = self.parse_impl_body()?;
5842 let item_kind = match ty_second {
5843 Some(ty_second) => {
5844 // impl Trait for Type
5846 self.span_err(missing_for_span, "missing `for` in a trait impl");
5849 let ty_first = ty_first.into_inner();
5850 let path = match ty_first.node {
5851 // This notably includes paths passed through `ty` macro fragments (#46438).
5852 TyKind::Path(None, path) => path,
5854 self.span_err(ty_first.span, "expected a trait, found type");
5855 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5858 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5860 ItemKind::Impl(unsafety, polarity, defaultness,
5861 generics, Some(trait_ref), ty_second, impl_items)
5865 ItemKind::Impl(unsafety, polarity, defaultness,
5866 generics, None, ty_first, impl_items)
5870 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5873 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5874 if self.eat_keyword(keywords::For) {
5876 let params = self.parse_generic_params()?;
5878 // We rely on AST validation to rule out invalid cases: There must not be type
5879 // parameters, and the lifetime parameters must not have bounds.
5886 /// Parse struct Foo { ... }
5887 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5888 let class_name = self.parse_ident()?;
5890 let mut generics = self.parse_generics()?;
5892 // There is a special case worth noting here, as reported in issue #17904.
5893 // If we are parsing a tuple struct it is the case that the where clause
5894 // should follow the field list. Like so:
5896 // struct Foo<T>(T) where T: Copy;
5898 // If we are parsing a normal record-style struct it is the case
5899 // that the where clause comes before the body, and after the generics.
5900 // So if we look ahead and see a brace or a where-clause we begin
5901 // parsing a record style struct.
5903 // Otherwise if we look ahead and see a paren we parse a tuple-style
5906 let vdata = if self.token.is_keyword(keywords::Where) {
5907 generics.where_clause = self.parse_where_clause()?;
5908 if self.eat(&token::Semi) {
5909 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5910 VariantData::Unit(ast::DUMMY_NODE_ID)
5912 // If we see: `struct Foo<T> where T: Copy { ... }`
5913 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5915 // No `where` so: `struct Foo<T>;`
5916 } else if self.eat(&token::Semi) {
5917 VariantData::Unit(ast::DUMMY_NODE_ID)
5918 // Record-style struct definition
5919 } else if self.token == token::OpenDelim(token::Brace) {
5920 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5921 // Tuple-style struct definition with optional where-clause.
5922 } else if self.token == token::OpenDelim(token::Paren) {
5923 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5924 generics.where_clause = self.parse_where_clause()?;
5925 self.expect(&token::Semi)?;
5928 let token_str = self.this_token_to_string();
5929 let mut err = self.fatal(&format!(
5930 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5933 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5937 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5940 /// Parse union Foo { ... }
5941 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5942 let class_name = self.parse_ident()?;
5944 let mut generics = self.parse_generics()?;
5946 let vdata = if self.token.is_keyword(keywords::Where) {
5947 generics.where_clause = self.parse_where_clause()?;
5948 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5949 } else if self.token == token::OpenDelim(token::Brace) {
5950 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5952 let token_str = self.this_token_to_string();
5953 let mut err = self.fatal(&format!(
5954 "expected `where` or `{{` after union name, found `{}`", token_str));
5955 err.span_label(self.span, "expected `where` or `{` after union name");
5959 Ok((class_name, ItemKind::Union(vdata, generics), None))
5962 fn consume_block(&mut self, delim: token::DelimToken) {
5963 let mut brace_depth = 0;
5964 if !self.eat(&token::OpenDelim(delim)) {
5968 if self.eat(&token::OpenDelim(delim)) {
5970 } else if self.eat(&token::CloseDelim(delim)) {
5971 if brace_depth == 0 {
5977 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5985 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5986 let mut fields = Vec::new();
5987 if self.eat(&token::OpenDelim(token::Brace)) {
5988 while self.token != token::CloseDelim(token::Brace) {
5989 let field = self.parse_struct_decl_field().map_err(|e| {
5990 self.recover_stmt();
5994 Ok(field) => fields.push(field),
6000 self.eat(&token::CloseDelim(token::Brace));
6002 let token_str = self.this_token_to_string();
6003 let mut err = self.fatal(&format!(
6004 "expected `where`, or `{{` after struct name, found `{}`", token_str));
6005 err.span_label(self.span, "expected `where`, or `{` after struct name");
6012 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6013 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6014 // Unit like structs are handled in parse_item_struct function
6015 let fields = self.parse_unspanned_seq(
6016 &token::OpenDelim(token::Paren),
6017 &token::CloseDelim(token::Paren),
6018 SeqSep::trailing_allowed(token::Comma),
6020 let attrs = p.parse_outer_attributes()?;
6022 let vis = p.parse_visibility(true)?;
6023 let ty = p.parse_ty()?;
6025 span: lo.to(ty.span),
6028 id: ast::DUMMY_NODE_ID,
6037 /// Parse a structure field declaration
6038 fn parse_single_struct_field(&mut self,
6041 attrs: Vec<Attribute> )
6042 -> PResult<'a, StructField> {
6043 let mut seen_comma: bool = false;
6044 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6045 if self.token == token::Comma {
6052 token::CloseDelim(token::Brace) => {}
6053 token::DocComment(_) => {
6054 let previous_span = self.prev_span;
6055 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6056 self.bump(); // consume the doc comment
6057 let comma_after_doc_seen = self.eat(&token::Comma);
6058 // `seen_comma` is always false, because we are inside doc block
6059 // condition is here to make code more readable
6060 if seen_comma == false && comma_after_doc_seen == true {
6063 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6066 if seen_comma == false {
6067 let sp = self.sess.source_map().next_point(previous_span);
6068 err.span_suggestion_with_applicability(
6070 "missing comma here",
6072 Applicability::MachineApplicable
6079 let sp = self.sess.source_map().next_point(self.prev_span);
6080 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
6081 self.this_token_to_string()));
6082 if self.token.is_ident() {
6083 // This is likely another field; emit the diagnostic and keep going
6084 err.span_suggestion_with_applicability(
6086 "try adding a comma",
6088 Applicability::MachineApplicable,
6099 /// Parse an element of a struct definition
6100 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6101 let attrs = self.parse_outer_attributes()?;
6103 let vis = self.parse_visibility(false)?;
6104 self.parse_single_struct_field(lo, vis, attrs)
6107 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6108 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6109 /// a function definition, it's not a tuple struct field) and the contents within the parens
6110 /// isn't valid, emit a proper diagnostic.
6111 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6112 maybe_whole!(self, NtVis, |x| x);
6114 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6115 if self.is_crate_vis() {
6116 self.bump(); // `crate`
6117 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6120 if !self.eat_keyword(keywords::Pub) {
6121 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6122 // keyword to grab a span from for inherited visibility; an empty span at the
6123 // beginning of the current token would seem to be the "Schelling span".
6124 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6126 let lo = self.prev_span;
6128 if self.check(&token::OpenDelim(token::Paren)) {
6129 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6130 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6131 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6132 // by the following tokens.
6133 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6136 self.bump(); // `crate`
6137 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6139 lo.to(self.prev_span),
6140 VisibilityKind::Crate(CrateSugar::PubCrate),
6143 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6146 self.bump(); // `in`
6147 let path = self.parse_path(PathStyle::Mod)?; // `path`
6148 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6149 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6151 id: ast::DUMMY_NODE_ID,
6154 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6155 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6156 t.is_keyword(keywords::SelfValue))
6158 // `pub(self)` or `pub(super)`
6160 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6161 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6162 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6164 id: ast::DUMMY_NODE_ID,
6167 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6168 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6170 let msg = "incorrect visibility restriction";
6171 let suggestion = r##"some possible visibility restrictions are:
6172 `pub(crate)`: visible only on the current crate
6173 `pub(super)`: visible only in the current module's parent
6174 `pub(in path::to::module)`: visible only on the specified path"##;
6175 let path = self.parse_path(PathStyle::Mod)?;
6176 let sp = self.prev_span;
6177 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6178 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6179 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6180 err.help(suggestion);
6181 err.span_suggestion_with_applicability(
6182 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6184 err.emit(); // emit diagnostic, but continue with public visibility
6188 Ok(respan(lo, VisibilityKind::Public))
6191 /// Parse defaultness: `default` or nothing.
6192 fn parse_defaultness(&mut self) -> Defaultness {
6193 // `pub` is included for better error messages
6194 if self.check_keyword(keywords::Default) &&
6195 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6196 t.is_keyword(keywords::Const) ||
6197 t.is_keyword(keywords::Fn) ||
6198 t.is_keyword(keywords::Unsafe) ||
6199 t.is_keyword(keywords::Extern) ||
6200 t.is_keyword(keywords::Type) ||
6201 t.is_keyword(keywords::Pub)) {
6202 self.bump(); // `default`
6203 Defaultness::Default
6209 /// Given a termination token, parse all of the items in a module
6210 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6211 let mut items = vec![];
6212 while let Some(item) = self.parse_item()? {
6216 if !self.eat(term) {
6217 let token_str = self.this_token_to_string();
6218 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6219 if token_str == ";" {
6220 let msg = "consider removing this semicolon";
6221 err.span_suggestion_short_with_applicability(
6222 self.span, msg, String::new(), Applicability::MachineApplicable
6224 if !items.is_empty() { // Issue #51603
6225 let previous_item = &items[items.len()-1];
6226 let previous_item_kind_name = match previous_item.node {
6227 // say "braced struct" because tuple-structs and
6228 // braceless-empty-struct declarations do take a semicolon
6229 ItemKind::Struct(..) => Some("braced struct"),
6230 ItemKind::Enum(..) => Some("enum"),
6231 ItemKind::Trait(..) => Some("trait"),
6232 ItemKind::Union(..) => Some("union"),
6235 if let Some(name) = previous_item_kind_name {
6236 err.help(&format!("{} declarations are not followed by a semicolon",
6241 err.span_label(self.span, "expected item");
6246 let hi = if self.span.is_dummy() {
6253 inner: inner_lo.to(hi),
6258 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6259 let id = self.parse_ident()?;
6260 self.expect(&token::Colon)?;
6261 let ty = self.parse_ty()?;
6262 self.expect(&token::Eq)?;
6263 let e = self.parse_expr()?;
6264 self.expect(&token::Semi)?;
6265 let item = match m {
6266 Some(m) => ItemKind::Static(ty, m, e),
6267 None => ItemKind::Const(ty, e),
6269 Ok((id, item, None))
6272 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6273 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6274 let (in_cfg, outer_attrs) = {
6275 let mut strip_unconfigured = ::config::StripUnconfigured {
6277 features: None, // don't perform gated feature checking
6279 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6280 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6283 let id_span = self.span;
6284 let id = self.parse_ident()?;
6285 if self.eat(&token::Semi) {
6286 if in_cfg && self.recurse_into_file_modules {
6287 // This mod is in an external file. Let's go get it!
6288 let ModulePathSuccess { path, directory_ownership, warn } =
6289 self.submod_path(id, &outer_attrs, id_span)?;
6290 let (module, mut attrs) =
6291 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6293 let attr = Attribute {
6294 id: attr::mk_attr_id(),
6295 style: ast::AttrStyle::Outer,
6296 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6297 tokens: TokenStream::empty(),
6298 is_sugared_doc: false,
6299 span: syntax_pos::DUMMY_SP,
6301 attr::mark_known(&attr);
6304 Ok((id, module, Some(attrs)))
6306 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6307 Ok((id, ItemKind::Mod(placeholder), None))
6310 let old_directory = self.directory.clone();
6311 self.push_directory(id, &outer_attrs);
6313 self.expect(&token::OpenDelim(token::Brace))?;
6314 let mod_inner_lo = self.span;
6315 let attrs = self.parse_inner_attributes()?;
6316 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6318 self.directory = old_directory;
6319 Ok((id, ItemKind::Mod(module), Some(attrs)))
6323 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6324 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6325 self.directory.path.to_mut().push(&path.as_str());
6326 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6328 self.directory.path.to_mut().push(&id.as_str());
6332 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6333 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6336 // On windows, the base path might have the form
6337 // `\\?\foo\bar` in which case it does not tolerate
6338 // mixed `/` and `\` separators, so canonicalize
6341 let s = s.replace("/", "\\");
6342 Some(dir_path.join(s))
6348 /// Returns either a path to a module, or .
6349 pub fn default_submod_path(
6351 relative: Option<ast::Ident>,
6353 source_map: &SourceMap) -> ModulePath
6355 // If we're in a foo.rs file instead of a mod.rs file,
6356 // we need to look for submodules in
6357 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6358 // `./<id>.rs` and `./<id>/mod.rs`.
6359 let relative_prefix_string;
6360 let relative_prefix = if let Some(ident) = relative {
6361 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6362 &relative_prefix_string
6367 let mod_name = id.to_string();
6368 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6369 let secondary_path_str = format!("{}{}{}mod.rs",
6370 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6371 let default_path = dir_path.join(&default_path_str);
6372 let secondary_path = dir_path.join(&secondary_path_str);
6373 let default_exists = source_map.file_exists(&default_path);
6374 let secondary_exists = source_map.file_exists(&secondary_path);
6376 let result = match (default_exists, secondary_exists) {
6377 (true, false) => Ok(ModulePathSuccess {
6379 directory_ownership: DirectoryOwnership::Owned {
6384 (false, true) => Ok(ModulePathSuccess {
6385 path: secondary_path,
6386 directory_ownership: DirectoryOwnership::Owned {
6391 (false, false) => Err(Error::FileNotFoundForModule {
6392 mod_name: mod_name.clone(),
6393 default_path: default_path_str,
6394 secondary_path: secondary_path_str,
6395 dir_path: dir_path.display().to_string(),
6397 (true, true) => Err(Error::DuplicatePaths {
6398 mod_name: mod_name.clone(),
6399 default_path: default_path_str,
6400 secondary_path: secondary_path_str,
6406 path_exists: default_exists || secondary_exists,
6411 fn submod_path(&mut self,
6413 outer_attrs: &[Attribute],
6415 -> PResult<'a, ModulePathSuccess> {
6416 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6417 return Ok(ModulePathSuccess {
6418 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6419 // All `#[path]` files are treated as though they are a `mod.rs` file.
6420 // This means that `mod foo;` declarations inside `#[path]`-included
6421 // files are siblings,
6423 // Note that this will produce weirdness when a file named `foo.rs` is
6424 // `#[path]` included and contains a `mod foo;` declaration.
6425 // If you encounter this, it's your own darn fault :P
6426 Some(_) => DirectoryOwnership::Owned { relative: None },
6427 _ => DirectoryOwnership::UnownedViaMod(true),
6434 let relative = match self.directory.ownership {
6435 DirectoryOwnership::Owned { relative } => {
6436 // Push the usage onto the list of non-mod.rs mod uses.
6437 // This is used later for feature-gate error reporting.
6438 if let Some(cur_file_ident) = relative {
6440 .non_modrs_mods.borrow_mut()
6441 .push((cur_file_ident, id_sp));
6445 DirectoryOwnership::UnownedViaBlock |
6446 DirectoryOwnership::UnownedViaMod(_) => None,
6448 let paths = Parser::default_submod_path(
6449 id, relative, &self.directory.path, self.sess.source_map());
6451 match self.directory.ownership {
6452 DirectoryOwnership::Owned { .. } => {
6453 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6455 DirectoryOwnership::UnownedViaBlock => {
6457 "Cannot declare a non-inline module inside a block \
6458 unless it has a path attribute";
6459 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6460 if paths.path_exists {
6461 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6463 err.span_note(id_sp, &msg);
6467 DirectoryOwnership::UnownedViaMod(warn) => {
6469 if let Ok(result) = paths.result {
6470 return Ok(ModulePathSuccess { warn: true, ..result });
6473 let mut err = self.diagnostic().struct_span_err(id_sp,
6474 "cannot declare a new module at this location");
6475 if !id_sp.is_dummy() {
6476 let src_path = self.sess.source_map().span_to_filename(id_sp);
6477 if let FileName::Real(src_path) = src_path {
6478 if let Some(stem) = src_path.file_stem() {
6479 let mut dest_path = src_path.clone();
6480 dest_path.set_file_name(stem);
6481 dest_path.push("mod.rs");
6482 err.span_note(id_sp,
6483 &format!("maybe move this module `{}` to its own \
6484 directory via `{}`", src_path.display(),
6485 dest_path.display()));
6489 if paths.path_exists {
6490 err.span_note(id_sp,
6491 &format!("... or maybe `use` the module `{}` instead \
6492 of possibly redeclaring it",
6500 /// Read a module from a source file.
6501 fn eval_src_mod(&mut self,
6503 directory_ownership: DirectoryOwnership,
6506 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6507 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6508 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6509 let mut err = String::from("circular modules: ");
6510 let len = included_mod_stack.len();
6511 for p in &included_mod_stack[i.. len] {
6512 err.push_str(&p.to_string_lossy());
6513 err.push_str(" -> ");
6515 err.push_str(&path.to_string_lossy());
6516 return Err(self.span_fatal(id_sp, &err[..]));
6518 included_mod_stack.push(path.clone());
6519 drop(included_mod_stack);
6522 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6523 p0.cfg_mods = self.cfg_mods;
6524 let mod_inner_lo = p0.span;
6525 let mod_attrs = p0.parse_inner_attributes()?;
6526 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6527 self.sess.included_mod_stack.borrow_mut().pop();
6528 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6531 /// Parse a function declaration from a foreign module
6532 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6533 -> PResult<'a, ForeignItem> {
6534 self.expect_keyword(keywords::Fn)?;
6536 let (ident, mut generics) = self.parse_fn_header()?;
6537 let decl = self.parse_fn_decl(true)?;
6538 generics.where_clause = self.parse_where_clause()?;
6540 self.expect(&token::Semi)?;
6541 Ok(ast::ForeignItem {
6544 node: ForeignItemKind::Fn(decl, generics),
6545 id: ast::DUMMY_NODE_ID,
6551 /// Parse a static item from a foreign module.
6552 /// Assumes that the `static` keyword is already parsed.
6553 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6554 -> PResult<'a, ForeignItem> {
6555 let mutbl = self.eat_keyword(keywords::Mut);
6556 let ident = self.parse_ident()?;
6557 self.expect(&token::Colon)?;
6558 let ty = self.parse_ty()?;
6560 self.expect(&token::Semi)?;
6564 node: ForeignItemKind::Static(ty, mutbl),
6565 id: ast::DUMMY_NODE_ID,
6571 /// Parse a type from a foreign module
6572 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6573 -> PResult<'a, ForeignItem> {
6574 self.expect_keyword(keywords::Type)?;
6576 let ident = self.parse_ident()?;
6578 self.expect(&token::Semi)?;
6579 Ok(ast::ForeignItem {
6582 node: ForeignItemKind::Ty,
6583 id: ast::DUMMY_NODE_ID,
6589 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6590 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6591 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6593 let mut ident = self.parse_ident()?;
6594 let mut idents = vec![];
6595 let mut replacement = vec![];
6596 let mut fixed_crate_name = false;
6597 // Accept `extern crate name-like-this` for better diagnostics
6598 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6599 if self.token == dash { // Do not include `-` as part of the expected tokens list
6600 while self.eat(&dash) {
6601 fixed_crate_name = true;
6602 replacement.push((self.prev_span, "_".to_string()));
6603 idents.push(self.parse_ident()?);
6606 if fixed_crate_name {
6607 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6608 let mut fixed_name = format!("{}", ident.name);
6609 for part in idents {
6610 fixed_name.push_str(&format!("_{}", part.name));
6612 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6614 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6615 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6616 err.multipart_suggestion(suggestion_msg, replacement);
6622 /// Parse extern crate links
6626 /// extern crate foo;
6627 /// extern crate bar as foo;
6628 fn parse_item_extern_crate(&mut self,
6630 visibility: Visibility,
6631 attrs: Vec<Attribute>)
6632 -> PResult<'a, P<Item>> {
6633 // Accept `extern crate name-like-this` for better diagnostics
6634 let orig_name = self.parse_crate_name_with_dashes()?;
6635 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6636 (rename, Some(orig_name.name))
6640 self.expect(&token::Semi)?;
6642 let span = lo.to(self.prev_span);
6643 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6646 /// Parse `extern` for foreign ABIs
6649 /// `extern` is expected to have been
6650 /// consumed before calling this method
6656 fn parse_item_foreign_mod(&mut self,
6658 opt_abi: Option<Abi>,
6659 visibility: Visibility,
6660 mut attrs: Vec<Attribute>)
6661 -> PResult<'a, P<Item>> {
6662 self.expect(&token::OpenDelim(token::Brace))?;
6664 let abi = opt_abi.unwrap_or(Abi::C);
6666 attrs.extend(self.parse_inner_attributes()?);
6668 let mut foreign_items = vec![];
6669 while let Some(item) = self.parse_foreign_item()? {
6670 foreign_items.push(item);
6672 self.expect(&token::CloseDelim(token::Brace))?;
6674 let prev_span = self.prev_span;
6675 let m = ast::ForeignMod {
6677 items: foreign_items
6679 let invalid = keywords::Invalid.ident();
6680 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6683 /// Parse type Foo = Bar;
6685 /// existential type Foo: Bar;
6687 /// return None without modifying the parser state
6688 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6689 // This parses the grammar:
6690 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6691 if self.check_keyword(keywords::Type) ||
6692 self.check_keyword(keywords::Existential) &&
6693 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6694 let existential = self.eat_keyword(keywords::Existential);
6695 assert!(self.eat_keyword(keywords::Type));
6696 Some(self.parse_existential_or_alias(existential))
6702 /// Parse type alias or existential type
6703 fn parse_existential_or_alias(
6706 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6707 let ident = self.parse_ident()?;
6708 let mut tps = self.parse_generics()?;
6709 tps.where_clause = self.parse_where_clause()?;
6710 let alias = if existential {
6711 self.expect(&token::Colon)?;
6712 let bounds = self.parse_generic_bounds()?;
6713 AliasKind::Existential(bounds)
6715 self.expect(&token::Eq)?;
6716 let ty = self.parse_ty()?;
6719 self.expect(&token::Semi)?;
6720 Ok((ident, alias, tps))
6723 /// Parse the part of an "enum" decl following the '{'
6724 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6725 let mut variants = Vec::new();
6726 let mut all_nullary = true;
6727 let mut any_disr = None;
6728 while self.token != token::CloseDelim(token::Brace) {
6729 let variant_attrs = self.parse_outer_attributes()?;
6730 let vlo = self.span;
6733 let mut disr_expr = None;
6734 let ident = self.parse_ident()?;
6735 if self.check(&token::OpenDelim(token::Brace)) {
6736 // Parse a struct variant.
6737 all_nullary = false;
6738 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6739 ast::DUMMY_NODE_ID);
6740 } else if self.check(&token::OpenDelim(token::Paren)) {
6741 all_nullary = false;
6742 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6743 ast::DUMMY_NODE_ID);
6744 } else if self.eat(&token::Eq) {
6745 disr_expr = Some(AnonConst {
6746 id: ast::DUMMY_NODE_ID,
6747 value: self.parse_expr()?,
6749 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6750 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6752 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6755 let vr = ast::Variant_ {
6757 attrs: variant_attrs,
6761 variants.push(respan(vlo.to(self.prev_span), vr));
6763 if !self.eat(&token::Comma) { break; }
6765 self.expect(&token::CloseDelim(token::Brace))?;
6767 Some(disr_span) if !all_nullary =>
6768 self.span_err(disr_span,
6769 "discriminator values can only be used with a field-less enum"),
6773 Ok(ast::EnumDef { variants: variants })
6776 /// Parse an "enum" declaration
6777 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6778 let id = self.parse_ident()?;
6779 let mut generics = self.parse_generics()?;
6780 generics.where_clause = self.parse_where_clause()?;
6781 self.expect(&token::OpenDelim(token::Brace))?;
6783 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6784 self.recover_stmt();
6785 self.eat(&token::CloseDelim(token::Brace));
6788 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6791 /// Parses a string as an ABI spec on an extern type or module. Consumes
6792 /// the `extern` keyword, if one is found.
6793 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6795 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6797 self.expect_no_suffix(sp, "ABI spec", suf);
6799 match abi::lookup(&s.as_str()) {
6800 Some(abi) => Ok(Some(abi)),
6802 let prev_span = self.prev_span;
6803 let mut err = struct_span_err!(
6804 self.sess.span_diagnostic,
6807 "invalid ABI: found `{}`",
6809 err.span_label(prev_span, "invalid ABI");
6810 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6821 fn is_static_global(&mut self) -> bool {
6822 if self.check_keyword(keywords::Static) {
6823 // Check if this could be a closure
6824 !self.look_ahead(1, |token| {
6825 if token.is_keyword(keywords::Move) {
6829 token::BinOp(token::Or) | token::OrOr => true,
6840 attrs: Vec<Attribute>,
6841 macros_allowed: bool,
6842 attributes_allowed: bool,
6843 ) -> PResult<'a, Option<P<Item>>> {
6844 let (ret, tokens) = self.collect_tokens(|this| {
6845 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
6848 // Once we've parsed an item and recorded the tokens we got while
6849 // parsing we may want to store `tokens` into the item we're about to
6850 // return. Note, though, that we specifically didn't capture tokens
6851 // related to outer attributes. The `tokens` field here may later be
6852 // used with procedural macros to convert this item back into a token
6853 // stream, but during expansion we may be removing attributes as we go
6856 // If we've got inner attributes then the `tokens` we've got above holds
6857 // these inner attributes. If an inner attribute is expanded we won't
6858 // actually remove it from the token stream, so we'll just keep yielding
6859 // it (bad!). To work around this case for now we just avoid recording
6860 // `tokens` if we detect any inner attributes. This should help keep
6861 // expansion correct, but we should fix this bug one day!
6864 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6865 i.tokens = Some(tokens);
6872 /// Parse one of the items allowed by the flags.
6873 fn parse_item_implementation(
6875 attrs: Vec<Attribute>,
6876 macros_allowed: bool,
6877 attributes_allowed: bool,
6878 ) -> PResult<'a, Option<P<Item>>> {
6879 maybe_whole!(self, NtItem, |item| {
6880 let mut item = item.into_inner();
6881 let mut attrs = attrs;
6882 mem::swap(&mut item.attrs, &mut attrs);
6883 item.attrs.extend(attrs);
6889 let visibility = self.parse_visibility(false)?;
6891 if self.eat_keyword(keywords::Use) {
6893 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6894 self.expect(&token::Semi)?;
6896 let span = lo.to(self.prev_span);
6897 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6898 return Ok(Some(item));
6901 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6902 self.bump(); // `extern`
6903 if self.eat_keyword(keywords::Crate) {
6904 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6907 let opt_abi = self.parse_opt_abi()?;
6909 if self.eat_keyword(keywords::Fn) {
6910 // EXTERN FUNCTION ITEM
6911 let fn_span = self.prev_span;
6912 let abi = opt_abi.unwrap_or(Abi::C);
6913 let (ident, item_, extra_attrs) =
6914 self.parse_item_fn(Unsafety::Normal,
6916 respan(fn_span, Constness::NotConst),
6918 let prev_span = self.prev_span;
6919 let item = self.mk_item(lo.to(prev_span),
6923 maybe_append(attrs, extra_attrs));
6924 return Ok(Some(item));
6925 } else if self.check(&token::OpenDelim(token::Brace)) {
6926 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6932 if self.is_static_global() {
6935 let m = if self.eat_keyword(keywords::Mut) {
6938 Mutability::Immutable
6940 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6941 let prev_span = self.prev_span;
6942 let item = self.mk_item(lo.to(prev_span),
6946 maybe_append(attrs, extra_attrs));
6947 return Ok(Some(item));
6949 if self.eat_keyword(keywords::Const) {
6950 let const_span = self.prev_span;
6951 if self.check_keyword(keywords::Fn)
6952 || (self.check_keyword(keywords::Unsafe)
6953 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6954 // CONST FUNCTION ITEM
6955 let unsafety = self.parse_unsafety();
6957 let (ident, item_, extra_attrs) =
6958 self.parse_item_fn(unsafety,
6960 respan(const_span, Constness::Const),
6962 let prev_span = self.prev_span;
6963 let item = self.mk_item(lo.to(prev_span),
6967 maybe_append(attrs, extra_attrs));
6968 return Ok(Some(item));
6972 if self.eat_keyword(keywords::Mut) {
6973 let prev_span = self.prev_span;
6974 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6975 .help("did you mean to declare a static?")
6978 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6979 let prev_span = self.prev_span;
6980 let item = self.mk_item(lo.to(prev_span),
6984 maybe_append(attrs, extra_attrs));
6985 return Ok(Some(item));
6988 // `unsafe async fn` or `async fn`
6990 self.check_keyword(keywords::Unsafe) &&
6991 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
6993 self.check_keyword(keywords::Async) &&
6994 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
6997 // ASYNC FUNCTION ITEM
6998 let unsafety = self.parse_unsafety();
6999 self.expect_keyword(keywords::Async)?;
7000 self.expect_keyword(keywords::Fn)?;
7001 let fn_span = self.prev_span;
7002 let (ident, item_, extra_attrs) =
7003 self.parse_item_fn(unsafety,
7005 closure_id: ast::DUMMY_NODE_ID,
7006 return_impl_trait_id: ast::DUMMY_NODE_ID,
7008 respan(fn_span, Constness::NotConst),
7010 let prev_span = self.prev_span;
7011 let item = self.mk_item(lo.to(prev_span),
7015 maybe_append(attrs, extra_attrs));
7016 return Ok(Some(item));
7018 if self.check_keyword(keywords::Unsafe) &&
7019 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7020 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7022 // UNSAFE TRAIT ITEM
7023 self.bump(); // `unsafe`
7024 let is_auto = if self.eat_keyword(keywords::Trait) {
7027 self.expect_keyword(keywords::Auto)?;
7028 self.expect_keyword(keywords::Trait)?;
7031 let (ident, item_, extra_attrs) =
7032 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7033 let prev_span = self.prev_span;
7034 let item = self.mk_item(lo.to(prev_span),
7038 maybe_append(attrs, extra_attrs));
7039 return Ok(Some(item));
7041 if self.check_keyword(keywords::Impl) ||
7042 self.check_keyword(keywords::Unsafe) &&
7043 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7044 self.check_keyword(keywords::Default) &&
7045 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7046 self.check_keyword(keywords::Default) &&
7047 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7049 let defaultness = self.parse_defaultness();
7050 let unsafety = self.parse_unsafety();
7051 self.expect_keyword(keywords::Impl)?;
7052 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7053 let span = lo.to(self.prev_span);
7054 return Ok(Some(self.mk_item(span, ident, item, visibility,
7055 maybe_append(attrs, extra_attrs))));
7057 if self.check_keyword(keywords::Fn) {
7060 let fn_span = self.prev_span;
7061 let (ident, item_, extra_attrs) =
7062 self.parse_item_fn(Unsafety::Normal,
7064 respan(fn_span, Constness::NotConst),
7066 let prev_span = self.prev_span;
7067 let item = self.mk_item(lo.to(prev_span),
7071 maybe_append(attrs, extra_attrs));
7072 return Ok(Some(item));
7074 if self.check_keyword(keywords::Unsafe)
7075 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7076 // UNSAFE FUNCTION ITEM
7077 self.bump(); // `unsafe`
7078 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7079 self.check(&token::OpenDelim(token::Brace));
7080 let abi = if self.eat_keyword(keywords::Extern) {
7081 self.parse_opt_abi()?.unwrap_or(Abi::C)
7085 self.expect_keyword(keywords::Fn)?;
7086 let fn_span = self.prev_span;
7087 let (ident, item_, extra_attrs) =
7088 self.parse_item_fn(Unsafety::Unsafe,
7090 respan(fn_span, Constness::NotConst),
7092 let prev_span = self.prev_span;
7093 let item = self.mk_item(lo.to(prev_span),
7097 maybe_append(attrs, extra_attrs));
7098 return Ok(Some(item));
7100 if self.eat_keyword(keywords::Mod) {
7102 let (ident, item_, extra_attrs) =
7103 self.parse_item_mod(&attrs[..])?;
7104 let prev_span = self.prev_span;
7105 let item = self.mk_item(lo.to(prev_span),
7109 maybe_append(attrs, extra_attrs));
7110 return Ok(Some(item));
7112 if let Some(type_) = self.eat_type() {
7113 let (ident, alias, generics) = type_?;
7115 let item_ = match alias {
7116 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7117 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7119 let prev_span = self.prev_span;
7120 let item = self.mk_item(lo.to(prev_span),
7125 return Ok(Some(item));
7127 if self.eat_keyword(keywords::Enum) {
7129 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7130 let prev_span = self.prev_span;
7131 let item = self.mk_item(lo.to(prev_span),
7135 maybe_append(attrs, extra_attrs));
7136 return Ok(Some(item));
7138 if self.check_keyword(keywords::Trait)
7139 || (self.check_keyword(keywords::Auto)
7140 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7142 let is_auto = if self.eat_keyword(keywords::Trait) {
7145 self.expect_keyword(keywords::Auto)?;
7146 self.expect_keyword(keywords::Trait)?;
7150 let (ident, item_, extra_attrs) =
7151 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7152 let prev_span = self.prev_span;
7153 let item = self.mk_item(lo.to(prev_span),
7157 maybe_append(attrs, extra_attrs));
7158 return Ok(Some(item));
7160 if self.eat_keyword(keywords::Struct) {
7162 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7163 let prev_span = self.prev_span;
7164 let item = self.mk_item(lo.to(prev_span),
7168 maybe_append(attrs, extra_attrs));
7169 return Ok(Some(item));
7171 if self.is_union_item() {
7174 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7175 let prev_span = self.prev_span;
7176 let item = self.mk_item(lo.to(prev_span),
7180 maybe_append(attrs, extra_attrs));
7181 return Ok(Some(item));
7183 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7184 return Ok(Some(macro_def));
7187 // Verify whether we have encountered a struct or method definition where the user forgot to
7188 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7189 if visibility.node.is_pub() &&
7190 self.check_ident() &&
7191 self.look_ahead(1, |t| *t != token::Not)
7193 // Space between `pub` keyword and the identifier
7196 // ^^^ `sp` points here
7197 let sp = self.prev_span.between(self.span);
7198 let full_sp = self.prev_span.to(self.span);
7199 let ident_sp = self.span;
7200 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7201 // possible public struct definition where `struct` was forgotten
7202 let ident = self.parse_ident().unwrap();
7203 let msg = format!("add `struct` here to parse `{}` as a public struct",
7205 let mut err = self.diagnostic()
7206 .struct_span_err(sp, "missing `struct` for struct definition");
7207 err.span_suggestion_short_with_applicability(
7208 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7211 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7212 let ident = self.parse_ident().unwrap();
7213 self.consume_block(token::Paren);
7214 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7215 self.check(&token::OpenDelim(token::Brace))
7217 ("fn", "method", false)
7218 } else if self.check(&token::Colon) {
7222 ("fn` or `struct", "method or struct", true)
7225 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7226 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7228 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7232 err.span_suggestion_short_with_applicability(
7233 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7236 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7237 err.span_suggestion_with_applicability(
7239 "if you meant to call a macro, try",
7240 format!("{}!", snippet),
7241 // this is the `ambiguous` conditional branch
7242 Applicability::MaybeIncorrect
7245 err.help("if you meant to call a macro, remove the `pub` \
7246 and add a trailing `!` after the identifier");
7252 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7255 /// Parse a foreign item.
7256 crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
7257 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
7259 let attrs = self.parse_outer_attributes()?;
7261 let visibility = self.parse_visibility(false)?;
7263 // FOREIGN STATIC ITEM
7264 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7265 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7266 if self.token.is_keyword(keywords::Const) {
7268 .struct_span_err(self.span, "extern items cannot be `const`")
7269 .span_suggestion_with_applicability(
7271 "try using a static value",
7272 "static".to_owned(),
7273 Applicability::MachineApplicable
7276 self.bump(); // `static` or `const`
7277 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
7279 // FOREIGN FUNCTION ITEM
7280 if self.check_keyword(keywords::Fn) {
7281 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
7283 // FOREIGN TYPE ITEM
7284 if self.check_keyword(keywords::Type) {
7285 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
7288 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7292 ident: keywords::Invalid.ident(),
7293 span: lo.to(self.prev_span),
7294 id: ast::DUMMY_NODE_ID,
7297 node: ForeignItemKind::Macro(mac),
7302 if !attrs.is_empty() {
7303 self.expected_item_err(&attrs);
7311 /// This is the fall-through for parsing items.
7312 fn parse_macro_use_or_failure(
7314 attrs: Vec<Attribute> ,
7315 macros_allowed: bool,
7316 attributes_allowed: bool,
7318 visibility: Visibility
7319 ) -> PResult<'a, Option<P<Item>>> {
7320 if macros_allowed && self.token.is_path_start() {
7321 // MACRO INVOCATION ITEM
7323 let prev_span = self.prev_span;
7324 self.complain_if_pub_macro(&visibility.node, prev_span);
7326 let mac_lo = self.span;
7329 let pth = self.parse_path(PathStyle::Mod)?;
7330 self.expect(&token::Not)?;
7332 // a 'special' identifier (like what `macro_rules!` uses)
7333 // is optional. We should eventually unify invoc syntax
7335 let id = if self.token.is_ident() {
7338 keywords::Invalid.ident() // no special identifier
7340 // eat a matched-delimiter token tree:
7341 let (delim, tts) = self.expect_delimited_token_tree()?;
7342 if delim != MacDelimiter::Brace {
7343 if !self.eat(&token::Semi) {
7344 self.span_err(self.prev_span,
7345 "macros that expand to items must either \
7346 be surrounded with braces or followed by \
7351 let hi = self.prev_span;
7352 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7353 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7354 return Ok(Some(item));
7357 // FAILURE TO PARSE ITEM
7358 match visibility.node {
7359 VisibilityKind::Inherited => {}
7361 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7365 if !attributes_allowed && !attrs.is_empty() {
7366 self.expected_item_err(&attrs);
7371 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7372 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7373 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7375 if self.token.is_path_start() && !self.is_extern_non_path() {
7376 let prev_span = self.prev_span;
7378 let pth = self.parse_path(PathStyle::Mod)?;
7380 if pth.segments.len() == 1 {
7381 if !self.eat(&token::Not) {
7382 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7385 self.expect(&token::Not)?;
7388 if let Some(vis) = vis {
7389 self.complain_if_pub_macro(&vis.node, prev_span);
7394 // eat a matched-delimiter token tree:
7395 let (delim, tts) = self.expect_delimited_token_tree()?;
7396 if delim != MacDelimiter::Brace {
7397 self.expect(&token::Semi)?
7400 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7406 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7407 where F: FnOnce(&mut Self) -> PResult<'a, R>
7409 // Record all tokens we parse when parsing this item.
7410 let mut tokens = Vec::new();
7411 let prev_collecting = match self.token_cursor.frame.last_token {
7412 LastToken::Collecting(ref mut list) => {
7413 Some(mem::replace(list, Vec::new()))
7415 LastToken::Was(ref mut last) => {
7416 tokens.extend(last.take());
7420 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7421 let prev = self.token_cursor.stack.len();
7423 let last_token = if self.token_cursor.stack.len() == prev {
7424 &mut self.token_cursor.frame.last_token
7426 &mut self.token_cursor.stack[prev].last_token
7429 // Pull our the toekns that we've collected from the call to `f` above
7430 let mut collected_tokens = match *last_token {
7431 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7432 LastToken::Was(_) => panic!("our vector went away?"),
7435 // If we're not at EOF our current token wasn't actually consumed by
7436 // `f`, but it'll still be in our list that we pulled out. In that case
7438 let extra_token = if self.token != token::Eof {
7439 collected_tokens.pop()
7444 // If we were previously collecting tokens, then this was a recursive
7445 // call. In that case we need to record all the tokens we collected in
7446 // our parent list as well. To do that we push a clone of our stream
7447 // onto the previous list.
7448 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7449 match prev_collecting {
7451 list.push(stream.clone());
7452 list.extend(extra_token);
7453 *last_token = LastToken::Collecting(list);
7456 *last_token = LastToken::Was(extra_token);
7463 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7464 let attrs = self.parse_outer_attributes()?;
7465 self.parse_item_(attrs, true, false)
7469 fn is_import_coupler(&mut self) -> bool {
7470 self.check(&token::ModSep) &&
7471 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7472 *t == token::BinOp(token::Star))
7477 /// USE_TREE = [`::`] `*` |
7478 /// [`::`] `{` USE_TREE_LIST `}` |
7480 /// PATH `::` `{` USE_TREE_LIST `}` |
7481 /// PATH [`as` IDENT]
7482 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7485 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7486 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7487 self.check(&token::BinOp(token::Star)) ||
7488 self.is_import_coupler() {
7489 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7490 if self.eat(&token::ModSep) {
7491 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7494 if self.eat(&token::BinOp(token::Star)) {
7497 UseTreeKind::Nested(self.parse_use_tree_list()?)
7500 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7501 prefix = self.parse_path(PathStyle::Mod)?;
7503 if self.eat(&token::ModSep) {
7504 if self.eat(&token::BinOp(token::Star)) {
7507 UseTreeKind::Nested(self.parse_use_tree_list()?)
7510 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7514 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7517 /// Parse UseTreeKind::Nested(list)
7519 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7520 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7521 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7522 &token::CloseDelim(token::Brace),
7523 SeqSep::trailing_allowed(token::Comma), |this| {
7524 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7528 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7529 if self.eat_keyword(keywords::As) {
7531 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7533 Ok(Some(ident.gensym()))
7535 _ => self.parse_ident().map(Some),
7542 /// Parses a source module as a crate. This is the main
7543 /// entry point for the parser.
7544 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7547 attrs: self.parse_inner_attributes()?,
7548 module: self.parse_mod_items(&token::Eof, lo)?,
7549 span: lo.to(self.span),
7553 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7554 let ret = match self.token {
7555 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7556 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7563 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7564 match self.parse_optional_str() {
7565 Some((s, style, suf)) => {
7566 let sp = self.prev_span;
7567 self.expect_no_suffix(sp, "string literal", suf);
7571 let msg = "expected string literal";
7572 let mut err = self.fatal(msg);
7573 err.span_label(self.span, msg);