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, 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: Span, 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)
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)
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 body = TokenTree::Delimited(sp, Delimited {
365 delim: token::Bracket,
366 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
367 TokenTree::Token(sp, token::Eq),
368 TokenTree::Token(sp, token::Literal(
369 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
370 .iter().cloned().collect::<TokenStream>().into(),
373 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
374 delim: token::NoDelim,
375 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
376 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
377 .iter().cloned().collect::<TokenStream>().into()
379 [TokenTree::Token(sp, token::Pound), body]
380 .iter().cloned().collect::<TokenStream>().into()
388 #[derive(Clone, PartialEq)]
389 crate enum TokenType {
391 Keyword(keywords::Keyword),
400 fn to_string(&self) -> String {
402 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
403 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
404 TokenType::Operator => "an operator".to_string(),
405 TokenType::Lifetime => "lifetime".to_string(),
406 TokenType::Ident => "identifier".to_string(),
407 TokenType::Path => "path".to_string(),
408 TokenType::Type => "type".to_string(),
413 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
414 /// `IDENT<<u8 as Trait>::AssocTy>`.
416 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
417 /// that IDENT is not the ident of a fn trait
418 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
419 t == &token::ModSep || t == &token::Lt ||
420 t == &token::BinOp(token::Shl)
423 /// Information about the path to a module.
424 pub struct ModulePath {
427 pub result: Result<ModulePathSuccess, Error>,
430 pub struct ModulePathSuccess {
432 pub directory_ownership: DirectoryOwnership,
437 FileNotFoundForModule {
439 default_path: String,
440 secondary_path: String,
445 default_path: String,
446 secondary_path: String,
449 InclusiveRangeWithNoEnd,
453 fn span_err<S: Into<MultiSpan>>(self,
455 handler: &errors::Handler) -> DiagnosticBuilder {
457 Error::FileNotFoundForModule { ref mod_name,
461 let mut err = struct_span_err!(handler, sp, E0583,
462 "file not found for module `{}`", mod_name);
463 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
469 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
470 let mut err = struct_span_err!(handler, sp, E0584,
471 "file for module `{}` found at both {} and {}",
475 err.help("delete or rename one of them to remove the ambiguity");
478 Error::UselessDocComment => {
479 let mut err = struct_span_err!(handler, sp, E0585,
480 "found a documentation comment that doesn't document anything");
481 err.help("doc comments must come before what they document, maybe a comment was \
482 intended with `//`?");
485 Error::InclusiveRangeWithNoEnd => {
486 let mut err = struct_span_err!(handler, sp, E0586,
487 "inclusive range with no end");
488 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
498 AttributesParsed(ThinVec<Attribute>),
499 AlreadyParsed(P<Expr>),
502 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
503 fn from(o: Option<ThinVec<Attribute>>) -> Self {
504 if let Some(attrs) = o {
505 LhsExpr::AttributesParsed(attrs)
507 LhsExpr::NotYetParsed
512 impl From<P<Expr>> for LhsExpr {
513 fn from(expr: P<Expr>) -> Self {
514 LhsExpr::AlreadyParsed(expr)
518 /// Create a placeholder argument.
519 fn dummy_arg(span: Span) -> Arg {
520 let ident = Ident::new(keywords::Invalid.name(), span);
522 id: ast::DUMMY_NODE_ID,
523 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
529 id: ast::DUMMY_NODE_ID
531 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
534 #[derive(Copy, Clone, Debug)]
535 enum TokenExpectType {
540 impl<'a> Parser<'a> {
541 pub fn new(sess: &'a ParseSess,
543 directory: Option<Directory<'a>>,
544 recurse_into_file_modules: bool,
545 desugar_doc_comments: bool)
547 let mut parser = Parser {
549 token: token::Whitespace,
550 span: syntax_pos::DUMMY_SP,
551 prev_span: syntax_pos::DUMMY_SP,
553 prev_token_kind: PrevTokenKind::Other,
554 restrictions: Restrictions::empty(),
555 recurse_into_file_modules,
556 directory: Directory {
557 path: Cow::from(PathBuf::new()),
558 ownership: DirectoryOwnership::Owned { relative: None }
560 root_module_name: None,
561 expected_tokens: Vec::new(),
562 token_cursor: TokenCursor {
563 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
564 delim: token::NoDelim,
569 desugar_doc_comments,
573 let tok = parser.next_tok();
574 parser.token = tok.tok;
575 parser.span = tok.sp;
577 if let Some(directory) = directory {
578 parser.directory = directory;
579 } else if !parser.span.is_dummy() {
580 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
582 parser.directory.path = Cow::from(path);
586 parser.process_potential_macro_variable();
590 fn next_tok(&mut self) -> TokenAndSpan {
591 let mut next = if self.desugar_doc_comments {
592 self.token_cursor.next_desugared()
594 self.token_cursor.next()
596 if next.sp.is_dummy() {
597 // Tweak the location for better diagnostics, but keep syntactic context intact.
598 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
603 /// Convert the current token to a string using self's reader
604 pub fn this_token_to_string(&self) -> String {
605 pprust::token_to_string(&self.token)
608 fn token_descr(&self) -> Option<&'static str> {
609 Some(match &self.token {
610 t if t.is_special_ident() => "reserved identifier",
611 t if t.is_used_keyword() => "keyword",
612 t if t.is_unused_keyword() => "reserved keyword",
617 fn this_token_descr(&self) -> String {
618 if let Some(prefix) = self.token_descr() {
619 format!("{} `{}`", prefix, self.this_token_to_string())
621 format!("`{}`", self.this_token_to_string())
625 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
626 let token_str = pprust::token_to_string(t);
627 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
630 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
631 match self.expect_one_of(&[], &[]) {
633 Ok(_) => unreachable!(),
637 /// Expect and consume the token t. Signal an error if
638 /// the next token is not t.
639 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
640 if self.expected_tokens.is_empty() {
641 if self.token == *t {
645 let token_str = pprust::token_to_string(t);
646 let this_token_str = self.this_token_to_string();
647 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
651 let sp = if self.token == token::Token::Eof {
652 // EOF, don't want to point at the following char, but rather the last token
655 self.sess.source_map().next_point(self.prev_span)
657 let label_exp = format!("expected `{}`", token_str);
658 let cm = self.sess.source_map();
659 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
660 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
661 // When the spans are in the same line, it means that the only content
662 // between them is whitespace, point only at the found token.
663 err.span_label(self.span, label_exp);
666 err.span_label(sp, label_exp);
667 err.span_label(self.span, "unexpected token");
673 self.expect_one_of(slice::from_ref(t), &[])
677 /// Expect next token to be edible or inedible token. If edible,
678 /// then consume it; if inedible, then return without consuming
679 /// anything. Signal a fatal error if next token is unexpected.
680 fn expect_one_of(&mut self,
681 edible: &[token::Token],
682 inedible: &[token::Token]) -> PResult<'a, ()>{
683 fn tokens_to_string(tokens: &[TokenType]) -> String {
684 let mut i = tokens.iter();
685 // This might be a sign we need a connect method on Iterator.
687 .map_or(String::new(), |t| t.to_string());
688 i.enumerate().fold(b, |mut b, (i, a)| {
689 if tokens.len() > 2 && i == tokens.len() - 2 {
691 } else if tokens.len() == 2 && i == tokens.len() - 2 {
696 b.push_str(&a.to_string());
700 if edible.contains(&self.token) {
703 } else if inedible.contains(&self.token) {
704 // leave it in the input
707 let mut expected = edible.iter()
708 .map(|x| TokenType::Token(x.clone()))
709 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
710 .chain(self.expected_tokens.iter().cloned())
711 .collect::<Vec<_>>();
712 expected.sort_by_cached_key(|x| x.to_string());
714 let expect = tokens_to_string(&expected[..]);
715 let actual = self.this_token_to_string();
716 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
717 let short_expect = if expected.len() > 6 {
718 format!("{} possible tokens", expected.len())
722 (format!("expected one of {}, found `{}`", expect, actual),
723 (self.sess.source_map().next_point(self.prev_span),
724 format!("expected one of {} here", short_expect)))
725 } else if expected.is_empty() {
726 (format!("unexpected token: `{}`", actual),
727 (self.prev_span, "unexpected token after this".to_string()))
729 (format!("expected {}, found `{}`", expect, actual),
730 (self.sess.source_map().next_point(self.prev_span),
731 format!("expected {} here", expect)))
733 let mut err = self.fatal(&msg_exp);
734 let sp = if self.token == token::Token::Eof {
735 // This is EOF, don't want to point at the following char, but rather the last token
741 let cm = self.sess.source_map();
742 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
743 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
744 // When the spans are in the same line, it means that the only content between
745 // them is whitespace, point at the found token in that case:
747 // X | () => { syntax error };
748 // | ^^^^^ expected one of 8 possible tokens here
750 // instead of having:
752 // X | () => { syntax error };
753 // | -^^^^^ unexpected token
755 // | expected one of 8 possible tokens here
756 err.span_label(self.span, label_exp);
759 err.span_label(sp, label_exp);
760 err.span_label(self.span, "unexpected token");
767 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
768 fn interpolated_or_expr_span(&self,
769 expr: PResult<'a, P<Expr>>)
770 -> PResult<'a, (Span, P<Expr>)> {
772 if self.prev_token_kind == PrevTokenKind::Interpolated {
780 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
781 let mut err = self.struct_span_err(self.span,
782 &format!("expected identifier, found {}",
783 self.this_token_descr()));
784 if let Some(token_descr) = self.token_descr() {
785 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
787 err.span_label(self.span, "expected identifier");
788 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
789 err.span_suggestion_with_applicability(
793 Applicability::MachineApplicable,
800 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
801 self.parse_ident_common(true)
804 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
806 token::Ident(ident, _) => {
807 if self.token.is_reserved_ident() {
808 let mut err = self.expected_ident_found();
815 let span = self.span;
817 Ok(Ident::new(ident.name, span))
820 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
821 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
823 self.expected_ident_found()
829 /// Check if the next token is `tok`, and return `true` if so.
831 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
833 crate fn check(&mut self, tok: &token::Token) -> bool {
834 let is_present = self.token == *tok;
835 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
839 /// Consume token 'tok' if it exists. Returns true if the given
840 /// token was present, false otherwise.
841 pub fn eat(&mut self, tok: &token::Token) -> bool {
842 let is_present = self.check(tok);
843 if is_present { self.bump() }
847 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
848 self.expected_tokens.push(TokenType::Keyword(kw));
849 self.token.is_keyword(kw)
852 /// If the next token is the given keyword, eat it and return
853 /// true. Otherwise, return false.
854 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
855 if self.check_keyword(kw) {
863 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
864 if self.token.is_keyword(kw) {
872 /// If the given word is not a keyword, signal an error.
873 /// If the next token is not the given word, signal an error.
874 /// Otherwise, eat it.
875 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
876 if !self.eat_keyword(kw) {
883 fn check_ident(&mut self) -> bool {
884 if self.token.is_ident() {
887 self.expected_tokens.push(TokenType::Ident);
892 fn check_path(&mut self) -> bool {
893 if self.token.is_path_start() {
896 self.expected_tokens.push(TokenType::Path);
901 fn check_type(&mut self) -> bool {
902 if self.token.can_begin_type() {
905 self.expected_tokens.push(TokenType::Type);
910 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
911 /// and continue. If a `+` is not seen, return false.
913 /// This is using when token splitting += into +.
914 /// See issue 47856 for an example of when this may occur.
915 fn eat_plus(&mut self) -> bool {
916 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
918 token::BinOp(token::Plus) => {
922 token::BinOpEq(token::Plus) => {
923 let span = self.span.with_lo(self.span.lo() + BytePos(1));
924 self.bump_with(token::Eq, span);
932 /// Checks to see if the next token is either `+` or `+=`.
933 /// Otherwise returns false.
934 fn check_plus(&mut self) -> bool {
935 if self.token.is_like_plus() {
939 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
944 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
945 /// `&` and continue. If an `&` is not seen, signal an error.
946 fn expect_and(&mut self) -> PResult<'a, ()> {
947 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
949 token::BinOp(token::And) => {
954 let span = self.span.with_lo(self.span.lo() + BytePos(1));
955 Ok(self.bump_with(token::BinOp(token::And), span))
957 _ => self.unexpected()
961 /// Expect and consume an `|`. If `||` is seen, replace it with a single
962 /// `|` and continue. If an `|` is not seen, signal an error.
963 fn expect_or(&mut self) -> PResult<'a, ()> {
964 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
966 token::BinOp(token::Or) => {
971 let span = self.span.with_lo(self.span.lo() + BytePos(1));
972 Ok(self.bump_with(token::BinOp(token::Or), span))
974 _ => self.unexpected()
978 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
980 None => {/* everything ok */}
982 let text = suf.as_str();
984 self.span_bug(sp, "found empty literal suffix in Some")
986 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
991 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
992 /// `<` and continue. If a `<` is not seen, return false.
994 /// This is meant to be used when parsing generics on a path to get the
996 fn eat_lt(&mut self) -> bool {
997 self.expected_tokens.push(TokenType::Token(token::Lt));
1003 token::BinOp(token::Shl) => {
1004 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1005 self.bump_with(token::Lt, span);
1012 fn expect_lt(&mut self) -> PResult<'a, ()> {
1020 /// Expect and consume a GT. if a >> is seen, replace it
1021 /// with a single > and continue. If a GT is not seen,
1022 /// signal an error.
1023 fn expect_gt(&mut self) -> PResult<'a, ()> {
1024 self.expected_tokens.push(TokenType::Token(token::Gt));
1030 token::BinOp(token::Shr) => {
1031 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1032 Ok(self.bump_with(token::Gt, span))
1034 token::BinOpEq(token::Shr) => {
1035 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1036 Ok(self.bump_with(token::Ge, span))
1039 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1040 Ok(self.bump_with(token::Eq, span))
1042 _ => self.unexpected()
1046 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1047 /// passes through any errors encountered. Used for error recovery.
1048 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1049 let handler = self.diagnostic();
1051 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1053 TokenExpectType::Expect,
1054 |p| Ok(p.parse_token_tree())) {
1055 handler.cancel(err);
1059 /// Parse a sequence, including the closing delimiter. The function
1060 /// f must consume tokens until reaching the next separator or
1061 /// closing bracket.
1062 pub fn parse_seq_to_end<T, F>(&mut self,
1066 -> PResult<'a, Vec<T>> where
1067 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1069 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1074 /// Parse a sequence, not including the closing delimiter. The function
1075 /// f must consume tokens until reaching the next separator or
1076 /// closing bracket.
1077 pub fn parse_seq_to_before_end<T, F>(&mut self,
1081 -> PResult<'a, Vec<T>>
1082 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1084 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1087 fn parse_seq_to_before_tokens<T, F>(
1089 kets: &[&token::Token],
1091 expect: TokenExpectType,
1093 ) -> PResult<'a, Vec<T>>
1094 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1096 let mut first: bool = true;
1098 while !kets.iter().any(|k| {
1100 TokenExpectType::Expect => self.check(k),
1101 TokenExpectType::NoExpect => self.token == **k,
1105 token::CloseDelim(..) | token::Eof => break,
1108 if let Some(ref t) = sep.sep {
1112 if let Err(mut e) = self.expect(t) {
1113 // Attempt to keep parsing if it was a similar separator
1114 if let Some(ref tokens) = t.similar_tokens() {
1115 if tokens.contains(&self.token) {
1120 // Attempt to keep parsing if it was an omitted separator
1134 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1136 TokenExpectType::Expect => self.check(k),
1137 TokenExpectType::NoExpect => self.token == **k,
1150 /// Parse a sequence, including the closing delimiter. The function
1151 /// f must consume tokens until reaching the next separator or
1152 /// closing bracket.
1153 fn parse_unspanned_seq<T, F>(&mut self,
1158 -> PResult<'a, Vec<T>> where
1159 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1162 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1163 if self.token == *ket {
1169 /// Advance the parser by one token
1170 pub fn bump(&mut self) {
1171 if self.prev_token_kind == PrevTokenKind::Eof {
1172 // Bumping after EOF is a bad sign, usually an infinite loop.
1173 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1176 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1178 // Record last token kind for possible error recovery.
1179 self.prev_token_kind = match self.token {
1180 token::DocComment(..) => PrevTokenKind::DocComment,
1181 token::Comma => PrevTokenKind::Comma,
1182 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1183 token::Interpolated(..) => PrevTokenKind::Interpolated,
1184 token::Eof => PrevTokenKind::Eof,
1185 token::Ident(..) => PrevTokenKind::Ident,
1186 _ => PrevTokenKind::Other,
1189 let next = self.next_tok();
1190 self.span = next.sp;
1191 self.token = next.tok;
1192 self.expected_tokens.clear();
1193 // check after each token
1194 self.process_potential_macro_variable();
1197 /// Advance the parser using provided token as a next one. Use this when
1198 /// consuming a part of a token. For example a single `<` from `<<`.
1199 fn bump_with(&mut self, next: token::Token, span: Span) {
1200 self.prev_span = self.span.with_hi(span.lo());
1201 // It would be incorrect to record the kind of the current token, but
1202 // fortunately for tokens currently using `bump_with`, the
1203 // prev_token_kind will be of no use anyway.
1204 self.prev_token_kind = PrevTokenKind::Other;
1207 self.expected_tokens.clear();
1210 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1211 F: FnOnce(&token::Token) -> R,
1214 return f(&self.token)
1217 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1218 Some(tree) => match tree {
1219 TokenTree::Token(_, tok) => tok,
1220 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1222 None => token::CloseDelim(self.token_cursor.frame.delim),
1226 fn look_ahead_span(&self, dist: usize) -> Span {
1231 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1232 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
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.check(&token::Eq) {
1363 let expr = self.parse_expr()?;
1364 self.expect(&token::Semi)?;
1367 self.expect(&token::Semi)?;
1370 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1371 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1372 // trait item macro.
1373 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1375 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1377 let ident = self.parse_ident()?;
1378 let mut generics = self.parse_generics()?;
1380 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1381 // This is somewhat dubious; We don't want to allow
1382 // argument names to be left off if there is a
1385 // We don't allow argument names to be left off in edition 2018.
1386 if p.span.edition() >= Edition::Edition2018 {
1387 p.parse_arg_general(true)
1389 p.parse_arg_general(false)
1392 generics.where_clause = self.parse_where_clause()?;
1394 let sig = ast::MethodSig {
1404 let body = match self.token {
1408 debug!("parse_trait_methods(): parsing required method");
1411 token::OpenDelim(token::Brace) => {
1412 debug!("parse_trait_methods(): parsing provided method");
1414 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1415 attrs.extend(inner_attrs.iter().cloned());
1419 let token_str = self.this_token_to_string();
1420 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1422 err.span_label(self.span, "expected `;` or `{`");
1426 (ident, ast::TraitItemKind::Method(sig, body), generics)
1430 id: ast::DUMMY_NODE_ID,
1435 span: lo.to(self.prev_span),
1440 /// Parse optional return type [ -> TY ] in function decl
1441 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1442 if self.eat(&token::RArrow) {
1443 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1445 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1450 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1451 self.parse_ty_common(true, true)
1454 /// Parse a type in restricted contexts where `+` is not permitted.
1455 /// Example 1: `&'a TYPE`
1456 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1457 /// Example 2: `value1 as TYPE + value2`
1458 /// `+` is prohibited to avoid interactions with expression grammar.
1459 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1460 self.parse_ty_common(false, true)
1463 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1464 -> PResult<'a, P<Ty>> {
1465 maybe_whole!(self, NtTy, |x| x);
1468 let mut impl_dyn_multi = false;
1469 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1470 // `(TYPE)` is a parenthesized type.
1471 // `(TYPE,)` is a tuple with a single field of type TYPE.
1472 let mut ts = vec![];
1473 let mut last_comma = false;
1474 while self.token != token::CloseDelim(token::Paren) {
1475 ts.push(self.parse_ty()?);
1476 if self.eat(&token::Comma) {
1483 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1484 self.expect(&token::CloseDelim(token::Paren))?;
1486 if ts.len() == 1 && !last_comma {
1487 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1488 let maybe_bounds = allow_plus && self.token.is_like_plus();
1490 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1491 TyKind::Path(None, ref path) if maybe_bounds => {
1492 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1494 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1495 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1496 let path = match bounds[0] {
1497 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1498 _ => self.bug("unexpected lifetime bound"),
1500 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1503 _ => TyKind::Paren(P(ty))
1508 } else if self.eat(&token::Not) {
1511 } else if self.eat(&token::BinOp(token::Star)) {
1513 TyKind::Ptr(self.parse_ptr()?)
1514 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1516 let t = self.parse_ty()?;
1517 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1518 let t = match self.maybe_parse_fixed_length_of_vec()? {
1519 None => TyKind::Slice(t),
1520 Some(length) => TyKind::Array(t, AnonConst {
1521 id: ast::DUMMY_NODE_ID,
1525 self.expect(&token::CloseDelim(token::Bracket))?;
1527 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1530 self.parse_borrowed_pointee()?
1531 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1533 // In order to not be ambiguous, the type must be surrounded by parens.
1534 self.expect(&token::OpenDelim(token::Paren))?;
1536 id: ast::DUMMY_NODE_ID,
1537 value: self.parse_expr()?,
1539 self.expect(&token::CloseDelim(token::Paren))?;
1541 } else if self.eat_keyword(keywords::Underscore) {
1542 // A type to be inferred `_`
1544 } else if self.token_is_bare_fn_keyword() {
1545 // Function pointer type
1546 self.parse_ty_bare_fn(Vec::new())?
1547 } else if self.check_keyword(keywords::For) {
1548 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1549 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1550 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1552 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1553 if self.token_is_bare_fn_keyword() {
1554 self.parse_ty_bare_fn(lifetime_defs)?
1556 let path = self.parse_path(PathStyle::Type)?;
1557 let parse_plus = allow_plus && self.check_plus();
1558 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1560 } else if self.eat_keyword(keywords::Impl) {
1561 // Always parse bounds greedily for better error recovery.
1562 let bounds = self.parse_generic_bounds()?;
1563 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1564 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1565 } else if self.check_keyword(keywords::Dyn) &&
1566 self.look_ahead(1, |t| t.can_begin_bound() &&
1567 !can_continue_type_after_non_fn_ident(t)) {
1568 self.bump(); // `dyn`
1569 // Always parse bounds greedily for better error recovery.
1570 let bounds = self.parse_generic_bounds()?;
1571 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1572 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1573 } else if self.check(&token::Question) ||
1574 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1575 // Bound list (trait object type)
1576 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1577 TraitObjectSyntax::None)
1578 } else if self.eat_lt() {
1580 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1581 TyKind::Path(Some(qself), path)
1582 } else if self.token.is_path_start() {
1584 let path = self.parse_path(PathStyle::Type)?;
1585 if self.eat(&token::Not) {
1586 // Macro invocation in type position
1587 let (delim, tts) = self.expect_delimited_token_tree()?;
1588 let node = Mac_ { path, tts, delim };
1589 TyKind::Mac(respan(lo.to(self.prev_span), node))
1591 // Just a type path or bound list (trait object type) starting with a trait.
1593 // `Trait1 + Trait2 + 'a`
1594 if allow_plus && self.check_plus() {
1595 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1597 TyKind::Path(None, path)
1601 let msg = format!("expected type, found {}", self.this_token_descr());
1602 return Err(self.fatal(&msg));
1605 let span = lo.to(self.prev_span);
1606 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1608 // Try to recover from use of `+` with incorrect priority.
1609 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1610 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1611 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1616 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1617 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1618 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1619 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1621 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1622 bounds.append(&mut self.parse_generic_bounds()?);
1624 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1627 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1628 if !allow_plus && impl_dyn_multi {
1629 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1630 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1631 .span_suggestion_with_applicability(
1633 "use parentheses to disambiguate",
1635 Applicability::MachineApplicable
1640 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1641 // Do not add `+` to expected tokens.
1642 if !allow_plus || !self.token.is_like_plus() {
1647 let bounds = self.parse_generic_bounds()?;
1648 let sum_span = ty.span.to(self.prev_span);
1650 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1651 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1654 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1655 let sum_with_parens = pprust::to_string(|s| {
1656 use print::pprust::PrintState;
1659 s.print_opt_lifetime(lifetime)?;
1660 s.print_mutability(mut_ty.mutbl)?;
1662 s.print_type(&mut_ty.ty)?;
1663 s.print_type_bounds(" +", &bounds)?;
1666 err.span_suggestion_with_applicability(
1668 "try adding parentheses",
1670 Applicability::MachineApplicable
1673 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1674 err.span_label(sum_span, "perhaps you forgot parentheses?");
1677 err.span_label(sum_span, "expected a path");
1684 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1685 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1687 // Do not add `::` to expected tokens.
1688 if !allow_recovery || self.token != token::ModSep {
1691 let ty = match base.to_ty() {
1693 None => return Ok(base),
1696 self.bump(); // `::`
1697 let mut segments = Vec::new();
1698 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1700 let span = ty.span.to(self.prev_span);
1701 let path_span = span.to(span); // use an empty path since `position` == 0
1702 let recovered = base.to_recovered(
1703 Some(QSelf { ty, path_span, position: 0 }),
1704 ast::Path { segments, span },
1708 .struct_span_err(span, "missing angle brackets in associated item path")
1709 .span_suggestion_with_applicability( // this is a best-effort recovery
1710 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1716 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1717 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1718 let mutbl = self.parse_mutability();
1719 let ty = self.parse_ty_no_plus()?;
1720 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1723 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1724 let mutbl = if self.eat_keyword(keywords::Mut) {
1726 } else if self.eat_keyword(keywords::Const) {
1727 Mutability::Immutable
1729 let span = self.prev_span;
1731 "expected mut or const in raw pointer type (use \
1732 `*mut T` or `*const T` as appropriate)");
1733 Mutability::Immutable
1735 let t = self.parse_ty_no_plus()?;
1736 Ok(MutTy { ty: t, mutbl: mutbl })
1739 fn is_named_argument(&mut self) -> bool {
1740 let offset = match self.token {
1741 token::Interpolated(ref nt) => match nt.0 {
1742 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1745 token::BinOp(token::And) | token::AndAnd => 1,
1746 _ if self.token.is_keyword(keywords::Mut) => 1,
1750 self.look_ahead(offset, |t| t.is_ident()) &&
1751 self.look_ahead(offset + 1, |t| t == &token::Colon)
1754 /// This version of parse arg doesn't necessarily require
1755 /// identifier names.
1756 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1757 maybe_whole!(self, NtArg, |x| x);
1759 let (pat, ty) = if require_name || self.is_named_argument() {
1760 debug!("parse_arg_general parse_pat (require_name:{})",
1762 let pat = self.parse_pat()?;
1764 self.expect(&token::Colon)?;
1765 (pat, self.parse_ty()?)
1767 debug!("parse_arg_general ident_to_pat");
1769 let parser_snapshot_before_pat = self.clone();
1771 // Once we can use edition 2018 in the compiler,
1772 // replace this with real try blocks.
1773 macro_rules! try_block {
1774 ($($inside:tt)*) => (
1775 (||{ ::std::ops::Try::from_ok({ $($inside)* }) })()
1779 // We're going to try parsing the argument as a pattern (even though it's not
1780 // allowed). This way we can provide better errors to the user.
1781 let pat_arg: PResult<'a, _> = try_block! {
1782 let pat = self.parse_pat()?;
1783 self.expect(&token::Colon)?;
1784 (pat, self.parse_ty()?)
1789 let mut err = self.diagnostic().struct_span_err_with_code(
1791 "patterns aren't allowed in methods without bodies",
1792 DiagnosticId::Error("E0642".into()),
1794 err.span_suggestion_short_with_applicability(
1796 "give this argument a name or use an underscore to ignore it",
1798 Applicability::MachineApplicable,
1801 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1803 node: PatKind::Wild,
1805 id: ast::DUMMY_NODE_ID
1811 // Recover from attempting to parse the argument as a pattern. This means
1812 // the type is alone, with no name, e.g. `fn foo(u32)`.
1813 mem::replace(self, parser_snapshot_before_pat);
1814 debug!("parse_arg_general ident_to_pat");
1815 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1816 let ty = self.parse_ty()?;
1818 id: ast::DUMMY_NODE_ID,
1819 node: PatKind::Ident(
1820 BindingMode::ByValue(Mutability::Immutable), ident, None),
1828 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1831 /// Parse a single function argument
1832 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1833 self.parse_arg_general(true)
1836 /// Parse an argument in a lambda header e.g. |arg, arg|
1837 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1838 let pat = self.parse_pat()?;
1839 let t = if self.eat(&token::Colon) {
1843 id: ast::DUMMY_NODE_ID,
1844 node: TyKind::Infer,
1851 id: ast::DUMMY_NODE_ID
1855 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1856 if self.eat(&token::Semi) {
1857 Ok(Some(self.parse_expr()?))
1863 /// Matches token_lit = LIT_INTEGER | ...
1864 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1865 let out = match self.token {
1866 token::Interpolated(ref nt) => match nt.0 {
1867 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1868 ExprKind::Lit(ref lit) => { lit.node.clone() }
1869 _ => { return self.unexpected_last(&self.token); }
1871 _ => { return self.unexpected_last(&self.token); }
1873 token::Literal(lit, suf) => {
1874 let diag = Some((self.span, &self.sess.span_diagnostic));
1875 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1879 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1884 _ => { return self.unexpected_last(&self.token); }
1891 /// Matches lit = true | false | token_lit
1892 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1894 let lit = if self.eat_keyword(keywords::True) {
1896 } else if self.eat_keyword(keywords::False) {
1897 LitKind::Bool(false)
1899 let lit = self.parse_lit_token()?;
1902 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
1905 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1906 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1907 maybe_whole_expr!(self);
1909 let minus_lo = self.span;
1910 let minus_present = self.eat(&token::BinOp(token::Minus));
1912 let literal = P(self.parse_lit()?);
1913 let hi = self.prev_span;
1914 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1917 let minus_hi = self.prev_span;
1918 let unary = self.mk_unary(UnOp::Neg, expr);
1919 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1925 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1927 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1928 let span = self.span;
1930 Ok(Ident::new(ident.name, span))
1932 _ => self.parse_ident(),
1936 /// Parses qualified path.
1937 /// Assumes that the leading `<` has been parsed already.
1939 /// `qualified_path = <type [as trait_ref]>::path`
1944 /// `<T as U>::F::a<S>` (without disambiguator)
1945 /// `<T as U>::F::a::<S>` (with disambiguator)
1946 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1947 let lo = self.prev_span;
1948 let ty = self.parse_ty()?;
1950 // `path` will contain the prefix of the path up to the `>`,
1951 // if any (e.g., `U` in the `<T as U>::*` examples
1952 // above). `path_span` has the span of that path, or an empty
1953 // span in the case of something like `<T>::Bar`.
1954 let (mut path, path_span);
1955 if self.eat_keyword(keywords::As) {
1956 let path_lo = self.span;
1957 path = self.parse_path(PathStyle::Type)?;
1958 path_span = path_lo.to(self.prev_span);
1960 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1961 path_span = self.span.to(self.span);
1964 self.expect(&token::Gt)?;
1965 self.expect(&token::ModSep)?;
1967 let qself = QSelf { ty, path_span, position: path.segments.len() };
1968 self.parse_path_segments(&mut path.segments, style, true)?;
1970 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1973 /// Parses simple paths.
1975 /// `path = [::] segment+`
1976 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1979 /// `a::b::C<D>` (without disambiguator)
1980 /// `a::b::C::<D>` (with disambiguator)
1981 /// `Fn(Args)` (without disambiguator)
1982 /// `Fn::(Args)` (with disambiguator)
1983 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1984 self.parse_path_common(style, true)
1987 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1988 -> PResult<'a, ast::Path> {
1989 maybe_whole!(self, NtPath, |path| {
1990 if style == PathStyle::Mod &&
1991 path.segments.iter().any(|segment| segment.args.is_some()) {
1992 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1997 let lo = self.meta_var_span.unwrap_or(self.span);
1998 let mut segments = Vec::new();
1999 if self.eat(&token::ModSep) {
2000 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
2002 self.parse_path_segments(&mut segments, style, enable_warning)?;
2004 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2007 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2008 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2009 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2010 let meta_ident = match self.token {
2011 token::Interpolated(ref nt) => match nt.0 {
2012 token::NtMeta(ref meta) => match meta.node {
2013 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2020 if let Some(path) = meta_ident {
2024 self.parse_path(style)
2027 fn parse_path_segments(&mut self,
2028 segments: &mut Vec<PathSegment>,
2030 enable_warning: bool)
2031 -> PResult<'a, ()> {
2033 segments.push(self.parse_path_segment(style, enable_warning)?);
2035 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2041 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2042 -> PResult<'a, PathSegment> {
2043 let ident = self.parse_path_segment_ident()?;
2045 let is_args_start = |token: &token::Token| match *token {
2046 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2049 let check_args_start = |this: &mut Self| {
2050 this.expected_tokens.extend_from_slice(
2051 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2053 is_args_start(&this.token)
2056 Ok(if style == PathStyle::Type && check_args_start(self) ||
2057 style != PathStyle::Mod && self.check(&token::ModSep)
2058 && self.look_ahead(1, |t| is_args_start(t)) {
2059 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2061 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2062 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2063 .span_label(self.prev_span, "try removing `::`").emit();
2066 let args = if self.eat_lt() {
2068 let (args, bindings) = self.parse_generic_args()?;
2070 let span = lo.to(self.prev_span);
2071 AngleBracketedArgs { args, bindings, span }.into()
2075 let inputs = self.parse_seq_to_before_tokens(
2076 &[&token::CloseDelim(token::Paren)],
2077 SeqSep::trailing_allowed(token::Comma),
2078 TokenExpectType::Expect,
2081 let span = lo.to(self.prev_span);
2082 let output = if self.eat(&token::RArrow) {
2083 Some(self.parse_ty_common(false, false)?)
2087 ParenthesisedArgs { inputs, output, span }.into()
2090 PathSegment { ident, args }
2092 // Generic arguments are not found.
2093 PathSegment::from_ident(ident)
2097 crate fn check_lifetime(&mut self) -> bool {
2098 self.expected_tokens.push(TokenType::Lifetime);
2099 self.token.is_lifetime()
2102 /// Parse single lifetime 'a or panic.
2103 crate fn expect_lifetime(&mut self) -> Lifetime {
2104 if let Some(ident) = self.token.lifetime() {
2105 let span = self.span;
2107 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2109 self.span_bug(self.span, "not a lifetime")
2113 fn eat_label(&mut self) -> Option<Label> {
2114 if let Some(ident) = self.token.lifetime() {
2115 let span = self.span;
2117 Some(Label { ident: Ident::new(ident.name, span) })
2123 /// Parse mutability (`mut` or nothing).
2124 fn parse_mutability(&mut self) -> Mutability {
2125 if self.eat_keyword(keywords::Mut) {
2128 Mutability::Immutable
2132 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2133 if let token::Literal(token::Integer(name), None) = self.token {
2135 Ok(Ident::new(name, self.prev_span))
2137 self.parse_ident_common(false)
2141 /// Parse ident (COLON expr)?
2142 fn parse_field(&mut self) -> PResult<'a, Field> {
2143 let attrs = self.parse_outer_attributes()?;
2146 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2147 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2148 let fieldname = self.parse_field_name()?;
2150 (fieldname, self.parse_expr()?, false)
2152 let fieldname = self.parse_ident_common(false)?;
2154 // Mimic `x: x` for the `x` field shorthand.
2155 let path = ast::Path::from_ident(fieldname);
2156 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2157 (fieldname, expr, true)
2161 span: lo.to(expr.span),
2164 attrs: attrs.into(),
2168 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2169 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2172 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2173 ExprKind::Unary(unop, expr)
2176 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2177 ExprKind::Binary(binop, lhs, rhs)
2180 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2181 ExprKind::Call(f, args)
2184 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2185 ExprKind::Index(expr, idx)
2188 fn mk_range(&mut self,
2189 start: Option<P<Expr>>,
2190 end: Option<P<Expr>>,
2191 limits: RangeLimits)
2192 -> PResult<'a, ast::ExprKind> {
2193 if end.is_none() && limits == RangeLimits::Closed {
2194 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2196 Ok(ExprKind::Range(start, end, limits))
2200 fn mk_assign_op(&mut self, binop: ast::BinOp,
2201 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2202 ExprKind::AssignOp(binop, lhs, rhs)
2205 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2207 id: ast::DUMMY_NODE_ID,
2208 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2214 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2215 let delim = match self.token {
2216 token::OpenDelim(delim) => delim,
2218 let msg = "expected open delimiter";
2219 let mut err = self.fatal(msg);
2220 err.span_label(self.span, msg);
2224 let delimited = match self.parse_token_tree() {
2225 TokenTree::Delimited(_, delimited) => delimited,
2226 _ => unreachable!(),
2228 let delim = match delim {
2229 token::Paren => MacDelimiter::Parenthesis,
2230 token::Bracket => MacDelimiter::Bracket,
2231 token::Brace => MacDelimiter::Brace,
2232 token::NoDelim => self.bug("unexpected no delimiter"),
2234 Ok((delim, delimited.stream().into()))
2237 /// At the bottom (top?) of the precedence hierarchy,
2238 /// parse things like parenthesized exprs,
2239 /// macros, return, etc.
2241 /// NB: This does not parse outer attributes,
2242 /// and is private because it only works
2243 /// correctly if called from parse_dot_or_call_expr().
2244 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2245 maybe_whole_expr!(self);
2247 // Outer attributes are already parsed and will be
2248 // added to the return value after the fact.
2250 // Therefore, prevent sub-parser from parsing
2251 // attributes by giving them a empty "already parsed" list.
2252 let mut attrs = ThinVec::new();
2255 let mut hi = self.span;
2259 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2261 token::OpenDelim(token::Paren) => {
2264 attrs.extend(self.parse_inner_attributes()?);
2266 // (e) is parenthesized e
2267 // (e,) is a tuple with only one field, e
2268 let mut es = vec![];
2269 let mut trailing_comma = false;
2270 while self.token != token::CloseDelim(token::Paren) {
2271 es.push(self.parse_expr()?);
2272 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2273 if self.check(&token::Comma) {
2274 trailing_comma = true;
2278 trailing_comma = false;
2284 hi = self.prev_span;
2285 ex = if es.len() == 1 && !trailing_comma {
2286 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2291 token::OpenDelim(token::Brace) => {
2292 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2294 token::BinOp(token::Or) | token::OrOr => {
2295 return self.parse_lambda_expr(attrs);
2297 token::OpenDelim(token::Bracket) => {
2300 attrs.extend(self.parse_inner_attributes()?);
2302 if self.check(&token::CloseDelim(token::Bracket)) {
2305 ex = ExprKind::Array(Vec::new());
2308 let first_expr = self.parse_expr()?;
2309 if self.check(&token::Semi) {
2310 // Repeating array syntax: [ 0; 512 ]
2312 let count = AnonConst {
2313 id: ast::DUMMY_NODE_ID,
2314 value: self.parse_expr()?,
2316 self.expect(&token::CloseDelim(token::Bracket))?;
2317 ex = ExprKind::Repeat(first_expr, count);
2318 } else if self.check(&token::Comma) {
2319 // Vector with two or more elements.
2321 let remaining_exprs = self.parse_seq_to_end(
2322 &token::CloseDelim(token::Bracket),
2323 SeqSep::trailing_allowed(token::Comma),
2324 |p| Ok(p.parse_expr()?)
2326 let mut exprs = vec![first_expr];
2327 exprs.extend(remaining_exprs);
2328 ex = ExprKind::Array(exprs);
2330 // Vector with one element.
2331 self.expect(&token::CloseDelim(token::Bracket))?;
2332 ex = ExprKind::Array(vec![first_expr]);
2335 hi = self.prev_span;
2339 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2341 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2343 if self.span.edition() >= Edition::Edition2018 &&
2344 self.check_keyword(keywords::Async)
2346 if self.is_async_block() { // check for `async {` and `async move {`
2347 return self.parse_async_block(attrs);
2349 return self.parse_lambda_expr(attrs);
2352 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2353 return self.parse_lambda_expr(attrs);
2355 if self.eat_keyword(keywords::If) {
2356 return self.parse_if_expr(attrs);
2358 if self.eat_keyword(keywords::For) {
2359 let lo = self.prev_span;
2360 return self.parse_for_expr(None, lo, attrs);
2362 if self.eat_keyword(keywords::While) {
2363 let lo = self.prev_span;
2364 return self.parse_while_expr(None, lo, attrs);
2366 if let Some(label) = self.eat_label() {
2367 let lo = label.ident.span;
2368 self.expect(&token::Colon)?;
2369 if self.eat_keyword(keywords::While) {
2370 return self.parse_while_expr(Some(label), lo, attrs)
2372 if self.eat_keyword(keywords::For) {
2373 return self.parse_for_expr(Some(label), lo, attrs)
2375 if self.eat_keyword(keywords::Loop) {
2376 return self.parse_loop_expr(Some(label), lo, attrs)
2378 if self.token == token::OpenDelim(token::Brace) {
2379 return self.parse_block_expr(Some(label),
2381 BlockCheckMode::Default,
2384 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2385 let mut err = self.fatal(msg);
2386 err.span_label(self.span, msg);
2389 if self.eat_keyword(keywords::Loop) {
2390 let lo = self.prev_span;
2391 return self.parse_loop_expr(None, lo, attrs);
2393 if self.eat_keyword(keywords::Continue) {
2394 let label = self.eat_label();
2395 let ex = ExprKind::Continue(label);
2396 let hi = self.prev_span;
2397 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2399 if self.eat_keyword(keywords::Match) {
2400 return self.parse_match_expr(attrs);
2402 if self.eat_keyword(keywords::Unsafe) {
2403 return self.parse_block_expr(
2406 BlockCheckMode::Unsafe(ast::UserProvided),
2409 if self.is_do_catch_block() {
2410 let mut db = self.fatal("found removed `do catch` syntax");
2411 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2414 if self.is_try_block() {
2416 assert!(self.eat_keyword(keywords::Try));
2417 return self.parse_try_block(lo, attrs);
2419 if self.eat_keyword(keywords::Return) {
2420 if self.token.can_begin_expr() {
2421 let e = self.parse_expr()?;
2423 ex = ExprKind::Ret(Some(e));
2425 ex = ExprKind::Ret(None);
2427 } else if self.eat_keyword(keywords::Break) {
2428 let label = self.eat_label();
2429 let e = if self.token.can_begin_expr()
2430 && !(self.token == token::OpenDelim(token::Brace)
2431 && self.restrictions.contains(
2432 Restrictions::NO_STRUCT_LITERAL)) {
2433 Some(self.parse_expr()?)
2437 ex = ExprKind::Break(label, e);
2438 hi = self.prev_span;
2439 } else if self.eat_keyword(keywords::Yield) {
2440 if self.token.can_begin_expr() {
2441 let e = self.parse_expr()?;
2443 ex = ExprKind::Yield(Some(e));
2445 ex = ExprKind::Yield(None);
2447 } else if self.token.is_keyword(keywords::Let) {
2448 // Catch this syntax error here, instead of in `parse_ident`, so
2449 // that we can explicitly mention that let is not to be used as an expression
2450 let mut db = self.fatal("expected expression, found statement (`let`)");
2451 db.span_label(self.span, "expected expression");
2452 db.note("variable declaration using `let` is a statement");
2454 } else if self.token.is_path_start() {
2455 let pth = self.parse_path(PathStyle::Expr)?;
2457 // `!`, as an operator, is prefix, so we know this isn't that
2458 if self.eat(&token::Not) {
2459 // MACRO INVOCATION expression
2460 let (delim, tts) = self.expect_delimited_token_tree()?;
2461 let hi = self.prev_span;
2462 let node = Mac_ { path: pth, tts, delim };
2463 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2465 if self.check(&token::OpenDelim(token::Brace)) {
2466 // This is a struct literal, unless we're prohibited
2467 // from parsing struct literals here.
2468 let prohibited = self.restrictions.contains(
2469 Restrictions::NO_STRUCT_LITERAL
2472 return self.parse_struct_expr(lo, pth, attrs);
2477 ex = ExprKind::Path(None, pth);
2479 match self.parse_literal_maybe_minus() {
2482 ex = expr.node.clone();
2485 self.cancel(&mut err);
2486 let msg = format!("expected expression, found {}",
2487 self.this_token_descr());
2488 let mut err = self.fatal(&msg);
2489 err.span_label(self.span, "expected expression");
2497 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2498 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2503 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2504 -> PResult<'a, P<Expr>> {
2505 let struct_sp = lo.to(self.prev_span);
2507 let mut fields = Vec::new();
2508 let mut base = None;
2510 attrs.extend(self.parse_inner_attributes()?);
2512 while self.token != token::CloseDelim(token::Brace) {
2513 if self.eat(&token::DotDot) {
2514 let exp_span = self.prev_span;
2515 match self.parse_expr() {
2521 self.recover_stmt();
2524 if self.token == token::Comma {
2525 let mut err = self.sess.span_diagnostic.mut_span_err(
2526 exp_span.to(self.prev_span),
2527 "cannot use a comma after the base struct",
2529 err.span_suggestion_short_with_applicability(
2531 "remove this comma",
2533 Applicability::MachineApplicable
2535 err.note("the base struct must always be the last field");
2537 self.recover_stmt();
2542 match self.parse_field() {
2543 Ok(f) => fields.push(f),
2545 e.span_label(struct_sp, "while parsing this struct");
2548 // If the next token is a comma, then try to parse
2549 // what comes next as additional fields, rather than
2550 // bailing out until next `}`.
2551 if self.token != token::Comma {
2552 self.recover_stmt();
2558 match self.expect_one_of(&[token::Comma],
2559 &[token::CloseDelim(token::Brace)]) {
2563 self.recover_stmt();
2569 let span = lo.to(self.span);
2570 self.expect(&token::CloseDelim(token::Brace))?;
2571 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2574 fn parse_or_use_outer_attributes(&mut self,
2575 already_parsed_attrs: Option<ThinVec<Attribute>>)
2576 -> PResult<'a, ThinVec<Attribute>> {
2577 if let Some(attrs) = already_parsed_attrs {
2580 self.parse_outer_attributes().map(|a| a.into())
2584 /// Parse a block or unsafe block
2585 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2586 lo: Span, blk_mode: BlockCheckMode,
2587 outer_attrs: ThinVec<Attribute>)
2588 -> PResult<'a, P<Expr>> {
2589 self.expect(&token::OpenDelim(token::Brace))?;
2591 let mut attrs = outer_attrs;
2592 attrs.extend(self.parse_inner_attributes()?);
2594 let blk = self.parse_block_tail(lo, blk_mode)?;
2595 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2598 /// parse a.b or a(13) or a[4] or just a
2599 fn parse_dot_or_call_expr(&mut self,
2600 already_parsed_attrs: Option<ThinVec<Attribute>>)
2601 -> PResult<'a, P<Expr>> {
2602 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2604 let b = self.parse_bottom_expr();
2605 let (span, b) = self.interpolated_or_expr_span(b)?;
2606 self.parse_dot_or_call_expr_with(b, span, attrs)
2609 fn parse_dot_or_call_expr_with(&mut self,
2612 mut attrs: ThinVec<Attribute>)
2613 -> PResult<'a, P<Expr>> {
2614 // Stitch the list of outer attributes onto the return value.
2615 // A little bit ugly, but the best way given the current code
2617 self.parse_dot_or_call_expr_with_(e0, lo)
2619 expr.map(|mut expr| {
2620 attrs.extend::<Vec<_>>(expr.attrs.into());
2623 ExprKind::If(..) | ExprKind::IfLet(..) => {
2624 if !expr.attrs.is_empty() {
2625 // Just point to the first attribute in there...
2626 let span = expr.attrs[0].span;
2629 "attributes are not yet allowed on `if` \
2640 // Assuming we have just parsed `.`, continue parsing into an expression.
2641 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2642 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2643 Ok(match self.token {
2644 token::OpenDelim(token::Paren) => {
2645 // Method call `expr.f()`
2646 let mut args = self.parse_unspanned_seq(
2647 &token::OpenDelim(token::Paren),
2648 &token::CloseDelim(token::Paren),
2649 SeqSep::trailing_allowed(token::Comma),
2650 |p| Ok(p.parse_expr()?)
2652 args.insert(0, self_arg);
2654 let span = lo.to(self.prev_span);
2655 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2658 // Field access `expr.f`
2659 if let Some(args) = segment.args {
2660 self.span_err(args.span(),
2661 "field expressions may not have generic arguments");
2664 let span = lo.to(self.prev_span);
2665 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2670 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2675 while self.eat(&token::Question) {
2676 let hi = self.prev_span;
2677 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2681 if self.eat(&token::Dot) {
2683 token::Ident(..) => {
2684 e = self.parse_dot_suffix(e, lo)?;
2686 token::Literal(token::Integer(name), _) => {
2687 let span = self.span;
2689 let field = ExprKind::Field(e, Ident::new(name, span));
2690 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2692 token::Literal(token::Float(n), _suf) => {
2694 let fstr = n.as_str();
2695 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2696 &format!("unexpected token: `{}`", n));
2697 err.span_label(self.prev_span, "unexpected token");
2698 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2699 let float = match fstr.parse::<f64>().ok() {
2703 let sugg = pprust::to_string(|s| {
2704 use print::pprust::PrintState;
2708 s.print_usize(float.trunc() as usize)?;
2711 s.s.word(fstr.splitn(2, ".").last().unwrap())
2713 err.span_suggestion_with_applicability(
2714 lo.to(self.prev_span),
2715 "try parenthesizing the first index",
2717 Applicability::MachineApplicable
2724 // FIXME Could factor this out into non_fatal_unexpected or something.
2725 let actual = self.this_token_to_string();
2726 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2731 if self.expr_is_complete(&e) { break; }
2734 token::OpenDelim(token::Paren) => {
2735 let es = self.parse_unspanned_seq(
2736 &token::OpenDelim(token::Paren),
2737 &token::CloseDelim(token::Paren),
2738 SeqSep::trailing_allowed(token::Comma),
2739 |p| Ok(p.parse_expr()?)
2741 hi = self.prev_span;
2743 let nd = self.mk_call(e, es);
2744 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2748 // Could be either an index expression or a slicing expression.
2749 token::OpenDelim(token::Bracket) => {
2751 let ix = self.parse_expr()?;
2753 self.expect(&token::CloseDelim(token::Bracket))?;
2754 let index = self.mk_index(e, ix);
2755 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2763 crate fn process_potential_macro_variable(&mut self) {
2764 let (token, span) = match self.token {
2765 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2766 self.look_ahead(1, |t| t.is_ident()) => {
2768 let name = match self.token {
2769 token::Ident(ident, _) => ident,
2772 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2773 err.span_label(self.span, "unknown macro variable");
2777 token::Interpolated(ref nt) => {
2778 self.meta_var_span = Some(self.span);
2779 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2780 // and lifetime tokens, so the former are never encountered during normal parsing.
2782 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2783 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2793 /// parse a single token tree from the input.
2794 crate fn parse_token_tree(&mut self) -> TokenTree {
2796 token::OpenDelim(..) => {
2797 let frame = mem::replace(&mut self.token_cursor.frame,
2798 self.token_cursor.stack.pop().unwrap());
2799 self.span = frame.span;
2801 TokenTree::Delimited(frame.span, Delimited {
2803 tts: frame.tree_cursor.original_stream().into(),
2806 token::CloseDelim(_) | token::Eof => unreachable!(),
2808 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2810 TokenTree::Token(span, token)
2815 // parse a stream of tokens into a list of TokenTree's,
2817 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2818 let mut tts = Vec::new();
2819 while self.token != token::Eof {
2820 tts.push(self.parse_token_tree());
2825 pub fn parse_tokens(&mut self) -> TokenStream {
2826 let mut result = Vec::new();
2829 token::Eof | token::CloseDelim(..) => break,
2830 _ => result.push(self.parse_token_tree().into()),
2833 TokenStream::concat(result)
2836 /// Parse a prefix-unary-operator expr
2837 fn parse_prefix_expr(&mut self,
2838 already_parsed_attrs: Option<ThinVec<Attribute>>)
2839 -> PResult<'a, P<Expr>> {
2840 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2842 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2843 let (hi, ex) = match self.token {
2846 let e = self.parse_prefix_expr(None);
2847 let (span, e) = self.interpolated_or_expr_span(e)?;
2848 (lo.to(span), self.mk_unary(UnOp::Not, e))
2850 // Suggest `!` for bitwise negation when encountering a `~`
2853 let e = self.parse_prefix_expr(None);
2854 let (span, e) = self.interpolated_or_expr_span(e)?;
2855 let span_of_tilde = lo;
2856 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2857 "`~` cannot be used as a unary operator");
2858 err.span_suggestion_short_with_applicability(
2860 "use `!` to perform bitwise negation",
2862 Applicability::MachineApplicable
2865 (lo.to(span), self.mk_unary(UnOp::Not, e))
2867 token::BinOp(token::Minus) => {
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::Neg, e))
2873 token::BinOp(token::Star) => {
2875 let e = self.parse_prefix_expr(None);
2876 let (span, e) = self.interpolated_or_expr_span(e)?;
2877 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2879 token::BinOp(token::And) | token::AndAnd => {
2881 let m = self.parse_mutability();
2882 let e = self.parse_prefix_expr(None);
2883 let (span, e) = self.interpolated_or_expr_span(e)?;
2884 (lo.to(span), ExprKind::AddrOf(m, e))
2886 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2888 let place = self.parse_expr_res(
2889 Restrictions::NO_STRUCT_LITERAL,
2892 let blk = self.parse_block()?;
2893 let span = blk.span;
2894 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2895 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2897 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2899 let e = self.parse_prefix_expr(None);
2900 let (span, e) = self.interpolated_or_expr_span(e)?;
2901 (lo.to(span), ExprKind::Box(e))
2903 token::Ident(..) if self.token.is_ident_named("not") => {
2904 // `not` is just an ordinary identifier in Rust-the-language,
2905 // but as `rustc`-the-compiler, we can issue clever diagnostics
2906 // for confused users who really want to say `!`
2907 let token_cannot_continue_expr = |t: &token::Token| match *t {
2908 // These tokens can start an expression after `!`, but
2909 // can't continue an expression after an ident
2910 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2911 token::Literal(..) | token::Pound => true,
2912 token::Interpolated(ref nt) => match nt.0 {
2913 token::NtIdent(..) | token::NtExpr(..) |
2914 token::NtBlock(..) | token::NtPath(..) => true,
2919 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2920 if cannot_continue_expr {
2922 // Emit the error ...
2923 let mut err = self.diagnostic()
2924 .struct_span_err(self.span,
2925 &format!("unexpected {} after identifier",
2926 self.this_token_descr()));
2927 // span the `not` plus trailing whitespace to avoid
2928 // trailing whitespace after the `!` in our suggestion
2929 let to_replace = self.sess.source_map()
2930 .span_until_non_whitespace(lo.to(self.span));
2931 err.span_suggestion_short_with_applicability(
2933 "use `!` to perform logical negation",
2935 Applicability::MachineApplicable
2938 // —and recover! (just as if we were in the block
2939 // for the `token::Not` arm)
2940 let e = self.parse_prefix_expr(None);
2941 let (span, e) = self.interpolated_or_expr_span(e)?;
2942 (lo.to(span), self.mk_unary(UnOp::Not, e))
2944 return self.parse_dot_or_call_expr(Some(attrs));
2947 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2949 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2952 /// Parse an associative expression
2954 /// This parses an expression accounting for associativity and precedence of the operators in
2956 fn parse_assoc_expr(&mut self,
2957 already_parsed_attrs: Option<ThinVec<Attribute>>)
2958 -> PResult<'a, P<Expr>> {
2959 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2962 /// Parse an associative expression with operators of at least `min_prec` precedence
2963 fn parse_assoc_expr_with(&mut self,
2966 -> PResult<'a, P<Expr>> {
2967 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2970 let attrs = match lhs {
2971 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2974 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2975 return self.parse_prefix_range_expr(attrs);
2977 self.parse_prefix_expr(attrs)?
2981 if self.expr_is_complete(&lhs) {
2982 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2985 self.expected_tokens.push(TokenType::Operator);
2986 while let Some(op) = AssocOp::from_token(&self.token) {
2988 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2989 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2990 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2991 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2992 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2993 (PrevTokenKind::Interpolated, _) => self.prev_span,
2994 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2995 if path.segments.len() == 1 => self.prev_span,
2999 let cur_op_span = self.span;
3000 let restrictions = if op.is_assign_like() {
3001 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3005 if op.precedence() < min_prec {
3008 // Check for deprecated `...` syntax
3009 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3010 self.err_dotdotdot_syntax(self.span);
3014 if op.is_comparison() {
3015 self.check_no_chained_comparison(&lhs, &op);
3018 if op == AssocOp::As {
3019 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3021 } else if op == AssocOp::Colon {
3022 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3025 err.span_label(self.span,
3026 "expecting a type here because of type ascription");
3027 let cm = self.sess.source_map();
3028 let cur_pos = cm.lookup_char_pos(self.span.lo());
3029 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3030 if cur_pos.line != op_pos.line {
3031 err.span_suggestion_with_applicability(
3033 "try using a semicolon",
3035 Applicability::MaybeIncorrect // speculative
3042 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3043 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3044 // generalise it to the Fixity::None code.
3046 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3047 // two variants are handled with `parse_prefix_range_expr` call above.
3048 let rhs = if self.is_at_start_of_range_notation_rhs() {
3049 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3050 LhsExpr::NotYetParsed)?)
3054 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3059 let limits = if op == AssocOp::DotDot {
3060 RangeLimits::HalfOpen
3065 let r = try!(self.mk_range(Some(lhs), rhs, limits));
3066 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3070 let rhs = match op.fixity() {
3071 Fixity::Right => self.with_res(
3072 restrictions - Restrictions::STMT_EXPR,
3074 this.parse_assoc_expr_with(op.precedence(),
3075 LhsExpr::NotYetParsed)
3077 Fixity::Left => self.with_res(
3078 restrictions - Restrictions::STMT_EXPR,
3080 this.parse_assoc_expr_with(op.precedence() + 1,
3081 LhsExpr::NotYetParsed)
3083 // We currently have no non-associative operators that are not handled above by
3084 // the special cases. The code is here only for future convenience.
3085 Fixity::None => self.with_res(
3086 restrictions - Restrictions::STMT_EXPR,
3088 this.parse_assoc_expr_with(op.precedence() + 1,
3089 LhsExpr::NotYetParsed)
3093 let span = lhs_span.to(rhs.span);
3095 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3096 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3097 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3098 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3099 AssocOp::Greater | AssocOp::GreaterEqual => {
3100 let ast_op = op.to_ast_binop().unwrap();
3101 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3102 self.mk_expr(span, binary, ThinVec::new())
3105 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3106 AssocOp::ObsoleteInPlace =>
3107 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3108 AssocOp::AssignOp(k) => {
3110 token::Plus => BinOpKind::Add,
3111 token::Minus => BinOpKind::Sub,
3112 token::Star => BinOpKind::Mul,
3113 token::Slash => BinOpKind::Div,
3114 token::Percent => BinOpKind::Rem,
3115 token::Caret => BinOpKind::BitXor,
3116 token::And => BinOpKind::BitAnd,
3117 token::Or => BinOpKind::BitOr,
3118 token::Shl => BinOpKind::Shl,
3119 token::Shr => BinOpKind::Shr,
3121 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3122 self.mk_expr(span, aopexpr, ThinVec::new())
3124 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3125 self.bug("AssocOp should have been handled by special case")
3129 if op.fixity() == Fixity::None { break }
3134 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3135 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3136 -> PResult<'a, P<Expr>> {
3137 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3138 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3141 // Save the state of the parser before parsing type normally, in case there is a
3142 // LessThan comparison after this cast.
3143 let parser_snapshot_before_type = self.clone();
3144 match self.parse_ty_no_plus() {
3146 Ok(mk_expr(self, rhs))
3148 Err(mut type_err) => {
3149 // Rewind to before attempting to parse the type with generics, to recover
3150 // from situations like `x as usize < y` in which we first tried to parse
3151 // `usize < y` as a type with generic arguments.
3152 let parser_snapshot_after_type = self.clone();
3153 mem::replace(self, parser_snapshot_before_type);
3155 match self.parse_path(PathStyle::Expr) {
3157 let (op_noun, op_verb) = match self.token {
3158 token::Lt => ("comparison", "comparing"),
3159 token::BinOp(token::Shl) => ("shift", "shifting"),
3161 // We can end up here even without `<` being the next token, for
3162 // example because `parse_ty_no_plus` returns `Err` on keywords,
3163 // but `parse_path` returns `Ok` on them due to error recovery.
3164 // Return original error and parser state.
3165 mem::replace(self, parser_snapshot_after_type);
3166 return Err(type_err);
3170 // Successfully parsed the type path leaving a `<` yet to parse.
3173 // Report non-fatal diagnostics, keep `x as usize` as an expression
3174 // in AST and continue parsing.
3175 let msg = format!("`<` is interpreted as a start of generic \
3176 arguments for `{}`, not a {}", path, op_noun);
3177 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3178 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3179 "interpreted as generic arguments");
3180 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3182 let expr = mk_expr(self, P(Ty {
3184 node: TyKind::Path(None, path),
3185 id: ast::DUMMY_NODE_ID
3188 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3189 .unwrap_or(pprust::expr_to_string(&expr));
3190 err.span_suggestion_with_applicability(
3192 &format!("try {} the cast value", op_verb),
3193 format!("({})", expr_str),
3194 Applicability::MachineApplicable
3200 Err(mut path_err) => {
3201 // Couldn't parse as a path, return original error and parser state.
3203 mem::replace(self, parser_snapshot_after_type);
3211 /// Produce an error if comparison operators are chained (RFC #558).
3212 /// We only need to check lhs, not rhs, because all comparison ops
3213 /// have same precedence and are left-associative
3214 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3215 debug_assert!(outer_op.is_comparison(),
3216 "check_no_chained_comparison: {:?} is not comparison",
3219 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3220 // respan to include both operators
3221 let op_span = op.span.to(self.span);
3222 let mut err = self.diagnostic().struct_span_err(op_span,
3223 "chained comparison operators require parentheses");
3224 if op.node == BinOpKind::Lt &&
3225 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3226 *outer_op == AssocOp::Greater // even in a case like the following:
3227 { // Foo<Bar<Baz<Qux, ()>>>
3229 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3230 err.help("or use `(...)` if you meant to specify fn arguments");
3238 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3239 fn parse_prefix_range_expr(&mut self,
3240 already_parsed_attrs: Option<ThinVec<Attribute>>)
3241 -> PResult<'a, P<Expr>> {
3242 // Check for deprecated `...` syntax
3243 if self.token == token::DotDotDot {
3244 self.err_dotdotdot_syntax(self.span);
3247 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3248 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3250 let tok = self.token.clone();
3251 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3253 let mut hi = self.span;
3255 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3256 // RHS must be parsed with more associativity than the dots.
3257 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3258 Some(self.parse_assoc_expr_with(next_prec,
3259 LhsExpr::NotYetParsed)
3267 let limits = if tok == token::DotDot {
3268 RangeLimits::HalfOpen
3273 let r = try!(self.mk_range(None,
3276 Ok(self.mk_expr(lo.to(hi), r, attrs))
3279 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3280 if self.token.can_begin_expr() {
3281 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3282 if self.token == token::OpenDelim(token::Brace) {
3283 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3291 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3292 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3293 if self.check_keyword(keywords::Let) {
3294 return self.parse_if_let_expr(attrs);
3296 let lo = self.prev_span;
3297 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3299 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3300 // verify that the last statement is either an implicit return (no `;`) or an explicit
3301 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3302 // the dead code lint.
3303 if self.eat_keyword(keywords::Else) || !cond.returns() {
3304 let sp = self.sess.source_map().next_point(lo);
3305 let mut err = self.diagnostic()
3306 .struct_span_err(sp, "missing condition for `if` statemement");
3307 err.span_label(sp, "expected if condition here");
3310 let not_block = self.token != token::OpenDelim(token::Brace);
3311 let thn = self.parse_block().map_err(|mut err| {
3313 err.span_label(lo, "this `if` statement has a condition, but no block");
3317 let mut els: Option<P<Expr>> = None;
3318 let mut hi = thn.span;
3319 if self.eat_keyword(keywords::Else) {
3320 let elexpr = self.parse_else_expr()?;
3324 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3327 /// Parse an 'if let' expression ('if' token already eaten)
3328 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3329 -> PResult<'a, P<Expr>> {
3330 let lo = self.prev_span;
3331 self.expect_keyword(keywords::Let)?;
3332 let pats = self.parse_pats()?;
3333 self.expect(&token::Eq)?;
3334 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3335 let thn = self.parse_block()?;
3336 let (hi, els) = if self.eat_keyword(keywords::Else) {
3337 let expr = self.parse_else_expr()?;
3338 (expr.span, Some(expr))
3342 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3345 // `move |args| expr`
3346 fn parse_lambda_expr(&mut self,
3347 attrs: ThinVec<Attribute>)
3348 -> PResult<'a, P<Expr>>
3351 let movability = if self.eat_keyword(keywords::Static) {
3356 let asyncness = if self.span.edition() >= Edition::Edition2018 {
3357 self.parse_asyncness()
3361 let capture_clause = if self.eat_keyword(keywords::Move) {
3366 let decl = self.parse_fn_block_decl()?;
3367 let decl_hi = self.prev_span;
3368 let body = match decl.output {
3369 FunctionRetTy::Default(_) => {
3370 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3371 self.parse_expr_res(restrictions, None)?
3374 // If an explicit return type is given, require a
3375 // block to appear (RFC 968).
3376 let body_lo = self.span;
3377 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3383 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3387 // `else` token already eaten
3388 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3389 if self.eat_keyword(keywords::If) {
3390 return self.parse_if_expr(ThinVec::new());
3392 let blk = self.parse_block()?;
3393 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3397 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3398 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3400 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3401 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3403 let pat = self.parse_top_level_pat()?;
3404 if !self.eat_keyword(keywords::In) {
3405 let in_span = self.prev_span.between(self.span);
3406 let mut err = self.sess.span_diagnostic
3407 .struct_span_err(in_span, "missing `in` in `for` loop");
3408 err.span_suggestion_short_with_applicability(
3409 in_span, "try adding `in` here", " in ".into(),
3410 // has been misleading, at least in the past (closed Issue #48492)
3411 Applicability::MaybeIncorrect
3415 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3416 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3417 attrs.extend(iattrs);
3419 let hi = self.prev_span;
3420 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3423 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3424 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3426 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3427 if self.token.is_keyword(keywords::Let) {
3428 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3430 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3431 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3432 attrs.extend(iattrs);
3433 let span = span_lo.to(body.span);
3434 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3437 /// Parse a 'while let' expression ('while' token already eaten)
3438 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3440 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3441 self.expect_keyword(keywords::Let)?;
3442 let pats = self.parse_pats()?;
3443 self.expect(&token::Eq)?;
3444 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3445 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3446 attrs.extend(iattrs);
3447 let span = span_lo.to(body.span);
3448 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3451 // parse `loop {...}`, `loop` token already eaten
3452 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3454 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3455 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3456 attrs.extend(iattrs);
3457 let span = span_lo.to(body.span);
3458 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3461 /// Parse an `async move {...}` expression
3462 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3463 -> PResult<'a, P<Expr>>
3465 let span_lo = self.span;
3466 self.expect_keyword(keywords::Async)?;
3467 let capture_clause = if self.eat_keyword(keywords::Move) {
3472 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3473 attrs.extend(iattrs);
3475 span_lo.to(body.span),
3476 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3479 /// Parse a `try {...}` expression (`try` token already eaten)
3480 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3481 -> PResult<'a, P<Expr>>
3483 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3484 attrs.extend(iattrs);
3485 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3488 // `match` token already eaten
3489 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3490 let match_span = self.prev_span;
3491 let lo = self.prev_span;
3492 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3494 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3495 if self.token == token::Token::Semi {
3496 e.span_suggestion_short_with_applicability(
3498 "try removing this `match`",
3500 Applicability::MaybeIncorrect // speculative
3505 attrs.extend(self.parse_inner_attributes()?);
3507 let mut arms: Vec<Arm> = Vec::new();
3508 while self.token != token::CloseDelim(token::Brace) {
3509 match self.parse_arm() {
3510 Ok(arm) => arms.push(arm),
3512 // Recover by skipping to the end of the block.
3514 self.recover_stmt();
3515 let span = lo.to(self.span);
3516 if self.token == token::CloseDelim(token::Brace) {
3519 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3525 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3528 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3529 maybe_whole!(self, NtArm, |x| x);
3531 let attrs = self.parse_outer_attributes()?;
3532 // Allow a '|' before the pats (RFC 1925)
3533 self.eat(&token::BinOp(token::Or));
3534 let pats = self.parse_pats()?;
3535 let guard = if self.eat_keyword(keywords::If) {
3536 Some(Guard::If(self.parse_expr()?))
3540 let arrow_span = self.span;
3541 self.expect(&token::FatArrow)?;
3542 let arm_start_span = self.span;
3544 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3545 .map_err(|mut err| {
3546 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3550 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3551 && self.token != token::CloseDelim(token::Brace);
3554 let cm = self.sess.source_map();
3555 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3556 .map_err(|mut err| {
3557 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3558 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3559 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3560 && expr_lines.lines.len() == 2
3561 && self.token == token::FatArrow => {
3562 // We check whether there's any trailing code in the parse span,
3563 // if there isn't, we very likely have the following:
3566 // | -- - missing comma
3572 // | parsed until here as `"y" & X`
3573 err.span_suggestion_short_with_applicability(
3574 cm.next_point(arm_start_span),
3575 "missing a comma here to end this `match` arm",
3577 Applicability::MachineApplicable
3581 err.span_label(arrow_span,
3582 "while parsing the `match` arm starting here");
3588 self.eat(&token::Comma);
3599 /// Parse an expression
3600 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3601 self.parse_expr_res(Restrictions::empty(), None)
3604 /// Evaluate the closure with restrictions in place.
3606 /// After the closure is evaluated, restrictions are reset.
3607 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3608 where F: FnOnce(&mut Self) -> T
3610 let old = self.restrictions;
3611 self.restrictions = r;
3613 self.restrictions = old;
3618 /// Parse an expression, subject to the given restrictions
3619 fn parse_expr_res(&mut self, r: Restrictions,
3620 already_parsed_attrs: Option<ThinVec<Attribute>>)
3621 -> PResult<'a, P<Expr>> {
3622 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3625 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3626 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3627 if self.check(&token::Eq) {
3629 Ok(Some(self.parse_expr()?))
3631 Ok(Some(self.parse_expr()?))
3637 /// Parse patterns, separated by '|' s
3638 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3639 let mut pats = Vec::new();
3641 pats.push(self.parse_top_level_pat()?);
3643 if self.token == token::OrOr {
3644 let mut err = self.struct_span_err(self.span,
3645 "unexpected token `||` after pattern");
3646 err.span_suggestion_with_applicability(
3648 "use a single `|` to specify multiple patterns",
3650 Applicability::MachineApplicable
3654 } else if self.check(&token::BinOp(token::Or)) {
3662 // Parses a parenthesized list of patterns like
3663 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3664 // - a vector of the patterns that were parsed
3665 // - an option indicating the index of the `..` element
3666 // - a boolean indicating whether a trailing comma was present.
3667 // Trailing commas are significant because (p) and (p,) are different patterns.
3668 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3669 self.expect(&token::OpenDelim(token::Paren))?;
3670 let result = self.parse_pat_list()?;
3671 self.expect(&token::CloseDelim(token::Paren))?;
3675 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3676 let mut fields = Vec::new();
3677 let mut ddpos = None;
3678 let mut trailing_comma = false;
3680 if self.eat(&token::DotDot) {
3681 if ddpos.is_none() {
3682 ddpos = Some(fields.len());
3684 // Emit a friendly error, ignore `..` and continue parsing
3685 self.span_err(self.prev_span,
3686 "`..` can only be used once per tuple or tuple struct pattern");
3688 } else if !self.check(&token::CloseDelim(token::Paren)) {
3689 fields.push(self.parse_pat()?);
3694 trailing_comma = self.eat(&token::Comma);
3695 if !trailing_comma {
3700 if ddpos == Some(fields.len()) && trailing_comma {
3701 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3702 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3705 Ok((fields, ddpos, trailing_comma))
3708 fn parse_pat_vec_elements(
3710 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3711 let mut before = Vec::new();
3712 let mut slice = None;
3713 let mut after = Vec::new();
3714 let mut first = true;
3715 let mut before_slice = true;
3717 while self.token != token::CloseDelim(token::Bracket) {
3721 self.expect(&token::Comma)?;
3723 if self.token == token::CloseDelim(token::Bracket)
3724 && (before_slice || !after.is_empty()) {
3730 if self.eat(&token::DotDot) {
3732 if self.check(&token::Comma) ||
3733 self.check(&token::CloseDelim(token::Bracket)) {
3734 slice = Some(P(Pat {
3735 id: ast::DUMMY_NODE_ID,
3736 node: PatKind::Wild,
3737 span: self.prev_span,
3739 before_slice = false;
3745 let subpat = self.parse_pat()?;
3746 if before_slice && self.eat(&token::DotDot) {
3747 slice = Some(subpat);
3748 before_slice = false;
3749 } else if before_slice {
3750 before.push(subpat);
3756 Ok((before, slice, after))
3762 attrs: Vec<Attribute>
3763 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3764 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3766 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3767 // Parsing a pattern of the form "fieldname: pat"
3768 let fieldname = self.parse_field_name()?;
3770 let pat = self.parse_pat()?;
3772 (pat, fieldname, false)
3774 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3775 let is_box = self.eat_keyword(keywords::Box);
3776 let boxed_span = self.span;
3777 let is_ref = self.eat_keyword(keywords::Ref);
3778 let is_mut = self.eat_keyword(keywords::Mut);
3779 let fieldname = self.parse_ident()?;
3780 hi = self.prev_span;
3782 let bind_type = match (is_ref, is_mut) {
3783 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3784 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3785 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3786 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3788 let fieldpat = P(Pat {
3789 id: ast::DUMMY_NODE_ID,
3790 node: PatKind::Ident(bind_type, fieldname, None),
3791 span: boxed_span.to(hi),
3794 let subpat = if is_box {
3796 id: ast::DUMMY_NODE_ID,
3797 node: PatKind::Box(fieldpat),
3803 (subpat, fieldname, true)
3806 Ok(source_map::Spanned {
3808 node: ast::FieldPat {
3812 attrs: attrs.into(),
3817 /// Parse the fields of a struct-like pattern
3818 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3819 let mut fields = Vec::new();
3820 let mut etc = false;
3821 let mut ate_comma = true;
3822 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3823 let mut etc_span = None;
3825 while self.token != token::CloseDelim(token::Brace) {
3826 let attrs = self.parse_outer_attributes()?;
3829 // check that a comma comes after every field
3831 let err = self.struct_span_err(self.prev_span, "expected `,`");
3836 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3838 let mut etc_sp = self.span;
3840 if self.token == token::DotDotDot { // Issue #46718
3841 // Accept `...` as if it were `..` to avoid further errors
3842 let mut err = self.struct_span_err(self.span,
3843 "expected field pattern, found `...`");
3844 err.span_suggestion_with_applicability(
3846 "to omit remaining fields, use one fewer `.`",
3848 Applicability::MachineApplicable
3852 self.bump(); // `..` || `...`:w
3854 if self.token == token::CloseDelim(token::Brace) {
3855 etc_span = Some(etc_sp);
3858 let token_str = self.this_token_to_string();
3859 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3861 err.span_label(self.span, "expected `}`");
3862 let mut comma_sp = None;
3863 if self.token == token::Comma { // Issue #49257
3864 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3865 err.span_label(etc_sp,
3866 "`..` must be at the end and cannot have a trailing comma");
3867 comma_sp = Some(self.span);
3872 etc_span = Some(etc_sp);
3873 if self.token == token::CloseDelim(token::Brace) {
3874 // If the struct looks otherwise well formed, recover and continue.
3875 if let Some(sp) = comma_sp {
3876 err.span_suggestion_short(sp, "remove this comma", String::new());
3880 } else if self.token.is_ident() && ate_comma {
3881 // Accept fields coming after `..,`.
3882 // This way we avoid "pattern missing fields" errors afterwards.
3883 // We delay this error until the end in order to have a span for a
3885 if let Some(mut delayed_err) = delayed_err {
3889 delayed_err = Some(err);
3892 if let Some(mut err) = delayed_err {
3899 fields.push(match self.parse_pat_field(lo, attrs) {
3902 if let Some(mut delayed_err) = delayed_err {
3908 ate_comma = self.eat(&token::Comma);
3911 if let Some(mut err) = delayed_err {
3912 if let Some(etc_span) = etc_span {
3913 err.multipart_suggestion(
3914 "move the `..` to the end of the field list",
3916 (etc_span, String::new()),
3917 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3923 return Ok((fields, etc));
3926 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3927 if self.token.is_path_start() {
3929 let (qself, path) = if self.eat_lt() {
3930 // Parse a qualified path
3931 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3934 // Parse an unqualified path
3935 (None, self.parse_path(PathStyle::Expr)?)
3937 let hi = self.prev_span;
3938 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3940 self.parse_literal_maybe_minus()
3944 // helper function to decide whether to parse as ident binding or to try to do
3945 // something more complex like range patterns
3946 fn parse_as_ident(&mut self) -> bool {
3947 self.look_ahead(1, |t| match *t {
3948 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3949 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3950 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3951 // range pattern branch
3952 token::DotDot => None,
3954 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3955 token::Comma | token::CloseDelim(token::Bracket) => true,
3960 /// A wrapper around `parse_pat` with some special error handling for the
3961 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3962 /// to subpatterns within such).
3963 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3964 let pat = self.parse_pat()?;
3965 if self.token == token::Comma {
3966 // An unexpected comma after a top-level pattern is a clue that the
3967 // user (perhaps more accustomed to some other language) forgot the
3968 // parentheses in what should have been a tuple pattern; return a
3969 // suggestion-enhanced error here rather than choking on the comma
3971 let comma_span = self.span;
3973 if let Err(mut err) = self.parse_pat_list() {
3974 // We didn't expect this to work anyway; we just wanted
3975 // to advance to the end of the comma-sequence so we know
3976 // the span to suggest parenthesizing
3979 let seq_span = pat.span.to(self.prev_span);
3980 let mut err = self.struct_span_err(comma_span,
3981 "unexpected `,` in pattern");
3982 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3983 err.span_suggestion_with_applicability(
3985 "try adding parentheses",
3986 format!("({})", seq_snippet),
3987 Applicability::MachineApplicable
3995 /// Parse a pattern.
3996 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3997 self.parse_pat_with_range_pat(true)
4000 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
4002 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
4003 maybe_whole!(self, NtPat, |x| x);
4008 token::BinOp(token::And) | token::AndAnd => {
4009 // Parse &pat / &mut pat
4011 let mutbl = self.parse_mutability();
4012 if let token::Lifetime(ident) = self.token {
4013 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4015 err.span_label(self.span, "unexpected lifetime");
4018 let subpat = self.parse_pat_with_range_pat(false)?;
4019 pat = PatKind::Ref(subpat, mutbl);
4021 token::OpenDelim(token::Paren) => {
4022 // Parse (pat,pat,pat,...) as tuple pattern
4023 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4024 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4025 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4027 PatKind::Tuple(fields, ddpos)
4030 token::OpenDelim(token::Bracket) => {
4031 // Parse [pat,pat,...] as slice pattern
4033 let (before, slice, after) = self.parse_pat_vec_elements()?;
4034 self.expect(&token::CloseDelim(token::Bracket))?;
4035 pat = PatKind::Slice(before, slice, after);
4037 // At this point, token != &, &&, (, [
4038 _ => if self.eat_keyword(keywords::Underscore) {
4040 pat = PatKind::Wild;
4041 } else if self.eat_keyword(keywords::Mut) {
4042 // Parse mut ident @ pat / mut ref ident @ pat
4043 let mutref_span = self.prev_span.to(self.span);
4044 let binding_mode = if self.eat_keyword(keywords::Ref) {
4046 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4047 .span_suggestion_with_applicability(
4049 "try switching the order",
4051 Applicability::MachineApplicable
4053 BindingMode::ByRef(Mutability::Mutable)
4055 BindingMode::ByValue(Mutability::Mutable)
4057 pat = self.parse_pat_ident(binding_mode)?;
4058 } else if self.eat_keyword(keywords::Ref) {
4059 // Parse ref ident @ pat / ref mut ident @ pat
4060 let mutbl = self.parse_mutability();
4061 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4062 } else if self.eat_keyword(keywords::Box) {
4064 let subpat = self.parse_pat_with_range_pat(false)?;
4065 pat = PatKind::Box(subpat);
4066 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4067 self.parse_as_ident() {
4068 // Parse ident @ pat
4069 // This can give false positives and parse nullary enums,
4070 // they are dealt with later in resolve
4071 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4072 pat = self.parse_pat_ident(binding_mode)?;
4073 } else if self.token.is_path_start() {
4074 // Parse pattern starting with a path
4075 let (qself, path) = if self.eat_lt() {
4076 // Parse a qualified path
4077 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4080 // Parse an unqualified path
4081 (None, self.parse_path(PathStyle::Expr)?)
4084 token::Not if qself.is_none() => {
4085 // Parse macro invocation
4087 let (delim, tts) = self.expect_delimited_token_tree()?;
4088 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4089 pat = PatKind::Mac(mac);
4091 token::DotDotDot | token::DotDotEq | token::DotDot => {
4092 let end_kind = match self.token {
4093 token::DotDot => RangeEnd::Excluded,
4094 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4095 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4096 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4099 let op_span = self.span;
4101 let span = lo.to(self.prev_span);
4102 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4104 let end = self.parse_pat_range_end()?;
4105 let op = Spanned { span: op_span, node: end_kind };
4106 pat = PatKind::Range(begin, end, op);
4108 token::OpenDelim(token::Brace) => {
4109 if qself.is_some() {
4110 let msg = "unexpected `{` after qualified path";
4111 let mut err = self.fatal(msg);
4112 err.span_label(self.span, msg);
4115 // Parse struct pattern
4117 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4119 self.recover_stmt();
4123 pat = PatKind::Struct(path, fields, etc);
4125 token::OpenDelim(token::Paren) => {
4126 if qself.is_some() {
4127 let msg = "unexpected `(` after qualified path";
4128 let mut err = self.fatal(msg);
4129 err.span_label(self.span, msg);
4132 // Parse tuple struct or enum pattern
4133 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4134 pat = PatKind::TupleStruct(path, fields, ddpos)
4136 _ => pat = PatKind::Path(qself, path),
4139 // Try to parse everything else as literal with optional minus
4140 match self.parse_literal_maybe_minus() {
4142 let op_span = self.span;
4143 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4144 self.check(&token::DotDotDot) {
4145 let end_kind = if self.eat(&token::DotDotDot) {
4146 RangeEnd::Included(RangeSyntax::DotDotDot)
4147 } else if self.eat(&token::DotDotEq) {
4148 RangeEnd::Included(RangeSyntax::DotDotEq)
4149 } else if self.eat(&token::DotDot) {
4152 panic!("impossible case: we already matched \
4153 on a range-operator token")
4155 let end = self.parse_pat_range_end()?;
4156 let op = Spanned { span: op_span, node: end_kind };
4157 pat = PatKind::Range(begin, end, op);
4159 pat = PatKind::Lit(begin);
4163 self.cancel(&mut err);
4164 let msg = format!("expected pattern, found {}", self.this_token_descr());
4165 let mut err = self.fatal(&msg);
4166 err.span_label(self.span, "expected pattern");
4173 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4174 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4176 if !allow_range_pat {
4179 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4181 PatKind::Range(..) => {
4182 let mut err = self.struct_span_err(
4184 "the range pattern here has ambiguous interpretation",
4186 err.span_suggestion_with_applicability(
4188 "add parentheses to clarify the precedence",
4189 format!("({})", pprust::pat_to_string(&pat)),
4190 // "ambiguous interpretation" implies that we have to be guessing
4191 Applicability::MaybeIncorrect
4202 /// Parse ident or ident @ pat
4203 /// used by the copy foo and ref foo patterns to give a good
4204 /// error message when parsing mistakes like ref foo(a,b)
4205 fn parse_pat_ident(&mut self,
4206 binding_mode: ast::BindingMode)
4207 -> PResult<'a, PatKind> {
4208 let ident = self.parse_ident()?;
4209 let sub = if self.eat(&token::At) {
4210 Some(self.parse_pat()?)
4215 // just to be friendly, if they write something like
4217 // we end up here with ( as the current token. This shortly
4218 // leads to a parse error. Note that if there is no explicit
4219 // binding mode then we do not end up here, because the lookahead
4220 // will direct us over to parse_enum_variant()
4221 if self.token == token::OpenDelim(token::Paren) {
4222 return Err(self.span_fatal(
4224 "expected identifier, found enum pattern"))
4227 Ok(PatKind::Ident(binding_mode, ident, sub))
4230 /// Parse a local variable declaration
4231 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4232 let lo = self.prev_span;
4233 let pat = self.parse_top_level_pat()?;
4235 let (err, ty) = if self.eat(&token::Colon) {
4236 // Save the state of the parser before parsing type normally, in case there is a `:`
4237 // instead of an `=` typo.
4238 let parser_snapshot_before_type = self.clone();
4239 let colon_sp = self.prev_span;
4240 match self.parse_ty() {
4241 Ok(ty) => (None, Some(ty)),
4243 // Rewind to before attempting to parse the type and continue parsing
4244 let parser_snapshot_after_type = self.clone();
4245 mem::replace(self, parser_snapshot_before_type);
4247 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4248 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4249 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4255 let init = match (self.parse_initializer(err.is_some()), err) {
4256 (Ok(init), None) => { // init parsed, ty parsed
4259 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4260 // Could parse the type as if it were the initializer, it is likely there was a
4261 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4262 err.span_suggestion_short_with_applicability(
4264 "use `=` if you meant to assign",
4266 Applicability::MachineApplicable
4269 // As this was parsed successfully, continue as if the code has been fixed for the
4270 // rest of the file. It will still fail due to the emitted error, but we avoid
4274 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4276 // Couldn't parse the type nor the initializer, only raise the type error and
4277 // return to the parser state before parsing the type as the initializer.
4278 // let x: <parse_error>;
4279 mem::replace(self, snapshot);
4282 (Err(err), None) => { // init error, ty parsed
4283 // Couldn't parse the initializer and we're not attempting to recover a failed
4284 // parse of the type, return the error.
4288 let hi = if self.token == token::Semi {
4297 id: ast::DUMMY_NODE_ID,
4303 /// Parse a structure field
4304 fn parse_name_and_ty(&mut self,
4307 attrs: Vec<Attribute>)
4308 -> PResult<'a, StructField> {
4309 let name = self.parse_ident()?;
4310 self.expect(&token::Colon)?;
4311 let ty = self.parse_ty()?;
4313 span: lo.to(self.prev_span),
4316 id: ast::DUMMY_NODE_ID,
4322 /// Emit an expected item after attributes error.
4323 fn expected_item_err(&self, attrs: &[Attribute]) {
4324 let message = match attrs.last() {
4325 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4326 _ => "expected item after attributes",
4329 self.span_err(self.prev_span, message);
4332 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4333 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4334 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4335 Ok(self.parse_stmt_(true))
4338 // Eat tokens until we can be relatively sure we reached the end of the
4339 // statement. This is something of a best-effort heuristic.
4341 // We terminate when we find an unmatched `}` (without consuming it).
4342 fn recover_stmt(&mut self) {
4343 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4346 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4347 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4348 // approximate - it can mean we break too early due to macros, but that
4349 // should only lead to sub-optimal recovery, not inaccurate parsing).
4351 // If `break_on_block` is `Break`, then we will stop consuming tokens
4352 // after finding (and consuming) a brace-delimited block.
4353 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4354 let mut brace_depth = 0;
4355 let mut bracket_depth = 0;
4356 let mut in_block = false;
4357 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4358 break_on_semi, break_on_block);
4360 debug!("recover_stmt_ loop {:?}", self.token);
4362 token::OpenDelim(token::DelimToken::Brace) => {
4365 if break_on_block == BlockMode::Break &&
4367 bracket_depth == 0 {
4371 token::OpenDelim(token::DelimToken::Bracket) => {
4375 token::CloseDelim(token::DelimToken::Brace) => {
4376 if brace_depth == 0 {
4377 debug!("recover_stmt_ return - close delim {:?}", self.token);
4382 if in_block && bracket_depth == 0 && brace_depth == 0 {
4383 debug!("recover_stmt_ return - block end {:?}", self.token);
4387 token::CloseDelim(token::DelimToken::Bracket) => {
4389 if bracket_depth < 0 {
4395 debug!("recover_stmt_ return - Eof");
4400 if break_on_semi == SemiColonMode::Break &&
4402 bracket_depth == 0 {
4403 debug!("recover_stmt_ return - Semi");
4414 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4415 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4417 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4422 fn is_async_block(&mut self) -> bool {
4423 self.token.is_keyword(keywords::Async) &&
4426 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4427 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4429 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4434 fn is_do_catch_block(&mut self) -> bool {
4435 self.token.is_keyword(keywords::Do) &&
4436 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4437 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4438 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4441 fn is_try_block(&mut self) -> bool {
4442 self.token.is_keyword(keywords::Try) &&
4443 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4445 self.span.edition() >= Edition::Edition2018 &&
4447 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4448 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4451 fn is_union_item(&self) -> bool {
4452 self.token.is_keyword(keywords::Union) &&
4453 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4456 fn is_crate_vis(&self) -> bool {
4457 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4460 fn is_extern_non_path(&self) -> bool {
4461 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4464 fn is_existential_type_decl(&self) -> bool {
4465 self.token.is_keyword(keywords::Existential) &&
4466 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4469 fn is_auto_trait_item(&mut self) -> bool {
4471 (self.token.is_keyword(keywords::Auto)
4472 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4473 || // unsafe auto trait
4474 (self.token.is_keyword(keywords::Unsafe) &&
4475 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4476 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4479 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4480 -> PResult<'a, Option<P<Item>>> {
4481 let token_lo = self.span;
4482 let (ident, def) = match self.token {
4483 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4485 let ident = self.parse_ident()?;
4486 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4487 match self.parse_token_tree() {
4488 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4489 _ => unreachable!(),
4491 } else if self.check(&token::OpenDelim(token::Paren)) {
4492 let args = self.parse_token_tree();
4493 let body = if self.check(&token::OpenDelim(token::Brace)) {
4494 self.parse_token_tree()
4499 TokenStream::concat(vec![
4501 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4509 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4511 token::Ident(ident, _) if ident.name == "macro_rules" &&
4512 self.look_ahead(1, |t| *t == token::Not) => {
4513 let prev_span = self.prev_span;
4514 self.complain_if_pub_macro(&vis.node, prev_span);
4518 let ident = self.parse_ident()?;
4519 let (delim, tokens) = self.expect_delimited_token_tree()?;
4520 if delim != MacDelimiter::Brace {
4521 if !self.eat(&token::Semi) {
4522 let msg = "macros that expand to items must either \
4523 be surrounded with braces or followed by a semicolon";
4524 self.span_err(self.prev_span, msg);
4528 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4530 _ => return Ok(None),
4533 let span = lo.to(self.prev_span);
4534 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4537 fn parse_stmt_without_recovery(&mut self,
4538 macro_legacy_warnings: bool)
4539 -> PResult<'a, Option<Stmt>> {
4540 maybe_whole!(self, NtStmt, |x| Some(x));
4542 let attrs = self.parse_outer_attributes()?;
4545 Ok(Some(if self.eat_keyword(keywords::Let) {
4547 id: ast::DUMMY_NODE_ID,
4548 node: StmtKind::Local(self.parse_local(attrs.into())?),
4549 span: lo.to(self.prev_span),
4551 } else if let Some(macro_def) = self.eat_macro_def(
4553 &source_map::respan(lo, VisibilityKind::Inherited),
4557 id: ast::DUMMY_NODE_ID,
4558 node: StmtKind::Item(macro_def),
4559 span: lo.to(self.prev_span),
4561 // Starts like a simple path, being careful to avoid contextual keywords
4562 // such as a union items, item with `crate` visibility or auto trait items.
4563 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4564 // like a path (1 token), but it fact not a path.
4565 // `union::b::c` - path, `union U { ... }` - not a path.
4566 // `crate::b::c` - path, `crate struct S;` - not a path.
4567 // `extern::b::c` - path, `extern crate c;` - not a path.
4568 } else if self.token.is_path_start() &&
4569 !self.token.is_qpath_start() &&
4570 !self.is_union_item() &&
4571 !self.is_crate_vis() &&
4572 !self.is_extern_non_path() &&
4573 !self.is_existential_type_decl() &&
4574 !self.is_auto_trait_item() {
4575 let pth = self.parse_path(PathStyle::Expr)?;
4577 if !self.eat(&token::Not) {
4578 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4579 self.parse_struct_expr(lo, pth, ThinVec::new())?
4581 let hi = self.prev_span;
4582 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4585 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4586 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4587 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4590 return Ok(Some(Stmt {
4591 id: ast::DUMMY_NODE_ID,
4592 node: StmtKind::Expr(expr),
4593 span: lo.to(self.prev_span),
4597 // it's a macro invocation
4598 let id = match self.token {
4599 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4600 _ => self.parse_ident()?,
4603 // check that we're pointing at delimiters (need to check
4604 // again after the `if`, because of `parse_ident`
4605 // consuming more tokens).
4607 token::OpenDelim(_) => {}
4609 // we only expect an ident if we didn't parse one
4611 let ident_str = if id.name == keywords::Invalid.name() {
4616 let tok_str = self.this_token_to_string();
4617 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4620 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4625 let (delim, tts) = self.expect_delimited_token_tree()?;
4626 let hi = self.prev_span;
4628 let style = if delim == MacDelimiter::Brace {
4629 MacStmtStyle::Braces
4631 MacStmtStyle::NoBraces
4634 if id.name == keywords::Invalid.name() {
4635 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4636 let node = if delim == MacDelimiter::Brace ||
4637 self.token == token::Semi || self.token == token::Eof {
4638 StmtKind::Mac(P((mac, style, attrs.into())))
4640 // We used to incorrectly stop parsing macro-expanded statements here.
4641 // If the next token will be an error anyway but could have parsed with the
4642 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4643 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4644 // These can continue an expression, so we can't stop parsing and warn.
4645 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4646 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4647 token::BinOp(token::And) | token::BinOp(token::Or) |
4648 token::AndAnd | token::OrOr |
4649 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4652 self.warn_missing_semicolon();
4653 StmtKind::Mac(P((mac, style, attrs.into())))
4655 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4656 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4657 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4661 id: ast::DUMMY_NODE_ID,
4666 // if it has a special ident, it's definitely an item
4668 // Require a semicolon or braces.
4669 if style != MacStmtStyle::Braces {
4670 if !self.eat(&token::Semi) {
4671 self.span_err(self.prev_span,
4672 "macros that expand to items must \
4673 either be surrounded with braces or \
4674 followed by a semicolon");
4677 let span = lo.to(hi);
4679 id: ast::DUMMY_NODE_ID,
4681 node: StmtKind::Item({
4683 span, id /*id is good here*/,
4684 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4685 respan(lo, VisibilityKind::Inherited),
4691 // FIXME: Bad copy of attrs
4692 let old_directory_ownership =
4693 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4694 let item = self.parse_item_(attrs.clone(), false, true)?;
4695 self.directory.ownership = old_directory_ownership;
4699 id: ast::DUMMY_NODE_ID,
4700 span: lo.to(i.span),
4701 node: StmtKind::Item(i),
4704 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4705 if !attrs.is_empty() {
4706 if s.prev_token_kind == PrevTokenKind::DocComment {
4707 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4708 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4709 s.span_err(s.span, "expected statement after outer attribute");
4714 // Do not attempt to parse an expression if we're done here.
4715 if self.token == token::Semi {
4716 unused_attrs(&attrs, self);
4721 if self.token == token::CloseDelim(token::Brace) {
4722 unused_attrs(&attrs, self);
4726 // Remainder are line-expr stmts.
4727 let e = self.parse_expr_res(
4728 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4730 id: ast::DUMMY_NODE_ID,
4731 span: lo.to(e.span),
4732 node: StmtKind::Expr(e),
4739 /// Is this expression a successfully-parsed statement?
4740 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4741 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4742 !classify::expr_requires_semi_to_be_stmt(e)
4745 /// Parse a block. No inner attrs are allowed.
4746 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4747 maybe_whole!(self, NtBlock, |x| x);
4751 if !self.eat(&token::OpenDelim(token::Brace)) {
4753 let tok = self.this_token_to_string();
4754 let mut do_not_suggest_help = false;
4755 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4756 if self.token.is_keyword(keywords::In) || self.token == token::Colon {
4757 do_not_suggest_help = true;
4758 e.span_label(sp, "expected `{`");
4761 // Check to see if the user has written something like
4766 // Which is valid in other languages, but not Rust.
4767 match self.parse_stmt_without_recovery(false) {
4769 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4770 || do_not_suggest_help {
4771 // if the next token is an open brace (e.g., `if a b {`), the place-
4772 // inside-a-block suggestion would be more likely wrong than right
4775 let mut stmt_span = stmt.span;
4776 // expand the span to include the semicolon, if it exists
4777 if self.eat(&token::Semi) {
4778 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4780 let sugg = pprust::to_string(|s| {
4781 use print::pprust::{PrintState, INDENT_UNIT};
4782 s.ibox(INDENT_UNIT)?;
4784 s.print_stmt(&stmt)?;
4785 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4787 e.span_suggestion_with_applicability(
4789 "try placing this code inside a block",
4791 // speculative, has been misleading in the past (closed Issue #46836)
4792 Applicability::MaybeIncorrect
4796 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4797 self.cancel(&mut e);
4804 self.parse_block_tail(lo, BlockCheckMode::Default)
4807 /// Parse a block. Inner attrs are allowed.
4808 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4809 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4812 self.expect(&token::OpenDelim(token::Brace))?;
4813 Ok((self.parse_inner_attributes()?,
4814 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4817 /// Parse the rest of a block expression or function body
4818 /// Precondition: already parsed the '{'.
4819 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4820 let mut stmts = vec![];
4821 let mut recovered = false;
4823 while !self.eat(&token::CloseDelim(token::Brace)) {
4824 let stmt = match self.parse_full_stmt(false) {
4827 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4828 self.eat(&token::CloseDelim(token::Brace));
4834 if let Some(stmt) = stmt {
4836 } else if self.token == token::Eof {
4839 // Found only `;` or `}`.
4845 id: ast::DUMMY_NODE_ID,
4847 span: lo.to(self.prev_span),
4852 /// Parse a statement, including the trailing semicolon.
4853 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4854 // skip looking for a trailing semicolon when we have an interpolated statement
4855 maybe_whole!(self, NtStmt, |x| Some(x));
4857 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4859 None => return Ok(None),
4863 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4864 // expression without semicolon
4865 if classify::expr_requires_semi_to_be_stmt(expr) {
4866 // Just check for errors and recover; do not eat semicolon yet.
4868 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4871 self.recover_stmt();
4875 StmtKind::Local(..) => {
4876 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4877 if macro_legacy_warnings && self.token != token::Semi {
4878 self.warn_missing_semicolon();
4880 self.expect_one_of(&[], &[token::Semi])?;
4886 if self.eat(&token::Semi) {
4887 stmt = stmt.add_trailing_semicolon();
4890 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4894 fn warn_missing_semicolon(&self) {
4895 self.diagnostic().struct_span_warn(self.span, {
4896 &format!("expected `;`, found `{}`", self.this_token_to_string())
4898 "This was erroneously allowed and will become a hard error in a future release"
4902 fn err_dotdotdot_syntax(&self, span: Span) {
4903 self.diagnostic().struct_span_err(span, {
4904 "unexpected token: `...`"
4905 }).span_suggestion_with_applicability(
4906 span, "use `..` for an exclusive range", "..".to_owned(),
4907 Applicability::MaybeIncorrect
4908 ).span_suggestion_with_applicability(
4909 span, "or `..=` for an inclusive range", "..=".to_owned(),
4910 Applicability::MaybeIncorrect
4914 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4915 // BOUND = TY_BOUND | LT_BOUND
4916 // LT_BOUND = LIFETIME (e.g. `'a`)
4917 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4918 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4919 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4920 let mut bounds = Vec::new();
4922 // This needs to be synchronized with `Token::can_begin_bound`.
4923 let is_bound_start = self.check_path() || self.check_lifetime() ||
4924 self.check(&token::Question) ||
4925 self.check_keyword(keywords::For) ||
4926 self.check(&token::OpenDelim(token::Paren));
4929 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4930 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4931 if self.token.is_lifetime() {
4932 if let Some(question_span) = question {
4933 self.span_err(question_span,
4934 "`?` may only modify trait bounds, not lifetime bounds");
4936 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4938 self.expect(&token::CloseDelim(token::Paren))?;
4939 self.span_err(self.prev_span,
4940 "parenthesized lifetime bounds are not supported");
4943 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4944 let path = self.parse_path(PathStyle::Type)?;
4946 self.expect(&token::CloseDelim(token::Paren))?;
4948 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4949 let modifier = if question.is_some() {
4950 TraitBoundModifier::Maybe
4952 TraitBoundModifier::None
4954 bounds.push(GenericBound::Trait(poly_trait, modifier));
4960 if !allow_plus || !self.eat_plus() {
4968 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
4969 self.parse_generic_bounds_common(true)
4972 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4973 // BOUND = LT_BOUND (e.g. `'a`)
4974 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4975 let mut lifetimes = Vec::new();
4976 while self.check_lifetime() {
4977 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4979 if !self.eat_plus() {
4986 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4987 fn parse_ty_param(&mut self,
4988 preceding_attrs: Vec<Attribute>)
4989 -> PResult<'a, GenericParam> {
4990 let ident = self.parse_ident()?;
4992 // Parse optional colon and param bounds.
4993 let bounds = if self.eat(&token::Colon) {
4994 self.parse_generic_bounds()?
4999 let default = if self.eat(&token::Eq) {
5000 Some(self.parse_ty()?)
5007 id: ast::DUMMY_NODE_ID,
5008 attrs: preceding_attrs.into(),
5010 kind: GenericParamKind::Type {
5016 /// Parses the following grammar:
5017 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5018 fn parse_trait_item_assoc_ty(&mut self)
5019 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5020 let ident = self.parse_ident()?;
5021 let mut generics = self.parse_generics()?;
5023 // Parse optional colon and param bounds.
5024 let bounds = if self.eat(&token::Colon) {
5025 self.parse_generic_bounds()?
5029 generics.where_clause = self.parse_where_clause()?;
5031 let default = if self.eat(&token::Eq) {
5032 Some(self.parse_ty()?)
5036 self.expect(&token::Semi)?;
5038 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5041 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5042 /// trailing comma and erroneous trailing attributes.
5043 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5044 let mut params = Vec::new();
5045 let mut seen_ty_param = false;
5047 let attrs = self.parse_outer_attributes()?;
5048 if self.check_lifetime() {
5049 let lifetime = self.expect_lifetime();
5050 // Parse lifetime parameter.
5051 let bounds = if self.eat(&token::Colon) {
5052 self.parse_lt_param_bounds()
5056 params.push(ast::GenericParam {
5057 ident: lifetime.ident,
5059 attrs: attrs.into(),
5061 kind: ast::GenericParamKind::Lifetime,
5064 self.span_err(self.prev_span,
5065 "lifetime parameters must be declared prior to type parameters");
5067 } else if self.check_ident() {
5068 // Parse type parameter.
5069 params.push(self.parse_ty_param(attrs)?);
5070 seen_ty_param = true;
5072 // Check for trailing attributes and stop parsing.
5073 if !attrs.is_empty() {
5074 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
5075 self.span_err(attrs[0].span,
5076 &format!("trailing attribute after {} parameters", param_kind));
5081 if !self.eat(&token::Comma) {
5088 /// Parse a set of optional generic type parameter declarations. Where
5089 /// clauses are not parsed here, and must be added later via
5090 /// `parse_where_clause()`.
5092 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5093 /// | ( < lifetimes , typaramseq ( , )? > )
5094 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5095 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5096 maybe_whole!(self, NtGenerics, |x| x);
5098 let span_lo = self.span;
5100 let params = self.parse_generic_params()?;
5104 where_clause: WhereClause {
5105 id: ast::DUMMY_NODE_ID,
5106 predicates: Vec::new(),
5107 span: syntax_pos::DUMMY_SP,
5109 span: span_lo.to(self.prev_span),
5112 Ok(ast::Generics::default())
5116 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5117 /// possibly including trailing comma.
5118 fn parse_generic_args(&mut self)
5119 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5120 let mut args = Vec::new();
5121 let mut bindings = Vec::new();
5122 let mut seen_type = false;
5123 let mut seen_binding = false;
5125 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5126 // Parse lifetime argument.
5127 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5128 if seen_type || seen_binding {
5129 self.span_err(self.prev_span,
5130 "lifetime parameters must be declared prior to type parameters");
5132 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5133 // Parse associated type binding.
5135 let ident = self.parse_ident()?;
5137 let ty = self.parse_ty()?;
5138 bindings.push(TypeBinding {
5139 id: ast::DUMMY_NODE_ID,
5142 span: lo.to(self.prev_span),
5144 seen_binding = true;
5145 } else if self.check_type() {
5146 // Parse type argument.
5147 let ty_param = self.parse_ty()?;
5149 self.span_err(ty_param.span,
5150 "type parameters must be declared prior to associated type bindings");
5152 args.push(GenericArg::Type(ty_param));
5158 if !self.eat(&token::Comma) {
5162 Ok((args, bindings))
5165 /// Parses an optional `where` clause and places it in `generics`.
5167 /// ```ignore (only-for-syntax-highlight)
5168 /// where T : Trait<U, V> + 'b, 'a : 'b
5170 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5171 maybe_whole!(self, NtWhereClause, |x| x);
5173 let mut where_clause = WhereClause {
5174 id: ast::DUMMY_NODE_ID,
5175 predicates: Vec::new(),
5176 span: syntax_pos::DUMMY_SP,
5179 if !self.eat_keyword(keywords::Where) {
5180 return Ok(where_clause);
5182 let lo = self.prev_span;
5184 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5185 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5186 // change we parse those generics now, but report an error.
5187 if self.choose_generics_over_qpath() {
5188 let generics = self.parse_generics()?;
5189 self.span_err(generics.span,
5190 "generic parameters on `where` clauses are reserved for future use");
5195 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5196 let lifetime = self.expect_lifetime();
5197 // Bounds starting with a colon are mandatory, but possibly empty.
5198 self.expect(&token::Colon)?;
5199 let bounds = self.parse_lt_param_bounds();
5200 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5201 ast::WhereRegionPredicate {
5202 span: lo.to(self.prev_span),
5207 } else if self.check_type() {
5208 // Parse optional `for<'a, 'b>`.
5209 // This `for` is parsed greedily and applies to the whole predicate,
5210 // the bounded type can have its own `for` applying only to it.
5211 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5212 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5213 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5214 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5216 // Parse type with mandatory colon and (possibly empty) bounds,
5217 // or with mandatory equality sign and the second type.
5218 let ty = self.parse_ty()?;
5219 if self.eat(&token::Colon) {
5220 let bounds = self.parse_generic_bounds()?;
5221 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5222 ast::WhereBoundPredicate {
5223 span: lo.to(self.prev_span),
5224 bound_generic_params: lifetime_defs,
5229 // FIXME: Decide what should be used here, `=` or `==`.
5230 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5231 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5232 let rhs_ty = self.parse_ty()?;
5233 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5234 ast::WhereEqPredicate {
5235 span: lo.to(self.prev_span),
5238 id: ast::DUMMY_NODE_ID,
5242 return self.unexpected();
5248 if !self.eat(&token::Comma) {
5253 where_clause.span = lo.to(self.prev_span);
5257 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5258 -> PResult<'a, (Vec<Arg> , bool)> {
5260 let mut variadic = false;
5261 let args: Vec<Option<Arg>> =
5262 self.parse_unspanned_seq(
5263 &token::OpenDelim(token::Paren),
5264 &token::CloseDelim(token::Paren),
5265 SeqSep::trailing_allowed(token::Comma),
5267 if p.token == token::DotDotDot {
5271 if p.token != token::CloseDelim(token::Paren) {
5274 "`...` must be last in argument list for variadic function");
5278 let span = p.prev_span;
5279 if p.token == token::CloseDelim(token::Paren) {
5280 // continue parsing to present any further errors
5283 "only foreign functions are allowed to be variadic"
5285 Ok(Some(dummy_arg(span)))
5287 // this function definition looks beyond recovery, stop parsing
5289 "only foreign functions are allowed to be variadic");
5294 match p.parse_arg_general(named_args) {
5295 Ok(arg) => Ok(Some(arg)),
5298 let lo = p.prev_span;
5299 // Skip every token until next possible arg or end.
5300 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5301 // Create a placeholder argument for proper arg count (#34264).
5302 let span = lo.to(p.prev_span);
5303 Ok(Some(dummy_arg(span)))
5310 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5312 if variadic && args.is_empty() {
5314 "variadic function must be declared with at least one named argument");
5317 Ok((args, variadic))
5320 /// Parse the argument list and result type of a function declaration
5321 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5323 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5324 let ret_ty = self.parse_ret_ty(true)?;
5333 /// Returns the parsed optional self argument and whether a self shortcut was used.
5334 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5335 let expect_ident = |this: &mut Self| match this.token {
5336 // Preserve hygienic context.
5337 token::Ident(ident, _) =>
5338 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5341 let isolated_self = |this: &mut Self, n| {
5342 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5343 this.look_ahead(n + 1, |t| t != &token::ModSep)
5346 // Parse optional self parameter of a method.
5347 // Only a limited set of initial token sequences is considered self parameters, anything
5348 // else is parsed as a normal function parameter list, so some lookahead is required.
5349 let eself_lo = self.span;
5350 let (eself, eself_ident, eself_hi) = match self.token {
5351 token::BinOp(token::And) => {
5357 (if isolated_self(self, 1) {
5359 SelfKind::Region(None, Mutability::Immutable)
5360 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5361 isolated_self(self, 2) {
5364 SelfKind::Region(None, Mutability::Mutable)
5365 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5366 isolated_self(self, 2) {
5368 let lt = self.expect_lifetime();
5369 SelfKind::Region(Some(lt), Mutability::Immutable)
5370 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5371 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5372 isolated_self(self, 3) {
5374 let lt = self.expect_lifetime();
5376 SelfKind::Region(Some(lt), Mutability::Mutable)
5379 }, expect_ident(self), self.prev_span)
5381 token::BinOp(token::Star) => {
5386 // Emit special error for `self` cases.
5387 (if isolated_self(self, 1) {
5389 self.span_err(self.span, "cannot pass `self` by raw pointer");
5390 SelfKind::Value(Mutability::Immutable)
5391 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5392 isolated_self(self, 2) {
5395 self.span_err(self.span, "cannot pass `self` by raw pointer");
5396 SelfKind::Value(Mutability::Immutable)
5399 }, expect_ident(self), self.prev_span)
5401 token::Ident(..) => {
5402 if isolated_self(self, 0) {
5405 let eself_ident = expect_ident(self);
5406 let eself_hi = self.prev_span;
5407 (if self.eat(&token::Colon) {
5408 let ty = self.parse_ty()?;
5409 SelfKind::Explicit(ty, Mutability::Immutable)
5411 SelfKind::Value(Mutability::Immutable)
5412 }, eself_ident, eself_hi)
5413 } else if self.token.is_keyword(keywords::Mut) &&
5414 isolated_self(self, 1) {
5418 let eself_ident = expect_ident(self);
5419 let eself_hi = self.prev_span;
5420 (if self.eat(&token::Colon) {
5421 let ty = self.parse_ty()?;
5422 SelfKind::Explicit(ty, Mutability::Mutable)
5424 SelfKind::Value(Mutability::Mutable)
5425 }, eself_ident, eself_hi)
5430 _ => return Ok(None),
5433 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5434 Ok(Some(Arg::from_self(eself, eself_ident)))
5437 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5438 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5439 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5441 self.expect(&token::OpenDelim(token::Paren))?;
5443 // Parse optional self argument
5444 let self_arg = self.parse_self_arg()?;
5446 // Parse the rest of the function parameter list.
5447 let sep = SeqSep::trailing_allowed(token::Comma);
5448 let fn_inputs = if let Some(self_arg) = self_arg {
5449 if self.check(&token::CloseDelim(token::Paren)) {
5451 } else if self.eat(&token::Comma) {
5452 let mut fn_inputs = vec![self_arg];
5453 fn_inputs.append(&mut self.parse_seq_to_before_end(
5454 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5458 return self.unexpected();
5461 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5464 // Parse closing paren and return type.
5465 self.expect(&token::CloseDelim(token::Paren))?;
5468 output: self.parse_ret_ty(true)?,
5473 // parse the |arg, arg| header on a lambda
5474 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5475 let inputs_captures = {
5476 if self.eat(&token::OrOr) {
5479 self.expect(&token::BinOp(token::Or))?;
5480 let args = self.parse_seq_to_before_tokens(
5481 &[&token::BinOp(token::Or), &token::OrOr],
5482 SeqSep::trailing_allowed(token::Comma),
5483 TokenExpectType::NoExpect,
5484 |p| p.parse_fn_block_arg()
5490 let output = self.parse_ret_ty(true)?;
5493 inputs: inputs_captures,
5499 /// Parse the name and optional generic types of a function header.
5500 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5501 let id = self.parse_ident()?;
5502 let generics = self.parse_generics()?;
5506 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5507 attrs: Vec<Attribute>) -> P<Item> {
5511 id: ast::DUMMY_NODE_ID,
5519 /// Parse an item-position function declaration.
5520 fn parse_item_fn(&mut self,
5523 constness: Spanned<Constness>,
5525 -> PResult<'a, ItemInfo> {
5526 let (ident, mut generics) = self.parse_fn_header()?;
5527 let decl = self.parse_fn_decl(false)?;
5528 generics.where_clause = self.parse_where_clause()?;
5529 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5530 let header = FnHeader { unsafety, asyncness, constness, abi };
5531 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5534 /// true if we are looking at `const ID`, false for things like `const fn` etc
5535 fn is_const_item(&mut self) -> bool {
5536 self.token.is_keyword(keywords::Const) &&
5537 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5538 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5541 /// parses all the "front matter" for a `fn` declaration, up to
5542 /// and including the `fn` keyword:
5546 /// - `const unsafe fn`
5549 fn parse_fn_front_matter(&mut self)
5557 let is_const_fn = self.eat_keyword(keywords::Const);
5558 let const_span = self.prev_span;
5559 let unsafety = self.parse_unsafety();
5560 let asyncness = self.parse_asyncness();
5561 let (constness, unsafety, abi) = if is_const_fn {
5562 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5564 let abi = if self.eat_keyword(keywords::Extern) {
5565 self.parse_opt_abi()?.unwrap_or(Abi::C)
5569 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5571 self.expect_keyword(keywords::Fn)?;
5572 Ok((constness, unsafety, asyncness, abi))
5575 /// Parse an impl item.
5576 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5577 maybe_whole!(self, NtImplItem, |x| x);
5578 let attrs = self.parse_outer_attributes()?;
5579 let (mut item, tokens) = self.collect_tokens(|this| {
5580 this.parse_impl_item_(at_end, attrs)
5583 // See `parse_item` for why this clause is here.
5584 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5585 item.tokens = Some(tokens);
5590 fn parse_impl_item_(&mut self,
5592 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5594 let vis = self.parse_visibility(false)?;
5595 let defaultness = self.parse_defaultness();
5596 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5597 let (name, alias, generics) = type_?;
5598 let kind = match alias {
5599 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5600 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5602 (name, kind, generics)
5603 } else if self.is_const_item() {
5604 // This parses the grammar:
5605 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5606 self.expect_keyword(keywords::Const)?;
5607 let name = self.parse_ident()?;
5608 self.expect(&token::Colon)?;
5609 let typ = self.parse_ty()?;
5610 self.expect(&token::Eq)?;
5611 let expr = self.parse_expr()?;
5612 self.expect(&token::Semi)?;
5613 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5615 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5616 attrs.extend(inner_attrs);
5617 (name, node, generics)
5621 id: ast::DUMMY_NODE_ID,
5622 span: lo.to(self.prev_span),
5633 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5634 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5639 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5641 VisibilityKind::Inherited => Ok(()),
5643 let is_macro_rules: bool = match self.token {
5644 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5648 let mut err = self.diagnostic()
5649 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5650 err.span_suggestion_with_applicability(
5652 "try exporting the macro",
5653 "#[macro_export]".to_owned(),
5654 Applicability::MaybeIncorrect // speculative
5658 let mut err = self.diagnostic()
5659 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5660 err.help("try adjusting the macro to put `pub` inside the invocation");
5667 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5668 -> DiagnosticBuilder<'a>
5670 let expected_kinds = if item_type == "extern" {
5671 "missing `fn`, `type`, or `static`"
5673 "missing `fn`, `type`, or `const`"
5676 // Given this code `path(`, it seems like this is not
5677 // setting the visibility of a macro invocation, but rather
5678 // a mistyped method declaration.
5679 // Create a diagnostic pointing out that `fn` is missing.
5681 // x | pub path(&self) {
5682 // | ^ missing `fn`, `type`, or `const`
5684 // ^^ `sp` below will point to this
5685 let sp = prev_span.between(self.prev_span);
5686 let mut err = self.diagnostic().struct_span_err(
5688 &format!("{} for {}-item declaration",
5689 expected_kinds, item_type));
5690 err.span_label(sp, expected_kinds);
5694 /// Parse a method or a macro invocation in a trait impl.
5695 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5696 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5697 ast::ImplItemKind)> {
5698 // code copied from parse_macro_use_or_failure... abstraction!
5699 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5701 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5702 ast::ImplItemKind::Macro(mac)))
5704 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5705 let ident = self.parse_ident()?;
5706 let mut generics = self.parse_generics()?;
5707 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5708 generics.where_clause = self.parse_where_clause()?;
5710 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5711 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5712 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5713 ast::MethodSig { header, decl },
5719 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5720 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5721 let ident = self.parse_ident()?;
5722 let mut tps = self.parse_generics()?;
5724 // Parse optional colon and supertrait bounds.
5725 let bounds = if self.eat(&token::Colon) {
5726 self.parse_generic_bounds()?
5731 if self.eat(&token::Eq) {
5732 // it's a trait alias
5733 let bounds = self.parse_generic_bounds()?;
5734 tps.where_clause = self.parse_where_clause()?;
5735 self.expect(&token::Semi)?;
5736 if unsafety != Unsafety::Normal {
5737 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5739 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5741 // it's a normal trait
5742 tps.where_clause = self.parse_where_clause()?;
5743 self.expect(&token::OpenDelim(token::Brace))?;
5744 let mut trait_items = vec![];
5745 while !self.eat(&token::CloseDelim(token::Brace)) {
5746 let mut at_end = false;
5747 match self.parse_trait_item(&mut at_end) {
5748 Ok(item) => trait_items.push(item),
5752 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5757 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5761 fn choose_generics_over_qpath(&self) -> bool {
5762 // There's an ambiguity between generic parameters and qualified paths in impls.
5763 // If we see `<` it may start both, so we have to inspect some following tokens.
5764 // The following combinations can only start generics,
5765 // but not qualified paths (with one exception):
5766 // `<` `>` - empty generic parameters
5767 // `<` `#` - generic parameters with attributes
5768 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5769 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5770 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5771 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5772 // The only truly ambiguous case is
5773 // `<` IDENT `>` `::` IDENT ...
5774 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5775 // because this is what almost always expected in practice, qualified paths in impls
5776 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5777 self.token == token::Lt &&
5778 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5779 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5780 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5781 t == &token::Colon || t == &token::Eq))
5784 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5785 self.expect(&token::OpenDelim(token::Brace))?;
5786 let attrs = self.parse_inner_attributes()?;
5788 let mut impl_items = Vec::new();
5789 while !self.eat(&token::CloseDelim(token::Brace)) {
5790 let mut at_end = false;
5791 match self.parse_impl_item(&mut at_end) {
5792 Ok(impl_item) => impl_items.push(impl_item),
5796 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5801 Ok((impl_items, attrs))
5804 /// Parses an implementation item, `impl` keyword is already parsed.
5805 /// impl<'a, T> TYPE { /* impl items */ }
5806 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5807 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5808 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5809 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5810 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5811 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5812 -> PResult<'a, ItemInfo> {
5813 // First, parse generic parameters if necessary.
5814 let mut generics = if self.choose_generics_over_qpath() {
5815 self.parse_generics()?
5817 ast::Generics::default()
5820 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5821 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5823 ast::ImplPolarity::Negative
5825 ast::ImplPolarity::Positive
5828 // Parse both types and traits as a type, then reinterpret if necessary.
5829 let ty_first = self.parse_ty()?;
5831 // If `for` is missing we try to recover.
5832 let has_for = self.eat_keyword(keywords::For);
5833 let missing_for_span = self.prev_span.between(self.span);
5835 let ty_second = if self.token == token::DotDot {
5836 // We need to report this error after `cfg` expansion for compatibility reasons
5837 self.bump(); // `..`, do not add it to expected tokens
5838 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5839 } else if has_for || self.token.can_begin_type() {
5840 Some(self.parse_ty()?)
5845 generics.where_clause = self.parse_where_clause()?;
5847 let (impl_items, attrs) = self.parse_impl_body()?;
5849 let item_kind = match ty_second {
5850 Some(ty_second) => {
5851 // impl Trait for Type
5853 self.span_err(missing_for_span, "missing `for` in a trait impl");
5856 let ty_first = ty_first.into_inner();
5857 let path = match ty_first.node {
5858 // This notably includes paths passed through `ty` macro fragments (#46438).
5859 TyKind::Path(None, path) => path,
5861 self.span_err(ty_first.span, "expected a trait, found type");
5862 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5865 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5867 ItemKind::Impl(unsafety, polarity, defaultness,
5868 generics, Some(trait_ref), ty_second, impl_items)
5872 ItemKind::Impl(unsafety, polarity, defaultness,
5873 generics, None, ty_first, impl_items)
5877 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5880 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5881 if self.eat_keyword(keywords::For) {
5883 let params = self.parse_generic_params()?;
5885 // We rely on AST validation to rule out invalid cases: There must not be type
5886 // parameters, and the lifetime parameters must not have bounds.
5893 /// Parse struct Foo { ... }
5894 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5895 let class_name = self.parse_ident()?;
5897 let mut generics = self.parse_generics()?;
5899 // There is a special case worth noting here, as reported in issue #17904.
5900 // If we are parsing a tuple struct it is the case that the where clause
5901 // should follow the field list. Like so:
5903 // struct Foo<T>(T) where T: Copy;
5905 // If we are parsing a normal record-style struct it is the case
5906 // that the where clause comes before the body, and after the generics.
5907 // So if we look ahead and see a brace or a where-clause we begin
5908 // parsing a record style struct.
5910 // Otherwise if we look ahead and see a paren we parse a tuple-style
5913 let vdata = if self.token.is_keyword(keywords::Where) {
5914 generics.where_clause = self.parse_where_clause()?;
5915 if self.eat(&token::Semi) {
5916 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5917 VariantData::Unit(ast::DUMMY_NODE_ID)
5919 // If we see: `struct Foo<T> where T: Copy { ... }`
5920 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5922 // No `where` so: `struct Foo<T>;`
5923 } else if self.eat(&token::Semi) {
5924 VariantData::Unit(ast::DUMMY_NODE_ID)
5925 // Record-style struct definition
5926 } else if self.token == token::OpenDelim(token::Brace) {
5927 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5928 // Tuple-style struct definition with optional where-clause.
5929 } else if self.token == token::OpenDelim(token::Paren) {
5930 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5931 generics.where_clause = self.parse_where_clause()?;
5932 self.expect(&token::Semi)?;
5935 let token_str = self.this_token_to_string();
5936 let mut err = self.fatal(&format!(
5937 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5940 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5944 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5947 /// Parse union Foo { ... }
5948 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5949 let class_name = self.parse_ident()?;
5951 let mut generics = self.parse_generics()?;
5953 let vdata = if self.token.is_keyword(keywords::Where) {
5954 generics.where_clause = self.parse_where_clause()?;
5955 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5956 } else if self.token == token::OpenDelim(token::Brace) {
5957 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5959 let token_str = self.this_token_to_string();
5960 let mut err = self.fatal(&format!(
5961 "expected `where` or `{{` after union name, found `{}`", token_str));
5962 err.span_label(self.span, "expected `where` or `{` after union name");
5966 Ok((class_name, ItemKind::Union(vdata, generics), None))
5969 fn consume_block(&mut self, delim: token::DelimToken) {
5970 let mut brace_depth = 0;
5971 if !self.eat(&token::OpenDelim(delim)) {
5975 if self.eat(&token::OpenDelim(delim)) {
5977 } else if self.eat(&token::CloseDelim(delim)) {
5978 if brace_depth == 0 {
5984 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5992 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5993 let mut fields = Vec::new();
5994 if self.eat(&token::OpenDelim(token::Brace)) {
5995 while self.token != token::CloseDelim(token::Brace) {
5996 let field = self.parse_struct_decl_field().map_err(|e| {
5997 self.recover_stmt();
6001 Ok(field) => fields.push(field),
6007 self.eat(&token::CloseDelim(token::Brace));
6009 let token_str = self.this_token_to_string();
6010 let mut err = self.fatal(&format!(
6011 "expected `where`, or `{{` after struct name, found `{}`", token_str));
6012 err.span_label(self.span, "expected `where`, or `{` after struct name");
6019 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6020 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6021 // Unit like structs are handled in parse_item_struct function
6022 let fields = self.parse_unspanned_seq(
6023 &token::OpenDelim(token::Paren),
6024 &token::CloseDelim(token::Paren),
6025 SeqSep::trailing_allowed(token::Comma),
6027 let attrs = p.parse_outer_attributes()?;
6029 let vis = p.parse_visibility(true)?;
6030 let ty = p.parse_ty()?;
6032 span: lo.to(ty.span),
6035 id: ast::DUMMY_NODE_ID,
6044 /// Parse a structure field declaration
6045 fn parse_single_struct_field(&mut self,
6048 attrs: Vec<Attribute> )
6049 -> PResult<'a, StructField> {
6050 let mut seen_comma: bool = false;
6051 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6052 if self.token == token::Comma {
6059 token::CloseDelim(token::Brace) => {}
6060 token::DocComment(_) => {
6061 let previous_span = self.prev_span;
6062 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6063 self.bump(); // consume the doc comment
6064 let comma_after_doc_seen = self.eat(&token::Comma);
6065 // `seen_comma` is always false, because we are inside doc block
6066 // condition is here to make code more readable
6067 if seen_comma == false && comma_after_doc_seen == true {
6070 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6073 if seen_comma == false {
6074 let sp = self.sess.source_map().next_point(previous_span);
6075 err.span_suggestion_with_applicability(
6077 "missing comma here",
6079 Applicability::MachineApplicable
6086 let sp = self.sess.source_map().next_point(self.prev_span);
6087 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
6088 self.this_token_to_string()));
6089 if self.token.is_ident() {
6090 // This is likely another field; emit the diagnostic and keep going
6091 err.span_suggestion_with_applicability(
6093 "try adding a comma",
6095 Applicability::MachineApplicable,
6106 /// Parse an element of a struct definition
6107 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6108 let attrs = self.parse_outer_attributes()?;
6110 let vis = self.parse_visibility(false)?;
6111 self.parse_single_struct_field(lo, vis, attrs)
6114 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6115 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6116 /// a function definition, it's not a tuple struct field) and the contents within the parens
6117 /// isn't valid, emit a proper diagnostic.
6118 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6119 maybe_whole!(self, NtVis, |x| x);
6121 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6122 if self.is_crate_vis() {
6123 self.bump(); // `crate`
6124 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6127 if !self.eat_keyword(keywords::Pub) {
6128 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6129 // keyword to grab a span from for inherited visibility; an empty span at the
6130 // beginning of the current token would seem to be the "Schelling span".
6131 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6133 let lo = self.prev_span;
6135 if self.check(&token::OpenDelim(token::Paren)) {
6136 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6137 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6138 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6139 // by the following tokens.
6140 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6143 self.bump(); // `crate`
6144 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6146 lo.to(self.prev_span),
6147 VisibilityKind::Crate(CrateSugar::PubCrate),
6150 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6153 self.bump(); // `in`
6154 let path = self.parse_path(PathStyle::Mod)?; // `path`
6155 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6156 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6158 id: ast::DUMMY_NODE_ID,
6161 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6162 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6163 t.is_keyword(keywords::SelfValue))
6165 // `pub(self)` or `pub(super)`
6167 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6168 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6169 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6171 id: ast::DUMMY_NODE_ID,
6174 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6175 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6177 let msg = "incorrect visibility restriction";
6178 let suggestion = r##"some possible visibility restrictions are:
6179 `pub(crate)`: visible only on the current crate
6180 `pub(super)`: visible only in the current module's parent
6181 `pub(in path::to::module)`: visible only on the specified path"##;
6182 let path = self.parse_path(PathStyle::Mod)?;
6183 let sp = self.prev_span;
6184 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6185 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6186 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6187 err.help(suggestion);
6188 err.span_suggestion_with_applicability(
6189 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6191 err.emit(); // emit diagnostic, but continue with public visibility
6195 Ok(respan(lo, VisibilityKind::Public))
6198 /// Parse defaultness: `default` or nothing.
6199 fn parse_defaultness(&mut self) -> Defaultness {
6200 // `pub` is included for better error messages
6201 if self.check_keyword(keywords::Default) &&
6202 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6203 t.is_keyword(keywords::Const) ||
6204 t.is_keyword(keywords::Fn) ||
6205 t.is_keyword(keywords::Unsafe) ||
6206 t.is_keyword(keywords::Extern) ||
6207 t.is_keyword(keywords::Type) ||
6208 t.is_keyword(keywords::Pub)) {
6209 self.bump(); // `default`
6210 Defaultness::Default
6216 /// Given a termination token, parse all of the items in a module
6217 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6218 let mut items = vec![];
6219 while let Some(item) = self.parse_item()? {
6223 if !self.eat(term) {
6224 let token_str = self.this_token_to_string();
6225 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6226 if token_str == ";" {
6227 let msg = "consider removing this semicolon";
6228 err.span_suggestion_short_with_applicability(
6229 self.span, msg, String::new(), Applicability::MachineApplicable
6231 if !items.is_empty() { // Issue #51603
6232 let previous_item = &items[items.len()-1];
6233 let previous_item_kind_name = match previous_item.node {
6234 // say "braced struct" because tuple-structs and
6235 // braceless-empty-struct declarations do take a semicolon
6236 ItemKind::Struct(..) => Some("braced struct"),
6237 ItemKind::Enum(..) => Some("enum"),
6238 ItemKind::Trait(..) => Some("trait"),
6239 ItemKind::Union(..) => Some("union"),
6242 if let Some(name) = previous_item_kind_name {
6243 err.help(&format!("{} declarations are not followed by a semicolon",
6248 err.span_label(self.span, "expected item");
6253 let hi = if self.span.is_dummy() {
6260 inner: inner_lo.to(hi),
6265 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6266 let id = self.parse_ident()?;
6267 self.expect(&token::Colon)?;
6268 let ty = self.parse_ty()?;
6269 self.expect(&token::Eq)?;
6270 let e = self.parse_expr()?;
6271 self.expect(&token::Semi)?;
6272 let item = match m {
6273 Some(m) => ItemKind::Static(ty, m, e),
6274 None => ItemKind::Const(ty, e),
6276 Ok((id, item, None))
6279 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6280 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6281 let (in_cfg, outer_attrs) = {
6282 let mut strip_unconfigured = ::config::StripUnconfigured {
6284 should_test: false, // irrelevant
6285 features: None, // don't perform gated feature checking
6287 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6288 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6291 let id_span = self.span;
6292 let id = self.parse_ident()?;
6293 if self.check(&token::Semi) {
6295 if in_cfg && self.recurse_into_file_modules {
6296 // This mod is in an external file. Let's go get it!
6297 let ModulePathSuccess { path, directory_ownership, warn } =
6298 self.submod_path(id, &outer_attrs, id_span)?;
6299 let (module, mut attrs) =
6300 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6302 let attr = Attribute {
6303 id: attr::mk_attr_id(),
6304 style: ast::AttrStyle::Outer,
6305 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6306 tokens: TokenStream::empty(),
6307 is_sugared_doc: false,
6308 span: syntax_pos::DUMMY_SP,
6310 attr::mark_known(&attr);
6313 Ok((id, module, Some(attrs)))
6315 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6316 Ok((id, ItemKind::Mod(placeholder), None))
6319 let old_directory = self.directory.clone();
6320 self.push_directory(id, &outer_attrs);
6322 self.expect(&token::OpenDelim(token::Brace))?;
6323 let mod_inner_lo = self.span;
6324 let attrs = self.parse_inner_attributes()?;
6325 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6327 self.directory = old_directory;
6328 Ok((id, ItemKind::Mod(module), Some(attrs)))
6332 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6333 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6334 self.directory.path.to_mut().push(&path.as_str());
6335 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6337 self.directory.path.to_mut().push(&id.as_str());
6341 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6342 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6345 // On windows, the base path might have the form
6346 // `\\?\foo\bar` in which case it does not tolerate
6347 // mixed `/` and `\` separators, so canonicalize
6350 let s = s.replace("/", "\\");
6351 Some(dir_path.join(s))
6357 /// Returns either a path to a module, or .
6358 pub fn default_submod_path(
6360 relative: Option<ast::Ident>,
6362 source_map: &SourceMap) -> ModulePath
6364 // If we're in a foo.rs file instead of a mod.rs file,
6365 // we need to look for submodules in
6366 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6367 // `./<id>.rs` and `./<id>/mod.rs`.
6368 let relative_prefix_string;
6369 let relative_prefix = if let Some(ident) = relative {
6370 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6371 &relative_prefix_string
6376 let mod_name = id.to_string();
6377 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6378 let secondary_path_str = format!("{}{}{}mod.rs",
6379 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6380 let default_path = dir_path.join(&default_path_str);
6381 let secondary_path = dir_path.join(&secondary_path_str);
6382 let default_exists = source_map.file_exists(&default_path);
6383 let secondary_exists = source_map.file_exists(&secondary_path);
6385 let result = match (default_exists, secondary_exists) {
6386 (true, false) => Ok(ModulePathSuccess {
6388 directory_ownership: DirectoryOwnership::Owned {
6393 (false, true) => Ok(ModulePathSuccess {
6394 path: secondary_path,
6395 directory_ownership: DirectoryOwnership::Owned {
6400 (false, false) => Err(Error::FileNotFoundForModule {
6401 mod_name: mod_name.clone(),
6402 default_path: default_path_str,
6403 secondary_path: secondary_path_str,
6404 dir_path: dir_path.display().to_string(),
6406 (true, true) => Err(Error::DuplicatePaths {
6407 mod_name: mod_name.clone(),
6408 default_path: default_path_str,
6409 secondary_path: secondary_path_str,
6415 path_exists: default_exists || secondary_exists,
6420 fn submod_path(&mut self,
6422 outer_attrs: &[Attribute],
6424 -> PResult<'a, ModulePathSuccess> {
6425 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6426 return Ok(ModulePathSuccess {
6427 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6428 // All `#[path]` files are treated as though they are a `mod.rs` file.
6429 // This means that `mod foo;` declarations inside `#[path]`-included
6430 // files are siblings,
6432 // Note that this will produce weirdness when a file named `foo.rs` is
6433 // `#[path]` included and contains a `mod foo;` declaration.
6434 // If you encounter this, it's your own darn fault :P
6435 Some(_) => DirectoryOwnership::Owned { relative: None },
6436 _ => DirectoryOwnership::UnownedViaMod(true),
6443 let relative = match self.directory.ownership {
6444 DirectoryOwnership::Owned { relative } => {
6445 // Push the usage onto the list of non-mod.rs mod uses.
6446 // This is used later for feature-gate error reporting.
6447 if let Some(cur_file_ident) = relative {
6449 .non_modrs_mods.borrow_mut()
6450 .push((cur_file_ident, id_sp));
6454 DirectoryOwnership::UnownedViaBlock |
6455 DirectoryOwnership::UnownedViaMod(_) => None,
6457 let paths = Parser::default_submod_path(
6458 id, relative, &self.directory.path, self.sess.source_map());
6460 match self.directory.ownership {
6461 DirectoryOwnership::Owned { .. } => {
6462 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6464 DirectoryOwnership::UnownedViaBlock => {
6466 "Cannot declare a non-inline module inside a block \
6467 unless it has a path attribute";
6468 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6469 if paths.path_exists {
6470 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6472 err.span_note(id_sp, &msg);
6476 DirectoryOwnership::UnownedViaMod(warn) => {
6478 if let Ok(result) = paths.result {
6479 return Ok(ModulePathSuccess { warn: true, ..result });
6482 let mut err = self.diagnostic().struct_span_err(id_sp,
6483 "cannot declare a new module at this location");
6484 if !id_sp.is_dummy() {
6485 let src_path = self.sess.source_map().span_to_filename(id_sp);
6486 if let FileName::Real(src_path) = src_path {
6487 if let Some(stem) = src_path.file_stem() {
6488 let mut dest_path = src_path.clone();
6489 dest_path.set_file_name(stem);
6490 dest_path.push("mod.rs");
6491 err.span_note(id_sp,
6492 &format!("maybe move this module `{}` to its own \
6493 directory via `{}`", src_path.display(),
6494 dest_path.display()));
6498 if paths.path_exists {
6499 err.span_note(id_sp,
6500 &format!("... or maybe `use` the module `{}` instead \
6501 of possibly redeclaring it",
6509 /// Read a module from a source file.
6510 fn eval_src_mod(&mut self,
6512 directory_ownership: DirectoryOwnership,
6515 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6516 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6517 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6518 let mut err = String::from("circular modules: ");
6519 let len = included_mod_stack.len();
6520 for p in &included_mod_stack[i.. len] {
6521 err.push_str(&p.to_string_lossy());
6522 err.push_str(" -> ");
6524 err.push_str(&path.to_string_lossy());
6525 return Err(self.span_fatal(id_sp, &err[..]));
6527 included_mod_stack.push(path.clone());
6528 drop(included_mod_stack);
6531 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6532 p0.cfg_mods = self.cfg_mods;
6533 let mod_inner_lo = p0.span;
6534 let mod_attrs = p0.parse_inner_attributes()?;
6535 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6536 self.sess.included_mod_stack.borrow_mut().pop();
6537 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6540 /// Parse a function declaration from a foreign module
6541 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6542 -> PResult<'a, ForeignItem> {
6543 self.expect_keyword(keywords::Fn)?;
6545 let (ident, mut generics) = self.parse_fn_header()?;
6546 let decl = self.parse_fn_decl(true)?;
6547 generics.where_clause = self.parse_where_clause()?;
6549 self.expect(&token::Semi)?;
6550 Ok(ast::ForeignItem {
6553 node: ForeignItemKind::Fn(decl, generics),
6554 id: ast::DUMMY_NODE_ID,
6560 /// Parse a static item from a foreign module.
6561 /// Assumes that the `static` keyword is already parsed.
6562 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6563 -> PResult<'a, ForeignItem> {
6564 let mutbl = self.eat_keyword(keywords::Mut);
6565 let ident = self.parse_ident()?;
6566 self.expect(&token::Colon)?;
6567 let ty = self.parse_ty()?;
6569 self.expect(&token::Semi)?;
6573 node: ForeignItemKind::Static(ty, mutbl),
6574 id: ast::DUMMY_NODE_ID,
6580 /// Parse a type from a foreign module
6581 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6582 -> PResult<'a, ForeignItem> {
6583 self.expect_keyword(keywords::Type)?;
6585 let ident = self.parse_ident()?;
6587 self.expect(&token::Semi)?;
6588 Ok(ast::ForeignItem {
6591 node: ForeignItemKind::Ty,
6592 id: ast::DUMMY_NODE_ID,
6598 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6599 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6600 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6602 let mut ident = self.parse_ident()?;
6603 let mut idents = vec![];
6604 let mut replacement = vec![];
6605 let mut fixed_crate_name = false;
6606 // Accept `extern crate name-like-this` for better diagnostics
6607 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6608 if self.token == dash { // Do not include `-` as part of the expected tokens list
6609 while self.eat(&dash) {
6610 fixed_crate_name = true;
6611 replacement.push((self.prev_span, "_".to_string()));
6612 idents.push(self.parse_ident()?);
6615 if fixed_crate_name {
6616 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6617 let mut fixed_name = format!("{}", ident.name);
6618 for part in idents {
6619 fixed_name.push_str(&format!("_{}", part.name));
6621 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6623 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6624 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6625 err.multipart_suggestion(suggestion_msg, replacement);
6631 /// Parse extern crate links
6635 /// extern crate foo;
6636 /// extern crate bar as foo;
6637 fn parse_item_extern_crate(&mut self,
6639 visibility: Visibility,
6640 attrs: Vec<Attribute>)
6641 -> PResult<'a, P<Item>> {
6642 // Accept `extern crate name-like-this` for better diagnostics
6643 let orig_name = self.parse_crate_name_with_dashes()?;
6644 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6645 (rename, Some(orig_name.name))
6649 self.expect(&token::Semi)?;
6651 let span = lo.to(self.prev_span);
6652 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6655 /// Parse `extern` for foreign ABIs
6658 /// `extern` is expected to have been
6659 /// consumed before calling this method
6665 fn parse_item_foreign_mod(&mut self,
6667 opt_abi: Option<Abi>,
6668 visibility: Visibility,
6669 mut attrs: Vec<Attribute>)
6670 -> PResult<'a, P<Item>> {
6671 self.expect(&token::OpenDelim(token::Brace))?;
6673 let abi = opt_abi.unwrap_or(Abi::C);
6675 attrs.extend(self.parse_inner_attributes()?);
6677 let mut foreign_items = vec![];
6678 while let Some(item) = self.parse_foreign_item()? {
6679 foreign_items.push(item);
6681 self.expect(&token::CloseDelim(token::Brace))?;
6683 let prev_span = self.prev_span;
6684 let m = ast::ForeignMod {
6686 items: foreign_items
6688 let invalid = keywords::Invalid.ident();
6689 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6692 /// Parse type Foo = Bar;
6694 /// existential type Foo: Bar;
6696 /// return None without modifying the parser state
6697 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6698 // This parses the grammar:
6699 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6700 if self.check_keyword(keywords::Type) ||
6701 self.check_keyword(keywords::Existential) &&
6702 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6703 let existential = self.eat_keyword(keywords::Existential);
6704 assert!(self.eat_keyword(keywords::Type));
6705 Some(self.parse_existential_or_alias(existential))
6711 /// Parse type alias or existential type
6712 fn parse_existential_or_alias(
6715 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6716 let ident = self.parse_ident()?;
6717 let mut tps = self.parse_generics()?;
6718 tps.where_clause = self.parse_where_clause()?;
6719 let alias = if existential {
6720 self.expect(&token::Colon)?;
6721 let bounds = self.parse_generic_bounds()?;
6722 AliasKind::Existential(bounds)
6724 self.expect(&token::Eq)?;
6725 let ty = self.parse_ty()?;
6728 self.expect(&token::Semi)?;
6729 Ok((ident, alias, tps))
6732 /// Parse the part of an "enum" decl following the '{'
6733 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6734 let mut variants = Vec::new();
6735 let mut all_nullary = true;
6736 let mut any_disr = None;
6737 while self.token != token::CloseDelim(token::Brace) {
6738 let variant_attrs = self.parse_outer_attributes()?;
6739 let vlo = self.span;
6742 let mut disr_expr = None;
6743 let ident = self.parse_ident()?;
6744 if self.check(&token::OpenDelim(token::Brace)) {
6745 // Parse a struct variant.
6746 all_nullary = false;
6747 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6748 ast::DUMMY_NODE_ID);
6749 } else if self.check(&token::OpenDelim(token::Paren)) {
6750 all_nullary = false;
6751 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6752 ast::DUMMY_NODE_ID);
6753 } else if self.eat(&token::Eq) {
6754 disr_expr = Some(AnonConst {
6755 id: ast::DUMMY_NODE_ID,
6756 value: self.parse_expr()?,
6758 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6759 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6761 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6764 let vr = ast::Variant_ {
6766 attrs: variant_attrs,
6770 variants.push(respan(vlo.to(self.prev_span), vr));
6772 if !self.eat(&token::Comma) { break; }
6774 self.expect(&token::CloseDelim(token::Brace))?;
6776 Some(disr_span) if !all_nullary =>
6777 self.span_err(disr_span,
6778 "discriminator values can only be used with a field-less enum"),
6782 Ok(ast::EnumDef { variants: variants })
6785 /// Parse an "enum" declaration
6786 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6787 let id = self.parse_ident()?;
6788 let mut generics = self.parse_generics()?;
6789 generics.where_clause = self.parse_where_clause()?;
6790 self.expect(&token::OpenDelim(token::Brace))?;
6792 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6793 self.recover_stmt();
6794 self.eat(&token::CloseDelim(token::Brace));
6797 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6800 /// Parses a string as an ABI spec on an extern type or module. Consumes
6801 /// the `extern` keyword, if one is found.
6802 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6804 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6806 self.expect_no_suffix(sp, "ABI spec", suf);
6808 match abi::lookup(&s.as_str()) {
6809 Some(abi) => Ok(Some(abi)),
6811 let prev_span = self.prev_span;
6812 let mut err = struct_span_err!(
6813 self.sess.span_diagnostic,
6816 "invalid ABI: found `{}`",
6818 err.span_label(prev_span, "invalid ABI");
6819 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6830 fn is_static_global(&mut self) -> bool {
6831 if self.check_keyword(keywords::Static) {
6832 // Check if this could be a closure
6833 !self.look_ahead(1, |token| {
6834 if token.is_keyword(keywords::Move) {
6838 token::BinOp(token::Or) | token::OrOr => true,
6849 attrs: Vec<Attribute>,
6850 macros_allowed: bool,
6851 attributes_allowed: bool,
6852 ) -> PResult<'a, Option<P<Item>>> {
6853 let (ret, tokens) = self.collect_tokens(|this| {
6854 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
6857 // Once we've parsed an item and recorded the tokens we got while
6858 // parsing we may want to store `tokens` into the item we're about to
6859 // return. Note, though, that we specifically didn't capture tokens
6860 // related to outer attributes. The `tokens` field here may later be
6861 // used with procedural macros to convert this item back into a token
6862 // stream, but during expansion we may be removing attributes as we go
6865 // If we've got inner attributes then the `tokens` we've got above holds
6866 // these inner attributes. If an inner attribute is expanded we won't
6867 // actually remove it from the token stream, so we'll just keep yielding
6868 // it (bad!). To work around this case for now we just avoid recording
6869 // `tokens` if we detect any inner attributes. This should help keep
6870 // expansion correct, but we should fix this bug one day!
6873 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6874 i.tokens = Some(tokens);
6881 /// Parse one of the items allowed by the flags.
6882 fn parse_item_implementation(
6884 attrs: Vec<Attribute>,
6885 macros_allowed: bool,
6886 attributes_allowed: bool,
6887 ) -> PResult<'a, Option<P<Item>>> {
6888 maybe_whole!(self, NtItem, |item| {
6889 let mut item = item.into_inner();
6890 let mut attrs = attrs;
6891 mem::swap(&mut item.attrs, &mut attrs);
6892 item.attrs.extend(attrs);
6898 let visibility = self.parse_visibility(false)?;
6900 if self.eat_keyword(keywords::Use) {
6902 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6903 self.expect(&token::Semi)?;
6905 let span = lo.to(self.prev_span);
6906 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6907 return Ok(Some(item));
6910 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6911 self.bump(); // `extern`
6912 if self.eat_keyword(keywords::Crate) {
6913 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6916 let opt_abi = self.parse_opt_abi()?;
6918 if self.eat_keyword(keywords::Fn) {
6919 // EXTERN FUNCTION ITEM
6920 let fn_span = self.prev_span;
6921 let abi = opt_abi.unwrap_or(Abi::C);
6922 let (ident, item_, extra_attrs) =
6923 self.parse_item_fn(Unsafety::Normal,
6925 respan(fn_span, Constness::NotConst),
6927 let prev_span = self.prev_span;
6928 let item = self.mk_item(lo.to(prev_span),
6932 maybe_append(attrs, extra_attrs));
6933 return Ok(Some(item));
6934 } else if self.check(&token::OpenDelim(token::Brace)) {
6935 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6941 if self.is_static_global() {
6944 let m = if self.eat_keyword(keywords::Mut) {
6947 Mutability::Immutable
6949 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6950 let prev_span = self.prev_span;
6951 let item = self.mk_item(lo.to(prev_span),
6955 maybe_append(attrs, extra_attrs));
6956 return Ok(Some(item));
6958 if self.eat_keyword(keywords::Const) {
6959 let const_span = self.prev_span;
6960 if self.check_keyword(keywords::Fn)
6961 || (self.check_keyword(keywords::Unsafe)
6962 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6963 // CONST FUNCTION ITEM
6964 let unsafety = self.parse_unsafety();
6966 let (ident, item_, extra_attrs) =
6967 self.parse_item_fn(unsafety,
6969 respan(const_span, Constness::Const),
6971 let prev_span = self.prev_span;
6972 let item = self.mk_item(lo.to(prev_span),
6976 maybe_append(attrs, extra_attrs));
6977 return Ok(Some(item));
6981 if self.eat_keyword(keywords::Mut) {
6982 let prev_span = self.prev_span;
6983 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6984 .help("did you mean to declare a static?")
6987 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6988 let prev_span = self.prev_span;
6989 let item = self.mk_item(lo.to(prev_span),
6993 maybe_append(attrs, extra_attrs));
6994 return Ok(Some(item));
6997 // `unsafe async fn` or `async fn`
6999 self.check_keyword(keywords::Unsafe) &&
7000 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7002 self.check_keyword(keywords::Async) &&
7003 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7006 // ASYNC FUNCTION ITEM
7007 let unsafety = self.parse_unsafety();
7008 self.expect_keyword(keywords::Async)?;
7009 self.expect_keyword(keywords::Fn)?;
7010 let fn_span = self.prev_span;
7011 let (ident, item_, extra_attrs) =
7012 self.parse_item_fn(unsafety,
7014 closure_id: ast::DUMMY_NODE_ID,
7015 return_impl_trait_id: ast::DUMMY_NODE_ID,
7017 respan(fn_span, Constness::NotConst),
7019 let prev_span = self.prev_span;
7020 let item = self.mk_item(lo.to(prev_span),
7024 maybe_append(attrs, extra_attrs));
7025 return Ok(Some(item));
7027 if self.check_keyword(keywords::Unsafe) &&
7028 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7029 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7031 // UNSAFE TRAIT ITEM
7032 self.bump(); // `unsafe`
7033 let is_auto = if self.eat_keyword(keywords::Trait) {
7036 self.expect_keyword(keywords::Auto)?;
7037 self.expect_keyword(keywords::Trait)?;
7040 let (ident, item_, extra_attrs) =
7041 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7042 let prev_span = self.prev_span;
7043 let item = self.mk_item(lo.to(prev_span),
7047 maybe_append(attrs, extra_attrs));
7048 return Ok(Some(item));
7050 if self.check_keyword(keywords::Impl) ||
7051 self.check_keyword(keywords::Unsafe) &&
7052 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7053 self.check_keyword(keywords::Default) &&
7054 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7055 self.check_keyword(keywords::Default) &&
7056 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7058 let defaultness = self.parse_defaultness();
7059 let unsafety = self.parse_unsafety();
7060 self.expect_keyword(keywords::Impl)?;
7061 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7062 let span = lo.to(self.prev_span);
7063 return Ok(Some(self.mk_item(span, ident, item, visibility,
7064 maybe_append(attrs, extra_attrs))));
7066 if self.check_keyword(keywords::Fn) {
7069 let fn_span = self.prev_span;
7070 let (ident, item_, extra_attrs) =
7071 self.parse_item_fn(Unsafety::Normal,
7073 respan(fn_span, Constness::NotConst),
7075 let prev_span = self.prev_span;
7076 let item = self.mk_item(lo.to(prev_span),
7080 maybe_append(attrs, extra_attrs));
7081 return Ok(Some(item));
7083 if self.check_keyword(keywords::Unsafe)
7084 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7085 // UNSAFE FUNCTION ITEM
7086 self.bump(); // `unsafe`
7087 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7088 self.check(&token::OpenDelim(token::Brace));
7089 let abi = if self.eat_keyword(keywords::Extern) {
7090 self.parse_opt_abi()?.unwrap_or(Abi::C)
7094 self.expect_keyword(keywords::Fn)?;
7095 let fn_span = self.prev_span;
7096 let (ident, item_, extra_attrs) =
7097 self.parse_item_fn(Unsafety::Unsafe,
7099 respan(fn_span, Constness::NotConst),
7101 let prev_span = self.prev_span;
7102 let item = self.mk_item(lo.to(prev_span),
7106 maybe_append(attrs, extra_attrs));
7107 return Ok(Some(item));
7109 if self.eat_keyword(keywords::Mod) {
7111 let (ident, item_, extra_attrs) =
7112 self.parse_item_mod(&attrs[..])?;
7113 let prev_span = self.prev_span;
7114 let item = self.mk_item(lo.to(prev_span),
7118 maybe_append(attrs, extra_attrs));
7119 return Ok(Some(item));
7121 if let Some(type_) = self.eat_type() {
7122 let (ident, alias, generics) = type_?;
7124 let item_ = match alias {
7125 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7126 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7128 let prev_span = self.prev_span;
7129 let item = self.mk_item(lo.to(prev_span),
7134 return Ok(Some(item));
7136 if self.eat_keyword(keywords::Enum) {
7138 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7139 let prev_span = self.prev_span;
7140 let item = self.mk_item(lo.to(prev_span),
7144 maybe_append(attrs, extra_attrs));
7145 return Ok(Some(item));
7147 if self.check_keyword(keywords::Trait)
7148 || (self.check_keyword(keywords::Auto)
7149 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7151 let is_auto = if self.eat_keyword(keywords::Trait) {
7154 self.expect_keyword(keywords::Auto)?;
7155 self.expect_keyword(keywords::Trait)?;
7159 let (ident, item_, extra_attrs) =
7160 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7161 let prev_span = self.prev_span;
7162 let item = self.mk_item(lo.to(prev_span),
7166 maybe_append(attrs, extra_attrs));
7167 return Ok(Some(item));
7169 if self.eat_keyword(keywords::Struct) {
7171 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7172 let prev_span = self.prev_span;
7173 let item = self.mk_item(lo.to(prev_span),
7177 maybe_append(attrs, extra_attrs));
7178 return Ok(Some(item));
7180 if self.is_union_item() {
7183 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7184 let prev_span = self.prev_span;
7185 let item = self.mk_item(lo.to(prev_span),
7189 maybe_append(attrs, extra_attrs));
7190 return Ok(Some(item));
7192 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7193 return Ok(Some(macro_def));
7196 // Verify whether we have encountered a struct or method definition where the user forgot to
7197 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7198 if visibility.node.is_pub() &&
7199 self.check_ident() &&
7200 self.look_ahead(1, |t| *t != token::Not)
7202 // Space between `pub` keyword and the identifier
7205 // ^^^ `sp` points here
7206 let sp = self.prev_span.between(self.span);
7207 let full_sp = self.prev_span.to(self.span);
7208 let ident_sp = self.span;
7209 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7210 // possible public struct definition where `struct` was forgotten
7211 let ident = self.parse_ident().unwrap();
7212 let msg = format!("add `struct` here to parse `{}` as a public struct",
7214 let mut err = self.diagnostic()
7215 .struct_span_err(sp, "missing `struct` for struct definition");
7216 err.span_suggestion_short_with_applicability(
7217 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7220 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7221 let ident = self.parse_ident().unwrap();
7222 self.consume_block(token::Paren);
7223 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7224 self.check(&token::OpenDelim(token::Brace))
7226 ("fn", "method", false)
7227 } else if self.check(&token::Colon) {
7231 ("fn` or `struct", "method or struct", true)
7234 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7235 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7237 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7241 err.span_suggestion_short_with_applicability(
7242 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7245 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7246 err.span_suggestion_with_applicability(
7248 "if you meant to call a macro, try",
7249 format!("{}!", snippet),
7250 // this is the `ambiguous` conditional branch
7251 Applicability::MaybeIncorrect
7254 err.help("if you meant to call a macro, remove the `pub` \
7255 and add a trailing `!` after the identifier");
7261 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7264 /// Parse a foreign item.
7265 crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
7266 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
7268 let attrs = self.parse_outer_attributes()?;
7270 let visibility = self.parse_visibility(false)?;
7272 // FOREIGN STATIC ITEM
7273 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7274 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7275 if self.token.is_keyword(keywords::Const) {
7277 .struct_span_err(self.span, "extern items cannot be `const`")
7278 .span_suggestion_with_applicability(
7280 "try using a static value",
7281 "static".to_owned(),
7282 Applicability::MachineApplicable
7285 self.bump(); // `static` or `const`
7286 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
7288 // FOREIGN FUNCTION ITEM
7289 if self.check_keyword(keywords::Fn) {
7290 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
7292 // FOREIGN TYPE ITEM
7293 if self.check_keyword(keywords::Type) {
7294 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
7297 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7301 ident: keywords::Invalid.ident(),
7302 span: lo.to(self.prev_span),
7303 id: ast::DUMMY_NODE_ID,
7306 node: ForeignItemKind::Macro(mac),
7311 if !attrs.is_empty() {
7312 self.expected_item_err(&attrs);
7320 /// This is the fall-through for parsing items.
7321 fn parse_macro_use_or_failure(
7323 attrs: Vec<Attribute> ,
7324 macros_allowed: bool,
7325 attributes_allowed: bool,
7327 visibility: Visibility
7328 ) -> PResult<'a, Option<P<Item>>> {
7329 if macros_allowed && self.token.is_path_start() {
7330 // MACRO INVOCATION ITEM
7332 let prev_span = self.prev_span;
7333 self.complain_if_pub_macro(&visibility.node, prev_span);
7335 let mac_lo = self.span;
7338 let pth = self.parse_path(PathStyle::Mod)?;
7339 self.expect(&token::Not)?;
7341 // a 'special' identifier (like what `macro_rules!` uses)
7342 // is optional. We should eventually unify invoc syntax
7344 let id = if self.token.is_ident() {
7347 keywords::Invalid.ident() // no special identifier
7349 // eat a matched-delimiter token tree:
7350 let (delim, tts) = self.expect_delimited_token_tree()?;
7351 if delim != MacDelimiter::Brace {
7352 if !self.eat(&token::Semi) {
7353 self.span_err(self.prev_span,
7354 "macros that expand to items must either \
7355 be surrounded with braces or followed by \
7360 let hi = self.prev_span;
7361 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7362 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7363 return Ok(Some(item));
7366 // FAILURE TO PARSE ITEM
7367 match visibility.node {
7368 VisibilityKind::Inherited => {}
7370 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7374 if !attributes_allowed && !attrs.is_empty() {
7375 self.expected_item_err(&attrs);
7380 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7381 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7382 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7384 if self.token.is_path_start() && !self.is_extern_non_path() {
7385 let prev_span = self.prev_span;
7387 let pth = self.parse_path(PathStyle::Mod)?;
7389 if pth.segments.len() == 1 {
7390 if !self.eat(&token::Not) {
7391 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7394 self.expect(&token::Not)?;
7397 if let Some(vis) = vis {
7398 self.complain_if_pub_macro(&vis.node, prev_span);
7403 // eat a matched-delimiter token tree:
7404 let (delim, tts) = self.expect_delimited_token_tree()?;
7405 if delim != MacDelimiter::Brace {
7406 self.expect(&token::Semi)?
7409 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7415 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7416 where F: FnOnce(&mut Self) -> PResult<'a, R>
7418 // Record all tokens we parse when parsing this item.
7419 let mut tokens = Vec::new();
7420 let prev_collecting = match self.token_cursor.frame.last_token {
7421 LastToken::Collecting(ref mut list) => {
7422 Some(mem::replace(list, Vec::new()))
7424 LastToken::Was(ref mut last) => {
7425 tokens.extend(last.take());
7429 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7430 let prev = self.token_cursor.stack.len();
7432 let last_token = if self.token_cursor.stack.len() == prev {
7433 &mut self.token_cursor.frame.last_token
7435 &mut self.token_cursor.stack[prev].last_token
7438 // Pull our the toekns that we've collected from the call to `f` above
7439 let mut collected_tokens = match *last_token {
7440 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7441 LastToken::Was(_) => panic!("our vector went away?"),
7444 // If we're not at EOF our current token wasn't actually consumed by
7445 // `f`, but it'll still be in our list that we pulled out. In that case
7447 let extra_token = if self.token != token::Eof {
7448 collected_tokens.pop()
7453 // If we were previously collecting tokens, then this was a recursive
7454 // call. In that case we need to record all the tokens we collected in
7455 // our parent list as well. To do that we push a clone of our stream
7456 // onto the previous list.
7457 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7458 match prev_collecting {
7460 list.push(stream.clone());
7461 list.extend(extra_token);
7462 *last_token = LastToken::Collecting(list);
7465 *last_token = LastToken::Was(extra_token);
7472 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7473 let attrs = self.parse_outer_attributes()?;
7474 self.parse_item_(attrs, true, false)
7478 fn is_import_coupler(&mut self) -> bool {
7479 self.check(&token::ModSep) &&
7480 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7481 *t == token::BinOp(token::Star))
7486 /// USE_TREE = [`::`] `*` |
7487 /// [`::`] `{` USE_TREE_LIST `}` |
7489 /// PATH `::` `{` USE_TREE_LIST `}` |
7490 /// PATH [`as` IDENT]
7491 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7494 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7495 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7496 self.check(&token::BinOp(token::Star)) ||
7497 self.is_import_coupler() {
7498 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7499 if self.eat(&token::ModSep) {
7500 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7503 if self.eat(&token::BinOp(token::Star)) {
7506 UseTreeKind::Nested(self.parse_use_tree_list()?)
7509 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7510 prefix = self.parse_path(PathStyle::Mod)?;
7512 if self.eat(&token::ModSep) {
7513 if self.eat(&token::BinOp(token::Star)) {
7516 UseTreeKind::Nested(self.parse_use_tree_list()?)
7519 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7523 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7526 /// Parse UseTreeKind::Nested(list)
7528 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7529 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7530 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7531 &token::CloseDelim(token::Brace),
7532 SeqSep::trailing_allowed(token::Comma), |this| {
7533 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7537 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7538 if self.eat_keyword(keywords::As) {
7540 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7542 Ok(Some(ident.gensym()))
7544 _ => self.parse_ident().map(Some),
7551 /// Parses a source module as a crate. This is the main
7552 /// entry point for the parser.
7553 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7556 attrs: self.parse_inner_attributes()?,
7557 module: self.parse_mod_items(&token::Eof, lo)?,
7558 span: lo.to(self.span),
7562 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7563 let ret = match self.token {
7564 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7565 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7572 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7573 match self.parse_optional_str() {
7574 Some((s, style, suf)) => {
7575 let sp = self.prev_span;
7576 self.expect_no_suffix(sp, "string literal", suf);
7580 let msg = "expected string literal";
7581 let mut err = self.fatal(msg);
7582 err.span_label(self.span, msg);