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, 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(self.span, "remove this comma", String::new());
795 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
796 self.parse_ident_common(true)
799 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
801 token::Ident(ident, _) => {
802 if self.token.is_reserved_ident() {
803 let mut err = self.expected_ident_found();
810 let span = self.span;
812 Ok(Ident::new(ident.name, span))
815 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
816 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
818 self.expected_ident_found()
824 /// Check if the next token is `tok`, and return `true` if so.
826 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
828 crate fn check(&mut self, tok: &token::Token) -> bool {
829 let is_present = self.token == *tok;
830 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
834 /// Consume token 'tok' if it exists. Returns true if the given
835 /// token was present, false otherwise.
836 pub fn eat(&mut self, tok: &token::Token) -> bool {
837 let is_present = self.check(tok);
838 if is_present { self.bump() }
842 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
843 self.expected_tokens.push(TokenType::Keyword(kw));
844 self.token.is_keyword(kw)
847 /// If the next token is the given keyword, eat it and return
848 /// true. Otherwise, return false.
849 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
850 if self.check_keyword(kw) {
858 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
859 if self.token.is_keyword(kw) {
867 /// If the given word is not a keyword, signal an error.
868 /// If the next token is not the given word, signal an error.
869 /// Otherwise, eat it.
870 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
871 if !self.eat_keyword(kw) {
878 fn check_ident(&mut self) -> bool {
879 if self.token.is_ident() {
882 self.expected_tokens.push(TokenType::Ident);
887 fn check_path(&mut self) -> bool {
888 if self.token.is_path_start() {
891 self.expected_tokens.push(TokenType::Path);
896 fn check_type(&mut self) -> bool {
897 if self.token.can_begin_type() {
900 self.expected_tokens.push(TokenType::Type);
905 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
906 /// and continue. If a `+` is not seen, return false.
908 /// This is using when token splitting += into +.
909 /// See issue 47856 for an example of when this may occur.
910 fn eat_plus(&mut self) -> bool {
911 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
913 token::BinOp(token::Plus) => {
917 token::BinOpEq(token::Plus) => {
918 let span = self.span.with_lo(self.span.lo() + BytePos(1));
919 self.bump_with(token::Eq, span);
927 /// Checks to see if the next token is either `+` or `+=`.
928 /// Otherwise returns false.
929 fn check_plus(&mut self) -> bool {
930 if self.token.is_like_plus() {
934 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
939 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
940 /// `&` and continue. If an `&` is not seen, signal an error.
941 fn expect_and(&mut self) -> PResult<'a, ()> {
942 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
944 token::BinOp(token::And) => {
949 let span = self.span.with_lo(self.span.lo() + BytePos(1));
950 Ok(self.bump_with(token::BinOp(token::And), span))
952 _ => self.unexpected()
956 /// Expect and consume an `|`. If `||` is seen, replace it with a single
957 /// `|` and continue. If an `|` is not seen, signal an error.
958 fn expect_or(&mut self) -> PResult<'a, ()> {
959 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
961 token::BinOp(token::Or) => {
966 let span = self.span.with_lo(self.span.lo() + BytePos(1));
967 Ok(self.bump_with(token::BinOp(token::Or), span))
969 _ => self.unexpected()
973 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
975 None => {/* everything ok */}
977 let text = suf.as_str();
979 self.span_bug(sp, "found empty literal suffix in Some")
981 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
986 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
987 /// `<` and continue. If a `<` is not seen, return false.
989 /// This is meant to be used when parsing generics on a path to get the
991 fn eat_lt(&mut self) -> bool {
992 self.expected_tokens.push(TokenType::Token(token::Lt));
998 token::BinOp(token::Shl) => {
999 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1000 self.bump_with(token::Lt, span);
1007 fn expect_lt(&mut self) -> PResult<'a, ()> {
1015 /// Expect and consume a GT. if a >> is seen, replace it
1016 /// with a single > and continue. If a GT is not seen,
1017 /// signal an error.
1018 fn expect_gt(&mut self) -> PResult<'a, ()> {
1019 self.expected_tokens.push(TokenType::Token(token::Gt));
1025 token::BinOp(token::Shr) => {
1026 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1027 Ok(self.bump_with(token::Gt, span))
1029 token::BinOpEq(token::Shr) => {
1030 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1031 Ok(self.bump_with(token::Ge, span))
1034 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1035 Ok(self.bump_with(token::Eq, span))
1037 _ => self.unexpected()
1041 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1042 /// passes through any errors encountered. Used for error recovery.
1043 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1044 let handler = self.diagnostic();
1046 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1048 TokenExpectType::Expect,
1049 |p| Ok(p.parse_token_tree())) {
1050 handler.cancel(err);
1054 /// Parse a sequence, including the closing delimiter. The function
1055 /// f must consume tokens until reaching the next separator or
1056 /// closing bracket.
1057 pub fn parse_seq_to_end<T, F>(&mut self,
1061 -> PResult<'a, Vec<T>> where
1062 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1064 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1069 /// Parse a sequence, not including the closing delimiter. The function
1070 /// f must consume tokens until reaching the next separator or
1071 /// closing bracket.
1072 pub fn parse_seq_to_before_end<T, F>(&mut self,
1076 -> PResult<'a, Vec<T>>
1077 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1079 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1082 fn parse_seq_to_before_tokens<T, F>(
1084 kets: &[&token::Token],
1086 expect: TokenExpectType,
1088 ) -> PResult<'a, Vec<T>>
1089 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1091 let mut first: bool = true;
1093 while !kets.iter().any(|k| {
1095 TokenExpectType::Expect => self.check(k),
1096 TokenExpectType::NoExpect => self.token == **k,
1100 token::CloseDelim(..) | token::Eof => break,
1103 if let Some(ref t) = sep.sep {
1107 if let Err(mut e) = self.expect(t) {
1108 // Attempt to keep parsing if it was a similar separator
1109 if let Some(ref tokens) = t.similar_tokens() {
1110 if tokens.contains(&self.token) {
1115 // Attempt to keep parsing if it was an omitted separator
1129 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1131 TokenExpectType::Expect => self.check(k),
1132 TokenExpectType::NoExpect => self.token == **k,
1145 /// Parse a sequence, including the closing delimiter. The function
1146 /// f must consume tokens until reaching the next separator or
1147 /// closing bracket.
1148 fn parse_unspanned_seq<T, F>(&mut self,
1153 -> PResult<'a, Vec<T>> where
1154 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1157 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1158 if self.token == *ket {
1164 /// Advance the parser by one token
1165 pub fn bump(&mut self) {
1166 if self.prev_token_kind == PrevTokenKind::Eof {
1167 // Bumping after EOF is a bad sign, usually an infinite loop.
1168 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1171 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1173 // Record last token kind for possible error recovery.
1174 self.prev_token_kind = match self.token {
1175 token::DocComment(..) => PrevTokenKind::DocComment,
1176 token::Comma => PrevTokenKind::Comma,
1177 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1178 token::Interpolated(..) => PrevTokenKind::Interpolated,
1179 token::Eof => PrevTokenKind::Eof,
1180 token::Ident(..) => PrevTokenKind::Ident,
1181 _ => PrevTokenKind::Other,
1184 let next = self.next_tok();
1185 self.span = next.sp;
1186 self.token = next.tok;
1187 self.expected_tokens.clear();
1188 // check after each token
1189 self.process_potential_macro_variable();
1192 /// Advance the parser using provided token as a next one. Use this when
1193 /// consuming a part of a token. For example a single `<` from `<<`.
1194 fn bump_with(&mut self, next: token::Token, span: Span) {
1195 self.prev_span = self.span.with_hi(span.lo());
1196 // It would be incorrect to record the kind of the current token, but
1197 // fortunately for tokens currently using `bump_with`, the
1198 // prev_token_kind will be of no use anyway.
1199 self.prev_token_kind = PrevTokenKind::Other;
1202 self.expected_tokens.clear();
1205 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1206 F: FnOnce(&token::Token) -> R,
1209 return f(&self.token)
1212 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1213 Some(tree) => match tree {
1214 TokenTree::Token(_, tok) => tok,
1215 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1217 None => token::CloseDelim(self.token_cursor.frame.delim),
1221 fn look_ahead_span(&self, dist: usize) -> Span {
1226 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1227 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1228 None => self.look_ahead_span(dist - 1),
1231 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1232 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1234 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1235 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1237 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1238 err.span_err(sp, self.diagnostic())
1240 fn bug(&self, m: &str) -> ! {
1241 self.sess.span_diagnostic.span_bug(self.span, m)
1243 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1244 self.sess.span_diagnostic.span_err(sp, m)
1246 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1247 self.sess.span_diagnostic.struct_span_err(sp, m)
1249 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1250 self.sess.span_diagnostic.span_bug(sp, m)
1252 crate fn abort_if_errors(&self) {
1253 self.sess.span_diagnostic.abort_if_errors();
1256 fn cancel(&self, err: &mut DiagnosticBuilder) {
1257 self.sess.span_diagnostic.cancel(err)
1260 crate fn diagnostic(&self) -> &'a errors::Handler {
1261 &self.sess.span_diagnostic
1264 /// Is the current token one of the keywords that signals a bare function
1266 fn token_is_bare_fn_keyword(&mut self) -> bool {
1267 self.check_keyword(keywords::Fn) ||
1268 self.check_keyword(keywords::Unsafe) ||
1269 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1272 /// parse a TyKind::BareFn type:
1273 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1276 [unsafe] [extern "ABI"] fn (S) -> T
1286 let unsafety = self.parse_unsafety();
1287 let abi = if self.eat_keyword(keywords::Extern) {
1288 self.parse_opt_abi()?.unwrap_or(Abi::C)
1293 self.expect_keyword(keywords::Fn)?;
1294 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1295 let ret_ty = self.parse_ret_ty(false)?;
1296 let decl = P(FnDecl {
1301 Ok(TyKind::BareFn(P(BareFnTy {
1309 /// Parse asyncness: `async` or nothing
1310 fn parse_asyncness(&mut self) -> IsAsync {
1311 if self.eat_keyword(keywords::Async) {
1313 closure_id: ast::DUMMY_NODE_ID,
1314 return_impl_trait_id: ast::DUMMY_NODE_ID,
1321 /// Parse unsafety: `unsafe` or nothing.
1322 fn parse_unsafety(&mut self) -> Unsafety {
1323 if self.eat_keyword(keywords::Unsafe) {
1330 /// Parse the items in a trait declaration
1331 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1332 maybe_whole!(self, NtTraitItem, |x| x);
1333 let attrs = self.parse_outer_attributes()?;
1334 let (mut item, tokens) = self.collect_tokens(|this| {
1335 this.parse_trait_item_(at_end, attrs)
1337 // See `parse_item` for why this clause is here.
1338 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1339 item.tokens = Some(tokens);
1344 fn parse_trait_item_(&mut self,
1346 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1349 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1350 self.parse_trait_item_assoc_ty()?
1351 } else if self.is_const_item() {
1352 self.expect_keyword(keywords::Const)?;
1353 let ident = self.parse_ident()?;
1354 self.expect(&token::Colon)?;
1355 let ty = self.parse_ty()?;
1356 let default = if self.check(&token::Eq) {
1358 let expr = self.parse_expr()?;
1359 self.expect(&token::Semi)?;
1362 self.expect(&token::Semi)?;
1365 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1366 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1367 // trait item macro.
1368 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1370 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1372 let ident = self.parse_ident()?;
1373 let mut generics = self.parse_generics()?;
1375 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1376 // This is somewhat dubious; We don't want to allow
1377 // argument names to be left off if there is a
1380 // We don't allow argument names to be left off in edition 2018.
1381 if p.span.edition() >= Edition::Edition2018 {
1382 p.parse_arg_general(true)
1384 p.parse_arg_general(false)
1387 generics.where_clause = self.parse_where_clause()?;
1389 let sig = ast::MethodSig {
1399 let body = match self.token {
1403 debug!("parse_trait_methods(): parsing required method");
1406 token::OpenDelim(token::Brace) => {
1407 debug!("parse_trait_methods(): parsing provided method");
1409 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1410 attrs.extend(inner_attrs.iter().cloned());
1414 let token_str = self.this_token_to_string();
1415 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1417 err.span_label(self.span, "expected `;` or `{`");
1421 (ident, ast::TraitItemKind::Method(sig, body), generics)
1425 id: ast::DUMMY_NODE_ID,
1430 span: lo.to(self.prev_span),
1435 /// Parse optional return type [ -> TY ] in function decl
1436 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1437 if self.eat(&token::RArrow) {
1438 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1440 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1445 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1446 self.parse_ty_common(true, true)
1449 /// Parse a type in restricted contexts where `+` is not permitted.
1450 /// Example 1: `&'a TYPE`
1451 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1452 /// Example 2: `value1 as TYPE + value2`
1453 /// `+` is prohibited to avoid interactions with expression grammar.
1454 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1455 self.parse_ty_common(false, true)
1458 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1459 -> PResult<'a, P<Ty>> {
1460 maybe_whole!(self, NtTy, |x| x);
1463 let mut impl_dyn_multi = false;
1464 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1465 // `(TYPE)` is a parenthesized type.
1466 // `(TYPE,)` is a tuple with a single field of type TYPE.
1467 let mut ts = vec![];
1468 let mut last_comma = false;
1469 while self.token != token::CloseDelim(token::Paren) {
1470 ts.push(self.parse_ty()?);
1471 if self.eat(&token::Comma) {
1478 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1479 self.expect(&token::CloseDelim(token::Paren))?;
1481 if ts.len() == 1 && !last_comma {
1482 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1483 let maybe_bounds = allow_plus && self.token.is_like_plus();
1485 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1486 TyKind::Path(None, ref path) if maybe_bounds => {
1487 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1489 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1490 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1491 let path = match bounds[0] {
1492 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1493 _ => self.bug("unexpected lifetime bound"),
1495 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1498 _ => TyKind::Paren(P(ty))
1503 } else if self.eat(&token::Not) {
1506 } else if self.eat(&token::BinOp(token::Star)) {
1508 TyKind::Ptr(self.parse_ptr()?)
1509 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1511 let t = self.parse_ty()?;
1512 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1513 let t = match self.maybe_parse_fixed_length_of_vec()? {
1514 None => TyKind::Slice(t),
1515 Some(length) => TyKind::Array(t, AnonConst {
1516 id: ast::DUMMY_NODE_ID,
1520 self.expect(&token::CloseDelim(token::Bracket))?;
1522 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1525 self.parse_borrowed_pointee()?
1526 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1528 // In order to not be ambiguous, the type must be surrounded by parens.
1529 self.expect(&token::OpenDelim(token::Paren))?;
1531 id: ast::DUMMY_NODE_ID,
1532 value: self.parse_expr()?,
1534 self.expect(&token::CloseDelim(token::Paren))?;
1536 } else if self.eat_keyword(keywords::Underscore) {
1537 // A type to be inferred `_`
1539 } else if self.token_is_bare_fn_keyword() {
1540 // Function pointer type
1541 self.parse_ty_bare_fn(Vec::new())?
1542 } else if self.check_keyword(keywords::For) {
1543 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1544 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1545 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1547 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1548 if self.token_is_bare_fn_keyword() {
1549 self.parse_ty_bare_fn(lifetime_defs)?
1551 let path = self.parse_path(PathStyle::Type)?;
1552 let parse_plus = allow_plus && self.check_plus();
1553 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1555 } else if self.eat_keyword(keywords::Impl) {
1556 // Always parse bounds greedily for better error recovery.
1557 let bounds = self.parse_generic_bounds()?;
1558 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1559 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1560 } else if self.check_keyword(keywords::Dyn) &&
1561 self.look_ahead(1, |t| t.can_begin_bound() &&
1562 !can_continue_type_after_non_fn_ident(t)) {
1563 self.bump(); // `dyn`
1564 // Always parse bounds greedily for better error recovery.
1565 let bounds = self.parse_generic_bounds()?;
1566 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1567 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1568 } else if self.check(&token::Question) ||
1569 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1570 // Bound list (trait object type)
1571 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1572 TraitObjectSyntax::None)
1573 } else if self.eat_lt() {
1575 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1576 TyKind::Path(Some(qself), path)
1577 } else if self.token.is_path_start() {
1579 let path = self.parse_path(PathStyle::Type)?;
1580 if self.eat(&token::Not) {
1581 // Macro invocation in type position
1582 let (delim, tts) = self.expect_delimited_token_tree()?;
1583 let node = Mac_ { path, tts, delim };
1584 TyKind::Mac(respan(lo.to(self.prev_span), node))
1586 // Just a type path or bound list (trait object type) starting with a trait.
1588 // `Trait1 + Trait2 + 'a`
1589 if allow_plus && self.check_plus() {
1590 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1592 TyKind::Path(None, path)
1596 let msg = format!("expected type, found {}", self.this_token_descr());
1597 return Err(self.fatal(&msg));
1600 let span = lo.to(self.prev_span);
1601 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1603 // Try to recover from use of `+` with incorrect priority.
1604 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1605 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1606 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1611 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1612 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1613 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1614 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1616 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1617 bounds.append(&mut self.parse_generic_bounds()?);
1619 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1622 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1623 if !allow_plus && impl_dyn_multi {
1624 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1625 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1626 .span_suggestion_with_applicability(
1628 "use parentheses to disambiguate",
1630 Applicability::MachineApplicable
1635 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1636 // Do not add `+` to expected tokens.
1637 if !allow_plus || !self.token.is_like_plus() {
1642 let bounds = self.parse_generic_bounds()?;
1643 let sum_span = ty.span.to(self.prev_span);
1645 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1646 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1649 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1650 let sum_with_parens = pprust::to_string(|s| {
1651 use print::pprust::PrintState;
1654 s.print_opt_lifetime(lifetime)?;
1655 s.print_mutability(mut_ty.mutbl)?;
1657 s.print_type(&mut_ty.ty)?;
1658 s.print_type_bounds(" +", &bounds)?;
1661 err.span_suggestion_with_applicability(
1663 "try adding parentheses",
1665 Applicability::MachineApplicable
1668 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1669 err.span_label(sum_span, "perhaps you forgot parentheses?");
1672 err.span_label(sum_span, "expected a path");
1679 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1680 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1682 // Do not add `::` to expected tokens.
1683 if !allow_recovery || self.token != token::ModSep {
1686 let ty = match base.to_ty() {
1688 None => return Ok(base),
1691 self.bump(); // `::`
1692 let mut segments = Vec::new();
1693 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1695 let span = ty.span.to(self.prev_span);
1696 let path_span = span.to(span); // use an empty path since `position` == 0
1697 let recovered = base.to_recovered(
1698 Some(QSelf { ty, path_span, position: 0 }),
1699 ast::Path { segments, span },
1703 .struct_span_err(span, "missing angle brackets in associated item path")
1704 .span_suggestion_with_applicability( // this is a best-effort recovery
1705 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1711 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1712 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1713 let mutbl = self.parse_mutability();
1714 let ty = self.parse_ty_no_plus()?;
1715 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1718 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1719 let mutbl = if self.eat_keyword(keywords::Mut) {
1721 } else if self.eat_keyword(keywords::Const) {
1722 Mutability::Immutable
1724 let span = self.prev_span;
1726 "expected mut or const in raw pointer type (use \
1727 `*mut T` or `*const T` as appropriate)");
1728 Mutability::Immutable
1730 let t = self.parse_ty_no_plus()?;
1731 Ok(MutTy { ty: t, mutbl: mutbl })
1734 fn is_named_argument(&mut self) -> bool {
1735 let offset = match self.token {
1736 token::Interpolated(ref nt) => match nt.0 {
1737 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1740 token::BinOp(token::And) | token::AndAnd => 1,
1741 _ if self.token.is_keyword(keywords::Mut) => 1,
1745 self.look_ahead(offset, |t| t.is_ident()) &&
1746 self.look_ahead(offset + 1, |t| t == &token::Colon)
1749 /// This version of parse arg doesn't necessarily require
1750 /// identifier names.
1751 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1752 maybe_whole!(self, NtArg, |x| x);
1754 let (pat, ty) = if require_name || self.is_named_argument() {
1755 debug!("parse_arg_general parse_pat (require_name:{})",
1757 let pat = self.parse_pat()?;
1759 self.expect(&token::Colon)?;
1760 (pat, self.parse_ty()?)
1762 debug!("parse_arg_general ident_to_pat");
1764 let parser_snapshot_before_pat = self.clone();
1766 // Once we can use edition 2018 in the compiler,
1767 // replace this with real try blocks.
1768 macro_rules! try_block {
1769 ($($inside:tt)*) => (
1770 (||{ ::std::ops::Try::from_ok({ $($inside)* }) })()
1774 // We're going to try parsing the argument as a pattern (even though it's not
1775 // allowed). This way we can provide better errors to the user.
1776 let pat_arg: PResult<'a, _> = try_block! {
1777 let pat = self.parse_pat()?;
1778 self.expect(&token::Colon)?;
1779 (pat, self.parse_ty()?)
1784 let mut err = self.diagnostic().struct_span_err_with_code(
1786 "patterns aren't allowed in methods without bodies",
1787 DiagnosticId::Error("E0642".into()),
1789 err.span_suggestion_short_with_applicability(
1791 "give this argument a name or use an underscore to ignore it",
1793 Applicability::MachineApplicable,
1796 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1798 node: PatKind::Wild,
1800 id: ast::DUMMY_NODE_ID
1806 // Recover from attempting to parse the argument as a pattern. This means
1807 // the type is alone, with no name, e.g. `fn foo(u32)`.
1808 mem::replace(self, parser_snapshot_before_pat);
1809 debug!("parse_arg_general ident_to_pat");
1810 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1811 let ty = self.parse_ty()?;
1813 id: ast::DUMMY_NODE_ID,
1814 node: PatKind::Ident(
1815 BindingMode::ByValue(Mutability::Immutable), ident, None),
1823 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1826 /// Parse a single function argument
1827 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1828 self.parse_arg_general(true)
1831 /// Parse an argument in a lambda header e.g. |arg, arg|
1832 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1833 let pat = self.parse_pat()?;
1834 let t = if self.eat(&token::Colon) {
1838 id: ast::DUMMY_NODE_ID,
1839 node: TyKind::Infer,
1846 id: ast::DUMMY_NODE_ID
1850 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1851 if self.eat(&token::Semi) {
1852 Ok(Some(self.parse_expr()?))
1858 /// Matches token_lit = LIT_INTEGER | ...
1859 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1860 let out = match self.token {
1861 token::Interpolated(ref nt) => match nt.0 {
1862 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1863 ExprKind::Lit(ref lit) => { lit.node.clone() }
1864 _ => { return self.unexpected_last(&self.token); }
1866 _ => { return self.unexpected_last(&self.token); }
1868 token::Literal(lit, suf) => {
1869 let diag = Some((self.span, &self.sess.span_diagnostic));
1870 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1874 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1879 _ => { return self.unexpected_last(&self.token); }
1886 /// Matches lit = true | false | token_lit
1887 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1889 let lit = if self.eat_keyword(keywords::True) {
1891 } else if self.eat_keyword(keywords::False) {
1892 LitKind::Bool(false)
1894 let lit = self.parse_lit_token()?;
1897 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
1900 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1901 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1902 maybe_whole_expr!(self);
1904 let minus_lo = self.span;
1905 let minus_present = self.eat(&token::BinOp(token::Minus));
1907 let literal = P(self.parse_lit()?);
1908 let hi = self.prev_span;
1909 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1912 let minus_hi = self.prev_span;
1913 let unary = self.mk_unary(UnOp::Neg, expr);
1914 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1920 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1922 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1923 let span = self.span;
1925 Ok(Ident::new(ident.name, span))
1927 _ => self.parse_ident(),
1931 /// Parses qualified path.
1932 /// Assumes that the leading `<` has been parsed already.
1934 /// `qualified_path = <type [as trait_ref]>::path`
1939 /// `<T as U>::F::a<S>` (without disambiguator)
1940 /// `<T as U>::F::a::<S>` (with disambiguator)
1941 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1942 let lo = self.prev_span;
1943 let ty = self.parse_ty()?;
1945 // `path` will contain the prefix of the path up to the `>`,
1946 // if any (e.g., `U` in the `<T as U>::*` examples
1947 // above). `path_span` has the span of that path, or an empty
1948 // span in the case of something like `<T>::Bar`.
1949 let (mut path, path_span);
1950 if self.eat_keyword(keywords::As) {
1951 let path_lo = self.span;
1952 path = self.parse_path(PathStyle::Type)?;
1953 path_span = path_lo.to(self.prev_span);
1955 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1956 path_span = self.span.to(self.span);
1959 self.expect(&token::Gt)?;
1960 self.expect(&token::ModSep)?;
1962 let qself = QSelf { ty, path_span, position: path.segments.len() };
1963 self.parse_path_segments(&mut path.segments, style, true)?;
1965 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1968 /// Parses simple paths.
1970 /// `path = [::] segment+`
1971 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1974 /// `a::b::C<D>` (without disambiguator)
1975 /// `a::b::C::<D>` (with disambiguator)
1976 /// `Fn(Args)` (without disambiguator)
1977 /// `Fn::(Args)` (with disambiguator)
1978 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1979 self.parse_path_common(style, true)
1982 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1983 -> PResult<'a, ast::Path> {
1984 maybe_whole!(self, NtPath, |path| {
1985 if style == PathStyle::Mod &&
1986 path.segments.iter().any(|segment| segment.args.is_some()) {
1987 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1992 let lo = self.meta_var_span.unwrap_or(self.span);
1993 let mut segments = Vec::new();
1994 if self.eat(&token::ModSep) {
1995 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1997 self.parse_path_segments(&mut segments, style, enable_warning)?;
1999 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2002 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2003 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2004 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2005 let meta_ident = match self.token {
2006 token::Interpolated(ref nt) => match nt.0 {
2007 token::NtMeta(ref meta) => match meta.node {
2008 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2015 if let Some(path) = meta_ident {
2019 self.parse_path(style)
2022 fn parse_path_segments(&mut self,
2023 segments: &mut Vec<PathSegment>,
2025 enable_warning: bool)
2026 -> PResult<'a, ()> {
2028 segments.push(self.parse_path_segment(style, enable_warning)?);
2030 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2036 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2037 -> PResult<'a, PathSegment> {
2038 let ident = self.parse_path_segment_ident()?;
2040 let is_args_start = |token: &token::Token| match *token {
2041 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2044 let check_args_start = |this: &mut Self| {
2045 this.expected_tokens.extend_from_slice(
2046 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2048 is_args_start(&this.token)
2051 Ok(if style == PathStyle::Type && check_args_start(self) ||
2052 style != PathStyle::Mod && self.check(&token::ModSep)
2053 && self.look_ahead(1, |t| is_args_start(t)) {
2054 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2056 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2057 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2058 .span_label(self.prev_span, "try removing `::`").emit();
2061 let args = if self.eat_lt() {
2063 let (args, bindings) = self.parse_generic_args()?;
2065 let span = lo.to(self.prev_span);
2066 AngleBracketedArgs { args, bindings, span }.into()
2070 let inputs = self.parse_seq_to_before_tokens(
2071 &[&token::CloseDelim(token::Paren)],
2072 SeqSep::trailing_allowed(token::Comma),
2073 TokenExpectType::Expect,
2076 let span = lo.to(self.prev_span);
2077 let output = if self.eat(&token::RArrow) {
2078 Some(self.parse_ty_common(false, false)?)
2082 ParenthesisedArgs { inputs, output, span }.into()
2085 PathSegment { ident, args }
2087 // Generic arguments are not found.
2088 PathSegment::from_ident(ident)
2092 crate fn check_lifetime(&mut self) -> bool {
2093 self.expected_tokens.push(TokenType::Lifetime);
2094 self.token.is_lifetime()
2097 /// Parse single lifetime 'a or panic.
2098 crate fn expect_lifetime(&mut self) -> Lifetime {
2099 if let Some(ident) = self.token.lifetime() {
2100 let span = self.span;
2102 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2104 self.span_bug(self.span, "not a lifetime")
2108 fn eat_label(&mut self) -> Option<Label> {
2109 if let Some(ident) = self.token.lifetime() {
2110 let span = self.span;
2112 Some(Label { ident: Ident::new(ident.name, span) })
2118 /// Parse mutability (`mut` or nothing).
2119 fn parse_mutability(&mut self) -> Mutability {
2120 if self.eat_keyword(keywords::Mut) {
2123 Mutability::Immutable
2127 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2128 if let token::Literal(token::Integer(name), None) = self.token {
2130 Ok(Ident::new(name, self.prev_span))
2132 self.parse_ident_common(false)
2136 /// Parse ident (COLON expr)?
2137 fn parse_field(&mut self) -> PResult<'a, Field> {
2138 let attrs = self.parse_outer_attributes()?;
2141 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2142 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2143 let fieldname = self.parse_field_name()?;
2145 (fieldname, self.parse_expr()?, false)
2147 let fieldname = self.parse_ident_common(false)?;
2149 // Mimic `x: x` for the `x` field shorthand.
2150 let path = ast::Path::from_ident(fieldname);
2151 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2152 (fieldname, expr, true)
2156 span: lo.to(expr.span),
2159 attrs: attrs.into(),
2163 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2164 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2167 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2168 ExprKind::Unary(unop, expr)
2171 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2172 ExprKind::Binary(binop, lhs, rhs)
2175 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2176 ExprKind::Call(f, args)
2179 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2180 ExprKind::Index(expr, idx)
2183 fn mk_range(&mut self,
2184 start: Option<P<Expr>>,
2185 end: Option<P<Expr>>,
2186 limits: RangeLimits)
2187 -> PResult<'a, ast::ExprKind> {
2188 if end.is_none() && limits == RangeLimits::Closed {
2189 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2191 Ok(ExprKind::Range(start, end, limits))
2195 fn mk_assign_op(&mut self, binop: ast::BinOp,
2196 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2197 ExprKind::AssignOp(binop, lhs, rhs)
2200 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2202 id: ast::DUMMY_NODE_ID,
2203 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2209 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2210 let delim = match self.token {
2211 token::OpenDelim(delim) => delim,
2213 let msg = "expected open delimiter";
2214 let mut err = self.fatal(msg);
2215 err.span_label(self.span, msg);
2219 let delimited = match self.parse_token_tree() {
2220 TokenTree::Delimited(_, delimited) => delimited,
2221 _ => unreachable!(),
2223 let delim = match delim {
2224 token::Paren => MacDelimiter::Parenthesis,
2225 token::Bracket => MacDelimiter::Bracket,
2226 token::Brace => MacDelimiter::Brace,
2227 token::NoDelim => self.bug("unexpected no delimiter"),
2229 Ok((delim, delimited.stream().into()))
2232 /// At the bottom (top?) of the precedence hierarchy,
2233 /// parse things like parenthesized exprs,
2234 /// macros, return, etc.
2236 /// NB: This does not parse outer attributes,
2237 /// and is private because it only works
2238 /// correctly if called from parse_dot_or_call_expr().
2239 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2240 maybe_whole_expr!(self);
2242 // Outer attributes are already parsed and will be
2243 // added to the return value after the fact.
2245 // Therefore, prevent sub-parser from parsing
2246 // attributes by giving them a empty "already parsed" list.
2247 let mut attrs = ThinVec::new();
2250 let mut hi = self.span;
2254 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2256 token::OpenDelim(token::Paren) => {
2259 attrs.extend(self.parse_inner_attributes()?);
2261 // (e) is parenthesized e
2262 // (e,) is a tuple with only one field, e
2263 let mut es = vec![];
2264 let mut trailing_comma = false;
2265 while self.token != token::CloseDelim(token::Paren) {
2266 es.push(self.parse_expr()?);
2267 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2268 if self.check(&token::Comma) {
2269 trailing_comma = true;
2273 trailing_comma = false;
2279 hi = self.prev_span;
2280 ex = if es.len() == 1 && !trailing_comma {
2281 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2286 token::OpenDelim(token::Brace) => {
2287 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2289 token::BinOp(token::Or) | token::OrOr => {
2290 return self.parse_lambda_expr(attrs);
2292 token::OpenDelim(token::Bracket) => {
2295 attrs.extend(self.parse_inner_attributes()?);
2297 if self.check(&token::CloseDelim(token::Bracket)) {
2300 ex = ExprKind::Array(Vec::new());
2303 let first_expr = self.parse_expr()?;
2304 if self.check(&token::Semi) {
2305 // Repeating array syntax: [ 0; 512 ]
2307 let count = AnonConst {
2308 id: ast::DUMMY_NODE_ID,
2309 value: self.parse_expr()?,
2311 self.expect(&token::CloseDelim(token::Bracket))?;
2312 ex = ExprKind::Repeat(first_expr, count);
2313 } else if self.check(&token::Comma) {
2314 // Vector with two or more elements.
2316 let remaining_exprs = self.parse_seq_to_end(
2317 &token::CloseDelim(token::Bracket),
2318 SeqSep::trailing_allowed(token::Comma),
2319 |p| Ok(p.parse_expr()?)
2321 let mut exprs = vec![first_expr];
2322 exprs.extend(remaining_exprs);
2323 ex = ExprKind::Array(exprs);
2325 // Vector with one element.
2326 self.expect(&token::CloseDelim(token::Bracket))?;
2327 ex = ExprKind::Array(vec![first_expr]);
2330 hi = self.prev_span;
2334 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2336 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2338 if self.span.edition() >= Edition::Edition2018 &&
2339 self.check_keyword(keywords::Async)
2341 if self.is_async_block() { // check for `async {` and `async move {`
2342 return self.parse_async_block(attrs);
2344 return self.parse_lambda_expr(attrs);
2347 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2348 return self.parse_lambda_expr(attrs);
2350 if self.eat_keyword(keywords::If) {
2351 return self.parse_if_expr(attrs);
2353 if self.eat_keyword(keywords::For) {
2354 let lo = self.prev_span;
2355 return self.parse_for_expr(None, lo, attrs);
2357 if self.eat_keyword(keywords::While) {
2358 let lo = self.prev_span;
2359 return self.parse_while_expr(None, lo, attrs);
2361 if let Some(label) = self.eat_label() {
2362 let lo = label.ident.span;
2363 self.expect(&token::Colon)?;
2364 if self.eat_keyword(keywords::While) {
2365 return self.parse_while_expr(Some(label), lo, attrs)
2367 if self.eat_keyword(keywords::For) {
2368 return self.parse_for_expr(Some(label), lo, attrs)
2370 if self.eat_keyword(keywords::Loop) {
2371 return self.parse_loop_expr(Some(label), lo, attrs)
2373 if self.token == token::OpenDelim(token::Brace) {
2374 return self.parse_block_expr(Some(label),
2376 BlockCheckMode::Default,
2379 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2380 let mut err = self.fatal(msg);
2381 err.span_label(self.span, msg);
2384 if self.eat_keyword(keywords::Loop) {
2385 let lo = self.prev_span;
2386 return self.parse_loop_expr(None, lo, attrs);
2388 if self.eat_keyword(keywords::Continue) {
2389 let label = self.eat_label();
2390 let ex = ExprKind::Continue(label);
2391 let hi = self.prev_span;
2392 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2394 if self.eat_keyword(keywords::Match) {
2395 return self.parse_match_expr(attrs);
2397 if self.eat_keyword(keywords::Unsafe) {
2398 return self.parse_block_expr(
2401 BlockCheckMode::Unsafe(ast::UserProvided),
2404 if self.is_do_catch_block() {
2405 let mut db = self.fatal("found removed `do catch` syntax");
2406 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2409 if self.is_try_block() {
2411 assert!(self.eat_keyword(keywords::Try));
2412 return self.parse_try_block(lo, attrs);
2414 if self.eat_keyword(keywords::Return) {
2415 if self.token.can_begin_expr() {
2416 let e = self.parse_expr()?;
2418 ex = ExprKind::Ret(Some(e));
2420 ex = ExprKind::Ret(None);
2422 } else if self.eat_keyword(keywords::Break) {
2423 let label = self.eat_label();
2424 let e = if self.token.can_begin_expr()
2425 && !(self.token == token::OpenDelim(token::Brace)
2426 && self.restrictions.contains(
2427 Restrictions::NO_STRUCT_LITERAL)) {
2428 Some(self.parse_expr()?)
2432 ex = ExprKind::Break(label, e);
2433 hi = self.prev_span;
2434 } else if self.eat_keyword(keywords::Yield) {
2435 if self.token.can_begin_expr() {
2436 let e = self.parse_expr()?;
2438 ex = ExprKind::Yield(Some(e));
2440 ex = ExprKind::Yield(None);
2442 } else if self.token.is_keyword(keywords::Let) {
2443 // Catch this syntax error here, instead of in `parse_ident`, so
2444 // that we can explicitly mention that let is not to be used as an expression
2445 let mut db = self.fatal("expected expression, found statement (`let`)");
2446 db.span_label(self.span, "expected expression");
2447 db.note("variable declaration using `let` is a statement");
2449 } else if self.token.is_path_start() {
2450 let pth = self.parse_path(PathStyle::Expr)?;
2452 // `!`, as an operator, is prefix, so we know this isn't that
2453 if self.eat(&token::Not) {
2454 // MACRO INVOCATION expression
2455 let (delim, tts) = self.expect_delimited_token_tree()?;
2456 let hi = self.prev_span;
2457 let node = Mac_ { path: pth, tts, delim };
2458 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2460 if self.check(&token::OpenDelim(token::Brace)) {
2461 // This is a struct literal, unless we're prohibited
2462 // from parsing struct literals here.
2463 let prohibited = self.restrictions.contains(
2464 Restrictions::NO_STRUCT_LITERAL
2467 return self.parse_struct_expr(lo, pth, attrs);
2472 ex = ExprKind::Path(None, pth);
2474 match self.parse_literal_maybe_minus() {
2477 ex = expr.node.clone();
2480 self.cancel(&mut err);
2481 let msg = format!("expected expression, found {}",
2482 self.this_token_descr());
2483 let mut err = self.fatal(&msg);
2484 err.span_label(self.span, "expected expression");
2492 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2493 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2498 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2499 -> PResult<'a, P<Expr>> {
2500 let struct_sp = lo.to(self.prev_span);
2502 let mut fields = Vec::new();
2503 let mut base = None;
2505 attrs.extend(self.parse_inner_attributes()?);
2507 while self.token != token::CloseDelim(token::Brace) {
2508 if self.eat(&token::DotDot) {
2509 let exp_span = self.prev_span;
2510 match self.parse_expr() {
2516 self.recover_stmt();
2519 if self.token == token::Comma {
2520 let mut err = self.sess.span_diagnostic.mut_span_err(
2521 exp_span.to(self.prev_span),
2522 "cannot use a comma after the base struct",
2524 err.span_suggestion_short_with_applicability(
2526 "remove this comma",
2528 Applicability::MachineApplicable
2530 err.note("the base struct must always be the last field");
2532 self.recover_stmt();
2537 match self.parse_field() {
2538 Ok(f) => fields.push(f),
2540 e.span_label(struct_sp, "while parsing this struct");
2543 // If the next token is a comma, then try to parse
2544 // what comes next as additional fields, rather than
2545 // bailing out until next `}`.
2546 if self.token != token::Comma {
2547 self.recover_stmt();
2553 match self.expect_one_of(&[token::Comma],
2554 &[token::CloseDelim(token::Brace)]) {
2558 self.recover_stmt();
2564 let span = lo.to(self.span);
2565 self.expect(&token::CloseDelim(token::Brace))?;
2566 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2569 fn parse_or_use_outer_attributes(&mut self,
2570 already_parsed_attrs: Option<ThinVec<Attribute>>)
2571 -> PResult<'a, ThinVec<Attribute>> {
2572 if let Some(attrs) = already_parsed_attrs {
2575 self.parse_outer_attributes().map(|a| a.into())
2579 /// Parse a block or unsafe block
2580 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2581 lo: Span, blk_mode: BlockCheckMode,
2582 outer_attrs: ThinVec<Attribute>)
2583 -> PResult<'a, P<Expr>> {
2584 self.expect(&token::OpenDelim(token::Brace))?;
2586 let mut attrs = outer_attrs;
2587 attrs.extend(self.parse_inner_attributes()?);
2589 let blk = self.parse_block_tail(lo, blk_mode)?;
2590 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2593 /// parse a.b or a(13) or a[4] or just a
2594 fn parse_dot_or_call_expr(&mut self,
2595 already_parsed_attrs: Option<ThinVec<Attribute>>)
2596 -> PResult<'a, P<Expr>> {
2597 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2599 let b = self.parse_bottom_expr();
2600 let (span, b) = self.interpolated_or_expr_span(b)?;
2601 self.parse_dot_or_call_expr_with(b, span, attrs)
2604 fn parse_dot_or_call_expr_with(&mut self,
2607 mut attrs: ThinVec<Attribute>)
2608 -> PResult<'a, P<Expr>> {
2609 // Stitch the list of outer attributes onto the return value.
2610 // A little bit ugly, but the best way given the current code
2612 self.parse_dot_or_call_expr_with_(e0, lo)
2614 expr.map(|mut expr| {
2615 attrs.extend::<Vec<_>>(expr.attrs.into());
2618 ExprKind::If(..) | ExprKind::IfLet(..) => {
2619 if !expr.attrs.is_empty() {
2620 // Just point to the first attribute in there...
2621 let span = expr.attrs[0].span;
2624 "attributes are not yet allowed on `if` \
2635 // Assuming we have just parsed `.`, continue parsing into an expression.
2636 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2637 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2638 Ok(match self.token {
2639 token::OpenDelim(token::Paren) => {
2640 // Method call `expr.f()`
2641 let mut args = self.parse_unspanned_seq(
2642 &token::OpenDelim(token::Paren),
2643 &token::CloseDelim(token::Paren),
2644 SeqSep::trailing_allowed(token::Comma),
2645 |p| Ok(p.parse_expr()?)
2647 args.insert(0, self_arg);
2649 let span = lo.to(self.prev_span);
2650 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2653 // Field access `expr.f`
2654 if let Some(args) = segment.args {
2655 self.span_err(args.span(),
2656 "field expressions may not have generic arguments");
2659 let span = lo.to(self.prev_span);
2660 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2665 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2670 while self.eat(&token::Question) {
2671 let hi = self.prev_span;
2672 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2676 if self.eat(&token::Dot) {
2678 token::Ident(..) => {
2679 e = self.parse_dot_suffix(e, lo)?;
2681 token::Literal(token::Integer(name), _) => {
2682 let span = self.span;
2684 let field = ExprKind::Field(e, Ident::new(name, span));
2685 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2687 token::Literal(token::Float(n), _suf) => {
2689 let fstr = n.as_str();
2690 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2691 &format!("unexpected token: `{}`", n));
2692 err.span_label(self.prev_span, "unexpected token");
2693 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2694 let float = match fstr.parse::<f64>().ok() {
2698 let sugg = pprust::to_string(|s| {
2699 use print::pprust::PrintState;
2703 s.print_usize(float.trunc() as usize)?;
2706 s.s.word(fstr.splitn(2, ".").last().unwrap())
2708 err.span_suggestion_with_applicability(
2709 lo.to(self.prev_span),
2710 "try parenthesizing the first index",
2712 Applicability::MachineApplicable
2719 // FIXME Could factor this out into non_fatal_unexpected or something.
2720 let actual = self.this_token_to_string();
2721 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2726 if self.expr_is_complete(&e) { break; }
2729 token::OpenDelim(token::Paren) => {
2730 let es = self.parse_unspanned_seq(
2731 &token::OpenDelim(token::Paren),
2732 &token::CloseDelim(token::Paren),
2733 SeqSep::trailing_allowed(token::Comma),
2734 |p| Ok(p.parse_expr()?)
2736 hi = self.prev_span;
2738 let nd = self.mk_call(e, es);
2739 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2743 // Could be either an index expression or a slicing expression.
2744 token::OpenDelim(token::Bracket) => {
2746 let ix = self.parse_expr()?;
2748 self.expect(&token::CloseDelim(token::Bracket))?;
2749 let index = self.mk_index(e, ix);
2750 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2758 crate fn process_potential_macro_variable(&mut self) {
2759 let (token, span) = match self.token {
2760 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2761 self.look_ahead(1, |t| t.is_ident()) => {
2763 let name = match self.token {
2764 token::Ident(ident, _) => ident,
2767 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2768 err.span_label(self.span, "unknown macro variable");
2772 token::Interpolated(ref nt) => {
2773 self.meta_var_span = Some(self.span);
2774 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2775 // and lifetime tokens, so the former are never encountered during normal parsing.
2777 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2778 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2788 /// parse a single token tree from the input.
2789 crate fn parse_token_tree(&mut self) -> TokenTree {
2791 token::OpenDelim(..) => {
2792 let frame = mem::replace(&mut self.token_cursor.frame,
2793 self.token_cursor.stack.pop().unwrap());
2794 self.span = frame.span;
2796 TokenTree::Delimited(frame.span, Delimited {
2798 tts: frame.tree_cursor.original_stream().into(),
2801 token::CloseDelim(_) | token::Eof => unreachable!(),
2803 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2805 TokenTree::Token(span, token)
2810 // parse a stream of tokens into a list of TokenTree's,
2812 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2813 let mut tts = Vec::new();
2814 while self.token != token::Eof {
2815 tts.push(self.parse_token_tree());
2820 pub fn parse_tokens(&mut self) -> TokenStream {
2821 let mut result = Vec::new();
2824 token::Eof | token::CloseDelim(..) => break,
2825 _ => result.push(self.parse_token_tree().into()),
2828 TokenStream::concat(result)
2831 /// Parse a prefix-unary-operator expr
2832 fn parse_prefix_expr(&mut self,
2833 already_parsed_attrs: Option<ThinVec<Attribute>>)
2834 -> PResult<'a, P<Expr>> {
2835 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2837 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2838 let (hi, ex) = match self.token {
2841 let e = self.parse_prefix_expr(None);
2842 let (span, e) = self.interpolated_or_expr_span(e)?;
2843 (lo.to(span), self.mk_unary(UnOp::Not, e))
2845 // Suggest `!` for bitwise negation when encountering a `~`
2848 let e = self.parse_prefix_expr(None);
2849 let (span, e) = self.interpolated_or_expr_span(e)?;
2850 let span_of_tilde = lo;
2851 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2852 "`~` cannot be used as a unary operator");
2853 err.span_suggestion_short_with_applicability(
2855 "use `!` to perform bitwise negation",
2857 Applicability::MachineApplicable
2860 (lo.to(span), self.mk_unary(UnOp::Not, e))
2862 token::BinOp(token::Minus) => {
2864 let e = self.parse_prefix_expr(None);
2865 let (span, e) = self.interpolated_or_expr_span(e)?;
2866 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2868 token::BinOp(token::Star) => {
2870 let e = self.parse_prefix_expr(None);
2871 let (span, e) = self.interpolated_or_expr_span(e)?;
2872 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2874 token::BinOp(token::And) | token::AndAnd => {
2876 let m = self.parse_mutability();
2877 let e = self.parse_prefix_expr(None);
2878 let (span, e) = self.interpolated_or_expr_span(e)?;
2879 (lo.to(span), ExprKind::AddrOf(m, e))
2881 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2883 let place = self.parse_expr_res(
2884 Restrictions::NO_STRUCT_LITERAL,
2887 let blk = self.parse_block()?;
2888 let span = blk.span;
2889 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2890 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2892 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2894 let e = self.parse_prefix_expr(None);
2895 let (span, e) = self.interpolated_or_expr_span(e)?;
2896 (lo.to(span), ExprKind::Box(e))
2898 token::Ident(..) if self.token.is_ident_named("not") => {
2899 // `not` is just an ordinary identifier in Rust-the-language,
2900 // but as `rustc`-the-compiler, we can issue clever diagnostics
2901 // for confused users who really want to say `!`
2902 let token_cannot_continue_expr = |t: &token::Token| match *t {
2903 // These tokens can start an expression after `!`, but
2904 // can't continue an expression after an ident
2905 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2906 token::Literal(..) | token::Pound => true,
2907 token::Interpolated(ref nt) => match nt.0 {
2908 token::NtIdent(..) | token::NtExpr(..) |
2909 token::NtBlock(..) | token::NtPath(..) => true,
2914 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2915 if cannot_continue_expr {
2917 // Emit the error ...
2918 let mut err = self.diagnostic()
2919 .struct_span_err(self.span,
2920 &format!("unexpected {} after identifier",
2921 self.this_token_descr()));
2922 // span the `not` plus trailing whitespace to avoid
2923 // trailing whitespace after the `!` in our suggestion
2924 let to_replace = self.sess.source_map()
2925 .span_until_non_whitespace(lo.to(self.span));
2926 err.span_suggestion_short_with_applicability(
2928 "use `!` to perform logical negation",
2930 Applicability::MachineApplicable
2933 // —and recover! (just as if we were in the block
2934 // for the `token::Not` arm)
2935 let e = self.parse_prefix_expr(None);
2936 let (span, e) = self.interpolated_or_expr_span(e)?;
2937 (lo.to(span), self.mk_unary(UnOp::Not, e))
2939 return self.parse_dot_or_call_expr(Some(attrs));
2942 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2944 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2947 /// Parse an associative expression
2949 /// This parses an expression accounting for associativity and precedence of the operators in
2951 fn parse_assoc_expr(&mut self,
2952 already_parsed_attrs: Option<ThinVec<Attribute>>)
2953 -> PResult<'a, P<Expr>> {
2954 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2957 /// Parse an associative expression with operators of at least `min_prec` precedence
2958 fn parse_assoc_expr_with(&mut self,
2961 -> PResult<'a, P<Expr>> {
2962 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2965 let attrs = match lhs {
2966 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2969 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2970 return self.parse_prefix_range_expr(attrs);
2972 self.parse_prefix_expr(attrs)?
2976 if self.expr_is_complete(&lhs) {
2977 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2980 self.expected_tokens.push(TokenType::Operator);
2981 while let Some(op) = AssocOp::from_token(&self.token) {
2983 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2984 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2985 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2986 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2987 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2988 (PrevTokenKind::Interpolated, _) => self.prev_span,
2989 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2990 if path.segments.len() == 1 => self.prev_span,
2994 let cur_op_span = self.span;
2995 let restrictions = if op.is_assign_like() {
2996 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3000 if op.precedence() < min_prec {
3003 // Check for deprecated `...` syntax
3004 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3005 self.err_dotdotdot_syntax(self.span);
3009 if op.is_comparison() {
3010 self.check_no_chained_comparison(&lhs, &op);
3013 if op == AssocOp::As {
3014 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3016 } else if op == AssocOp::Colon {
3017 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3020 err.span_label(self.span,
3021 "expecting a type here because of type ascription");
3022 let cm = self.sess.source_map();
3023 let cur_pos = cm.lookup_char_pos(self.span.lo());
3024 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3025 if cur_pos.line != op_pos.line {
3026 err.span_suggestion_with_applicability(
3028 "try using a semicolon",
3030 Applicability::MaybeIncorrect // speculative
3037 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3038 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3039 // generalise it to the Fixity::None code.
3041 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3042 // two variants are handled with `parse_prefix_range_expr` call above.
3043 let rhs = if self.is_at_start_of_range_notation_rhs() {
3044 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3045 LhsExpr::NotYetParsed)?)
3049 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3054 let limits = if op == AssocOp::DotDot {
3055 RangeLimits::HalfOpen
3060 let r = try!(self.mk_range(Some(lhs), rhs, limits));
3061 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3065 let rhs = match op.fixity() {
3066 Fixity::Right => self.with_res(
3067 restrictions - Restrictions::STMT_EXPR,
3069 this.parse_assoc_expr_with(op.precedence(),
3070 LhsExpr::NotYetParsed)
3072 Fixity::Left => self.with_res(
3073 restrictions - Restrictions::STMT_EXPR,
3075 this.parse_assoc_expr_with(op.precedence() + 1,
3076 LhsExpr::NotYetParsed)
3078 // We currently have no non-associative operators that are not handled above by
3079 // the special cases. The code is here only for future convenience.
3080 Fixity::None => self.with_res(
3081 restrictions - Restrictions::STMT_EXPR,
3083 this.parse_assoc_expr_with(op.precedence() + 1,
3084 LhsExpr::NotYetParsed)
3088 let span = lhs_span.to(rhs.span);
3090 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3091 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3092 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3093 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3094 AssocOp::Greater | AssocOp::GreaterEqual => {
3095 let ast_op = op.to_ast_binop().unwrap();
3096 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3097 self.mk_expr(span, binary, ThinVec::new())
3100 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3101 AssocOp::ObsoleteInPlace =>
3102 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3103 AssocOp::AssignOp(k) => {
3105 token::Plus => BinOpKind::Add,
3106 token::Minus => BinOpKind::Sub,
3107 token::Star => BinOpKind::Mul,
3108 token::Slash => BinOpKind::Div,
3109 token::Percent => BinOpKind::Rem,
3110 token::Caret => BinOpKind::BitXor,
3111 token::And => BinOpKind::BitAnd,
3112 token::Or => BinOpKind::BitOr,
3113 token::Shl => BinOpKind::Shl,
3114 token::Shr => BinOpKind::Shr,
3116 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3117 self.mk_expr(span, aopexpr, ThinVec::new())
3119 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3120 self.bug("AssocOp should have been handled by special case")
3124 if op.fixity() == Fixity::None { break }
3129 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3130 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3131 -> PResult<'a, P<Expr>> {
3132 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3133 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3136 // Save the state of the parser before parsing type normally, in case there is a
3137 // LessThan comparison after this cast.
3138 let parser_snapshot_before_type = self.clone();
3139 match self.parse_ty_no_plus() {
3141 Ok(mk_expr(self, rhs))
3143 Err(mut type_err) => {
3144 // Rewind to before attempting to parse the type with generics, to recover
3145 // from situations like `x as usize < y` in which we first tried to parse
3146 // `usize < y` as a type with generic arguments.
3147 let parser_snapshot_after_type = self.clone();
3148 mem::replace(self, parser_snapshot_before_type);
3150 match self.parse_path(PathStyle::Expr) {
3152 let (op_noun, op_verb) = match self.token {
3153 token::Lt => ("comparison", "comparing"),
3154 token::BinOp(token::Shl) => ("shift", "shifting"),
3156 // We can end up here even without `<` being the next token, for
3157 // example because `parse_ty_no_plus` returns `Err` on keywords,
3158 // but `parse_path` returns `Ok` on them due to error recovery.
3159 // Return original error and parser state.
3160 mem::replace(self, parser_snapshot_after_type);
3161 return Err(type_err);
3165 // Successfully parsed the type path leaving a `<` yet to parse.
3168 // Report non-fatal diagnostics, keep `x as usize` as an expression
3169 // in AST and continue parsing.
3170 let msg = format!("`<` is interpreted as a start of generic \
3171 arguments for `{}`, not a {}", path, op_noun);
3172 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3173 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3174 "interpreted as generic arguments");
3175 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3177 let expr = mk_expr(self, P(Ty {
3179 node: TyKind::Path(None, path),
3180 id: ast::DUMMY_NODE_ID
3183 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3184 .unwrap_or(pprust::expr_to_string(&expr));
3185 err.span_suggestion_with_applicability(
3187 &format!("try {} the cast value", op_verb),
3188 format!("({})", expr_str),
3189 Applicability::MachineApplicable
3195 Err(mut path_err) => {
3196 // Couldn't parse as a path, return original error and parser state.
3198 mem::replace(self, parser_snapshot_after_type);
3206 /// Produce an error if comparison operators are chained (RFC #558).
3207 /// We only need to check lhs, not rhs, because all comparison ops
3208 /// have same precedence and are left-associative
3209 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3210 debug_assert!(outer_op.is_comparison(),
3211 "check_no_chained_comparison: {:?} is not comparison",
3214 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3215 // respan to include both operators
3216 let op_span = op.span.to(self.span);
3217 let mut err = self.diagnostic().struct_span_err(op_span,
3218 "chained comparison operators require parentheses");
3219 if op.node == BinOpKind::Lt &&
3220 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3221 *outer_op == AssocOp::Greater // even in a case like the following:
3222 { // Foo<Bar<Baz<Qux, ()>>>
3224 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3225 err.help("or use `(...)` if you meant to specify fn arguments");
3233 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3234 fn parse_prefix_range_expr(&mut self,
3235 already_parsed_attrs: Option<ThinVec<Attribute>>)
3236 -> PResult<'a, P<Expr>> {
3237 // Check for deprecated `...` syntax
3238 if self.token == token::DotDotDot {
3239 self.err_dotdotdot_syntax(self.span);
3242 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3243 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3245 let tok = self.token.clone();
3246 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3248 let mut hi = self.span;
3250 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3251 // RHS must be parsed with more associativity than the dots.
3252 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3253 Some(self.parse_assoc_expr_with(next_prec,
3254 LhsExpr::NotYetParsed)
3262 let limits = if tok == token::DotDot {
3263 RangeLimits::HalfOpen
3268 let r = try!(self.mk_range(None,
3271 Ok(self.mk_expr(lo.to(hi), r, attrs))
3274 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3275 if self.token.can_begin_expr() {
3276 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3277 if self.token == token::OpenDelim(token::Brace) {
3278 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3286 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3287 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3288 if self.check_keyword(keywords::Let) {
3289 return self.parse_if_let_expr(attrs);
3291 let lo = self.prev_span;
3292 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3294 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3295 // verify that the last statement is either an implicit return (no `;`) or an explicit
3296 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3297 // the dead code lint.
3298 if self.eat_keyword(keywords::Else) || !cond.returns() {
3299 let sp = self.sess.source_map().next_point(lo);
3300 let mut err = self.diagnostic()
3301 .struct_span_err(sp, "missing condition for `if` statemement");
3302 err.span_label(sp, "expected if condition here");
3305 let not_block = self.token != token::OpenDelim(token::Brace);
3306 let thn = self.parse_block().map_err(|mut err| {
3308 err.span_label(lo, "this `if` statement has a condition, but no block");
3312 let mut els: Option<P<Expr>> = None;
3313 let mut hi = thn.span;
3314 if self.eat_keyword(keywords::Else) {
3315 let elexpr = self.parse_else_expr()?;
3319 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3322 /// Parse an 'if let' expression ('if' token already eaten)
3323 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3324 -> PResult<'a, P<Expr>> {
3325 let lo = self.prev_span;
3326 self.expect_keyword(keywords::Let)?;
3327 let pats = self.parse_pats()?;
3328 self.expect(&token::Eq)?;
3329 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3330 let thn = self.parse_block()?;
3331 let (hi, els) = if self.eat_keyword(keywords::Else) {
3332 let expr = self.parse_else_expr()?;
3333 (expr.span, Some(expr))
3337 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3340 // `move |args| expr`
3341 fn parse_lambda_expr(&mut self,
3342 attrs: ThinVec<Attribute>)
3343 -> PResult<'a, P<Expr>>
3346 let movability = if self.eat_keyword(keywords::Static) {
3351 let asyncness = if self.span.edition() >= Edition::Edition2018 {
3352 self.parse_asyncness()
3356 let capture_clause = if self.eat_keyword(keywords::Move) {
3361 let decl = self.parse_fn_block_decl()?;
3362 let decl_hi = self.prev_span;
3363 let body = match decl.output {
3364 FunctionRetTy::Default(_) => {
3365 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3366 self.parse_expr_res(restrictions, None)?
3369 // If an explicit return type is given, require a
3370 // block to appear (RFC 968).
3371 let body_lo = self.span;
3372 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3378 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3382 // `else` token already eaten
3383 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3384 if self.eat_keyword(keywords::If) {
3385 return self.parse_if_expr(ThinVec::new());
3387 let blk = self.parse_block()?;
3388 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3392 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3393 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3395 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3396 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3398 let pat = self.parse_top_level_pat()?;
3399 if !self.eat_keyword(keywords::In) {
3400 let in_span = self.prev_span.between(self.span);
3401 let mut err = self.sess.span_diagnostic
3402 .struct_span_err(in_span, "missing `in` in `for` loop");
3403 err.span_suggestion_short_with_applicability(
3404 in_span, "try adding `in` here", " in ".into(),
3405 // has been misleading, at least in the past (closed Issue #48492)
3406 Applicability::MaybeIncorrect
3410 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3411 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3412 attrs.extend(iattrs);
3414 let hi = self.prev_span;
3415 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3418 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3419 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3421 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3422 if self.token.is_keyword(keywords::Let) {
3423 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3425 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3426 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3427 attrs.extend(iattrs);
3428 let span = span_lo.to(body.span);
3429 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3432 /// Parse a 'while let' expression ('while' token already eaten)
3433 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3435 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3436 self.expect_keyword(keywords::Let)?;
3437 let pats = self.parse_pats()?;
3438 self.expect(&token::Eq)?;
3439 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3440 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3441 attrs.extend(iattrs);
3442 let span = span_lo.to(body.span);
3443 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3446 // parse `loop {...}`, `loop` token already eaten
3447 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3449 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3450 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3451 attrs.extend(iattrs);
3452 let span = span_lo.to(body.span);
3453 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3456 /// Parse an `async move {...}` expression
3457 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3458 -> PResult<'a, P<Expr>>
3460 let span_lo = self.span;
3461 self.expect_keyword(keywords::Async)?;
3462 let capture_clause = if self.eat_keyword(keywords::Move) {
3467 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3468 attrs.extend(iattrs);
3470 span_lo.to(body.span),
3471 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3474 /// Parse a `try {...}` expression (`try` token already eaten)
3475 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3476 -> PResult<'a, P<Expr>>
3478 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3479 attrs.extend(iattrs);
3480 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3483 // `match` token already eaten
3484 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3485 let match_span = self.prev_span;
3486 let lo = self.prev_span;
3487 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3489 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3490 if self.token == token::Token::Semi {
3491 e.span_suggestion_short_with_applicability(
3493 "try removing this `match`",
3495 Applicability::MaybeIncorrect // speculative
3500 attrs.extend(self.parse_inner_attributes()?);
3502 let mut arms: Vec<Arm> = Vec::new();
3503 while self.token != token::CloseDelim(token::Brace) {
3504 match self.parse_arm() {
3505 Ok(arm) => arms.push(arm),
3507 // Recover by skipping to the end of the block.
3509 self.recover_stmt();
3510 let span = lo.to(self.span);
3511 if self.token == token::CloseDelim(token::Brace) {
3514 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3520 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3523 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3524 maybe_whole!(self, NtArm, |x| x);
3526 let attrs = self.parse_outer_attributes()?;
3527 // Allow a '|' before the pats (RFC 1925)
3528 self.eat(&token::BinOp(token::Or));
3529 let pats = self.parse_pats()?;
3530 let guard = if self.eat_keyword(keywords::If) {
3531 Some(self.parse_expr()?)
3535 let arrow_span = self.span;
3536 self.expect(&token::FatArrow)?;
3537 let arm_start_span = self.span;
3539 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3540 .map_err(|mut err| {
3541 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3545 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3546 && self.token != token::CloseDelim(token::Brace);
3549 let cm = self.sess.source_map();
3550 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3551 .map_err(|mut err| {
3552 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3553 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3554 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3555 && expr_lines.lines.len() == 2
3556 && self.token == token::FatArrow => {
3557 // We check whether there's any trailing code in the parse span,
3558 // if there isn't, we very likely have the following:
3561 // | -- - missing comma
3567 // | parsed until here as `"y" & X`
3568 err.span_suggestion_short_with_applicability(
3569 cm.next_point(arm_start_span),
3570 "missing a comma here to end this `match` arm",
3572 Applicability::MachineApplicable
3576 err.span_label(arrow_span,
3577 "while parsing the `match` arm starting here");
3583 self.eat(&token::Comma);
3594 /// Parse an expression
3595 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3596 self.parse_expr_res(Restrictions::empty(), None)
3599 /// Evaluate the closure with restrictions in place.
3601 /// After the closure is evaluated, restrictions are reset.
3602 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3603 where F: FnOnce(&mut Self) -> T
3605 let old = self.restrictions;
3606 self.restrictions = r;
3608 self.restrictions = old;
3613 /// Parse an expression, subject to the given restrictions
3614 fn parse_expr_res(&mut self, r: Restrictions,
3615 already_parsed_attrs: Option<ThinVec<Attribute>>)
3616 -> PResult<'a, P<Expr>> {
3617 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3620 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3621 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3622 if self.check(&token::Eq) {
3624 Ok(Some(self.parse_expr()?))
3626 Ok(Some(self.parse_expr()?))
3632 /// Parse patterns, separated by '|' s
3633 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3634 let mut pats = Vec::new();
3636 pats.push(self.parse_top_level_pat()?);
3638 if self.token == token::OrOr {
3639 let mut err = self.struct_span_err(self.span,
3640 "unexpected token `||` after pattern");
3641 err.span_suggestion_with_applicability(
3643 "use a single `|` to specify multiple patterns",
3645 Applicability::MachineApplicable
3649 } else if self.check(&token::BinOp(token::Or)) {
3657 // Parses a parenthesized list of patterns like
3658 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3659 // - a vector of the patterns that were parsed
3660 // - an option indicating the index of the `..` element
3661 // - a boolean indicating whether a trailing comma was present.
3662 // Trailing commas are significant because (p) and (p,) are different patterns.
3663 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3664 self.expect(&token::OpenDelim(token::Paren))?;
3665 let result = self.parse_pat_list()?;
3666 self.expect(&token::CloseDelim(token::Paren))?;
3670 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3671 let mut fields = Vec::new();
3672 let mut ddpos = None;
3673 let mut trailing_comma = false;
3675 if self.eat(&token::DotDot) {
3676 if ddpos.is_none() {
3677 ddpos = Some(fields.len());
3679 // Emit a friendly error, ignore `..` and continue parsing
3680 self.span_err(self.prev_span,
3681 "`..` can only be used once per tuple or tuple struct pattern");
3683 } else if !self.check(&token::CloseDelim(token::Paren)) {
3684 fields.push(self.parse_pat()?);
3689 trailing_comma = self.eat(&token::Comma);
3690 if !trailing_comma {
3695 if ddpos == Some(fields.len()) && trailing_comma {
3696 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3697 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3700 Ok((fields, ddpos, trailing_comma))
3703 fn parse_pat_vec_elements(
3705 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3706 let mut before = Vec::new();
3707 let mut slice = None;
3708 let mut after = Vec::new();
3709 let mut first = true;
3710 let mut before_slice = true;
3712 while self.token != token::CloseDelim(token::Bracket) {
3716 self.expect(&token::Comma)?;
3718 if self.token == token::CloseDelim(token::Bracket)
3719 && (before_slice || !after.is_empty()) {
3725 if self.eat(&token::DotDot) {
3727 if self.check(&token::Comma) ||
3728 self.check(&token::CloseDelim(token::Bracket)) {
3729 slice = Some(P(Pat {
3730 id: ast::DUMMY_NODE_ID,
3731 node: PatKind::Wild,
3732 span: self.prev_span,
3734 before_slice = false;
3740 let subpat = self.parse_pat()?;
3741 if before_slice && self.eat(&token::DotDot) {
3742 slice = Some(subpat);
3743 before_slice = false;
3744 } else if before_slice {
3745 before.push(subpat);
3751 Ok((before, slice, after))
3757 attrs: Vec<Attribute>
3758 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3759 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3761 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3762 // Parsing a pattern of the form "fieldname: pat"
3763 let fieldname = self.parse_field_name()?;
3765 let pat = self.parse_pat()?;
3767 (pat, fieldname, false)
3769 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3770 let is_box = self.eat_keyword(keywords::Box);
3771 let boxed_span = self.span;
3772 let is_ref = self.eat_keyword(keywords::Ref);
3773 let is_mut = self.eat_keyword(keywords::Mut);
3774 let fieldname = self.parse_ident()?;
3775 hi = self.prev_span;
3777 let bind_type = match (is_ref, is_mut) {
3778 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3779 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3780 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3781 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3783 let fieldpat = P(Pat {
3784 id: ast::DUMMY_NODE_ID,
3785 node: PatKind::Ident(bind_type, fieldname, None),
3786 span: boxed_span.to(hi),
3789 let subpat = if is_box {
3791 id: ast::DUMMY_NODE_ID,
3792 node: PatKind::Box(fieldpat),
3798 (subpat, fieldname, true)
3801 Ok(source_map::Spanned {
3803 node: ast::FieldPat {
3807 attrs: attrs.into(),
3812 /// Parse the fields of a struct-like pattern
3813 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3814 let mut fields = Vec::new();
3815 let mut etc = false;
3816 let mut ate_comma = true;
3817 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3818 let mut etc_span = None;
3820 while self.token != token::CloseDelim(token::Brace) {
3821 let attrs = self.parse_outer_attributes()?;
3824 // check that a comma comes after every field
3826 let err = self.struct_span_err(self.prev_span, "expected `,`");
3831 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3833 let mut etc_sp = self.span;
3835 if self.token == token::DotDotDot { // Issue #46718
3836 // Accept `...` as if it were `..` to avoid further errors
3837 let mut err = self.struct_span_err(self.span,
3838 "expected field pattern, found `...`");
3839 err.span_suggestion_with_applicability(
3841 "to omit remaining fields, use one fewer `.`",
3843 Applicability::MachineApplicable
3847 self.bump(); // `..` || `...`:w
3849 if self.token == token::CloseDelim(token::Brace) {
3850 etc_span = Some(etc_sp);
3853 let token_str = self.this_token_to_string();
3854 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3856 err.span_label(self.span, "expected `}`");
3857 let mut comma_sp = None;
3858 if self.token == token::Comma { // Issue #49257
3859 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3860 err.span_label(etc_sp,
3861 "`..` must be at the end and cannot have a trailing comma");
3862 comma_sp = Some(self.span);
3867 etc_span = Some(etc_sp);
3868 if self.token == token::CloseDelim(token::Brace) {
3869 // If the struct looks otherwise well formed, recover and continue.
3870 if let Some(sp) = comma_sp {
3871 err.span_suggestion_short(sp, "remove this comma", String::new());
3875 } else if self.token.is_ident() && ate_comma {
3876 // Accept fields coming after `..,`.
3877 // This way we avoid "pattern missing fields" errors afterwards.
3878 // We delay this error until the end in order to have a span for a
3880 if let Some(mut delayed_err) = delayed_err {
3884 delayed_err = Some(err);
3887 if let Some(mut err) = delayed_err {
3894 fields.push(match self.parse_pat_field(lo, attrs) {
3897 if let Some(mut delayed_err) = delayed_err {
3903 ate_comma = self.eat(&token::Comma);
3906 if let Some(mut err) = delayed_err {
3907 if let Some(etc_span) = etc_span {
3908 err.multipart_suggestion(
3909 "move the `..` to the end of the field list",
3911 (etc_span, String::new()),
3912 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3918 return Ok((fields, etc));
3921 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3922 if self.token.is_path_start() {
3924 let (qself, path) = if self.eat_lt() {
3925 // Parse a qualified path
3926 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3929 // Parse an unqualified path
3930 (None, self.parse_path(PathStyle::Expr)?)
3932 let hi = self.prev_span;
3933 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3935 self.parse_literal_maybe_minus()
3939 // helper function to decide whether to parse as ident binding or to try to do
3940 // something more complex like range patterns
3941 fn parse_as_ident(&mut self) -> bool {
3942 self.look_ahead(1, |t| match *t {
3943 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3944 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3945 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3946 // range pattern branch
3947 token::DotDot => None,
3949 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3950 token::Comma | token::CloseDelim(token::Bracket) => true,
3955 /// A wrapper around `parse_pat` with some special error handling for the
3956 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3957 /// to subpatterns within such).
3958 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3959 let pat = self.parse_pat()?;
3960 if self.token == token::Comma {
3961 // An unexpected comma after a top-level pattern is a clue that the
3962 // user (perhaps more accustomed to some other language) forgot the
3963 // parentheses in what should have been a tuple pattern; return a
3964 // suggestion-enhanced error here rather than choking on the comma
3966 let comma_span = self.span;
3968 if let Err(mut err) = self.parse_pat_list() {
3969 // We didn't expect this to work anyway; we just wanted
3970 // to advance to the end of the comma-sequence so we know
3971 // the span to suggest parenthesizing
3974 let seq_span = pat.span.to(self.prev_span);
3975 let mut err = self.struct_span_err(comma_span,
3976 "unexpected `,` in pattern");
3977 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3978 err.span_suggestion_with_applicability(
3980 "try adding parentheses",
3981 format!("({})", seq_snippet),
3982 Applicability::MachineApplicable
3990 /// Parse a pattern.
3991 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3992 self.parse_pat_with_range_pat(true)
3995 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3997 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3998 maybe_whole!(self, NtPat, |x| x);
4003 token::BinOp(token::And) | token::AndAnd => {
4004 // Parse &pat / &mut pat
4006 let mutbl = self.parse_mutability();
4007 if let token::Lifetime(ident) = self.token {
4008 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4010 err.span_label(self.span, "unexpected lifetime");
4013 let subpat = self.parse_pat_with_range_pat(false)?;
4014 pat = PatKind::Ref(subpat, mutbl);
4016 token::OpenDelim(token::Paren) => {
4017 // Parse (pat,pat,pat,...) as tuple pattern
4018 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4019 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4020 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4022 PatKind::Tuple(fields, ddpos)
4025 token::OpenDelim(token::Bracket) => {
4026 // Parse [pat,pat,...] as slice pattern
4028 let (before, slice, after) = self.parse_pat_vec_elements()?;
4029 self.expect(&token::CloseDelim(token::Bracket))?;
4030 pat = PatKind::Slice(before, slice, after);
4032 // At this point, token != &, &&, (, [
4033 _ => if self.eat_keyword(keywords::Underscore) {
4035 pat = PatKind::Wild;
4036 } else if self.eat_keyword(keywords::Mut) {
4037 // Parse mut ident @ pat / mut ref ident @ pat
4038 let mutref_span = self.prev_span.to(self.span);
4039 let binding_mode = if self.eat_keyword(keywords::Ref) {
4041 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4042 .span_suggestion_with_applicability(
4044 "try switching the order",
4046 Applicability::MachineApplicable
4048 BindingMode::ByRef(Mutability::Mutable)
4050 BindingMode::ByValue(Mutability::Mutable)
4052 pat = self.parse_pat_ident(binding_mode)?;
4053 } else if self.eat_keyword(keywords::Ref) {
4054 // Parse ref ident @ pat / ref mut ident @ pat
4055 let mutbl = self.parse_mutability();
4056 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4057 } else if self.eat_keyword(keywords::Box) {
4059 let subpat = self.parse_pat_with_range_pat(false)?;
4060 pat = PatKind::Box(subpat);
4061 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4062 self.parse_as_ident() {
4063 // Parse ident @ pat
4064 // This can give false positives and parse nullary enums,
4065 // they are dealt with later in resolve
4066 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4067 pat = self.parse_pat_ident(binding_mode)?;
4068 } else if self.token.is_path_start() {
4069 // Parse pattern starting with a path
4070 let (qself, path) = if self.eat_lt() {
4071 // Parse a qualified path
4072 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4075 // Parse an unqualified path
4076 (None, self.parse_path(PathStyle::Expr)?)
4079 token::Not if qself.is_none() => {
4080 // Parse macro invocation
4082 let (delim, tts) = self.expect_delimited_token_tree()?;
4083 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4084 pat = PatKind::Mac(mac);
4086 token::DotDotDot | token::DotDotEq | token::DotDot => {
4087 let end_kind = match self.token {
4088 token::DotDot => RangeEnd::Excluded,
4089 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4090 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4091 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4094 let op_span = self.span;
4096 let span = lo.to(self.prev_span);
4097 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4099 let end = self.parse_pat_range_end()?;
4100 let op = Spanned { span: op_span, node: end_kind };
4101 pat = PatKind::Range(begin, end, op);
4103 token::OpenDelim(token::Brace) => {
4104 if qself.is_some() {
4105 let msg = "unexpected `{` after qualified path";
4106 let mut err = self.fatal(msg);
4107 err.span_label(self.span, msg);
4110 // Parse struct pattern
4112 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4114 self.recover_stmt();
4118 pat = PatKind::Struct(path, fields, etc);
4120 token::OpenDelim(token::Paren) => {
4121 if qself.is_some() {
4122 let msg = "unexpected `(` after qualified path";
4123 let mut err = self.fatal(msg);
4124 err.span_label(self.span, msg);
4127 // Parse tuple struct or enum pattern
4128 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4129 pat = PatKind::TupleStruct(path, fields, ddpos)
4131 _ => pat = PatKind::Path(qself, path),
4134 // Try to parse everything else as literal with optional minus
4135 match self.parse_literal_maybe_minus() {
4137 let op_span = self.span;
4138 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4139 self.check(&token::DotDotDot) {
4140 let end_kind = if self.eat(&token::DotDotDot) {
4141 RangeEnd::Included(RangeSyntax::DotDotDot)
4142 } else if self.eat(&token::DotDotEq) {
4143 RangeEnd::Included(RangeSyntax::DotDotEq)
4144 } else if self.eat(&token::DotDot) {
4147 panic!("impossible case: we already matched \
4148 on a range-operator token")
4150 let end = self.parse_pat_range_end()?;
4151 let op = Spanned { span: op_span, node: end_kind };
4152 pat = PatKind::Range(begin, end, op);
4154 pat = PatKind::Lit(begin);
4158 self.cancel(&mut err);
4159 let msg = format!("expected pattern, found {}", self.this_token_descr());
4160 let mut err = self.fatal(&msg);
4161 err.span_label(self.span, "expected pattern");
4168 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4169 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4171 if !allow_range_pat {
4174 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4176 PatKind::Range(..) => {
4177 let mut err = self.struct_span_err(
4179 "the range pattern here has ambiguous interpretation",
4181 err.span_suggestion_with_applicability(
4183 "add parentheses to clarify the precedence",
4184 format!("({})", pprust::pat_to_string(&pat)),
4185 // "ambiguous interpretation" implies that we have to be guessing
4186 Applicability::MaybeIncorrect
4197 /// Parse ident or ident @ pat
4198 /// used by the copy foo and ref foo patterns to give a good
4199 /// error message when parsing mistakes like ref foo(a,b)
4200 fn parse_pat_ident(&mut self,
4201 binding_mode: ast::BindingMode)
4202 -> PResult<'a, PatKind> {
4203 let ident = self.parse_ident()?;
4204 let sub = if self.eat(&token::At) {
4205 Some(self.parse_pat()?)
4210 // just to be friendly, if they write something like
4212 // we end up here with ( as the current token. This shortly
4213 // leads to a parse error. Note that if there is no explicit
4214 // binding mode then we do not end up here, because the lookahead
4215 // will direct us over to parse_enum_variant()
4216 if self.token == token::OpenDelim(token::Paren) {
4217 return Err(self.span_fatal(
4219 "expected identifier, found enum pattern"))
4222 Ok(PatKind::Ident(binding_mode, ident, sub))
4225 /// Parse a local variable declaration
4226 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4227 let lo = self.prev_span;
4228 let pat = self.parse_top_level_pat()?;
4230 let (err, ty) = if self.eat(&token::Colon) {
4231 // Save the state of the parser before parsing type normally, in case there is a `:`
4232 // instead of an `=` typo.
4233 let parser_snapshot_before_type = self.clone();
4234 let colon_sp = self.prev_span;
4235 match self.parse_ty() {
4236 Ok(ty) => (None, Some(ty)),
4238 // Rewind to before attempting to parse the type and continue parsing
4239 let parser_snapshot_after_type = self.clone();
4240 mem::replace(self, parser_snapshot_before_type);
4242 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4243 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4244 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4250 let init = match (self.parse_initializer(err.is_some()), err) {
4251 (Ok(init), None) => { // init parsed, ty parsed
4254 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4255 // Could parse the type as if it were the initializer, it is likely there was a
4256 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4257 err.span_suggestion_short_with_applicability(
4259 "use `=` if you meant to assign",
4261 Applicability::MachineApplicable
4264 // As this was parsed successfully, continue as if the code has been fixed for the
4265 // rest of the file. It will still fail due to the emitted error, but we avoid
4269 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4271 // Couldn't parse the type nor the initializer, only raise the type error and
4272 // return to the parser state before parsing the type as the initializer.
4273 // let x: <parse_error>;
4274 mem::replace(self, snapshot);
4277 (Err(err), None) => { // init error, ty parsed
4278 // Couldn't parse the initializer and we're not attempting to recover a failed
4279 // parse of the type, return the error.
4283 let hi = if self.token == token::Semi {
4292 id: ast::DUMMY_NODE_ID,
4298 /// Parse a structure field
4299 fn parse_name_and_ty(&mut self,
4302 attrs: Vec<Attribute>)
4303 -> PResult<'a, StructField> {
4304 let name = self.parse_ident()?;
4305 self.expect(&token::Colon)?;
4306 let ty = self.parse_ty()?;
4308 span: lo.to(self.prev_span),
4311 id: ast::DUMMY_NODE_ID,
4317 /// Emit an expected item after attributes error.
4318 fn expected_item_err(&self, attrs: &[Attribute]) {
4319 let message = match attrs.last() {
4320 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4321 _ => "expected item after attributes",
4324 self.span_err(self.prev_span, message);
4327 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4328 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4329 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4330 Ok(self.parse_stmt_(true))
4333 // Eat tokens until we can be relatively sure we reached the end of the
4334 // statement. This is something of a best-effort heuristic.
4336 // We terminate when we find an unmatched `}` (without consuming it).
4337 fn recover_stmt(&mut self) {
4338 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4341 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4342 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4343 // approximate - it can mean we break too early due to macros, but that
4344 // should only lead to sub-optimal recovery, not inaccurate parsing).
4346 // If `break_on_block` is `Break`, then we will stop consuming tokens
4347 // after finding (and consuming) a brace-delimited block.
4348 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4349 let mut brace_depth = 0;
4350 let mut bracket_depth = 0;
4351 let mut in_block = false;
4352 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4353 break_on_semi, break_on_block);
4355 debug!("recover_stmt_ loop {:?}", self.token);
4357 token::OpenDelim(token::DelimToken::Brace) => {
4360 if break_on_block == BlockMode::Break &&
4362 bracket_depth == 0 {
4366 token::OpenDelim(token::DelimToken::Bracket) => {
4370 token::CloseDelim(token::DelimToken::Brace) => {
4371 if brace_depth == 0 {
4372 debug!("recover_stmt_ return - close delim {:?}", self.token);
4377 if in_block && bracket_depth == 0 && brace_depth == 0 {
4378 debug!("recover_stmt_ return - block end {:?}", self.token);
4382 token::CloseDelim(token::DelimToken::Bracket) => {
4384 if bracket_depth < 0 {
4390 debug!("recover_stmt_ return - Eof");
4395 if break_on_semi == SemiColonMode::Break &&
4397 bracket_depth == 0 {
4398 debug!("recover_stmt_ return - Semi");
4409 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4410 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4412 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4417 fn is_async_block(&mut self) -> bool {
4418 self.token.is_keyword(keywords::Async) &&
4421 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4422 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4424 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4429 fn is_do_catch_block(&mut self) -> bool {
4430 self.token.is_keyword(keywords::Do) &&
4431 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4432 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4433 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4436 fn is_try_block(&mut self) -> bool {
4437 self.token.is_keyword(keywords::Try) &&
4438 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4440 self.span.edition() >= Edition::Edition2018 &&
4442 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4443 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4446 fn is_union_item(&self) -> bool {
4447 self.token.is_keyword(keywords::Union) &&
4448 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4451 fn is_crate_vis(&self) -> bool {
4452 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4455 fn is_extern_non_path(&self) -> bool {
4456 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4459 fn is_existential_type_decl(&self) -> bool {
4460 self.token.is_keyword(keywords::Existential) &&
4461 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4464 fn is_auto_trait_item(&mut self) -> bool {
4466 (self.token.is_keyword(keywords::Auto)
4467 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4468 || // unsafe auto trait
4469 (self.token.is_keyword(keywords::Unsafe) &&
4470 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4471 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4474 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4475 -> PResult<'a, Option<P<Item>>> {
4476 let token_lo = self.span;
4477 let (ident, def) = match self.token {
4478 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4480 let ident = self.parse_ident()?;
4481 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4482 match self.parse_token_tree() {
4483 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4484 _ => unreachable!(),
4486 } else if self.check(&token::OpenDelim(token::Paren)) {
4487 let args = self.parse_token_tree();
4488 let body = if self.check(&token::OpenDelim(token::Brace)) {
4489 self.parse_token_tree()
4494 TokenStream::concat(vec![
4496 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4504 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4506 token::Ident(ident, _) if ident.name == "macro_rules" &&
4507 self.look_ahead(1, |t| *t == token::Not) => {
4508 let prev_span = self.prev_span;
4509 self.complain_if_pub_macro(&vis.node, prev_span);
4513 let ident = self.parse_ident()?;
4514 let (delim, tokens) = self.expect_delimited_token_tree()?;
4515 if delim != MacDelimiter::Brace {
4516 if !self.eat(&token::Semi) {
4517 let msg = "macros that expand to items must either \
4518 be surrounded with braces or followed by a semicolon";
4519 self.span_err(self.prev_span, msg);
4523 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4525 _ => return Ok(None),
4528 let span = lo.to(self.prev_span);
4529 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4532 fn parse_stmt_without_recovery(&mut self,
4533 macro_legacy_warnings: bool)
4534 -> PResult<'a, Option<Stmt>> {
4535 maybe_whole!(self, NtStmt, |x| Some(x));
4537 let attrs = self.parse_outer_attributes()?;
4540 Ok(Some(if self.eat_keyword(keywords::Let) {
4542 id: ast::DUMMY_NODE_ID,
4543 node: StmtKind::Local(self.parse_local(attrs.into())?),
4544 span: lo.to(self.prev_span),
4546 } else if let Some(macro_def) = self.eat_macro_def(
4548 &source_map::respan(lo, VisibilityKind::Inherited),
4552 id: ast::DUMMY_NODE_ID,
4553 node: StmtKind::Item(macro_def),
4554 span: lo.to(self.prev_span),
4556 // Starts like a simple path, being careful to avoid contextual keywords
4557 // such as a union items, item with `crate` visibility or auto trait items.
4558 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4559 // like a path (1 token), but it fact not a path.
4560 // `union::b::c` - path, `union U { ... }` - not a path.
4561 // `crate::b::c` - path, `crate struct S;` - not a path.
4562 // `extern::b::c` - path, `extern crate c;` - not a path.
4563 } else if self.token.is_path_start() &&
4564 !self.token.is_qpath_start() &&
4565 !self.is_union_item() &&
4566 !self.is_crate_vis() &&
4567 !self.is_extern_non_path() &&
4568 !self.is_existential_type_decl() &&
4569 !self.is_auto_trait_item() {
4570 let pth = self.parse_path(PathStyle::Expr)?;
4572 if !self.eat(&token::Not) {
4573 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4574 self.parse_struct_expr(lo, pth, ThinVec::new())?
4576 let hi = self.prev_span;
4577 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4580 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4581 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4582 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4585 return Ok(Some(Stmt {
4586 id: ast::DUMMY_NODE_ID,
4587 node: StmtKind::Expr(expr),
4588 span: lo.to(self.prev_span),
4592 // it's a macro invocation
4593 let id = match self.token {
4594 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4595 _ => self.parse_ident()?,
4598 // check that we're pointing at delimiters (need to check
4599 // again after the `if`, because of `parse_ident`
4600 // consuming more tokens).
4602 token::OpenDelim(_) => {}
4604 // we only expect an ident if we didn't parse one
4606 let ident_str = if id.name == keywords::Invalid.name() {
4611 let tok_str = self.this_token_to_string();
4612 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4615 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4620 let (delim, tts) = self.expect_delimited_token_tree()?;
4621 let hi = self.prev_span;
4623 let style = if delim == MacDelimiter::Brace {
4624 MacStmtStyle::Braces
4626 MacStmtStyle::NoBraces
4629 if id.name == keywords::Invalid.name() {
4630 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4631 let node = if delim == MacDelimiter::Brace ||
4632 self.token == token::Semi || self.token == token::Eof {
4633 StmtKind::Mac(P((mac, style, attrs.into())))
4635 // We used to incorrectly stop parsing macro-expanded statements here.
4636 // If the next token will be an error anyway but could have parsed with the
4637 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4638 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4639 // These can continue an expression, so we can't stop parsing and warn.
4640 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4641 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4642 token::BinOp(token::And) | token::BinOp(token::Or) |
4643 token::AndAnd | token::OrOr |
4644 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4647 self.warn_missing_semicolon();
4648 StmtKind::Mac(P((mac, style, attrs.into())))
4650 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4651 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4652 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4656 id: ast::DUMMY_NODE_ID,
4661 // if it has a special ident, it's definitely an item
4663 // Require a semicolon or braces.
4664 if style != MacStmtStyle::Braces {
4665 if !self.eat(&token::Semi) {
4666 self.span_err(self.prev_span,
4667 "macros that expand to items must \
4668 either be surrounded with braces or \
4669 followed by a semicolon");
4672 let span = lo.to(hi);
4674 id: ast::DUMMY_NODE_ID,
4676 node: StmtKind::Item({
4678 span, id /*id is good here*/,
4679 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4680 respan(lo, VisibilityKind::Inherited),
4686 // FIXME: Bad copy of attrs
4687 let old_directory_ownership =
4688 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4689 let item = self.parse_item_(attrs.clone(), false, true)?;
4690 self.directory.ownership = old_directory_ownership;
4694 id: ast::DUMMY_NODE_ID,
4695 span: lo.to(i.span),
4696 node: StmtKind::Item(i),
4699 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4700 if !attrs.is_empty() {
4701 if s.prev_token_kind == PrevTokenKind::DocComment {
4702 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4703 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4704 s.span_err(s.span, "expected statement after outer attribute");
4709 // Do not attempt to parse an expression if we're done here.
4710 if self.token == token::Semi {
4711 unused_attrs(&attrs, self);
4716 if self.token == token::CloseDelim(token::Brace) {
4717 unused_attrs(&attrs, self);
4721 // Remainder are line-expr stmts.
4722 let e = self.parse_expr_res(
4723 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4725 id: ast::DUMMY_NODE_ID,
4726 span: lo.to(e.span),
4727 node: StmtKind::Expr(e),
4734 /// Is this expression a successfully-parsed statement?
4735 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4736 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4737 !classify::expr_requires_semi_to_be_stmt(e)
4740 /// Parse a block. No inner attrs are allowed.
4741 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4742 maybe_whole!(self, NtBlock, |x| x);
4746 if !self.eat(&token::OpenDelim(token::Brace)) {
4748 let tok = self.this_token_to_string();
4749 let mut do_not_suggest_help = false;
4750 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4751 if self.token.is_keyword(keywords::In) || self.token == token::Colon {
4752 do_not_suggest_help = true;
4753 e.span_label(sp, "expected `{`");
4756 // Check to see if the user has written something like
4761 // Which is valid in other languages, but not Rust.
4762 match self.parse_stmt_without_recovery(false) {
4764 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4765 || do_not_suggest_help {
4766 // if the next token is an open brace (e.g., `if a b {`), the place-
4767 // inside-a-block suggestion would be more likely wrong than right
4770 let mut stmt_span = stmt.span;
4771 // expand the span to include the semicolon, if it exists
4772 if self.eat(&token::Semi) {
4773 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4775 let sugg = pprust::to_string(|s| {
4776 use print::pprust::{PrintState, INDENT_UNIT};
4777 s.ibox(INDENT_UNIT)?;
4779 s.print_stmt(&stmt)?;
4780 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4782 e.span_suggestion_with_applicability(
4784 "try placing this code inside a block",
4786 // speculative, has been misleading in the past (closed Issue #46836)
4787 Applicability::MaybeIncorrect
4791 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4792 self.cancel(&mut e);
4799 self.parse_block_tail(lo, BlockCheckMode::Default)
4802 /// Parse a block. Inner attrs are allowed.
4803 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4804 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4807 self.expect(&token::OpenDelim(token::Brace))?;
4808 Ok((self.parse_inner_attributes()?,
4809 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4812 /// Parse the rest of a block expression or function body
4813 /// Precondition: already parsed the '{'.
4814 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4815 let mut stmts = vec![];
4816 let mut recovered = false;
4818 while !self.eat(&token::CloseDelim(token::Brace)) {
4819 let stmt = match self.parse_full_stmt(false) {
4822 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4823 self.eat(&token::CloseDelim(token::Brace));
4829 if let Some(stmt) = stmt {
4831 } else if self.token == token::Eof {
4834 // Found only `;` or `}`.
4840 id: ast::DUMMY_NODE_ID,
4842 span: lo.to(self.prev_span),
4847 /// Parse a statement, including the trailing semicolon.
4848 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4849 // skip looking for a trailing semicolon when we have an interpolated statement
4850 maybe_whole!(self, NtStmt, |x| Some(x));
4852 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4854 None => return Ok(None),
4858 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4859 // expression without semicolon
4860 if classify::expr_requires_semi_to_be_stmt(expr) {
4861 // Just check for errors and recover; do not eat semicolon yet.
4863 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4866 self.recover_stmt();
4870 StmtKind::Local(..) => {
4871 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4872 if macro_legacy_warnings && self.token != token::Semi {
4873 self.warn_missing_semicolon();
4875 self.expect_one_of(&[], &[token::Semi])?;
4881 if self.eat(&token::Semi) {
4882 stmt = stmt.add_trailing_semicolon();
4885 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4889 fn warn_missing_semicolon(&self) {
4890 self.diagnostic().struct_span_warn(self.span, {
4891 &format!("expected `;`, found `{}`", self.this_token_to_string())
4893 "This was erroneously allowed and will become a hard error in a future release"
4897 fn err_dotdotdot_syntax(&self, span: Span) {
4898 self.diagnostic().struct_span_err(span, {
4899 "unexpected token: `...`"
4900 }).span_suggestion_with_applicability(
4901 span, "use `..` for an exclusive range", "..".to_owned(),
4902 Applicability::MaybeIncorrect
4903 ).span_suggestion_with_applicability(
4904 span, "or `..=` for an inclusive range", "..=".to_owned(),
4905 Applicability::MaybeIncorrect
4909 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4910 // BOUND = TY_BOUND | LT_BOUND
4911 // LT_BOUND = LIFETIME (e.g. `'a`)
4912 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4913 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4914 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4915 let mut bounds = Vec::new();
4917 // This needs to be synchronized with `Token::can_begin_bound`.
4918 let is_bound_start = self.check_path() || self.check_lifetime() ||
4919 self.check(&token::Question) ||
4920 self.check_keyword(keywords::For) ||
4921 self.check(&token::OpenDelim(token::Paren));
4924 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4925 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4926 if self.token.is_lifetime() {
4927 if let Some(question_span) = question {
4928 self.span_err(question_span,
4929 "`?` may only modify trait bounds, not lifetime bounds");
4931 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4933 self.expect(&token::CloseDelim(token::Paren))?;
4934 self.span_err(self.prev_span,
4935 "parenthesized lifetime bounds are not supported");
4938 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4939 let path = self.parse_path(PathStyle::Type)?;
4941 self.expect(&token::CloseDelim(token::Paren))?;
4943 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4944 let modifier = if question.is_some() {
4945 TraitBoundModifier::Maybe
4947 TraitBoundModifier::None
4949 bounds.push(GenericBound::Trait(poly_trait, modifier));
4955 if !allow_plus || !self.eat_plus() {
4963 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
4964 self.parse_generic_bounds_common(true)
4967 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4968 // BOUND = LT_BOUND (e.g. `'a`)
4969 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4970 let mut lifetimes = Vec::new();
4971 while self.check_lifetime() {
4972 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4974 if !self.eat_plus() {
4981 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4982 fn parse_ty_param(&mut self,
4983 preceding_attrs: Vec<Attribute>)
4984 -> PResult<'a, GenericParam> {
4985 let ident = self.parse_ident()?;
4987 // Parse optional colon and param bounds.
4988 let bounds = if self.eat(&token::Colon) {
4989 self.parse_generic_bounds()?
4994 let default = if self.eat(&token::Eq) {
4995 Some(self.parse_ty()?)
5002 id: ast::DUMMY_NODE_ID,
5003 attrs: preceding_attrs.into(),
5005 kind: GenericParamKind::Type {
5011 /// Parses the following grammar:
5012 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5013 fn parse_trait_item_assoc_ty(&mut self)
5014 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5015 let ident = self.parse_ident()?;
5016 let mut generics = self.parse_generics()?;
5018 // Parse optional colon and param bounds.
5019 let bounds = if self.eat(&token::Colon) {
5020 self.parse_generic_bounds()?
5024 generics.where_clause = self.parse_where_clause()?;
5026 let default = if self.eat(&token::Eq) {
5027 Some(self.parse_ty()?)
5031 self.expect(&token::Semi)?;
5033 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5036 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5037 /// trailing comma and erroneous trailing attributes.
5038 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5039 let mut params = Vec::new();
5040 let mut seen_ty_param = false;
5042 let attrs = self.parse_outer_attributes()?;
5043 if self.check_lifetime() {
5044 let lifetime = self.expect_lifetime();
5045 // Parse lifetime parameter.
5046 let bounds = if self.eat(&token::Colon) {
5047 self.parse_lt_param_bounds()
5051 params.push(ast::GenericParam {
5052 ident: lifetime.ident,
5054 attrs: attrs.into(),
5056 kind: ast::GenericParamKind::Lifetime,
5059 self.span_err(self.prev_span,
5060 "lifetime parameters must be declared prior to type parameters");
5062 } else if self.check_ident() {
5063 // Parse type parameter.
5064 params.push(self.parse_ty_param(attrs)?);
5065 seen_ty_param = true;
5067 // Check for trailing attributes and stop parsing.
5068 if !attrs.is_empty() {
5069 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
5070 self.span_err(attrs[0].span,
5071 &format!("trailing attribute after {} parameters", param_kind));
5076 if !self.eat(&token::Comma) {
5083 /// Parse a set of optional generic type parameter declarations. Where
5084 /// clauses are not parsed here, and must be added later via
5085 /// `parse_where_clause()`.
5087 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5088 /// | ( < lifetimes , typaramseq ( , )? > )
5089 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5090 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5091 maybe_whole!(self, NtGenerics, |x| x);
5093 let span_lo = self.span;
5095 let params = self.parse_generic_params()?;
5099 where_clause: WhereClause {
5100 id: ast::DUMMY_NODE_ID,
5101 predicates: Vec::new(),
5102 span: syntax_pos::DUMMY_SP,
5104 span: span_lo.to(self.prev_span),
5107 Ok(ast::Generics::default())
5111 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5112 /// possibly including trailing comma.
5113 fn parse_generic_args(&mut self)
5114 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5115 let mut args = Vec::new();
5116 let mut bindings = Vec::new();
5117 let mut seen_type = false;
5118 let mut seen_binding = false;
5120 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5121 // Parse lifetime argument.
5122 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5123 if seen_type || seen_binding {
5124 self.span_err(self.prev_span,
5125 "lifetime parameters must be declared prior to type parameters");
5127 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5128 // Parse associated type binding.
5130 let ident = self.parse_ident()?;
5132 let ty = self.parse_ty()?;
5133 bindings.push(TypeBinding {
5134 id: ast::DUMMY_NODE_ID,
5137 span: lo.to(self.prev_span),
5139 seen_binding = true;
5140 } else if self.check_type() {
5141 // Parse type argument.
5142 let ty_param = self.parse_ty()?;
5144 self.span_err(ty_param.span,
5145 "type parameters must be declared prior to associated type bindings");
5147 args.push(GenericArg::Type(ty_param));
5153 if !self.eat(&token::Comma) {
5157 Ok((args, bindings))
5160 /// Parses an optional `where` clause and places it in `generics`.
5162 /// ```ignore (only-for-syntax-highlight)
5163 /// where T : Trait<U, V> + 'b, 'a : 'b
5165 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5166 maybe_whole!(self, NtWhereClause, |x| x);
5168 let mut where_clause = WhereClause {
5169 id: ast::DUMMY_NODE_ID,
5170 predicates: Vec::new(),
5171 span: syntax_pos::DUMMY_SP,
5174 if !self.eat_keyword(keywords::Where) {
5175 return Ok(where_clause);
5177 let lo = self.prev_span;
5179 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5180 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5181 // change we parse those generics now, but report an error.
5182 if self.choose_generics_over_qpath() {
5183 let generics = self.parse_generics()?;
5184 self.span_err(generics.span,
5185 "generic parameters on `where` clauses are reserved for future use");
5190 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5191 let lifetime = self.expect_lifetime();
5192 // Bounds starting with a colon are mandatory, but possibly empty.
5193 self.expect(&token::Colon)?;
5194 let bounds = self.parse_lt_param_bounds();
5195 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5196 ast::WhereRegionPredicate {
5197 span: lo.to(self.prev_span),
5202 } else if self.check_type() {
5203 // Parse optional `for<'a, 'b>`.
5204 // This `for` is parsed greedily and applies to the whole predicate,
5205 // the bounded type can have its own `for` applying only to it.
5206 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5207 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5208 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5209 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5211 // Parse type with mandatory colon and (possibly empty) bounds,
5212 // or with mandatory equality sign and the second type.
5213 let ty = self.parse_ty()?;
5214 if self.eat(&token::Colon) {
5215 let bounds = self.parse_generic_bounds()?;
5216 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5217 ast::WhereBoundPredicate {
5218 span: lo.to(self.prev_span),
5219 bound_generic_params: lifetime_defs,
5224 // FIXME: Decide what should be used here, `=` or `==`.
5225 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5226 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5227 let rhs_ty = self.parse_ty()?;
5228 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5229 ast::WhereEqPredicate {
5230 span: lo.to(self.prev_span),
5233 id: ast::DUMMY_NODE_ID,
5237 return self.unexpected();
5243 if !self.eat(&token::Comma) {
5248 where_clause.span = lo.to(self.prev_span);
5252 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5253 -> PResult<'a, (Vec<Arg> , bool)> {
5255 let mut variadic = false;
5256 let args: Vec<Option<Arg>> =
5257 self.parse_unspanned_seq(
5258 &token::OpenDelim(token::Paren),
5259 &token::CloseDelim(token::Paren),
5260 SeqSep::trailing_allowed(token::Comma),
5262 if p.token == token::DotDotDot {
5266 if p.token != token::CloseDelim(token::Paren) {
5269 "`...` must be last in argument list for variadic function");
5273 let span = p.prev_span;
5274 if p.token == token::CloseDelim(token::Paren) {
5275 // continue parsing to present any further errors
5278 "only foreign functions are allowed to be variadic"
5280 Ok(Some(dummy_arg(span)))
5282 // this function definition looks beyond recovery, stop parsing
5284 "only foreign functions are allowed to be variadic");
5289 match p.parse_arg_general(named_args) {
5290 Ok(arg) => Ok(Some(arg)),
5293 let lo = p.prev_span;
5294 // Skip every token until next possible arg or end.
5295 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5296 // Create a placeholder argument for proper arg count (#34264).
5297 let span = lo.to(p.prev_span);
5298 Ok(Some(dummy_arg(span)))
5305 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5307 if variadic && args.is_empty() {
5309 "variadic function must be declared with at least one named argument");
5312 Ok((args, variadic))
5315 /// Parse the argument list and result type of a function declaration
5316 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5318 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5319 let ret_ty = self.parse_ret_ty(true)?;
5328 /// Returns the parsed optional self argument and whether a self shortcut was used.
5329 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5330 let expect_ident = |this: &mut Self| match this.token {
5331 // Preserve hygienic context.
5332 token::Ident(ident, _) =>
5333 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5336 let isolated_self = |this: &mut Self, n| {
5337 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5338 this.look_ahead(n + 1, |t| t != &token::ModSep)
5341 // Parse optional self parameter of a method.
5342 // Only a limited set of initial token sequences is considered self parameters, anything
5343 // else is parsed as a normal function parameter list, so some lookahead is required.
5344 let eself_lo = self.span;
5345 let (eself, eself_ident, eself_hi) = match self.token {
5346 token::BinOp(token::And) => {
5352 (if isolated_self(self, 1) {
5354 SelfKind::Region(None, Mutability::Immutable)
5355 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5356 isolated_self(self, 2) {
5359 SelfKind::Region(None, Mutability::Mutable)
5360 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5361 isolated_self(self, 2) {
5363 let lt = self.expect_lifetime();
5364 SelfKind::Region(Some(lt), Mutability::Immutable)
5365 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5366 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5367 isolated_self(self, 3) {
5369 let lt = self.expect_lifetime();
5371 SelfKind::Region(Some(lt), Mutability::Mutable)
5374 }, expect_ident(self), self.prev_span)
5376 token::BinOp(token::Star) => {
5381 // Emit special error for `self` cases.
5382 (if isolated_self(self, 1) {
5384 self.span_err(self.span, "cannot pass `self` by raw pointer");
5385 SelfKind::Value(Mutability::Immutable)
5386 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5387 isolated_self(self, 2) {
5390 self.span_err(self.span, "cannot pass `self` by raw pointer");
5391 SelfKind::Value(Mutability::Immutable)
5394 }, expect_ident(self), self.prev_span)
5396 token::Ident(..) => {
5397 if isolated_self(self, 0) {
5400 let eself_ident = expect_ident(self);
5401 let eself_hi = self.prev_span;
5402 (if self.eat(&token::Colon) {
5403 let ty = self.parse_ty()?;
5404 SelfKind::Explicit(ty, Mutability::Immutable)
5406 SelfKind::Value(Mutability::Immutable)
5407 }, eself_ident, eself_hi)
5408 } else if self.token.is_keyword(keywords::Mut) &&
5409 isolated_self(self, 1) {
5413 let eself_ident = expect_ident(self);
5414 let eself_hi = self.prev_span;
5415 (if self.eat(&token::Colon) {
5416 let ty = self.parse_ty()?;
5417 SelfKind::Explicit(ty, Mutability::Mutable)
5419 SelfKind::Value(Mutability::Mutable)
5420 }, eself_ident, eself_hi)
5425 _ => return Ok(None),
5428 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5429 Ok(Some(Arg::from_self(eself, eself_ident)))
5432 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5433 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5434 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5436 self.expect(&token::OpenDelim(token::Paren))?;
5438 // Parse optional self argument
5439 let self_arg = self.parse_self_arg()?;
5441 // Parse the rest of the function parameter list.
5442 let sep = SeqSep::trailing_allowed(token::Comma);
5443 let fn_inputs = if let Some(self_arg) = self_arg {
5444 if self.check(&token::CloseDelim(token::Paren)) {
5446 } else if self.eat(&token::Comma) {
5447 let mut fn_inputs = vec![self_arg];
5448 fn_inputs.append(&mut self.parse_seq_to_before_end(
5449 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5453 return self.unexpected();
5456 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5459 // Parse closing paren and return type.
5460 self.expect(&token::CloseDelim(token::Paren))?;
5463 output: self.parse_ret_ty(true)?,
5468 // parse the |arg, arg| header on a lambda
5469 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5470 let inputs_captures = {
5471 if self.eat(&token::OrOr) {
5474 self.expect(&token::BinOp(token::Or))?;
5475 let args = self.parse_seq_to_before_tokens(
5476 &[&token::BinOp(token::Or), &token::OrOr],
5477 SeqSep::trailing_allowed(token::Comma),
5478 TokenExpectType::NoExpect,
5479 |p| p.parse_fn_block_arg()
5485 let output = self.parse_ret_ty(true)?;
5488 inputs: inputs_captures,
5494 /// Parse the name and optional generic types of a function header.
5495 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5496 let id = self.parse_ident()?;
5497 let generics = self.parse_generics()?;
5501 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5502 attrs: Vec<Attribute>) -> P<Item> {
5506 id: ast::DUMMY_NODE_ID,
5514 /// Parse an item-position function declaration.
5515 fn parse_item_fn(&mut self,
5518 constness: Spanned<Constness>,
5520 -> PResult<'a, ItemInfo> {
5521 let (ident, mut generics) = self.parse_fn_header()?;
5522 let decl = self.parse_fn_decl(false)?;
5523 generics.where_clause = self.parse_where_clause()?;
5524 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5525 let header = FnHeader { unsafety, asyncness, constness, abi };
5526 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5529 /// true if we are looking at `const ID`, false for things like `const fn` etc
5530 fn is_const_item(&mut self) -> bool {
5531 self.token.is_keyword(keywords::Const) &&
5532 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5533 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5536 /// parses all the "front matter" for a `fn` declaration, up to
5537 /// and including the `fn` keyword:
5541 /// - `const unsafe fn`
5544 fn parse_fn_front_matter(&mut self)
5552 let is_const_fn = self.eat_keyword(keywords::Const);
5553 let const_span = self.prev_span;
5554 let unsafety = self.parse_unsafety();
5555 let asyncness = self.parse_asyncness();
5556 let (constness, unsafety, abi) = if is_const_fn {
5557 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5559 let abi = if self.eat_keyword(keywords::Extern) {
5560 self.parse_opt_abi()?.unwrap_or(Abi::C)
5564 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5566 self.expect_keyword(keywords::Fn)?;
5567 Ok((constness, unsafety, asyncness, abi))
5570 /// Parse an impl item.
5571 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5572 maybe_whole!(self, NtImplItem, |x| x);
5573 let attrs = self.parse_outer_attributes()?;
5574 let (mut item, tokens) = self.collect_tokens(|this| {
5575 this.parse_impl_item_(at_end, attrs)
5578 // See `parse_item` for why this clause is here.
5579 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5580 item.tokens = Some(tokens);
5585 fn parse_impl_item_(&mut self,
5587 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5589 let vis = self.parse_visibility(false)?;
5590 let defaultness = self.parse_defaultness();
5591 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5592 let (name, alias, generics) = type_?;
5593 let kind = match alias {
5594 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5595 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5597 (name, kind, generics)
5598 } else if self.is_const_item() {
5599 // This parses the grammar:
5600 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5601 self.expect_keyword(keywords::Const)?;
5602 let name = self.parse_ident()?;
5603 self.expect(&token::Colon)?;
5604 let typ = self.parse_ty()?;
5605 self.expect(&token::Eq)?;
5606 let expr = self.parse_expr()?;
5607 self.expect(&token::Semi)?;
5608 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5610 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5611 attrs.extend(inner_attrs);
5612 (name, node, generics)
5616 id: ast::DUMMY_NODE_ID,
5617 span: lo.to(self.prev_span),
5628 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5629 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5634 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5636 VisibilityKind::Inherited => Ok(()),
5638 let is_macro_rules: bool = match self.token {
5639 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5643 let mut err = self.diagnostic()
5644 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5645 err.span_suggestion_with_applicability(
5647 "try exporting the macro",
5648 "#[macro_export]".to_owned(),
5649 Applicability::MaybeIncorrect // speculative
5653 let mut err = self.diagnostic()
5654 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5655 err.help("try adjusting the macro to put `pub` inside the invocation");
5662 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5663 -> DiagnosticBuilder<'a>
5665 let expected_kinds = if item_type == "extern" {
5666 "missing `fn`, `type`, or `static`"
5668 "missing `fn`, `type`, or `const`"
5671 // Given this code `path(`, it seems like this is not
5672 // setting the visibility of a macro invocation, but rather
5673 // a mistyped method declaration.
5674 // Create a diagnostic pointing out that `fn` is missing.
5676 // x | pub path(&self) {
5677 // | ^ missing `fn`, `type`, or `const`
5679 // ^^ `sp` below will point to this
5680 let sp = prev_span.between(self.prev_span);
5681 let mut err = self.diagnostic().struct_span_err(
5683 &format!("{} for {}-item declaration",
5684 expected_kinds, item_type));
5685 err.span_label(sp, expected_kinds);
5689 /// Parse a method or a macro invocation in a trait impl.
5690 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5691 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5692 ast::ImplItemKind)> {
5693 // code copied from parse_macro_use_or_failure... abstraction!
5694 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5696 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5697 ast::ImplItemKind::Macro(mac)))
5699 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5700 let ident = self.parse_ident()?;
5701 let mut generics = self.parse_generics()?;
5702 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5703 generics.where_clause = self.parse_where_clause()?;
5705 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5706 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5707 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5708 ast::MethodSig { header, decl },
5714 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5715 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5716 let ident = self.parse_ident()?;
5717 let mut tps = self.parse_generics()?;
5719 // Parse optional colon and supertrait bounds.
5720 let bounds = if self.eat(&token::Colon) {
5721 self.parse_generic_bounds()?
5726 if self.eat(&token::Eq) {
5727 // it's a trait alias
5728 let bounds = self.parse_generic_bounds()?;
5729 tps.where_clause = self.parse_where_clause()?;
5730 self.expect(&token::Semi)?;
5731 if unsafety != Unsafety::Normal {
5732 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5734 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5736 // it's a normal trait
5737 tps.where_clause = self.parse_where_clause()?;
5738 self.expect(&token::OpenDelim(token::Brace))?;
5739 let mut trait_items = vec![];
5740 while !self.eat(&token::CloseDelim(token::Brace)) {
5741 let mut at_end = false;
5742 match self.parse_trait_item(&mut at_end) {
5743 Ok(item) => trait_items.push(item),
5747 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5752 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5756 fn choose_generics_over_qpath(&self) -> bool {
5757 // There's an ambiguity between generic parameters and qualified paths in impls.
5758 // If we see `<` it may start both, so we have to inspect some following tokens.
5759 // The following combinations can only start generics,
5760 // but not qualified paths (with one exception):
5761 // `<` `>` - empty generic parameters
5762 // `<` `#` - generic parameters with attributes
5763 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5764 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5765 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5766 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5767 // The only truly ambiguous case is
5768 // `<` IDENT `>` `::` IDENT ...
5769 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5770 // because this is what almost always expected in practice, qualified paths in impls
5771 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5772 self.token == token::Lt &&
5773 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5774 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5775 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5776 t == &token::Colon || t == &token::Eq))
5779 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5780 self.expect(&token::OpenDelim(token::Brace))?;
5781 let attrs = self.parse_inner_attributes()?;
5783 let mut impl_items = Vec::new();
5784 while !self.eat(&token::CloseDelim(token::Brace)) {
5785 let mut at_end = false;
5786 match self.parse_impl_item(&mut at_end) {
5787 Ok(impl_item) => impl_items.push(impl_item),
5791 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5796 Ok((impl_items, attrs))
5799 /// Parses an implementation item, `impl` keyword is already parsed.
5800 /// impl<'a, T> TYPE { /* impl items */ }
5801 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5802 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5803 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5804 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5805 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5806 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5807 -> PResult<'a, ItemInfo> {
5808 // First, parse generic parameters if necessary.
5809 let mut generics = if self.choose_generics_over_qpath() {
5810 self.parse_generics()?
5812 ast::Generics::default()
5815 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5816 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5818 ast::ImplPolarity::Negative
5820 ast::ImplPolarity::Positive
5823 // Parse both types and traits as a type, then reinterpret if necessary.
5824 let ty_first = self.parse_ty()?;
5826 // If `for` is missing we try to recover.
5827 let has_for = self.eat_keyword(keywords::For);
5828 let missing_for_span = self.prev_span.between(self.span);
5830 let ty_second = if self.token == token::DotDot {
5831 // We need to report this error after `cfg` expansion for compatibility reasons
5832 self.bump(); // `..`, do not add it to expected tokens
5833 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5834 } else if has_for || self.token.can_begin_type() {
5835 Some(self.parse_ty()?)
5840 generics.where_clause = self.parse_where_clause()?;
5842 let (impl_items, attrs) = self.parse_impl_body()?;
5844 let item_kind = match ty_second {
5845 Some(ty_second) => {
5846 // impl Trait for Type
5848 self.span_err(missing_for_span, "missing `for` in a trait impl");
5851 let ty_first = ty_first.into_inner();
5852 let path = match ty_first.node {
5853 // This notably includes paths passed through `ty` macro fragments (#46438).
5854 TyKind::Path(None, path) => path,
5856 self.span_err(ty_first.span, "expected a trait, found type");
5857 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5860 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5862 ItemKind::Impl(unsafety, polarity, defaultness,
5863 generics, Some(trait_ref), ty_second, impl_items)
5867 ItemKind::Impl(unsafety, polarity, defaultness,
5868 generics, None, ty_first, impl_items)
5872 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5875 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5876 if self.eat_keyword(keywords::For) {
5878 let params = self.parse_generic_params()?;
5880 // We rely on AST validation to rule out invalid cases: There must not be type
5881 // parameters, and the lifetime parameters must not have bounds.
5888 /// Parse struct Foo { ... }
5889 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5890 let class_name = self.parse_ident()?;
5892 let mut generics = self.parse_generics()?;
5894 // There is a special case worth noting here, as reported in issue #17904.
5895 // If we are parsing a tuple struct it is the case that the where clause
5896 // should follow the field list. Like so:
5898 // struct Foo<T>(T) where T: Copy;
5900 // If we are parsing a normal record-style struct it is the case
5901 // that the where clause comes before the body, and after the generics.
5902 // So if we look ahead and see a brace or a where-clause we begin
5903 // parsing a record style struct.
5905 // Otherwise if we look ahead and see a paren we parse a tuple-style
5908 let vdata = if self.token.is_keyword(keywords::Where) {
5909 generics.where_clause = self.parse_where_clause()?;
5910 if self.eat(&token::Semi) {
5911 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5912 VariantData::Unit(ast::DUMMY_NODE_ID)
5914 // If we see: `struct Foo<T> where T: Copy { ... }`
5915 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5917 // No `where` so: `struct Foo<T>;`
5918 } else if self.eat(&token::Semi) {
5919 VariantData::Unit(ast::DUMMY_NODE_ID)
5920 // Record-style struct definition
5921 } else if self.token == token::OpenDelim(token::Brace) {
5922 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5923 // Tuple-style struct definition with optional where-clause.
5924 } else if self.token == token::OpenDelim(token::Paren) {
5925 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5926 generics.where_clause = self.parse_where_clause()?;
5927 self.expect(&token::Semi)?;
5930 let token_str = self.this_token_to_string();
5931 let mut err = self.fatal(&format!(
5932 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5935 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5939 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5942 /// Parse union Foo { ... }
5943 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5944 let class_name = self.parse_ident()?;
5946 let mut generics = self.parse_generics()?;
5948 let vdata = if self.token.is_keyword(keywords::Where) {
5949 generics.where_clause = self.parse_where_clause()?;
5950 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5951 } else if self.token == token::OpenDelim(token::Brace) {
5952 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5954 let token_str = self.this_token_to_string();
5955 let mut err = self.fatal(&format!(
5956 "expected `where` or `{{` after union name, found `{}`", token_str));
5957 err.span_label(self.span, "expected `where` or `{` after union name");
5961 Ok((class_name, ItemKind::Union(vdata, generics), None))
5964 fn consume_block(&mut self, delim: token::DelimToken) {
5965 let mut brace_depth = 0;
5966 if !self.eat(&token::OpenDelim(delim)) {
5970 if self.eat(&token::OpenDelim(delim)) {
5972 } else if self.eat(&token::CloseDelim(delim)) {
5973 if brace_depth == 0 {
5979 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5987 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5988 let mut fields = Vec::new();
5989 if self.eat(&token::OpenDelim(token::Brace)) {
5990 while self.token != token::CloseDelim(token::Brace) {
5991 let field = self.parse_struct_decl_field().map_err(|e| {
5992 self.recover_stmt();
5996 Ok(field) => fields.push(field),
6002 self.eat(&token::CloseDelim(token::Brace));
6004 let token_str = self.this_token_to_string();
6005 let mut err = self.fatal(&format!(
6006 "expected `where`, or `{{` after struct name, found `{}`", token_str));
6007 err.span_label(self.span, "expected `where`, or `{` after struct name");
6014 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6015 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6016 // Unit like structs are handled in parse_item_struct function
6017 let fields = self.parse_unspanned_seq(
6018 &token::OpenDelim(token::Paren),
6019 &token::CloseDelim(token::Paren),
6020 SeqSep::trailing_allowed(token::Comma),
6022 let attrs = p.parse_outer_attributes()?;
6024 let vis = p.parse_visibility(true)?;
6025 let ty = p.parse_ty()?;
6027 span: lo.to(ty.span),
6030 id: ast::DUMMY_NODE_ID,
6039 /// Parse a structure field declaration
6040 fn parse_single_struct_field(&mut self,
6043 attrs: Vec<Attribute> )
6044 -> PResult<'a, StructField> {
6045 let mut seen_comma: bool = false;
6046 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6047 if self.token == token::Comma {
6054 token::CloseDelim(token::Brace) => {}
6055 token::DocComment(_) => {
6056 let previous_span = self.prev_span;
6057 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6058 self.bump(); // consume the doc comment
6059 let comma_after_doc_seen = self.eat(&token::Comma);
6060 // `seen_comma` is always false, because we are inside doc block
6061 // condition is here to make code more readable
6062 if seen_comma == false && comma_after_doc_seen == true {
6065 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6068 if seen_comma == false {
6069 let sp = self.sess.source_map().next_point(previous_span);
6070 err.span_suggestion_with_applicability(
6072 "missing comma here",
6074 Applicability::MachineApplicable
6081 let sp = self.sess.source_map().next_point(self.prev_span);
6082 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
6083 self.this_token_to_string()));
6084 if self.token.is_ident() {
6085 // This is likely another field; emit the diagnostic and keep going
6086 err.span_suggestion(sp, "try adding a comma", ",".into());
6096 /// Parse an element of a struct definition
6097 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6098 let attrs = self.parse_outer_attributes()?;
6100 let vis = self.parse_visibility(false)?;
6101 self.parse_single_struct_field(lo, vis, attrs)
6104 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6105 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6106 /// a function definition, it's not a tuple struct field) and the contents within the parens
6107 /// isn't valid, emit a proper diagnostic.
6108 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6109 maybe_whole!(self, NtVis, |x| x);
6111 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6112 if self.is_crate_vis() {
6113 self.bump(); // `crate`
6114 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6117 if !self.eat_keyword(keywords::Pub) {
6118 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6119 // keyword to grab a span from for inherited visibility; an empty span at the
6120 // beginning of the current token would seem to be the "Schelling span".
6121 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6123 let lo = self.prev_span;
6125 if self.check(&token::OpenDelim(token::Paren)) {
6126 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6127 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6128 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6129 // by the following tokens.
6130 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6133 self.bump(); // `crate`
6134 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6136 lo.to(self.prev_span),
6137 VisibilityKind::Crate(CrateSugar::PubCrate),
6140 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6143 self.bump(); // `in`
6144 let path = self.parse_path(PathStyle::Mod)?; // `path`
6145 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6146 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6148 id: ast::DUMMY_NODE_ID,
6151 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6152 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6153 t.is_keyword(keywords::SelfValue))
6155 // `pub(self)` or `pub(super)`
6157 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6158 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6159 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6161 id: ast::DUMMY_NODE_ID,
6164 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6165 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6167 let msg = "incorrect visibility restriction";
6168 let suggestion = r##"some possible visibility restrictions are:
6169 `pub(crate)`: visible only on the current crate
6170 `pub(super)`: visible only in the current module's parent
6171 `pub(in path::to::module)`: visible only on the specified path"##;
6172 let path = self.parse_path(PathStyle::Mod)?;
6173 let sp = self.prev_span;
6174 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6175 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6176 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6177 err.help(suggestion);
6178 err.span_suggestion_with_applicability(
6179 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6181 err.emit(); // emit diagnostic, but continue with public visibility
6185 Ok(respan(lo, VisibilityKind::Public))
6188 /// Parse defaultness: `default` or nothing.
6189 fn parse_defaultness(&mut self) -> Defaultness {
6190 // `pub` is included for better error messages
6191 if self.check_keyword(keywords::Default) &&
6192 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6193 t.is_keyword(keywords::Const) ||
6194 t.is_keyword(keywords::Fn) ||
6195 t.is_keyword(keywords::Unsafe) ||
6196 t.is_keyword(keywords::Extern) ||
6197 t.is_keyword(keywords::Type) ||
6198 t.is_keyword(keywords::Pub)) {
6199 self.bump(); // `default`
6200 Defaultness::Default
6206 /// Given a termination token, parse all of the items in a module
6207 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6208 let mut items = vec![];
6209 while let Some(item) = self.parse_item()? {
6213 if !self.eat(term) {
6214 let token_str = self.this_token_to_string();
6215 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6216 if token_str == ";" {
6217 let msg = "consider removing this semicolon";
6218 err.span_suggestion_short_with_applicability(
6219 self.span, msg, String::new(), Applicability::MachineApplicable
6221 if !items.is_empty() { // Issue #51603
6222 let previous_item = &items[items.len()-1];
6223 let previous_item_kind_name = match previous_item.node {
6224 // say "braced struct" because tuple-structs and
6225 // braceless-empty-struct declarations do take a semicolon
6226 ItemKind::Struct(..) => Some("braced struct"),
6227 ItemKind::Enum(..) => Some("enum"),
6228 ItemKind::Trait(..) => Some("trait"),
6229 ItemKind::Union(..) => Some("union"),
6232 if let Some(name) = previous_item_kind_name {
6233 err.help(&format!("{} declarations are not followed by a semicolon",
6238 err.span_label(self.span, "expected item");
6243 let hi = if self.span.is_dummy() {
6250 inner: inner_lo.to(hi),
6255 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6256 let id = self.parse_ident()?;
6257 self.expect(&token::Colon)?;
6258 let ty = self.parse_ty()?;
6259 self.expect(&token::Eq)?;
6260 let e = self.parse_expr()?;
6261 self.expect(&token::Semi)?;
6262 let item = match m {
6263 Some(m) => ItemKind::Static(ty, m, e),
6264 None => ItemKind::Const(ty, e),
6266 Ok((id, item, None))
6269 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6270 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6271 let (in_cfg, outer_attrs) = {
6272 let mut strip_unconfigured = ::config::StripUnconfigured {
6274 should_test: false, // irrelevant
6275 features: None, // don't perform gated feature checking
6277 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6278 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6281 let id_span = self.span;
6282 let id = self.parse_ident()?;
6283 if self.check(&token::Semi) {
6285 if in_cfg && self.recurse_into_file_modules {
6286 // This mod is in an external file. Let's go get it!
6287 let ModulePathSuccess { path, directory_ownership, warn } =
6288 self.submod_path(id, &outer_attrs, id_span)?;
6289 let (module, mut attrs) =
6290 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6292 let attr = Attribute {
6293 id: attr::mk_attr_id(),
6294 style: ast::AttrStyle::Outer,
6295 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6296 tokens: TokenStream::empty(),
6297 is_sugared_doc: false,
6298 span: syntax_pos::DUMMY_SP,
6300 attr::mark_known(&attr);
6303 Ok((id, module, Some(attrs)))
6305 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6306 Ok((id, ItemKind::Mod(placeholder), None))
6309 let old_directory = self.directory.clone();
6310 self.push_directory(id, &outer_attrs);
6312 self.expect(&token::OpenDelim(token::Brace))?;
6313 let mod_inner_lo = self.span;
6314 let attrs = self.parse_inner_attributes()?;
6315 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6317 self.directory = old_directory;
6318 Ok((id, ItemKind::Mod(module), Some(attrs)))
6322 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6323 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6324 self.directory.path.to_mut().push(&path.as_str());
6325 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6327 self.directory.path.to_mut().push(&id.as_str());
6331 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6332 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6335 // On windows, the base path might have the form
6336 // `\\?\foo\bar` in which case it does not tolerate
6337 // mixed `/` and `\` separators, so canonicalize
6340 let s = s.replace("/", "\\");
6341 Some(dir_path.join(s))
6347 /// Returns either a path to a module, or .
6348 pub fn default_submod_path(
6350 relative: Option<ast::Ident>,
6352 source_map: &SourceMap) -> ModulePath
6354 // If we're in a foo.rs file instead of a mod.rs file,
6355 // we need to look for submodules in
6356 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6357 // `./<id>.rs` and `./<id>/mod.rs`.
6358 let relative_prefix_string;
6359 let relative_prefix = if let Some(ident) = relative {
6360 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6361 &relative_prefix_string
6366 let mod_name = id.to_string();
6367 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6368 let secondary_path_str = format!("{}{}{}mod.rs",
6369 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6370 let default_path = dir_path.join(&default_path_str);
6371 let secondary_path = dir_path.join(&secondary_path_str);
6372 let default_exists = source_map.file_exists(&default_path);
6373 let secondary_exists = source_map.file_exists(&secondary_path);
6375 let result = match (default_exists, secondary_exists) {
6376 (true, false) => Ok(ModulePathSuccess {
6378 directory_ownership: DirectoryOwnership::Owned {
6383 (false, true) => Ok(ModulePathSuccess {
6384 path: secondary_path,
6385 directory_ownership: DirectoryOwnership::Owned {
6390 (false, false) => Err(Error::FileNotFoundForModule {
6391 mod_name: mod_name.clone(),
6392 default_path: default_path_str,
6393 secondary_path: secondary_path_str,
6394 dir_path: dir_path.display().to_string(),
6396 (true, true) => Err(Error::DuplicatePaths {
6397 mod_name: mod_name.clone(),
6398 default_path: default_path_str,
6399 secondary_path: secondary_path_str,
6405 path_exists: default_exists || secondary_exists,
6410 fn submod_path(&mut self,
6412 outer_attrs: &[Attribute],
6414 -> PResult<'a, ModulePathSuccess> {
6415 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6416 return Ok(ModulePathSuccess {
6417 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6418 // All `#[path]` files are treated as though they are a `mod.rs` file.
6419 // This means that `mod foo;` declarations inside `#[path]`-included
6420 // files are siblings,
6422 // Note that this will produce weirdness when a file named `foo.rs` is
6423 // `#[path]` included and contains a `mod foo;` declaration.
6424 // If you encounter this, it's your own darn fault :P
6425 Some(_) => DirectoryOwnership::Owned { relative: None },
6426 _ => DirectoryOwnership::UnownedViaMod(true),
6433 let relative = match self.directory.ownership {
6434 DirectoryOwnership::Owned { relative } => {
6435 // Push the usage onto the list of non-mod.rs mod uses.
6436 // This is used later for feature-gate error reporting.
6437 if let Some(cur_file_ident) = relative {
6439 .non_modrs_mods.borrow_mut()
6440 .push((cur_file_ident, id_sp));
6444 DirectoryOwnership::UnownedViaBlock |
6445 DirectoryOwnership::UnownedViaMod(_) => None,
6447 let paths = Parser::default_submod_path(
6448 id, relative, &self.directory.path, self.sess.source_map());
6450 match self.directory.ownership {
6451 DirectoryOwnership::Owned { .. } => {
6452 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6454 DirectoryOwnership::UnownedViaBlock => {
6456 "Cannot declare a non-inline module inside a block \
6457 unless it has a path attribute";
6458 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6459 if paths.path_exists {
6460 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6462 err.span_note(id_sp, &msg);
6466 DirectoryOwnership::UnownedViaMod(warn) => {
6468 if let Ok(result) = paths.result {
6469 return Ok(ModulePathSuccess { warn: true, ..result });
6472 let mut err = self.diagnostic().struct_span_err(id_sp,
6473 "cannot declare a new module at this location");
6474 if !id_sp.is_dummy() {
6475 let src_path = self.sess.source_map().span_to_filename(id_sp);
6476 if let FileName::Real(src_path) = src_path {
6477 if let Some(stem) = src_path.file_stem() {
6478 let mut dest_path = src_path.clone();
6479 dest_path.set_file_name(stem);
6480 dest_path.push("mod.rs");
6481 err.span_note(id_sp,
6482 &format!("maybe move this module `{}` to its own \
6483 directory via `{}`", src_path.display(),
6484 dest_path.display()));
6488 if paths.path_exists {
6489 err.span_note(id_sp,
6490 &format!("... or maybe `use` the module `{}` instead \
6491 of possibly redeclaring it",
6499 /// Read a module from a source file.
6500 fn eval_src_mod(&mut self,
6502 directory_ownership: DirectoryOwnership,
6505 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6506 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6507 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6508 let mut err = String::from("circular modules: ");
6509 let len = included_mod_stack.len();
6510 for p in &included_mod_stack[i.. len] {
6511 err.push_str(&p.to_string_lossy());
6512 err.push_str(" -> ");
6514 err.push_str(&path.to_string_lossy());
6515 return Err(self.span_fatal(id_sp, &err[..]));
6517 included_mod_stack.push(path.clone());
6518 drop(included_mod_stack);
6521 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6522 p0.cfg_mods = self.cfg_mods;
6523 let mod_inner_lo = p0.span;
6524 let mod_attrs = p0.parse_inner_attributes()?;
6525 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6526 self.sess.included_mod_stack.borrow_mut().pop();
6527 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6530 /// Parse a function declaration from a foreign module
6531 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6532 -> PResult<'a, ForeignItem> {
6533 self.expect_keyword(keywords::Fn)?;
6535 let (ident, mut generics) = self.parse_fn_header()?;
6536 let decl = self.parse_fn_decl(true)?;
6537 generics.where_clause = self.parse_where_clause()?;
6539 self.expect(&token::Semi)?;
6540 Ok(ast::ForeignItem {
6543 node: ForeignItemKind::Fn(decl, generics),
6544 id: ast::DUMMY_NODE_ID,
6550 /// Parse a static item from a foreign module.
6551 /// Assumes that the `static` keyword is already parsed.
6552 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6553 -> PResult<'a, ForeignItem> {
6554 let mutbl = self.eat_keyword(keywords::Mut);
6555 let ident = self.parse_ident()?;
6556 self.expect(&token::Colon)?;
6557 let ty = self.parse_ty()?;
6559 self.expect(&token::Semi)?;
6563 node: ForeignItemKind::Static(ty, mutbl),
6564 id: ast::DUMMY_NODE_ID,
6570 /// Parse a type from a foreign module
6571 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6572 -> PResult<'a, ForeignItem> {
6573 self.expect_keyword(keywords::Type)?;
6575 let ident = self.parse_ident()?;
6577 self.expect(&token::Semi)?;
6578 Ok(ast::ForeignItem {
6581 node: ForeignItemKind::Ty,
6582 id: ast::DUMMY_NODE_ID,
6588 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6589 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6590 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6592 let mut ident = self.parse_ident()?;
6593 let mut idents = vec![];
6594 let mut replacement = vec![];
6595 let mut fixed_crate_name = false;
6596 // Accept `extern crate name-like-this` for better diagnostics
6597 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6598 if self.token == dash { // Do not include `-` as part of the expected tokens list
6599 while self.eat(&dash) {
6600 fixed_crate_name = true;
6601 replacement.push((self.prev_span, "_".to_string()));
6602 idents.push(self.parse_ident()?);
6605 if fixed_crate_name {
6606 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6607 let mut fixed_name = format!("{}", ident.name);
6608 for part in idents {
6609 fixed_name.push_str(&format!("_{}", part.name));
6611 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6613 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6614 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6615 err.multipart_suggestion(suggestion_msg, replacement);
6621 /// Parse extern crate links
6625 /// extern crate foo;
6626 /// extern crate bar as foo;
6627 fn parse_item_extern_crate(&mut self,
6629 visibility: Visibility,
6630 attrs: Vec<Attribute>)
6631 -> PResult<'a, P<Item>> {
6632 // Accept `extern crate name-like-this` for better diagnostics
6633 let orig_name = self.parse_crate_name_with_dashes()?;
6634 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6635 (rename, Some(orig_name.name))
6639 self.expect(&token::Semi)?;
6641 let span = lo.to(self.prev_span);
6642 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6645 /// Parse `extern` for foreign ABIs
6648 /// `extern` is expected to have been
6649 /// consumed before calling this method
6655 fn parse_item_foreign_mod(&mut self,
6657 opt_abi: Option<Abi>,
6658 visibility: Visibility,
6659 mut attrs: Vec<Attribute>)
6660 -> PResult<'a, P<Item>> {
6661 self.expect(&token::OpenDelim(token::Brace))?;
6663 let abi = opt_abi.unwrap_or(Abi::C);
6665 attrs.extend(self.parse_inner_attributes()?);
6667 let mut foreign_items = vec![];
6668 while let Some(item) = self.parse_foreign_item()? {
6669 foreign_items.push(item);
6671 self.expect(&token::CloseDelim(token::Brace))?;
6673 let prev_span = self.prev_span;
6674 let m = ast::ForeignMod {
6676 items: foreign_items
6678 let invalid = keywords::Invalid.ident();
6679 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6682 /// Parse type Foo = Bar;
6684 /// existential type Foo: Bar;
6686 /// return None without modifying the parser state
6687 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6688 // This parses the grammar:
6689 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6690 if self.check_keyword(keywords::Type) ||
6691 self.check_keyword(keywords::Existential) &&
6692 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6693 let existential = self.eat_keyword(keywords::Existential);
6694 assert!(self.eat_keyword(keywords::Type));
6695 Some(self.parse_existential_or_alias(existential))
6701 /// Parse type alias or existential type
6702 fn parse_existential_or_alias(
6705 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6706 let ident = self.parse_ident()?;
6707 let mut tps = self.parse_generics()?;
6708 tps.where_clause = self.parse_where_clause()?;
6709 let alias = if existential {
6710 self.expect(&token::Colon)?;
6711 let bounds = self.parse_generic_bounds()?;
6712 AliasKind::Existential(bounds)
6714 self.expect(&token::Eq)?;
6715 let ty = self.parse_ty()?;
6718 self.expect(&token::Semi)?;
6719 Ok((ident, alias, tps))
6722 /// Parse the part of an "enum" decl following the '{'
6723 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6724 let mut variants = Vec::new();
6725 let mut all_nullary = true;
6726 let mut any_disr = None;
6727 while self.token != token::CloseDelim(token::Brace) {
6728 let variant_attrs = self.parse_outer_attributes()?;
6729 let vlo = self.span;
6732 let mut disr_expr = None;
6733 let ident = self.parse_ident()?;
6734 if self.check(&token::OpenDelim(token::Brace)) {
6735 // Parse a struct variant.
6736 all_nullary = false;
6737 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6738 ast::DUMMY_NODE_ID);
6739 } else if self.check(&token::OpenDelim(token::Paren)) {
6740 all_nullary = false;
6741 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6742 ast::DUMMY_NODE_ID);
6743 } else if self.eat(&token::Eq) {
6744 disr_expr = Some(AnonConst {
6745 id: ast::DUMMY_NODE_ID,
6746 value: self.parse_expr()?,
6748 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6749 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6751 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6754 let vr = ast::Variant_ {
6756 attrs: variant_attrs,
6760 variants.push(respan(vlo.to(self.prev_span), vr));
6762 if !self.eat(&token::Comma) { break; }
6764 self.expect(&token::CloseDelim(token::Brace))?;
6766 Some(disr_span) if !all_nullary =>
6767 self.span_err(disr_span,
6768 "discriminator values can only be used with a field-less enum"),
6772 Ok(ast::EnumDef { variants: variants })
6775 /// Parse an "enum" declaration
6776 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6777 let id = self.parse_ident()?;
6778 let mut generics = self.parse_generics()?;
6779 generics.where_clause = self.parse_where_clause()?;
6780 self.expect(&token::OpenDelim(token::Brace))?;
6782 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6783 self.recover_stmt();
6784 self.eat(&token::CloseDelim(token::Brace));
6787 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6790 /// Parses a string as an ABI spec on an extern type or module. Consumes
6791 /// the `extern` keyword, if one is found.
6792 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6794 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6796 self.expect_no_suffix(sp, "ABI spec", suf);
6798 match abi::lookup(&s.as_str()) {
6799 Some(abi) => Ok(Some(abi)),
6801 let prev_span = self.prev_span;
6802 let mut err = struct_span_err!(
6803 self.sess.span_diagnostic,
6806 "invalid ABI: found `{}`",
6808 err.span_label(prev_span, "invalid ABI");
6809 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6820 fn is_static_global(&mut self) -> bool {
6821 if self.check_keyword(keywords::Static) {
6822 // Check if this could be a closure
6823 !self.look_ahead(1, |token| {
6824 if token.is_keyword(keywords::Move) {
6828 token::BinOp(token::Or) | token::OrOr => true,
6839 attrs: Vec<Attribute>,
6840 macros_allowed: bool,
6841 attributes_allowed: bool,
6842 ) -> PResult<'a, Option<P<Item>>> {
6843 let (ret, tokens) = self.collect_tokens(|this| {
6844 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
6847 // Once we've parsed an item and recorded the tokens we got while
6848 // parsing we may want to store `tokens` into the item we're about to
6849 // return. Note, though, that we specifically didn't capture tokens
6850 // related to outer attributes. The `tokens` field here may later be
6851 // used with procedural macros to convert this item back into a token
6852 // stream, but during expansion we may be removing attributes as we go
6855 // If we've got inner attributes then the `tokens` we've got above holds
6856 // these inner attributes. If an inner attribute is expanded we won't
6857 // actually remove it from the token stream, so we'll just keep yielding
6858 // it (bad!). To work around this case for now we just avoid recording
6859 // `tokens` if we detect any inner attributes. This should help keep
6860 // expansion correct, but we should fix this bug one day!
6863 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6864 i.tokens = Some(tokens);
6871 /// Parse one of the items allowed by the flags.
6872 fn parse_item_implementation(
6874 attrs: Vec<Attribute>,
6875 macros_allowed: bool,
6876 attributes_allowed: bool,
6877 ) -> PResult<'a, Option<P<Item>>> {
6878 maybe_whole!(self, NtItem, |item| {
6879 let mut item = item.into_inner();
6880 let mut attrs = attrs;
6881 mem::swap(&mut item.attrs, &mut attrs);
6882 item.attrs.extend(attrs);
6888 let visibility = self.parse_visibility(false)?;
6890 if self.eat_keyword(keywords::Use) {
6892 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6893 self.expect(&token::Semi)?;
6895 let span = lo.to(self.prev_span);
6896 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6897 return Ok(Some(item));
6900 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6901 self.bump(); // `extern`
6902 if self.eat_keyword(keywords::Crate) {
6903 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6906 let opt_abi = self.parse_opt_abi()?;
6908 if self.eat_keyword(keywords::Fn) {
6909 // EXTERN FUNCTION ITEM
6910 let fn_span = self.prev_span;
6911 let abi = opt_abi.unwrap_or(Abi::C);
6912 let (ident, item_, extra_attrs) =
6913 self.parse_item_fn(Unsafety::Normal,
6915 respan(fn_span, Constness::NotConst),
6917 let prev_span = self.prev_span;
6918 let item = self.mk_item(lo.to(prev_span),
6922 maybe_append(attrs, extra_attrs));
6923 return Ok(Some(item));
6924 } else if self.check(&token::OpenDelim(token::Brace)) {
6925 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6931 if self.is_static_global() {
6934 let m = if self.eat_keyword(keywords::Mut) {
6937 Mutability::Immutable
6939 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6940 let prev_span = self.prev_span;
6941 let item = self.mk_item(lo.to(prev_span),
6945 maybe_append(attrs, extra_attrs));
6946 return Ok(Some(item));
6948 if self.eat_keyword(keywords::Const) {
6949 let const_span = self.prev_span;
6950 if self.check_keyword(keywords::Fn)
6951 || (self.check_keyword(keywords::Unsafe)
6952 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6953 // CONST FUNCTION ITEM
6954 let unsafety = self.parse_unsafety();
6956 let (ident, item_, extra_attrs) =
6957 self.parse_item_fn(unsafety,
6959 respan(const_span, Constness::Const),
6961 let prev_span = self.prev_span;
6962 let item = self.mk_item(lo.to(prev_span),
6966 maybe_append(attrs, extra_attrs));
6967 return Ok(Some(item));
6971 if self.eat_keyword(keywords::Mut) {
6972 let prev_span = self.prev_span;
6973 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6974 .help("did you mean to declare a static?")
6977 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6978 let prev_span = self.prev_span;
6979 let item = self.mk_item(lo.to(prev_span),
6983 maybe_append(attrs, extra_attrs));
6984 return Ok(Some(item));
6987 // `unsafe async fn` or `async fn`
6989 self.check_keyword(keywords::Unsafe) &&
6990 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
6992 self.check_keyword(keywords::Async) &&
6993 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
6996 // ASYNC FUNCTION ITEM
6997 let unsafety = self.parse_unsafety();
6998 self.expect_keyword(keywords::Async)?;
6999 self.expect_keyword(keywords::Fn)?;
7000 let fn_span = self.prev_span;
7001 let (ident, item_, extra_attrs) =
7002 self.parse_item_fn(unsafety,
7004 closure_id: ast::DUMMY_NODE_ID,
7005 return_impl_trait_id: ast::DUMMY_NODE_ID,
7007 respan(fn_span, Constness::NotConst),
7009 let prev_span = self.prev_span;
7010 let item = self.mk_item(lo.to(prev_span),
7014 maybe_append(attrs, extra_attrs));
7015 return Ok(Some(item));
7017 if self.check_keyword(keywords::Unsafe) &&
7018 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7019 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7021 // UNSAFE TRAIT ITEM
7022 self.bump(); // `unsafe`
7023 let is_auto = if self.eat_keyword(keywords::Trait) {
7026 self.expect_keyword(keywords::Auto)?;
7027 self.expect_keyword(keywords::Trait)?;
7030 let (ident, item_, extra_attrs) =
7031 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7032 let prev_span = self.prev_span;
7033 let item = self.mk_item(lo.to(prev_span),
7037 maybe_append(attrs, extra_attrs));
7038 return Ok(Some(item));
7040 if self.check_keyword(keywords::Impl) ||
7041 self.check_keyword(keywords::Unsafe) &&
7042 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7043 self.check_keyword(keywords::Default) &&
7044 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7045 self.check_keyword(keywords::Default) &&
7046 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7048 let defaultness = self.parse_defaultness();
7049 let unsafety = self.parse_unsafety();
7050 self.expect_keyword(keywords::Impl)?;
7051 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7052 let span = lo.to(self.prev_span);
7053 return Ok(Some(self.mk_item(span, ident, item, visibility,
7054 maybe_append(attrs, extra_attrs))));
7056 if self.check_keyword(keywords::Fn) {
7059 let fn_span = self.prev_span;
7060 let (ident, item_, extra_attrs) =
7061 self.parse_item_fn(Unsafety::Normal,
7063 respan(fn_span, Constness::NotConst),
7065 let prev_span = self.prev_span;
7066 let item = self.mk_item(lo.to(prev_span),
7070 maybe_append(attrs, extra_attrs));
7071 return Ok(Some(item));
7073 if self.check_keyword(keywords::Unsafe)
7074 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7075 // UNSAFE FUNCTION ITEM
7076 self.bump(); // `unsafe`
7077 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7078 self.check(&token::OpenDelim(token::Brace));
7079 let abi = if self.eat_keyword(keywords::Extern) {
7080 self.parse_opt_abi()?.unwrap_or(Abi::C)
7084 self.expect_keyword(keywords::Fn)?;
7085 let fn_span = self.prev_span;
7086 let (ident, item_, extra_attrs) =
7087 self.parse_item_fn(Unsafety::Unsafe,
7089 respan(fn_span, Constness::NotConst),
7091 let prev_span = self.prev_span;
7092 let item = self.mk_item(lo.to(prev_span),
7096 maybe_append(attrs, extra_attrs));
7097 return Ok(Some(item));
7099 if self.eat_keyword(keywords::Mod) {
7101 let (ident, item_, extra_attrs) =
7102 self.parse_item_mod(&attrs[..])?;
7103 let prev_span = self.prev_span;
7104 let item = self.mk_item(lo.to(prev_span),
7108 maybe_append(attrs, extra_attrs));
7109 return Ok(Some(item));
7111 if let Some(type_) = self.eat_type() {
7112 let (ident, alias, generics) = type_?;
7114 let item_ = match alias {
7115 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7116 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7118 let prev_span = self.prev_span;
7119 let item = self.mk_item(lo.to(prev_span),
7124 return Ok(Some(item));
7126 if self.eat_keyword(keywords::Enum) {
7128 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7129 let prev_span = self.prev_span;
7130 let item = self.mk_item(lo.to(prev_span),
7134 maybe_append(attrs, extra_attrs));
7135 return Ok(Some(item));
7137 if self.check_keyword(keywords::Trait)
7138 || (self.check_keyword(keywords::Auto)
7139 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7141 let is_auto = if self.eat_keyword(keywords::Trait) {
7144 self.expect_keyword(keywords::Auto)?;
7145 self.expect_keyword(keywords::Trait)?;
7149 let (ident, item_, extra_attrs) =
7150 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7151 let prev_span = self.prev_span;
7152 let item = self.mk_item(lo.to(prev_span),
7156 maybe_append(attrs, extra_attrs));
7157 return Ok(Some(item));
7159 if self.eat_keyword(keywords::Struct) {
7161 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7162 let prev_span = self.prev_span;
7163 let item = self.mk_item(lo.to(prev_span),
7167 maybe_append(attrs, extra_attrs));
7168 return Ok(Some(item));
7170 if self.is_union_item() {
7173 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7174 let prev_span = self.prev_span;
7175 let item = self.mk_item(lo.to(prev_span),
7179 maybe_append(attrs, extra_attrs));
7180 return Ok(Some(item));
7182 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7183 return Ok(Some(macro_def));
7186 // Verify whether we have encountered a struct or method definition where the user forgot to
7187 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7188 if visibility.node.is_pub() &&
7189 self.check_ident() &&
7190 self.look_ahead(1, |t| *t != token::Not)
7192 // Space between `pub` keyword and the identifier
7195 // ^^^ `sp` points here
7196 let sp = self.prev_span.between(self.span);
7197 let full_sp = self.prev_span.to(self.span);
7198 let ident_sp = self.span;
7199 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7200 // possible public struct definition where `struct` was forgotten
7201 let ident = self.parse_ident().unwrap();
7202 let msg = format!("add `struct` here to parse `{}` as a public struct",
7204 let mut err = self.diagnostic()
7205 .struct_span_err(sp, "missing `struct` for struct definition");
7206 err.span_suggestion_short_with_applicability(
7207 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7210 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7211 let ident = self.parse_ident().unwrap();
7212 self.consume_block(token::Paren);
7213 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7214 self.check(&token::OpenDelim(token::Brace))
7216 ("fn", "method", false)
7217 } else if self.check(&token::Colon) {
7221 ("fn` or `struct", "method or struct", true)
7224 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7225 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7227 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7231 err.span_suggestion_short_with_applicability(
7232 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7235 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7236 err.span_suggestion_with_applicability(
7238 "if you meant to call a macro, try",
7239 format!("{}!", snippet),
7240 // this is the `ambiguous` conditional branch
7241 Applicability::MaybeIncorrect
7244 err.help("if you meant to call a macro, remove the `pub` \
7245 and add a trailing `!` after the identifier");
7251 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7254 /// Parse a foreign item.
7255 crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
7256 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
7258 let attrs = self.parse_outer_attributes()?;
7260 let visibility = self.parse_visibility(false)?;
7262 // FOREIGN STATIC ITEM
7263 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7264 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7265 if self.token.is_keyword(keywords::Const) {
7267 .struct_span_err(self.span, "extern items cannot be `const`")
7268 .span_suggestion_with_applicability(
7270 "try using a static value",
7271 "static".to_owned(),
7272 Applicability::MachineApplicable
7275 self.bump(); // `static` or `const`
7276 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
7278 // FOREIGN FUNCTION ITEM
7279 if self.check_keyword(keywords::Fn) {
7280 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
7282 // FOREIGN TYPE ITEM
7283 if self.check_keyword(keywords::Type) {
7284 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
7287 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7291 ident: keywords::Invalid.ident(),
7292 span: lo.to(self.prev_span),
7293 id: ast::DUMMY_NODE_ID,
7296 node: ForeignItemKind::Macro(mac),
7301 if !attrs.is_empty() {
7302 self.expected_item_err(&attrs);
7310 /// This is the fall-through for parsing items.
7311 fn parse_macro_use_or_failure(
7313 attrs: Vec<Attribute> ,
7314 macros_allowed: bool,
7315 attributes_allowed: bool,
7317 visibility: Visibility
7318 ) -> PResult<'a, Option<P<Item>>> {
7319 if macros_allowed && self.token.is_path_start() {
7320 // MACRO INVOCATION ITEM
7322 let prev_span = self.prev_span;
7323 self.complain_if_pub_macro(&visibility.node, prev_span);
7325 let mac_lo = self.span;
7328 let pth = self.parse_path(PathStyle::Mod)?;
7329 self.expect(&token::Not)?;
7331 // a 'special' identifier (like what `macro_rules!` uses)
7332 // is optional. We should eventually unify invoc syntax
7334 let id = if self.token.is_ident() {
7337 keywords::Invalid.ident() // no special identifier
7339 // eat a matched-delimiter token tree:
7340 let (delim, tts) = self.expect_delimited_token_tree()?;
7341 if delim != MacDelimiter::Brace {
7342 if !self.eat(&token::Semi) {
7343 self.span_err(self.prev_span,
7344 "macros that expand to items must either \
7345 be surrounded with braces or followed by \
7350 let hi = self.prev_span;
7351 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7352 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7353 return Ok(Some(item));
7356 // FAILURE TO PARSE ITEM
7357 match visibility.node {
7358 VisibilityKind::Inherited => {}
7360 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7364 if !attributes_allowed && !attrs.is_empty() {
7365 self.expected_item_err(&attrs);
7370 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7371 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7372 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7374 if self.token.is_path_start() && !self.is_extern_non_path() {
7375 let prev_span = self.prev_span;
7377 let pth = self.parse_path(PathStyle::Mod)?;
7379 if pth.segments.len() == 1 {
7380 if !self.eat(&token::Not) {
7381 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7384 self.expect(&token::Not)?;
7387 if let Some(vis) = vis {
7388 self.complain_if_pub_macro(&vis.node, prev_span);
7393 // eat a matched-delimiter token tree:
7394 let (delim, tts) = self.expect_delimited_token_tree()?;
7395 if delim != MacDelimiter::Brace {
7396 self.expect(&token::Semi)?
7399 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7405 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7406 where F: FnOnce(&mut Self) -> PResult<'a, R>
7408 // Record all tokens we parse when parsing this item.
7409 let mut tokens = Vec::new();
7410 let prev_collecting = match self.token_cursor.frame.last_token {
7411 LastToken::Collecting(ref mut list) => {
7412 Some(mem::replace(list, Vec::new()))
7414 LastToken::Was(ref mut last) => {
7415 tokens.extend(last.take());
7419 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7420 let prev = self.token_cursor.stack.len();
7422 let last_token = if self.token_cursor.stack.len() == prev {
7423 &mut self.token_cursor.frame.last_token
7425 &mut self.token_cursor.stack[prev].last_token
7428 // Pull our the toekns that we've collected from the call to `f` above
7429 let mut collected_tokens = match *last_token {
7430 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7431 LastToken::Was(_) => panic!("our vector went away?"),
7434 // If we're not at EOF our current token wasn't actually consumed by
7435 // `f`, but it'll still be in our list that we pulled out. In that case
7437 let extra_token = if self.token != token::Eof {
7438 collected_tokens.pop()
7443 // If we were previously collecting tokens, then this was a recursive
7444 // call. In that case we need to record all the tokens we collected in
7445 // our parent list as well. To do that we push a clone of our stream
7446 // onto the previous list.
7447 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7448 match prev_collecting {
7450 list.push(stream.clone());
7451 list.extend(extra_token);
7452 *last_token = LastToken::Collecting(list);
7455 *last_token = LastToken::Was(extra_token);
7462 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7463 let attrs = self.parse_outer_attributes()?;
7464 self.parse_item_(attrs, true, false)
7468 fn is_import_coupler(&mut self) -> bool {
7469 self.check(&token::ModSep) &&
7470 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7471 *t == token::BinOp(token::Star))
7476 /// USE_TREE = [`::`] `*` |
7477 /// [`::`] `{` USE_TREE_LIST `}` |
7479 /// PATH `::` `{` USE_TREE_LIST `}` |
7480 /// PATH [`as` IDENT]
7481 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7484 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7485 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7486 self.check(&token::BinOp(token::Star)) ||
7487 self.is_import_coupler() {
7488 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7489 if self.eat(&token::ModSep) {
7490 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7493 if self.eat(&token::BinOp(token::Star)) {
7496 UseTreeKind::Nested(self.parse_use_tree_list()?)
7499 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7500 prefix = self.parse_path(PathStyle::Mod)?;
7502 if self.eat(&token::ModSep) {
7503 if self.eat(&token::BinOp(token::Star)) {
7506 UseTreeKind::Nested(self.parse_use_tree_list()?)
7509 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7513 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7516 /// Parse UseTreeKind::Nested(list)
7518 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7519 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7520 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7521 &token::CloseDelim(token::Brace),
7522 SeqSep::trailing_allowed(token::Comma), |this| {
7523 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7527 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7528 if self.eat_keyword(keywords::As) {
7530 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7532 Ok(Some(ident.gensym()))
7534 _ => self.parse_ident().map(Some),
7541 /// Parses a source module as a crate. This is the main
7542 /// entry point for the parser.
7543 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7546 attrs: self.parse_inner_attributes()?,
7547 module: self.parse_mod_items(&token::Eof, lo)?,
7548 span: lo.to(self.span),
7552 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7553 let ret = match self.token {
7554 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7555 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7562 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7563 match self.parse_optional_str() {
7564 Some((s, style, suf)) => {
7565 let sp = self.prev_span;
7566 self.expect_no_suffix(sp, "string literal", suf);
7570 let msg = "expected string literal";
7571 let mut err = self.fatal(msg);
7572 err.span_label(self.span, msg);