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
1379 p.parse_arg_general(false)
1381 generics.where_clause = self.parse_where_clause()?;
1383 let sig = ast::MethodSig {
1393 let body = match self.token {
1397 debug!("parse_trait_methods(): parsing required method");
1400 token::OpenDelim(token::Brace) => {
1401 debug!("parse_trait_methods(): parsing provided method");
1403 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1404 attrs.extend(inner_attrs.iter().cloned());
1408 let token_str = self.this_token_to_string();
1409 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1411 err.span_label(self.span, "expected `;` or `{`");
1415 (ident, ast::TraitItemKind::Method(sig, body), generics)
1419 id: ast::DUMMY_NODE_ID,
1424 span: lo.to(self.prev_span),
1429 /// Parse optional return type [ -> TY ] in function decl
1430 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1431 if self.eat(&token::RArrow) {
1432 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1434 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1439 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1440 self.parse_ty_common(true, true)
1443 /// Parse a type in restricted contexts where `+` is not permitted.
1444 /// Example 1: `&'a TYPE`
1445 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1446 /// Example 2: `value1 as TYPE + value2`
1447 /// `+` is prohibited to avoid interactions with expression grammar.
1448 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1449 self.parse_ty_common(false, true)
1452 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1453 -> PResult<'a, P<Ty>> {
1454 maybe_whole!(self, NtTy, |x| x);
1457 let mut impl_dyn_multi = false;
1458 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1459 // `(TYPE)` is a parenthesized type.
1460 // `(TYPE,)` is a tuple with a single field of type TYPE.
1461 let mut ts = vec![];
1462 let mut last_comma = false;
1463 while self.token != token::CloseDelim(token::Paren) {
1464 ts.push(self.parse_ty()?);
1465 if self.eat(&token::Comma) {
1472 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1473 self.expect(&token::CloseDelim(token::Paren))?;
1475 if ts.len() == 1 && !last_comma {
1476 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1477 let maybe_bounds = allow_plus && self.token.is_like_plus();
1479 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1480 TyKind::Path(None, ref path) if maybe_bounds => {
1481 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1483 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1484 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1485 let path = match bounds[0] {
1486 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1487 _ => self.bug("unexpected lifetime bound"),
1489 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1492 _ => TyKind::Paren(P(ty))
1497 } else if self.eat(&token::Not) {
1500 } else if self.eat(&token::BinOp(token::Star)) {
1502 TyKind::Ptr(self.parse_ptr()?)
1503 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1505 let t = self.parse_ty()?;
1506 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1507 let t = match self.maybe_parse_fixed_length_of_vec()? {
1508 None => TyKind::Slice(t),
1509 Some(length) => TyKind::Array(t, AnonConst {
1510 id: ast::DUMMY_NODE_ID,
1514 self.expect(&token::CloseDelim(token::Bracket))?;
1516 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1519 self.parse_borrowed_pointee()?
1520 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1522 // In order to not be ambiguous, the type must be surrounded by parens.
1523 self.expect(&token::OpenDelim(token::Paren))?;
1525 id: ast::DUMMY_NODE_ID,
1526 value: self.parse_expr()?,
1528 self.expect(&token::CloseDelim(token::Paren))?;
1530 } else if self.eat_keyword(keywords::Underscore) {
1531 // A type to be inferred `_`
1533 } else if self.token_is_bare_fn_keyword() {
1534 // Function pointer type
1535 self.parse_ty_bare_fn(Vec::new())?
1536 } else if self.check_keyword(keywords::For) {
1537 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1538 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1539 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1541 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1542 if self.token_is_bare_fn_keyword() {
1543 self.parse_ty_bare_fn(lifetime_defs)?
1545 let path = self.parse_path(PathStyle::Type)?;
1546 let parse_plus = allow_plus && self.check_plus();
1547 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1549 } else if self.eat_keyword(keywords::Impl) {
1550 // Always parse bounds greedily for better error recovery.
1551 let bounds = self.parse_generic_bounds()?;
1552 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1553 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1554 } else if self.check_keyword(keywords::Dyn) &&
1555 self.look_ahead(1, |t| t.can_begin_bound() &&
1556 !can_continue_type_after_non_fn_ident(t)) {
1557 self.bump(); // `dyn`
1558 // Always parse bounds greedily for better error recovery.
1559 let bounds = self.parse_generic_bounds()?;
1560 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1561 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1562 } else if self.check(&token::Question) ||
1563 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1564 // Bound list (trait object type)
1565 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1566 TraitObjectSyntax::None)
1567 } else if self.eat_lt() {
1569 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1570 TyKind::Path(Some(qself), path)
1571 } else if self.token.is_path_start() {
1573 let path = self.parse_path(PathStyle::Type)?;
1574 if self.eat(&token::Not) {
1575 // Macro invocation in type position
1576 let (delim, tts) = self.expect_delimited_token_tree()?;
1577 let node = Mac_ { path, tts, delim };
1578 TyKind::Mac(respan(lo.to(self.prev_span), node))
1580 // Just a type path or bound list (trait object type) starting with a trait.
1582 // `Trait1 + Trait2 + 'a`
1583 if allow_plus && self.check_plus() {
1584 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1586 TyKind::Path(None, path)
1590 let msg = format!("expected type, found {}", self.this_token_descr());
1591 return Err(self.fatal(&msg));
1594 let span = lo.to(self.prev_span);
1595 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1597 // Try to recover from use of `+` with incorrect priority.
1598 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1599 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1600 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1605 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1606 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1607 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1608 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1610 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1611 bounds.append(&mut self.parse_generic_bounds()?);
1613 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1616 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1617 if !allow_plus && impl_dyn_multi {
1618 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1619 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1620 .span_suggestion_with_applicability(
1622 "use parentheses to disambiguate",
1624 Applicability::MachineApplicable
1629 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1630 // Do not add `+` to expected tokens.
1631 if !allow_plus || !self.token.is_like_plus() {
1636 let bounds = self.parse_generic_bounds()?;
1637 let sum_span = ty.span.to(self.prev_span);
1639 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1640 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1643 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1644 let sum_with_parens = pprust::to_string(|s| {
1645 use print::pprust::PrintState;
1648 s.print_opt_lifetime(lifetime)?;
1649 s.print_mutability(mut_ty.mutbl)?;
1651 s.print_type(&mut_ty.ty)?;
1652 s.print_type_bounds(" +", &bounds)?;
1655 err.span_suggestion_with_applicability(
1657 "try adding parentheses",
1659 Applicability::MachineApplicable
1662 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1663 err.span_label(sum_span, "perhaps you forgot parentheses?");
1666 err.span_label(sum_span, "expected a path");
1673 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1674 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1676 // Do not add `::` to expected tokens.
1677 if !allow_recovery || self.token != token::ModSep {
1680 let ty = match base.to_ty() {
1682 None => return Ok(base),
1685 self.bump(); // `::`
1686 let mut segments = Vec::new();
1687 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1689 let span = ty.span.to(self.prev_span);
1690 let path_span = span.to(span); // use an empty path since `position` == 0
1691 let recovered = base.to_recovered(
1692 Some(QSelf { ty, path_span, position: 0 }),
1693 ast::Path { segments, span },
1697 .struct_span_err(span, "missing angle brackets in associated item path")
1698 .span_suggestion_with_applicability( // this is a best-effort recovery
1699 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1705 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1706 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1707 let mutbl = self.parse_mutability();
1708 let ty = self.parse_ty_no_plus()?;
1709 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1712 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1713 let mutbl = if self.eat_keyword(keywords::Mut) {
1715 } else if self.eat_keyword(keywords::Const) {
1716 Mutability::Immutable
1718 let span = self.prev_span;
1720 "expected mut or const in raw pointer type (use \
1721 `*mut T` or `*const T` as appropriate)");
1722 Mutability::Immutable
1724 let t = self.parse_ty_no_plus()?;
1725 Ok(MutTy { ty: t, mutbl: mutbl })
1728 fn is_named_argument(&mut self) -> bool {
1729 let offset = match self.token {
1730 token::Interpolated(ref nt) => match nt.0 {
1731 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1734 token::BinOp(token::And) | token::AndAnd => 1,
1735 _ if self.token.is_keyword(keywords::Mut) => 1,
1739 self.look_ahead(offset, |t| t.is_ident()) &&
1740 self.look_ahead(offset + 1, |t| t == &token::Colon)
1743 /// This version of parse arg doesn't necessarily require
1744 /// identifier names.
1745 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1746 maybe_whole!(self, NtArg, |x| x);
1748 let (pat, ty) = if require_name || self.is_named_argument() {
1749 debug!("parse_arg_general parse_pat (require_name:{})",
1751 let pat = self.parse_pat()?;
1753 self.expect(&token::Colon)?;
1754 (pat, self.parse_ty()?)
1756 debug!("parse_arg_general ident_to_pat");
1758 let parser_snapshot_before_pat = self.clone();
1760 // Once we can use edition 2018 in the compiler,
1761 // replace this with real try blocks.
1762 macro_rules! try_block {
1763 ($($inside:tt)*) => (
1764 (||{ ::std::ops::Try::from_ok({ $($inside)* }) })()
1768 // We're going to try parsing the argument as a pattern (even though it's not
1769 // allowed). This way we can provide better errors to the user.
1770 let pat_arg: PResult<'a, _> = try_block! {
1771 let pat = self.parse_pat()?;
1772 self.expect(&token::Colon)?;
1773 (pat, self.parse_ty()?)
1778 let mut err = self.diagnostic().struct_span_err_with_code(
1780 "patterns aren't allowed in methods without bodies",
1781 DiagnosticId::Error("E0642".into()),
1783 err.span_suggestion_short_with_applicability(
1785 "give this argument a name or use an underscore to ignore it",
1787 Applicability::MachineApplicable,
1790 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1792 node: PatKind::Wild,
1794 id: ast::DUMMY_NODE_ID
1800 // Recover from attempting to parse the argument as a pattern. This means
1801 // the type is alone, with no name, e.g. `fn foo(u32)`.
1802 mem::replace(self, parser_snapshot_before_pat);
1803 debug!("parse_arg_general ident_to_pat");
1804 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1805 let ty = self.parse_ty()?;
1807 id: ast::DUMMY_NODE_ID,
1808 node: PatKind::Ident(
1809 BindingMode::ByValue(Mutability::Immutable), ident, None),
1817 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1820 /// Parse a single function argument
1821 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1822 self.parse_arg_general(true)
1825 /// Parse an argument in a lambda header e.g. |arg, arg|
1826 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1827 let pat = self.parse_pat()?;
1828 let t = if self.eat(&token::Colon) {
1832 id: ast::DUMMY_NODE_ID,
1833 node: TyKind::Infer,
1840 id: ast::DUMMY_NODE_ID
1844 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1845 if self.eat(&token::Semi) {
1846 Ok(Some(self.parse_expr()?))
1852 /// Matches token_lit = LIT_INTEGER | ...
1853 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1854 let out = match self.token {
1855 token::Interpolated(ref nt) => match nt.0 {
1856 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1857 ExprKind::Lit(ref lit) => { lit.node.clone() }
1858 _ => { return self.unexpected_last(&self.token); }
1860 _ => { return self.unexpected_last(&self.token); }
1862 token::Literal(lit, suf) => {
1863 let diag = Some((self.span, &self.sess.span_diagnostic));
1864 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1868 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1873 _ => { return self.unexpected_last(&self.token); }
1880 /// Matches lit = true | false | token_lit
1881 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1883 let lit = if self.eat_keyword(keywords::True) {
1885 } else if self.eat_keyword(keywords::False) {
1886 LitKind::Bool(false)
1888 let lit = self.parse_lit_token()?;
1891 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
1894 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1895 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1896 maybe_whole_expr!(self);
1898 let minus_lo = self.span;
1899 let minus_present = self.eat(&token::BinOp(token::Minus));
1901 let literal = P(self.parse_lit()?);
1902 let hi = self.prev_span;
1903 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1906 let minus_hi = self.prev_span;
1907 let unary = self.mk_unary(UnOp::Neg, expr);
1908 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1914 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1916 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1917 let span = self.span;
1919 Ok(Ident::new(ident.name, span))
1921 _ => self.parse_ident(),
1925 /// Parses qualified path.
1926 /// Assumes that the leading `<` has been parsed already.
1928 /// `qualified_path = <type [as trait_ref]>::path`
1933 /// `<T as U>::F::a<S>` (without disambiguator)
1934 /// `<T as U>::F::a::<S>` (with disambiguator)
1935 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1936 let lo = self.prev_span;
1937 let ty = self.parse_ty()?;
1939 // `path` will contain the prefix of the path up to the `>`,
1940 // if any (e.g., `U` in the `<T as U>::*` examples
1941 // above). `path_span` has the span of that path, or an empty
1942 // span in the case of something like `<T>::Bar`.
1943 let (mut path, path_span);
1944 if self.eat_keyword(keywords::As) {
1945 let path_lo = self.span;
1946 path = self.parse_path(PathStyle::Type)?;
1947 path_span = path_lo.to(self.prev_span);
1949 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1950 path_span = self.span.to(self.span);
1953 self.expect(&token::Gt)?;
1954 self.expect(&token::ModSep)?;
1956 let qself = QSelf { ty, path_span, position: path.segments.len() };
1957 self.parse_path_segments(&mut path.segments, style, true)?;
1959 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1962 /// Parses simple paths.
1964 /// `path = [::] segment+`
1965 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1968 /// `a::b::C<D>` (without disambiguator)
1969 /// `a::b::C::<D>` (with disambiguator)
1970 /// `Fn(Args)` (without disambiguator)
1971 /// `Fn::(Args)` (with disambiguator)
1972 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1973 self.parse_path_common(style, true)
1976 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1977 -> PResult<'a, ast::Path> {
1978 maybe_whole!(self, NtPath, |path| {
1979 if style == PathStyle::Mod &&
1980 path.segments.iter().any(|segment| segment.args.is_some()) {
1981 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1986 let lo = self.meta_var_span.unwrap_or(self.span);
1987 let mut segments = Vec::new();
1988 if self.eat(&token::ModSep) {
1989 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1991 self.parse_path_segments(&mut segments, style, enable_warning)?;
1993 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1996 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1997 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1998 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1999 let meta_ident = match self.token {
2000 token::Interpolated(ref nt) => match nt.0 {
2001 token::NtMeta(ref meta) => match meta.node {
2002 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2009 if let Some(path) = meta_ident {
2013 self.parse_path(style)
2016 fn parse_path_segments(&mut self,
2017 segments: &mut Vec<PathSegment>,
2019 enable_warning: bool)
2020 -> PResult<'a, ()> {
2022 segments.push(self.parse_path_segment(style, enable_warning)?);
2024 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2030 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2031 -> PResult<'a, PathSegment> {
2032 let ident = self.parse_path_segment_ident()?;
2034 let is_args_start = |token: &token::Token| match *token {
2035 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2038 let check_args_start = |this: &mut Self| {
2039 this.expected_tokens.extend_from_slice(
2040 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2042 is_args_start(&this.token)
2045 Ok(if style == PathStyle::Type && check_args_start(self) ||
2046 style != PathStyle::Mod && self.check(&token::ModSep)
2047 && self.look_ahead(1, |t| is_args_start(t)) {
2048 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2050 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2051 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2052 .span_label(self.prev_span, "try removing `::`").emit();
2055 let args = if self.eat_lt() {
2057 let (args, bindings) = self.parse_generic_args()?;
2059 let span = lo.to(self.prev_span);
2060 AngleBracketedArgs { args, bindings, span }.into()
2064 let inputs = self.parse_seq_to_before_tokens(
2065 &[&token::CloseDelim(token::Paren)],
2066 SeqSep::trailing_allowed(token::Comma),
2067 TokenExpectType::Expect,
2070 let span = lo.to(self.prev_span);
2071 let output = if self.eat(&token::RArrow) {
2072 Some(self.parse_ty_common(false, false)?)
2076 ParenthesisedArgs { inputs, output, span }.into()
2079 PathSegment { ident, args }
2081 // Generic arguments are not found.
2082 PathSegment::from_ident(ident)
2086 crate fn check_lifetime(&mut self) -> bool {
2087 self.expected_tokens.push(TokenType::Lifetime);
2088 self.token.is_lifetime()
2091 /// Parse single lifetime 'a or panic.
2092 crate fn expect_lifetime(&mut self) -> Lifetime {
2093 if let Some(ident) = self.token.lifetime() {
2094 let span = self.span;
2096 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2098 self.span_bug(self.span, "not a lifetime")
2102 fn eat_label(&mut self) -> Option<Label> {
2103 if let Some(ident) = self.token.lifetime() {
2104 let span = self.span;
2106 Some(Label { ident: Ident::new(ident.name, span) })
2112 /// Parse mutability (`mut` or nothing).
2113 fn parse_mutability(&mut self) -> Mutability {
2114 if self.eat_keyword(keywords::Mut) {
2117 Mutability::Immutable
2121 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2122 if let token::Literal(token::Integer(name), None) = self.token {
2124 Ok(Ident::new(name, self.prev_span))
2126 self.parse_ident_common(false)
2130 /// Parse ident (COLON expr)?
2131 fn parse_field(&mut self) -> PResult<'a, Field> {
2132 let attrs = self.parse_outer_attributes()?;
2135 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2136 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2137 let fieldname = self.parse_field_name()?;
2139 (fieldname, self.parse_expr()?, false)
2141 let fieldname = self.parse_ident_common(false)?;
2143 // Mimic `x: x` for the `x` field shorthand.
2144 let path = ast::Path::from_ident(fieldname);
2145 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2146 (fieldname, expr, true)
2150 span: lo.to(expr.span),
2153 attrs: attrs.into(),
2157 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2158 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2161 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2162 ExprKind::Unary(unop, expr)
2165 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2166 ExprKind::Binary(binop, lhs, rhs)
2169 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2170 ExprKind::Call(f, args)
2173 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2174 ExprKind::Index(expr, idx)
2177 fn mk_range(&mut self,
2178 start: Option<P<Expr>>,
2179 end: Option<P<Expr>>,
2180 limits: RangeLimits)
2181 -> PResult<'a, ast::ExprKind> {
2182 if end.is_none() && limits == RangeLimits::Closed {
2183 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2185 Ok(ExprKind::Range(start, end, limits))
2189 fn mk_assign_op(&mut self, binop: ast::BinOp,
2190 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2191 ExprKind::AssignOp(binop, lhs, rhs)
2194 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2196 id: ast::DUMMY_NODE_ID,
2197 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2203 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2204 let delim = match self.token {
2205 token::OpenDelim(delim) => delim,
2207 let msg = "expected open delimiter";
2208 let mut err = self.fatal(msg);
2209 err.span_label(self.span, msg);
2213 let delimited = match self.parse_token_tree() {
2214 TokenTree::Delimited(_, delimited) => delimited,
2215 _ => unreachable!(),
2217 let delim = match delim {
2218 token::Paren => MacDelimiter::Parenthesis,
2219 token::Bracket => MacDelimiter::Bracket,
2220 token::Brace => MacDelimiter::Brace,
2221 token::NoDelim => self.bug("unexpected no delimiter"),
2223 Ok((delim, delimited.stream().into()))
2226 /// At the bottom (top?) of the precedence hierarchy,
2227 /// parse things like parenthesized exprs,
2228 /// macros, return, etc.
2230 /// NB: This does not parse outer attributes,
2231 /// and is private because it only works
2232 /// correctly if called from parse_dot_or_call_expr().
2233 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2234 maybe_whole_expr!(self);
2236 // Outer attributes are already parsed and will be
2237 // added to the return value after the fact.
2239 // Therefore, prevent sub-parser from parsing
2240 // attributes by giving them a empty "already parsed" list.
2241 let mut attrs = ThinVec::new();
2244 let mut hi = self.span;
2248 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2250 token::OpenDelim(token::Paren) => {
2253 attrs.extend(self.parse_inner_attributes()?);
2255 // (e) is parenthesized e
2256 // (e,) is a tuple with only one field, e
2257 let mut es = vec![];
2258 let mut trailing_comma = false;
2259 while self.token != token::CloseDelim(token::Paren) {
2260 es.push(self.parse_expr()?);
2261 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2262 if self.check(&token::Comma) {
2263 trailing_comma = true;
2267 trailing_comma = false;
2273 hi = self.prev_span;
2274 ex = if es.len() == 1 && !trailing_comma {
2275 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2280 token::OpenDelim(token::Brace) => {
2281 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2283 token::BinOp(token::Or) | token::OrOr => {
2284 return self.parse_lambda_expr(attrs);
2286 token::OpenDelim(token::Bracket) => {
2289 attrs.extend(self.parse_inner_attributes()?);
2291 if self.check(&token::CloseDelim(token::Bracket)) {
2294 ex = ExprKind::Array(Vec::new());
2297 let first_expr = self.parse_expr()?;
2298 if self.check(&token::Semi) {
2299 // Repeating array syntax: [ 0; 512 ]
2301 let count = AnonConst {
2302 id: ast::DUMMY_NODE_ID,
2303 value: self.parse_expr()?,
2305 self.expect(&token::CloseDelim(token::Bracket))?;
2306 ex = ExprKind::Repeat(first_expr, count);
2307 } else if self.check(&token::Comma) {
2308 // Vector with two or more elements.
2310 let remaining_exprs = self.parse_seq_to_end(
2311 &token::CloseDelim(token::Bracket),
2312 SeqSep::trailing_allowed(token::Comma),
2313 |p| Ok(p.parse_expr()?)
2315 let mut exprs = vec![first_expr];
2316 exprs.extend(remaining_exprs);
2317 ex = ExprKind::Array(exprs);
2319 // Vector with one element.
2320 self.expect(&token::CloseDelim(token::Bracket))?;
2321 ex = ExprKind::Array(vec![first_expr]);
2324 hi = self.prev_span;
2328 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2330 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2332 if self.span.edition() >= Edition::Edition2018 &&
2333 self.check_keyword(keywords::Async)
2335 if self.is_async_block() { // check for `async {` and `async move {`
2336 return self.parse_async_block(attrs);
2338 return self.parse_lambda_expr(attrs);
2341 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2342 return self.parse_lambda_expr(attrs);
2344 if self.eat_keyword(keywords::If) {
2345 return self.parse_if_expr(attrs);
2347 if self.eat_keyword(keywords::For) {
2348 let lo = self.prev_span;
2349 return self.parse_for_expr(None, lo, attrs);
2351 if self.eat_keyword(keywords::While) {
2352 let lo = self.prev_span;
2353 return self.parse_while_expr(None, lo, attrs);
2355 if let Some(label) = self.eat_label() {
2356 let lo = label.ident.span;
2357 self.expect(&token::Colon)?;
2358 if self.eat_keyword(keywords::While) {
2359 return self.parse_while_expr(Some(label), lo, attrs)
2361 if self.eat_keyword(keywords::For) {
2362 return self.parse_for_expr(Some(label), lo, attrs)
2364 if self.eat_keyword(keywords::Loop) {
2365 return self.parse_loop_expr(Some(label), lo, attrs)
2367 if self.token == token::OpenDelim(token::Brace) {
2368 return self.parse_block_expr(Some(label),
2370 BlockCheckMode::Default,
2373 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2374 let mut err = self.fatal(msg);
2375 err.span_label(self.span, msg);
2378 if self.eat_keyword(keywords::Loop) {
2379 let lo = self.prev_span;
2380 return self.parse_loop_expr(None, lo, attrs);
2382 if self.eat_keyword(keywords::Continue) {
2383 let label = self.eat_label();
2384 let ex = ExprKind::Continue(label);
2385 let hi = self.prev_span;
2386 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2388 if self.eat_keyword(keywords::Match) {
2389 return self.parse_match_expr(attrs);
2391 if self.eat_keyword(keywords::Unsafe) {
2392 return self.parse_block_expr(
2395 BlockCheckMode::Unsafe(ast::UserProvided),
2398 if self.is_do_catch_block() {
2399 let mut db = self.fatal("found removed `do catch` syntax");
2400 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2403 if self.is_try_block() {
2405 assert!(self.eat_keyword(keywords::Try));
2406 return self.parse_try_block(lo, attrs);
2408 if self.eat_keyword(keywords::Return) {
2409 if self.token.can_begin_expr() {
2410 let e = self.parse_expr()?;
2412 ex = ExprKind::Ret(Some(e));
2414 ex = ExprKind::Ret(None);
2416 } else if self.eat_keyword(keywords::Break) {
2417 let label = self.eat_label();
2418 let e = if self.token.can_begin_expr()
2419 && !(self.token == token::OpenDelim(token::Brace)
2420 && self.restrictions.contains(
2421 Restrictions::NO_STRUCT_LITERAL)) {
2422 Some(self.parse_expr()?)
2426 ex = ExprKind::Break(label, e);
2427 hi = self.prev_span;
2428 } else if self.eat_keyword(keywords::Yield) {
2429 if self.token.can_begin_expr() {
2430 let e = self.parse_expr()?;
2432 ex = ExprKind::Yield(Some(e));
2434 ex = ExprKind::Yield(None);
2436 } else if self.token.is_keyword(keywords::Let) {
2437 // Catch this syntax error here, instead of in `parse_ident`, so
2438 // that we can explicitly mention that let is not to be used as an expression
2439 let mut db = self.fatal("expected expression, found statement (`let`)");
2440 db.span_label(self.span, "expected expression");
2441 db.note("variable declaration using `let` is a statement");
2443 } else if self.token.is_path_start() {
2444 let pth = self.parse_path(PathStyle::Expr)?;
2446 // `!`, as an operator, is prefix, so we know this isn't that
2447 if self.eat(&token::Not) {
2448 // MACRO INVOCATION expression
2449 let (delim, tts) = self.expect_delimited_token_tree()?;
2450 let hi = self.prev_span;
2451 let node = Mac_ { path: pth, tts, delim };
2452 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2454 if self.check(&token::OpenDelim(token::Brace)) {
2455 // This is a struct literal, unless we're prohibited
2456 // from parsing struct literals here.
2457 let prohibited = self.restrictions.contains(
2458 Restrictions::NO_STRUCT_LITERAL
2461 return self.parse_struct_expr(lo, pth, attrs);
2466 ex = ExprKind::Path(None, pth);
2468 match self.parse_literal_maybe_minus() {
2471 ex = expr.node.clone();
2474 self.cancel(&mut err);
2475 let msg = format!("expected expression, found {}",
2476 self.this_token_descr());
2477 let mut err = self.fatal(&msg);
2478 err.span_label(self.span, "expected expression");
2486 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2487 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2492 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2493 -> PResult<'a, P<Expr>> {
2494 let struct_sp = lo.to(self.prev_span);
2496 let mut fields = Vec::new();
2497 let mut base = None;
2499 attrs.extend(self.parse_inner_attributes()?);
2501 while self.token != token::CloseDelim(token::Brace) {
2502 if self.eat(&token::DotDot) {
2503 let exp_span = self.prev_span;
2504 match self.parse_expr() {
2510 self.recover_stmt();
2513 if self.token == token::Comma {
2514 let mut err = self.sess.span_diagnostic.mut_span_err(
2515 exp_span.to(self.prev_span),
2516 "cannot use a comma after the base struct",
2518 err.span_suggestion_short_with_applicability(
2520 "remove this comma",
2522 Applicability::MachineApplicable
2524 err.note("the base struct must always be the last field");
2526 self.recover_stmt();
2531 match self.parse_field() {
2532 Ok(f) => fields.push(f),
2534 e.span_label(struct_sp, "while parsing this struct");
2537 // If the next token is a comma, then try to parse
2538 // what comes next as additional fields, rather than
2539 // bailing out until next `}`.
2540 if self.token != token::Comma {
2541 self.recover_stmt();
2547 match self.expect_one_of(&[token::Comma],
2548 &[token::CloseDelim(token::Brace)]) {
2552 self.recover_stmt();
2558 let span = lo.to(self.span);
2559 self.expect(&token::CloseDelim(token::Brace))?;
2560 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2563 fn parse_or_use_outer_attributes(&mut self,
2564 already_parsed_attrs: Option<ThinVec<Attribute>>)
2565 -> PResult<'a, ThinVec<Attribute>> {
2566 if let Some(attrs) = already_parsed_attrs {
2569 self.parse_outer_attributes().map(|a| a.into())
2573 /// Parse a block or unsafe block
2574 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2575 lo: Span, blk_mode: BlockCheckMode,
2576 outer_attrs: ThinVec<Attribute>)
2577 -> PResult<'a, P<Expr>> {
2578 self.expect(&token::OpenDelim(token::Brace))?;
2580 let mut attrs = outer_attrs;
2581 attrs.extend(self.parse_inner_attributes()?);
2583 let blk = self.parse_block_tail(lo, blk_mode)?;
2584 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2587 /// parse a.b or a(13) or a[4] or just a
2588 fn parse_dot_or_call_expr(&mut self,
2589 already_parsed_attrs: Option<ThinVec<Attribute>>)
2590 -> PResult<'a, P<Expr>> {
2591 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2593 let b = self.parse_bottom_expr();
2594 let (span, b) = self.interpolated_or_expr_span(b)?;
2595 self.parse_dot_or_call_expr_with(b, span, attrs)
2598 fn parse_dot_or_call_expr_with(&mut self,
2601 mut attrs: ThinVec<Attribute>)
2602 -> PResult<'a, P<Expr>> {
2603 // Stitch the list of outer attributes onto the return value.
2604 // A little bit ugly, but the best way given the current code
2606 self.parse_dot_or_call_expr_with_(e0, lo)
2608 expr.map(|mut expr| {
2609 attrs.extend::<Vec<_>>(expr.attrs.into());
2612 ExprKind::If(..) | ExprKind::IfLet(..) => {
2613 if !expr.attrs.is_empty() {
2614 // Just point to the first attribute in there...
2615 let span = expr.attrs[0].span;
2618 "attributes are not yet allowed on `if` \
2629 // Assuming we have just parsed `.`, continue parsing into an expression.
2630 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2631 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2632 Ok(match self.token {
2633 token::OpenDelim(token::Paren) => {
2634 // Method call `expr.f()`
2635 let mut args = self.parse_unspanned_seq(
2636 &token::OpenDelim(token::Paren),
2637 &token::CloseDelim(token::Paren),
2638 SeqSep::trailing_allowed(token::Comma),
2639 |p| Ok(p.parse_expr()?)
2641 args.insert(0, self_arg);
2643 let span = lo.to(self.prev_span);
2644 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2647 // Field access `expr.f`
2648 if let Some(args) = segment.args {
2649 self.span_err(args.span(),
2650 "field expressions may not have generic arguments");
2653 let span = lo.to(self.prev_span);
2654 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2659 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2664 while self.eat(&token::Question) {
2665 let hi = self.prev_span;
2666 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2670 if self.eat(&token::Dot) {
2672 token::Ident(..) => {
2673 e = self.parse_dot_suffix(e, lo)?;
2675 token::Literal(token::Integer(name), _) => {
2676 let span = self.span;
2678 let field = ExprKind::Field(e, Ident::new(name, span));
2679 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2681 token::Literal(token::Float(n), _suf) => {
2683 let fstr = n.as_str();
2684 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2685 &format!("unexpected token: `{}`", n));
2686 err.span_label(self.prev_span, "unexpected token");
2687 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2688 let float = match fstr.parse::<f64>().ok() {
2692 let sugg = pprust::to_string(|s| {
2693 use print::pprust::PrintState;
2697 s.print_usize(float.trunc() as usize)?;
2700 s.s.word(fstr.splitn(2, ".").last().unwrap())
2702 err.span_suggestion_with_applicability(
2703 lo.to(self.prev_span),
2704 "try parenthesizing the first index",
2706 Applicability::MachineApplicable
2713 // FIXME Could factor this out into non_fatal_unexpected or something.
2714 let actual = self.this_token_to_string();
2715 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2720 if self.expr_is_complete(&e) { break; }
2723 token::OpenDelim(token::Paren) => {
2724 let es = self.parse_unspanned_seq(
2725 &token::OpenDelim(token::Paren),
2726 &token::CloseDelim(token::Paren),
2727 SeqSep::trailing_allowed(token::Comma),
2728 |p| Ok(p.parse_expr()?)
2730 hi = self.prev_span;
2732 let nd = self.mk_call(e, es);
2733 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2737 // Could be either an index expression or a slicing expression.
2738 token::OpenDelim(token::Bracket) => {
2740 let ix = self.parse_expr()?;
2742 self.expect(&token::CloseDelim(token::Bracket))?;
2743 let index = self.mk_index(e, ix);
2744 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2752 crate fn process_potential_macro_variable(&mut self) {
2753 let (token, span) = match self.token {
2754 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2755 self.look_ahead(1, |t| t.is_ident()) => {
2757 let name = match self.token {
2758 token::Ident(ident, _) => ident,
2761 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2762 err.span_label(self.span, "unknown macro variable");
2766 token::Interpolated(ref nt) => {
2767 self.meta_var_span = Some(self.span);
2768 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2769 // and lifetime tokens, so the former are never encountered during normal parsing.
2771 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2772 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2782 /// parse a single token tree from the input.
2783 crate fn parse_token_tree(&mut self) -> TokenTree {
2785 token::OpenDelim(..) => {
2786 let frame = mem::replace(&mut self.token_cursor.frame,
2787 self.token_cursor.stack.pop().unwrap());
2788 self.span = frame.span;
2790 TokenTree::Delimited(frame.span, Delimited {
2792 tts: frame.tree_cursor.original_stream().into(),
2795 token::CloseDelim(_) | token::Eof => unreachable!(),
2797 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2799 TokenTree::Token(span, token)
2804 // parse a stream of tokens into a list of TokenTree's,
2806 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2807 let mut tts = Vec::new();
2808 while self.token != token::Eof {
2809 tts.push(self.parse_token_tree());
2814 pub fn parse_tokens(&mut self) -> TokenStream {
2815 let mut result = Vec::new();
2818 token::Eof | token::CloseDelim(..) => break,
2819 _ => result.push(self.parse_token_tree().into()),
2822 TokenStream::concat(result)
2825 /// Parse a prefix-unary-operator expr
2826 fn parse_prefix_expr(&mut self,
2827 already_parsed_attrs: Option<ThinVec<Attribute>>)
2828 -> PResult<'a, P<Expr>> {
2829 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2831 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2832 let (hi, ex) = match self.token {
2835 let e = self.parse_prefix_expr(None);
2836 let (span, e) = self.interpolated_or_expr_span(e)?;
2837 (lo.to(span), self.mk_unary(UnOp::Not, e))
2839 // Suggest `!` for bitwise negation when encountering a `~`
2842 let e = self.parse_prefix_expr(None);
2843 let (span, e) = self.interpolated_or_expr_span(e)?;
2844 let span_of_tilde = lo;
2845 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2846 "`~` cannot be used as a unary operator");
2847 err.span_suggestion_short_with_applicability(
2849 "use `!` to perform bitwise negation",
2851 Applicability::MachineApplicable
2854 (lo.to(span), self.mk_unary(UnOp::Not, e))
2856 token::BinOp(token::Minus) => {
2858 let e = self.parse_prefix_expr(None);
2859 let (span, e) = self.interpolated_or_expr_span(e)?;
2860 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2862 token::BinOp(token::Star) => {
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::Deref, e))
2868 token::BinOp(token::And) | token::AndAnd => {
2870 let m = self.parse_mutability();
2871 let e = self.parse_prefix_expr(None);
2872 let (span, e) = self.interpolated_or_expr_span(e)?;
2873 (lo.to(span), ExprKind::AddrOf(m, e))
2875 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2877 let place = self.parse_expr_res(
2878 Restrictions::NO_STRUCT_LITERAL,
2881 let blk = self.parse_block()?;
2882 let span = blk.span;
2883 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2884 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2886 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2888 let e = self.parse_prefix_expr(None);
2889 let (span, e) = self.interpolated_or_expr_span(e)?;
2890 (lo.to(span), ExprKind::Box(e))
2892 token::Ident(..) if self.token.is_ident_named("not") => {
2893 // `not` is just an ordinary identifier in Rust-the-language,
2894 // but as `rustc`-the-compiler, we can issue clever diagnostics
2895 // for confused users who really want to say `!`
2896 let token_cannot_continue_expr = |t: &token::Token| match *t {
2897 // These tokens can start an expression after `!`, but
2898 // can't continue an expression after an ident
2899 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2900 token::Literal(..) | token::Pound => true,
2901 token::Interpolated(ref nt) => match nt.0 {
2902 token::NtIdent(..) | token::NtExpr(..) |
2903 token::NtBlock(..) | token::NtPath(..) => true,
2908 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2909 if cannot_continue_expr {
2911 // Emit the error ...
2912 let mut err = self.diagnostic()
2913 .struct_span_err(self.span,
2914 &format!("unexpected {} after identifier",
2915 self.this_token_descr()));
2916 // span the `not` plus trailing whitespace to avoid
2917 // trailing whitespace after the `!` in our suggestion
2918 let to_replace = self.sess.source_map()
2919 .span_until_non_whitespace(lo.to(self.span));
2920 err.span_suggestion_short_with_applicability(
2922 "use `!` to perform logical negation",
2924 Applicability::MachineApplicable
2927 // —and recover! (just as if we were in the block
2928 // for the `token::Not` arm)
2929 let e = self.parse_prefix_expr(None);
2930 let (span, e) = self.interpolated_or_expr_span(e)?;
2931 (lo.to(span), self.mk_unary(UnOp::Not, e))
2933 return self.parse_dot_or_call_expr(Some(attrs));
2936 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2938 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2941 /// Parse an associative expression
2943 /// This parses an expression accounting for associativity and precedence of the operators in
2945 fn parse_assoc_expr(&mut self,
2946 already_parsed_attrs: Option<ThinVec<Attribute>>)
2947 -> PResult<'a, P<Expr>> {
2948 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2951 /// Parse an associative expression with operators of at least `min_prec` precedence
2952 fn parse_assoc_expr_with(&mut self,
2955 -> PResult<'a, P<Expr>> {
2956 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2959 let attrs = match lhs {
2960 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2963 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2964 return self.parse_prefix_range_expr(attrs);
2966 self.parse_prefix_expr(attrs)?
2970 if self.expr_is_complete(&lhs) {
2971 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2974 self.expected_tokens.push(TokenType::Operator);
2975 while let Some(op) = AssocOp::from_token(&self.token) {
2977 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2978 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2979 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2980 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2981 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2982 (PrevTokenKind::Interpolated, _) => self.prev_span,
2983 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2984 if path.segments.len() == 1 => self.prev_span,
2988 let cur_op_span = self.span;
2989 let restrictions = if op.is_assign_like() {
2990 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2994 if op.precedence() < min_prec {
2997 // Check for deprecated `...` syntax
2998 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2999 self.err_dotdotdot_syntax(self.span);
3003 if op.is_comparison() {
3004 self.check_no_chained_comparison(&lhs, &op);
3007 if op == AssocOp::As {
3008 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3010 } else if op == AssocOp::Colon {
3011 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3014 err.span_label(self.span,
3015 "expecting a type here because of type ascription");
3016 let cm = self.sess.source_map();
3017 let cur_pos = cm.lookup_char_pos(self.span.lo());
3018 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3019 if cur_pos.line != op_pos.line {
3020 err.span_suggestion_with_applicability(
3022 "try using a semicolon",
3024 Applicability::MaybeIncorrect // speculative
3031 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3032 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3033 // generalise it to the Fixity::None code.
3035 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3036 // two variants are handled with `parse_prefix_range_expr` call above.
3037 let rhs = if self.is_at_start_of_range_notation_rhs() {
3038 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3039 LhsExpr::NotYetParsed)?)
3043 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3048 let limits = if op == AssocOp::DotDot {
3049 RangeLimits::HalfOpen
3054 let r = try!(self.mk_range(Some(lhs), rhs, limits));
3055 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3059 let rhs = match op.fixity() {
3060 Fixity::Right => self.with_res(
3061 restrictions - Restrictions::STMT_EXPR,
3063 this.parse_assoc_expr_with(op.precedence(),
3064 LhsExpr::NotYetParsed)
3066 Fixity::Left => self.with_res(
3067 restrictions - Restrictions::STMT_EXPR,
3069 this.parse_assoc_expr_with(op.precedence() + 1,
3070 LhsExpr::NotYetParsed)
3072 // We currently have no non-associative operators that are not handled above by
3073 // the special cases. The code is here only for future convenience.
3074 Fixity::None => self.with_res(
3075 restrictions - Restrictions::STMT_EXPR,
3077 this.parse_assoc_expr_with(op.precedence() + 1,
3078 LhsExpr::NotYetParsed)
3082 let span = lhs_span.to(rhs.span);
3084 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3085 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3086 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3087 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3088 AssocOp::Greater | AssocOp::GreaterEqual => {
3089 let ast_op = op.to_ast_binop().unwrap();
3090 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3091 self.mk_expr(span, binary, ThinVec::new())
3094 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3095 AssocOp::ObsoleteInPlace =>
3096 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3097 AssocOp::AssignOp(k) => {
3099 token::Plus => BinOpKind::Add,
3100 token::Minus => BinOpKind::Sub,
3101 token::Star => BinOpKind::Mul,
3102 token::Slash => BinOpKind::Div,
3103 token::Percent => BinOpKind::Rem,
3104 token::Caret => BinOpKind::BitXor,
3105 token::And => BinOpKind::BitAnd,
3106 token::Or => BinOpKind::BitOr,
3107 token::Shl => BinOpKind::Shl,
3108 token::Shr => BinOpKind::Shr,
3110 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3111 self.mk_expr(span, aopexpr, ThinVec::new())
3113 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3114 self.bug("AssocOp should have been handled by special case")
3118 if op.fixity() == Fixity::None { break }
3123 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3124 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3125 -> PResult<'a, P<Expr>> {
3126 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3127 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3130 // Save the state of the parser before parsing type normally, in case there is a
3131 // LessThan comparison after this cast.
3132 let parser_snapshot_before_type = self.clone();
3133 match self.parse_ty_no_plus() {
3135 Ok(mk_expr(self, rhs))
3137 Err(mut type_err) => {
3138 // Rewind to before attempting to parse the type with generics, to recover
3139 // from situations like `x as usize < y` in which we first tried to parse
3140 // `usize < y` as a type with generic arguments.
3141 let parser_snapshot_after_type = self.clone();
3142 mem::replace(self, parser_snapshot_before_type);
3144 match self.parse_path(PathStyle::Expr) {
3146 let (op_noun, op_verb) = match self.token {
3147 token::Lt => ("comparison", "comparing"),
3148 token::BinOp(token::Shl) => ("shift", "shifting"),
3150 // We can end up here even without `<` being the next token, for
3151 // example because `parse_ty_no_plus` returns `Err` on keywords,
3152 // but `parse_path` returns `Ok` on them due to error recovery.
3153 // Return original error and parser state.
3154 mem::replace(self, parser_snapshot_after_type);
3155 return Err(type_err);
3159 // Successfully parsed the type path leaving a `<` yet to parse.
3162 // Report non-fatal diagnostics, keep `x as usize` as an expression
3163 // in AST and continue parsing.
3164 let msg = format!("`<` is interpreted as a start of generic \
3165 arguments for `{}`, not a {}", path, op_noun);
3166 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3167 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3168 "interpreted as generic arguments");
3169 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3171 let expr = mk_expr(self, P(Ty {
3173 node: TyKind::Path(None, path),
3174 id: ast::DUMMY_NODE_ID
3177 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3178 .unwrap_or(pprust::expr_to_string(&expr));
3179 err.span_suggestion_with_applicability(
3181 &format!("try {} the cast value", op_verb),
3182 format!("({})", expr_str),
3183 Applicability::MachineApplicable
3189 Err(mut path_err) => {
3190 // Couldn't parse as a path, return original error and parser state.
3192 mem::replace(self, parser_snapshot_after_type);
3200 /// Produce an error if comparison operators are chained (RFC #558).
3201 /// We only need to check lhs, not rhs, because all comparison ops
3202 /// have same precedence and are left-associative
3203 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3204 debug_assert!(outer_op.is_comparison(),
3205 "check_no_chained_comparison: {:?} is not comparison",
3208 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3209 // respan to include both operators
3210 let op_span = op.span.to(self.span);
3211 let mut err = self.diagnostic().struct_span_err(op_span,
3212 "chained comparison operators require parentheses");
3213 if op.node == BinOpKind::Lt &&
3214 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3215 *outer_op == AssocOp::Greater // even in a case like the following:
3216 { // Foo<Bar<Baz<Qux, ()>>>
3218 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3219 err.help("or use `(...)` if you meant to specify fn arguments");
3227 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3228 fn parse_prefix_range_expr(&mut self,
3229 already_parsed_attrs: Option<ThinVec<Attribute>>)
3230 -> PResult<'a, P<Expr>> {
3231 // Check for deprecated `...` syntax
3232 if self.token == token::DotDotDot {
3233 self.err_dotdotdot_syntax(self.span);
3236 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3237 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3239 let tok = self.token.clone();
3240 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3242 let mut hi = self.span;
3244 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3245 // RHS must be parsed with more associativity than the dots.
3246 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3247 Some(self.parse_assoc_expr_with(next_prec,
3248 LhsExpr::NotYetParsed)
3256 let limits = if tok == token::DotDot {
3257 RangeLimits::HalfOpen
3262 let r = try!(self.mk_range(None,
3265 Ok(self.mk_expr(lo.to(hi), r, attrs))
3268 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3269 if self.token.can_begin_expr() {
3270 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3271 if self.token == token::OpenDelim(token::Brace) {
3272 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3280 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3281 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3282 if self.check_keyword(keywords::Let) {
3283 return self.parse_if_let_expr(attrs);
3285 let lo = self.prev_span;
3286 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3288 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3289 // verify that the last statement is either an implicit return (no `;`) or an explicit
3290 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3291 // the dead code lint.
3292 if self.eat_keyword(keywords::Else) || !cond.returns() {
3293 let sp = self.sess.source_map().next_point(lo);
3294 let mut err = self.diagnostic()
3295 .struct_span_err(sp, "missing condition for `if` statemement");
3296 err.span_label(sp, "expected if condition here");
3299 let not_block = self.token != token::OpenDelim(token::Brace);
3300 let thn = self.parse_block().map_err(|mut err| {
3302 err.span_label(lo, "this `if` statement has a condition, but no block");
3306 let mut els: Option<P<Expr>> = None;
3307 let mut hi = thn.span;
3308 if self.eat_keyword(keywords::Else) {
3309 let elexpr = self.parse_else_expr()?;
3313 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3316 /// Parse an 'if let' expression ('if' token already eaten)
3317 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3318 -> PResult<'a, P<Expr>> {
3319 let lo = self.prev_span;
3320 self.expect_keyword(keywords::Let)?;
3321 let pats = self.parse_pats()?;
3322 self.expect(&token::Eq)?;
3323 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3324 let thn = self.parse_block()?;
3325 let (hi, els) = if self.eat_keyword(keywords::Else) {
3326 let expr = self.parse_else_expr()?;
3327 (expr.span, Some(expr))
3331 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3334 // `move |args| expr`
3335 fn parse_lambda_expr(&mut self,
3336 attrs: ThinVec<Attribute>)
3337 -> PResult<'a, P<Expr>>
3340 let movability = if self.eat_keyword(keywords::Static) {
3345 let asyncness = if self.span.edition() >= Edition::Edition2018 {
3346 self.parse_asyncness()
3350 let capture_clause = if self.eat_keyword(keywords::Move) {
3355 let decl = self.parse_fn_block_decl()?;
3356 let decl_hi = self.prev_span;
3357 let body = match decl.output {
3358 FunctionRetTy::Default(_) => {
3359 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3360 self.parse_expr_res(restrictions, None)?
3363 // If an explicit return type is given, require a
3364 // block to appear (RFC 968).
3365 let body_lo = self.span;
3366 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3372 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3376 // `else` token already eaten
3377 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3378 if self.eat_keyword(keywords::If) {
3379 return self.parse_if_expr(ThinVec::new());
3381 let blk = self.parse_block()?;
3382 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3386 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3387 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3389 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3390 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3392 let pat = self.parse_top_level_pat()?;
3393 if !self.eat_keyword(keywords::In) {
3394 let in_span = self.prev_span.between(self.span);
3395 let mut err = self.sess.span_diagnostic
3396 .struct_span_err(in_span, "missing `in` in `for` loop");
3397 err.span_suggestion_short_with_applicability(
3398 in_span, "try adding `in` here", " in ".into(),
3399 // has been misleading, at least in the past (closed Issue #48492)
3400 Applicability::MaybeIncorrect
3404 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3405 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3406 attrs.extend(iattrs);
3408 let hi = self.prev_span;
3409 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3412 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3413 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3415 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3416 if self.token.is_keyword(keywords::Let) {
3417 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3419 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3420 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3421 attrs.extend(iattrs);
3422 let span = span_lo.to(body.span);
3423 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3426 /// Parse a 'while let' expression ('while' token already eaten)
3427 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3429 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3430 self.expect_keyword(keywords::Let)?;
3431 let pats = self.parse_pats()?;
3432 self.expect(&token::Eq)?;
3433 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3434 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3435 attrs.extend(iattrs);
3436 let span = span_lo.to(body.span);
3437 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3440 // parse `loop {...}`, `loop` token already eaten
3441 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3443 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3444 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3445 attrs.extend(iattrs);
3446 let span = span_lo.to(body.span);
3447 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3450 /// Parse an `async move {...}` expression
3451 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3452 -> PResult<'a, P<Expr>>
3454 let span_lo = self.span;
3455 self.expect_keyword(keywords::Async)?;
3456 let capture_clause = if self.eat_keyword(keywords::Move) {
3461 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3462 attrs.extend(iattrs);
3464 span_lo.to(body.span),
3465 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3468 /// Parse a `try {...}` expression (`try` token already eaten)
3469 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3470 -> PResult<'a, P<Expr>>
3472 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3473 attrs.extend(iattrs);
3474 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3477 // `match` token already eaten
3478 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3479 let match_span = self.prev_span;
3480 let lo = self.prev_span;
3481 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3483 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3484 if self.token == token::Token::Semi {
3485 e.span_suggestion_short_with_applicability(
3487 "try removing this `match`",
3489 Applicability::MaybeIncorrect // speculative
3494 attrs.extend(self.parse_inner_attributes()?);
3496 let mut arms: Vec<Arm> = Vec::new();
3497 while self.token != token::CloseDelim(token::Brace) {
3498 match self.parse_arm() {
3499 Ok(arm) => arms.push(arm),
3501 // Recover by skipping to the end of the block.
3503 self.recover_stmt();
3504 let span = lo.to(self.span);
3505 if self.token == token::CloseDelim(token::Brace) {
3508 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3514 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3517 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3518 maybe_whole!(self, NtArm, |x| x);
3520 let attrs = self.parse_outer_attributes()?;
3521 // Allow a '|' before the pats (RFC 1925)
3522 self.eat(&token::BinOp(token::Or));
3523 let pats = self.parse_pats()?;
3524 let guard = if self.eat_keyword(keywords::If) {
3525 Some(self.parse_expr()?)
3529 let arrow_span = self.span;
3530 self.expect(&token::FatArrow)?;
3531 let arm_start_span = self.span;
3533 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3534 .map_err(|mut err| {
3535 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3539 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3540 && self.token != token::CloseDelim(token::Brace);
3543 let cm = self.sess.source_map();
3544 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3545 .map_err(|mut err| {
3546 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3547 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3548 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3549 && expr_lines.lines.len() == 2
3550 && self.token == token::FatArrow => {
3551 // We check whether there's any trailing code in the parse span,
3552 // if there isn't, we very likely have the following:
3555 // | -- - missing comma
3561 // | parsed until here as `"y" & X`
3562 err.span_suggestion_short_with_applicability(
3563 cm.next_point(arm_start_span),
3564 "missing a comma here to end this `match` arm",
3566 Applicability::MachineApplicable
3570 err.span_label(arrow_span,
3571 "while parsing the `match` arm starting here");
3577 self.eat(&token::Comma);
3588 /// Parse an expression
3589 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3590 self.parse_expr_res(Restrictions::empty(), None)
3593 /// Evaluate the closure with restrictions in place.
3595 /// After the closure is evaluated, restrictions are reset.
3596 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3597 where F: FnOnce(&mut Self) -> T
3599 let old = self.restrictions;
3600 self.restrictions = r;
3602 self.restrictions = old;
3607 /// Parse an expression, subject to the given restrictions
3608 fn parse_expr_res(&mut self, r: Restrictions,
3609 already_parsed_attrs: Option<ThinVec<Attribute>>)
3610 -> PResult<'a, P<Expr>> {
3611 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3614 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3615 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3616 if self.check(&token::Eq) {
3618 Ok(Some(self.parse_expr()?))
3620 Ok(Some(self.parse_expr()?))
3626 /// Parse patterns, separated by '|' s
3627 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3628 let mut pats = Vec::new();
3630 pats.push(self.parse_top_level_pat()?);
3632 if self.token == token::OrOr {
3633 let mut err = self.struct_span_err(self.span,
3634 "unexpected token `||` after pattern");
3635 err.span_suggestion_with_applicability(
3637 "use a single `|` to specify multiple patterns",
3639 Applicability::MachineApplicable
3643 } else if self.check(&token::BinOp(token::Or)) {
3651 // Parses a parenthesized list of patterns like
3652 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3653 // - a vector of the patterns that were parsed
3654 // - an option indicating the index of the `..` element
3655 // - a boolean indicating whether a trailing comma was present.
3656 // Trailing commas are significant because (p) and (p,) are different patterns.
3657 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3658 self.expect(&token::OpenDelim(token::Paren))?;
3659 let result = self.parse_pat_list()?;
3660 self.expect(&token::CloseDelim(token::Paren))?;
3664 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3665 let mut fields = Vec::new();
3666 let mut ddpos = None;
3667 let mut trailing_comma = false;
3669 if self.eat(&token::DotDot) {
3670 if ddpos.is_none() {
3671 ddpos = Some(fields.len());
3673 // Emit a friendly error, ignore `..` and continue parsing
3674 self.span_err(self.prev_span,
3675 "`..` can only be used once per tuple or tuple struct pattern");
3677 } else if !self.check(&token::CloseDelim(token::Paren)) {
3678 fields.push(self.parse_pat()?);
3683 trailing_comma = self.eat(&token::Comma);
3684 if !trailing_comma {
3689 if ddpos == Some(fields.len()) && trailing_comma {
3690 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3691 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3694 Ok((fields, ddpos, trailing_comma))
3697 fn parse_pat_vec_elements(
3699 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3700 let mut before = Vec::new();
3701 let mut slice = None;
3702 let mut after = Vec::new();
3703 let mut first = true;
3704 let mut before_slice = true;
3706 while self.token != token::CloseDelim(token::Bracket) {
3710 self.expect(&token::Comma)?;
3712 if self.token == token::CloseDelim(token::Bracket)
3713 && (before_slice || !after.is_empty()) {
3719 if self.eat(&token::DotDot) {
3721 if self.check(&token::Comma) ||
3722 self.check(&token::CloseDelim(token::Bracket)) {
3723 slice = Some(P(Pat {
3724 id: ast::DUMMY_NODE_ID,
3725 node: PatKind::Wild,
3726 span: self.prev_span,
3728 before_slice = false;
3734 let subpat = self.parse_pat()?;
3735 if before_slice && self.eat(&token::DotDot) {
3736 slice = Some(subpat);
3737 before_slice = false;
3738 } else if before_slice {
3739 before.push(subpat);
3745 Ok((before, slice, after))
3751 attrs: Vec<Attribute>
3752 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3753 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3755 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3756 // Parsing a pattern of the form "fieldname: pat"
3757 let fieldname = self.parse_field_name()?;
3759 let pat = self.parse_pat()?;
3761 (pat, fieldname, false)
3763 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3764 let is_box = self.eat_keyword(keywords::Box);
3765 let boxed_span = self.span;
3766 let is_ref = self.eat_keyword(keywords::Ref);
3767 let is_mut = self.eat_keyword(keywords::Mut);
3768 let fieldname = self.parse_ident()?;
3769 hi = self.prev_span;
3771 let bind_type = match (is_ref, is_mut) {
3772 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3773 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3774 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3775 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3777 let fieldpat = P(Pat {
3778 id: ast::DUMMY_NODE_ID,
3779 node: PatKind::Ident(bind_type, fieldname, None),
3780 span: boxed_span.to(hi),
3783 let subpat = if is_box {
3785 id: ast::DUMMY_NODE_ID,
3786 node: PatKind::Box(fieldpat),
3792 (subpat, fieldname, true)
3795 Ok(source_map::Spanned {
3797 node: ast::FieldPat {
3801 attrs: attrs.into(),
3806 /// Parse the fields of a struct-like pattern
3807 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3808 let mut fields = Vec::new();
3809 let mut etc = false;
3810 let mut ate_comma = true;
3811 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3812 let mut etc_span = None;
3814 while self.token != token::CloseDelim(token::Brace) {
3815 let attrs = self.parse_outer_attributes()?;
3818 // check that a comma comes after every field
3820 let err = self.struct_span_err(self.prev_span, "expected `,`");
3825 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3827 let mut etc_sp = self.span;
3829 if self.token == token::DotDotDot { // Issue #46718
3830 // Accept `...` as if it were `..` to avoid further errors
3831 let mut err = self.struct_span_err(self.span,
3832 "expected field pattern, found `...`");
3833 err.span_suggestion_with_applicability(
3835 "to omit remaining fields, use one fewer `.`",
3837 Applicability::MachineApplicable
3841 self.bump(); // `..` || `...`:w
3843 if self.token == token::CloseDelim(token::Brace) {
3844 etc_span = Some(etc_sp);
3847 let token_str = self.this_token_to_string();
3848 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3850 err.span_label(self.span, "expected `}`");
3851 let mut comma_sp = None;
3852 if self.token == token::Comma { // Issue #49257
3853 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3854 err.span_label(etc_sp,
3855 "`..` must be at the end and cannot have a trailing comma");
3856 comma_sp = Some(self.span);
3861 etc_span = Some(etc_sp);
3862 if self.token == token::CloseDelim(token::Brace) {
3863 // If the struct looks otherwise well formed, recover and continue.
3864 if let Some(sp) = comma_sp {
3865 err.span_suggestion_short(sp, "remove this comma", String::new());
3869 } else if self.token.is_ident() && ate_comma {
3870 // Accept fields coming after `..,`.
3871 // This way we avoid "pattern missing fields" errors afterwards.
3872 // We delay this error until the end in order to have a span for a
3874 if let Some(mut delayed_err) = delayed_err {
3878 delayed_err = Some(err);
3881 if let Some(mut err) = delayed_err {
3888 fields.push(match self.parse_pat_field(lo, attrs) {
3891 if let Some(mut delayed_err) = delayed_err {
3897 ate_comma = self.eat(&token::Comma);
3900 if let Some(mut err) = delayed_err {
3901 if let Some(etc_span) = etc_span {
3902 err.multipart_suggestion(
3903 "move the `..` to the end of the field list",
3905 (etc_span, String::new()),
3906 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3912 return Ok((fields, etc));
3915 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3916 if self.token.is_path_start() {
3918 let (qself, path) = if self.eat_lt() {
3919 // Parse a qualified path
3920 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3923 // Parse an unqualified path
3924 (None, self.parse_path(PathStyle::Expr)?)
3926 let hi = self.prev_span;
3927 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3929 self.parse_literal_maybe_minus()
3933 // helper function to decide whether to parse as ident binding or to try to do
3934 // something more complex like range patterns
3935 fn parse_as_ident(&mut self) -> bool {
3936 self.look_ahead(1, |t| match *t {
3937 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3938 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3939 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3940 // range pattern branch
3941 token::DotDot => None,
3943 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3944 token::Comma | token::CloseDelim(token::Bracket) => true,
3949 /// A wrapper around `parse_pat` with some special error handling for the
3950 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3951 /// to subpatterns within such).
3952 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3953 let pat = self.parse_pat()?;
3954 if self.token == token::Comma {
3955 // An unexpected comma after a top-level pattern is a clue that the
3956 // user (perhaps more accustomed to some other language) forgot the
3957 // parentheses in what should have been a tuple pattern; return a
3958 // suggestion-enhanced error here rather than choking on the comma
3960 let comma_span = self.span;
3962 if let Err(mut err) = self.parse_pat_list() {
3963 // We didn't expect this to work anyway; we just wanted
3964 // to advance to the end of the comma-sequence so we know
3965 // the span to suggest parenthesizing
3968 let seq_span = pat.span.to(self.prev_span);
3969 let mut err = self.struct_span_err(comma_span,
3970 "unexpected `,` in pattern");
3971 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3972 err.span_suggestion_with_applicability(
3974 "try adding parentheses",
3975 format!("({})", seq_snippet),
3976 Applicability::MachineApplicable
3984 /// Parse a pattern.
3985 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3986 self.parse_pat_with_range_pat(true)
3989 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3991 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3992 maybe_whole!(self, NtPat, |x| x);
3997 token::BinOp(token::And) | token::AndAnd => {
3998 // Parse &pat / &mut pat
4000 let mutbl = self.parse_mutability();
4001 if let token::Lifetime(ident) = self.token {
4002 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4004 err.span_label(self.span, "unexpected lifetime");
4007 let subpat = self.parse_pat_with_range_pat(false)?;
4008 pat = PatKind::Ref(subpat, mutbl);
4010 token::OpenDelim(token::Paren) => {
4011 // Parse (pat,pat,pat,...) as tuple pattern
4012 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4013 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4014 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4016 PatKind::Tuple(fields, ddpos)
4019 token::OpenDelim(token::Bracket) => {
4020 // Parse [pat,pat,...] as slice pattern
4022 let (before, slice, after) = self.parse_pat_vec_elements()?;
4023 self.expect(&token::CloseDelim(token::Bracket))?;
4024 pat = PatKind::Slice(before, slice, after);
4026 // At this point, token != &, &&, (, [
4027 _ => if self.eat_keyword(keywords::Underscore) {
4029 pat = PatKind::Wild;
4030 } else if self.eat_keyword(keywords::Mut) {
4031 // Parse mut ident @ pat / mut ref ident @ pat
4032 let mutref_span = self.prev_span.to(self.span);
4033 let binding_mode = if self.eat_keyword(keywords::Ref) {
4035 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4036 .span_suggestion_with_applicability(
4038 "try switching the order",
4040 Applicability::MachineApplicable
4042 BindingMode::ByRef(Mutability::Mutable)
4044 BindingMode::ByValue(Mutability::Mutable)
4046 pat = self.parse_pat_ident(binding_mode)?;
4047 } else if self.eat_keyword(keywords::Ref) {
4048 // Parse ref ident @ pat / ref mut ident @ pat
4049 let mutbl = self.parse_mutability();
4050 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4051 } else if self.eat_keyword(keywords::Box) {
4053 let subpat = self.parse_pat_with_range_pat(false)?;
4054 pat = PatKind::Box(subpat);
4055 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4056 self.parse_as_ident() {
4057 // Parse ident @ pat
4058 // This can give false positives and parse nullary enums,
4059 // they are dealt with later in resolve
4060 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4061 pat = self.parse_pat_ident(binding_mode)?;
4062 } else if self.token.is_path_start() {
4063 // Parse pattern starting with a path
4064 let (qself, path) = if self.eat_lt() {
4065 // Parse a qualified path
4066 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4069 // Parse an unqualified path
4070 (None, self.parse_path(PathStyle::Expr)?)
4073 token::Not if qself.is_none() => {
4074 // Parse macro invocation
4076 let (delim, tts) = self.expect_delimited_token_tree()?;
4077 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4078 pat = PatKind::Mac(mac);
4080 token::DotDotDot | token::DotDotEq | token::DotDot => {
4081 let end_kind = match self.token {
4082 token::DotDot => RangeEnd::Excluded,
4083 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4084 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4085 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4088 let op_span = self.span;
4090 let span = lo.to(self.prev_span);
4091 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4093 let end = self.parse_pat_range_end()?;
4094 let op = Spanned { span: op_span, node: end_kind };
4095 pat = PatKind::Range(begin, end, op);
4097 token::OpenDelim(token::Brace) => {
4098 if qself.is_some() {
4099 let msg = "unexpected `{` after qualified path";
4100 let mut err = self.fatal(msg);
4101 err.span_label(self.span, msg);
4104 // Parse struct pattern
4106 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4108 self.recover_stmt();
4112 pat = PatKind::Struct(path, fields, etc);
4114 token::OpenDelim(token::Paren) => {
4115 if qself.is_some() {
4116 let msg = "unexpected `(` after qualified path";
4117 let mut err = self.fatal(msg);
4118 err.span_label(self.span, msg);
4121 // Parse tuple struct or enum pattern
4122 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4123 pat = PatKind::TupleStruct(path, fields, ddpos)
4125 _ => pat = PatKind::Path(qself, path),
4128 // Try to parse everything else as literal with optional minus
4129 match self.parse_literal_maybe_minus() {
4131 let op_span = self.span;
4132 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4133 self.check(&token::DotDotDot) {
4134 let end_kind = if self.eat(&token::DotDotDot) {
4135 RangeEnd::Included(RangeSyntax::DotDotDot)
4136 } else if self.eat(&token::DotDotEq) {
4137 RangeEnd::Included(RangeSyntax::DotDotEq)
4138 } else if self.eat(&token::DotDot) {
4141 panic!("impossible case: we already matched \
4142 on a range-operator token")
4144 let end = self.parse_pat_range_end()?;
4145 let op = Spanned { span: op_span, node: end_kind };
4146 pat = PatKind::Range(begin, end, op);
4148 pat = PatKind::Lit(begin);
4152 self.cancel(&mut err);
4153 let msg = format!("expected pattern, found {}", self.this_token_descr());
4154 let mut err = self.fatal(&msg);
4155 err.span_label(self.span, "expected pattern");
4162 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4163 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4165 if !allow_range_pat {
4168 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4170 PatKind::Range(..) => {
4171 let mut err = self.struct_span_err(
4173 "the range pattern here has ambiguous interpretation",
4175 err.span_suggestion_with_applicability(
4177 "add parentheses to clarify the precedence",
4178 format!("({})", pprust::pat_to_string(&pat)),
4179 // "ambiguous interpretation" implies that we have to be guessing
4180 Applicability::MaybeIncorrect
4191 /// Parse ident or ident @ pat
4192 /// used by the copy foo and ref foo patterns to give a good
4193 /// error message when parsing mistakes like ref foo(a,b)
4194 fn parse_pat_ident(&mut self,
4195 binding_mode: ast::BindingMode)
4196 -> PResult<'a, PatKind> {
4197 let ident = self.parse_ident()?;
4198 let sub = if self.eat(&token::At) {
4199 Some(self.parse_pat()?)
4204 // just to be friendly, if they write something like
4206 // we end up here with ( as the current token. This shortly
4207 // leads to a parse error. Note that if there is no explicit
4208 // binding mode then we do not end up here, because the lookahead
4209 // will direct us over to parse_enum_variant()
4210 if self.token == token::OpenDelim(token::Paren) {
4211 return Err(self.span_fatal(
4213 "expected identifier, found enum pattern"))
4216 Ok(PatKind::Ident(binding_mode, ident, sub))
4219 /// Parse a local variable declaration
4220 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4221 let lo = self.prev_span;
4222 let pat = self.parse_top_level_pat()?;
4224 let (err, ty) = if self.eat(&token::Colon) {
4225 // Save the state of the parser before parsing type normally, in case there is a `:`
4226 // instead of an `=` typo.
4227 let parser_snapshot_before_type = self.clone();
4228 let colon_sp = self.prev_span;
4229 match self.parse_ty() {
4230 Ok(ty) => (None, Some(ty)),
4232 // Rewind to before attempting to parse the type and continue parsing
4233 let parser_snapshot_after_type = self.clone();
4234 mem::replace(self, parser_snapshot_before_type);
4236 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4237 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4238 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4244 let init = match (self.parse_initializer(err.is_some()), err) {
4245 (Ok(init), None) => { // init parsed, ty parsed
4248 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4249 // Could parse the type as if it were the initializer, it is likely there was a
4250 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4251 err.span_suggestion_short_with_applicability(
4253 "use `=` if you meant to assign",
4255 Applicability::MachineApplicable
4258 // As this was parsed successfully, continue as if the code has been fixed for the
4259 // rest of the file. It will still fail due to the emitted error, but we avoid
4263 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4265 // Couldn't parse the type nor the initializer, only raise the type error and
4266 // return to the parser state before parsing the type as the initializer.
4267 // let x: <parse_error>;
4268 mem::replace(self, snapshot);
4271 (Err(err), None) => { // init error, ty parsed
4272 // Couldn't parse the initializer and we're not attempting to recover a failed
4273 // parse of the type, return the error.
4277 let hi = if self.token == token::Semi {
4286 id: ast::DUMMY_NODE_ID,
4292 /// Parse a structure field
4293 fn parse_name_and_ty(&mut self,
4296 attrs: Vec<Attribute>)
4297 -> PResult<'a, StructField> {
4298 let name = self.parse_ident()?;
4299 self.expect(&token::Colon)?;
4300 let ty = self.parse_ty()?;
4302 span: lo.to(self.prev_span),
4305 id: ast::DUMMY_NODE_ID,
4311 /// Emit an expected item after attributes error.
4312 fn expected_item_err(&self, attrs: &[Attribute]) {
4313 let message = match attrs.last() {
4314 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4315 _ => "expected item after attributes",
4318 self.span_err(self.prev_span, message);
4321 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4322 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4323 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4324 Ok(self.parse_stmt_(true))
4327 // Eat tokens until we can be relatively sure we reached the end of the
4328 // statement. This is something of a best-effort heuristic.
4330 // We terminate when we find an unmatched `}` (without consuming it).
4331 fn recover_stmt(&mut self) {
4332 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4335 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4336 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4337 // approximate - it can mean we break too early due to macros, but that
4338 // should only lead to sub-optimal recovery, not inaccurate parsing).
4340 // If `break_on_block` is `Break`, then we will stop consuming tokens
4341 // after finding (and consuming) a brace-delimited block.
4342 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4343 let mut brace_depth = 0;
4344 let mut bracket_depth = 0;
4345 let mut in_block = false;
4346 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4347 break_on_semi, break_on_block);
4349 debug!("recover_stmt_ loop {:?}", self.token);
4351 token::OpenDelim(token::DelimToken::Brace) => {
4354 if break_on_block == BlockMode::Break &&
4356 bracket_depth == 0 {
4360 token::OpenDelim(token::DelimToken::Bracket) => {
4364 token::CloseDelim(token::DelimToken::Brace) => {
4365 if brace_depth == 0 {
4366 debug!("recover_stmt_ return - close delim {:?}", self.token);
4371 if in_block && bracket_depth == 0 && brace_depth == 0 {
4372 debug!("recover_stmt_ return - block end {:?}", self.token);
4376 token::CloseDelim(token::DelimToken::Bracket) => {
4378 if bracket_depth < 0 {
4384 debug!("recover_stmt_ return - Eof");
4389 if break_on_semi == SemiColonMode::Break &&
4391 bracket_depth == 0 {
4392 debug!("recover_stmt_ return - Semi");
4403 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4404 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4406 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4411 fn is_async_block(&mut self) -> bool {
4412 self.token.is_keyword(keywords::Async) &&
4415 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4416 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4418 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4423 fn is_do_catch_block(&mut self) -> bool {
4424 self.token.is_keyword(keywords::Do) &&
4425 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4426 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4427 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4430 fn is_try_block(&mut self) -> bool {
4431 self.token.is_keyword(keywords::Try) &&
4432 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4434 self.span.edition() >= Edition::Edition2018 &&
4436 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4437 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4440 fn is_union_item(&self) -> bool {
4441 self.token.is_keyword(keywords::Union) &&
4442 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4445 fn is_crate_vis(&self) -> bool {
4446 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4449 fn is_extern_non_path(&self) -> bool {
4450 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4453 fn is_existential_type_decl(&self) -> bool {
4454 self.token.is_keyword(keywords::Existential) &&
4455 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4458 fn is_auto_trait_item(&mut self) -> bool {
4460 (self.token.is_keyword(keywords::Auto)
4461 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4462 || // unsafe auto trait
4463 (self.token.is_keyword(keywords::Unsafe) &&
4464 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4465 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4468 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4469 -> PResult<'a, Option<P<Item>>> {
4470 let token_lo = self.span;
4471 let (ident, def) = match self.token {
4472 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4474 let ident = self.parse_ident()?;
4475 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4476 match self.parse_token_tree() {
4477 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4478 _ => unreachable!(),
4480 } else if self.check(&token::OpenDelim(token::Paren)) {
4481 let args = self.parse_token_tree();
4482 let body = if self.check(&token::OpenDelim(token::Brace)) {
4483 self.parse_token_tree()
4488 TokenStream::concat(vec![
4490 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4498 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4500 token::Ident(ident, _) if ident.name == "macro_rules" &&
4501 self.look_ahead(1, |t| *t == token::Not) => {
4502 let prev_span = self.prev_span;
4503 self.complain_if_pub_macro(&vis.node, prev_span);
4507 let ident = self.parse_ident()?;
4508 let (delim, tokens) = self.expect_delimited_token_tree()?;
4509 if delim != MacDelimiter::Brace {
4510 if !self.eat(&token::Semi) {
4511 let msg = "macros that expand to items must either \
4512 be surrounded with braces or followed by a semicolon";
4513 self.span_err(self.prev_span, msg);
4517 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4519 _ => return Ok(None),
4522 let span = lo.to(self.prev_span);
4523 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4526 fn parse_stmt_without_recovery(&mut self,
4527 macro_legacy_warnings: bool)
4528 -> PResult<'a, Option<Stmt>> {
4529 maybe_whole!(self, NtStmt, |x| Some(x));
4531 let attrs = self.parse_outer_attributes()?;
4534 Ok(Some(if self.eat_keyword(keywords::Let) {
4536 id: ast::DUMMY_NODE_ID,
4537 node: StmtKind::Local(self.parse_local(attrs.into())?),
4538 span: lo.to(self.prev_span),
4540 } else if let Some(macro_def) = self.eat_macro_def(
4542 &source_map::respan(lo, VisibilityKind::Inherited),
4546 id: ast::DUMMY_NODE_ID,
4547 node: StmtKind::Item(macro_def),
4548 span: lo.to(self.prev_span),
4550 // Starts like a simple path, being careful to avoid contextual keywords
4551 // such as a union items, item with `crate` visibility or auto trait items.
4552 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4553 // like a path (1 token), but it fact not a path.
4554 // `union::b::c` - path, `union U { ... }` - not a path.
4555 // `crate::b::c` - path, `crate struct S;` - not a path.
4556 // `extern::b::c` - path, `extern crate c;` - not a path.
4557 } else if self.token.is_path_start() &&
4558 !self.token.is_qpath_start() &&
4559 !self.is_union_item() &&
4560 !self.is_crate_vis() &&
4561 !self.is_extern_non_path() &&
4562 !self.is_existential_type_decl() &&
4563 !self.is_auto_trait_item() {
4564 let pth = self.parse_path(PathStyle::Expr)?;
4566 if !self.eat(&token::Not) {
4567 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4568 self.parse_struct_expr(lo, pth, ThinVec::new())?
4570 let hi = self.prev_span;
4571 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4574 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4575 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4576 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4579 return Ok(Some(Stmt {
4580 id: ast::DUMMY_NODE_ID,
4581 node: StmtKind::Expr(expr),
4582 span: lo.to(self.prev_span),
4586 // it's a macro invocation
4587 let id = match self.token {
4588 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4589 _ => self.parse_ident()?,
4592 // check that we're pointing at delimiters (need to check
4593 // again after the `if`, because of `parse_ident`
4594 // consuming more tokens).
4596 token::OpenDelim(_) => {}
4598 // we only expect an ident if we didn't parse one
4600 let ident_str = if id.name == keywords::Invalid.name() {
4605 let tok_str = self.this_token_to_string();
4606 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4609 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4614 let (delim, tts) = self.expect_delimited_token_tree()?;
4615 let hi = self.prev_span;
4617 let style = if delim == MacDelimiter::Brace {
4618 MacStmtStyle::Braces
4620 MacStmtStyle::NoBraces
4623 if id.name == keywords::Invalid.name() {
4624 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4625 let node = if delim == MacDelimiter::Brace ||
4626 self.token == token::Semi || self.token == token::Eof {
4627 StmtKind::Mac(P((mac, style, attrs.into())))
4629 // We used to incorrectly stop parsing macro-expanded statements here.
4630 // If the next token will be an error anyway but could have parsed with the
4631 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4632 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4633 // These can continue an expression, so we can't stop parsing and warn.
4634 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4635 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4636 token::BinOp(token::And) | token::BinOp(token::Or) |
4637 token::AndAnd | token::OrOr |
4638 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4641 self.warn_missing_semicolon();
4642 StmtKind::Mac(P((mac, style, attrs.into())))
4644 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4645 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4646 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4650 id: ast::DUMMY_NODE_ID,
4655 // if it has a special ident, it's definitely an item
4657 // Require a semicolon or braces.
4658 if style != MacStmtStyle::Braces {
4659 if !self.eat(&token::Semi) {
4660 self.span_err(self.prev_span,
4661 "macros that expand to items must \
4662 either be surrounded with braces or \
4663 followed by a semicolon");
4666 let span = lo.to(hi);
4668 id: ast::DUMMY_NODE_ID,
4670 node: StmtKind::Item({
4672 span, id /*id is good here*/,
4673 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4674 respan(lo, VisibilityKind::Inherited),
4680 // FIXME: Bad copy of attrs
4681 let old_directory_ownership =
4682 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4683 let item = self.parse_item_(attrs.clone(), false, true)?;
4684 self.directory.ownership = old_directory_ownership;
4688 id: ast::DUMMY_NODE_ID,
4689 span: lo.to(i.span),
4690 node: StmtKind::Item(i),
4693 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4694 if !attrs.is_empty() {
4695 if s.prev_token_kind == PrevTokenKind::DocComment {
4696 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4697 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4698 s.span_err(s.span, "expected statement after outer attribute");
4703 // Do not attempt to parse an expression if we're done here.
4704 if self.token == token::Semi {
4705 unused_attrs(&attrs, self);
4710 if self.token == token::CloseDelim(token::Brace) {
4711 unused_attrs(&attrs, self);
4715 // Remainder are line-expr stmts.
4716 let e = self.parse_expr_res(
4717 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4719 id: ast::DUMMY_NODE_ID,
4720 span: lo.to(e.span),
4721 node: StmtKind::Expr(e),
4728 /// Is this expression a successfully-parsed statement?
4729 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4730 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4731 !classify::expr_requires_semi_to_be_stmt(e)
4734 /// Parse a block. No inner attrs are allowed.
4735 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4736 maybe_whole!(self, NtBlock, |x| x);
4740 if !self.eat(&token::OpenDelim(token::Brace)) {
4742 let tok = self.this_token_to_string();
4743 let mut do_not_suggest_help = false;
4744 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4745 if self.token.is_keyword(keywords::In) || self.token == token::Colon {
4746 do_not_suggest_help = true;
4747 e.span_label(sp, "expected `{`");
4750 // Check to see if the user has written something like
4755 // Which is valid in other languages, but not Rust.
4756 match self.parse_stmt_without_recovery(false) {
4758 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4759 || do_not_suggest_help {
4760 // if the next token is an open brace (e.g., `if a b {`), the place-
4761 // inside-a-block suggestion would be more likely wrong than right
4764 let mut stmt_span = stmt.span;
4765 // expand the span to include the semicolon, if it exists
4766 if self.eat(&token::Semi) {
4767 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4769 let sugg = pprust::to_string(|s| {
4770 use print::pprust::{PrintState, INDENT_UNIT};
4771 s.ibox(INDENT_UNIT)?;
4773 s.print_stmt(&stmt)?;
4774 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4776 e.span_suggestion_with_applicability(
4778 "try placing this code inside a block",
4780 // speculative, has been misleading in the past (closed Issue #46836)
4781 Applicability::MaybeIncorrect
4785 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4786 self.cancel(&mut e);
4793 self.parse_block_tail(lo, BlockCheckMode::Default)
4796 /// Parse a block. Inner attrs are allowed.
4797 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4798 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4801 self.expect(&token::OpenDelim(token::Brace))?;
4802 Ok((self.parse_inner_attributes()?,
4803 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4806 /// Parse the rest of a block expression or function body
4807 /// Precondition: already parsed the '{'.
4808 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4809 let mut stmts = vec![];
4810 let mut recovered = false;
4812 while !self.eat(&token::CloseDelim(token::Brace)) {
4813 let stmt = match self.parse_full_stmt(false) {
4816 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4817 self.eat(&token::CloseDelim(token::Brace));
4823 if let Some(stmt) = stmt {
4825 } else if self.token == token::Eof {
4828 // Found only `;` or `}`.
4834 id: ast::DUMMY_NODE_ID,
4836 span: lo.to(self.prev_span),
4841 /// Parse a statement, including the trailing semicolon.
4842 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4843 // skip looking for a trailing semicolon when we have an interpolated statement
4844 maybe_whole!(self, NtStmt, |x| Some(x));
4846 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4848 None => return Ok(None),
4852 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4853 // expression without semicolon
4854 if classify::expr_requires_semi_to_be_stmt(expr) {
4855 // Just check for errors and recover; do not eat semicolon yet.
4857 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4860 self.recover_stmt();
4864 StmtKind::Local(..) => {
4865 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4866 if macro_legacy_warnings && self.token != token::Semi {
4867 self.warn_missing_semicolon();
4869 self.expect_one_of(&[], &[token::Semi])?;
4875 if self.eat(&token::Semi) {
4876 stmt = stmt.add_trailing_semicolon();
4879 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4883 fn warn_missing_semicolon(&self) {
4884 self.diagnostic().struct_span_warn(self.span, {
4885 &format!("expected `;`, found `{}`", self.this_token_to_string())
4887 "This was erroneously allowed and will become a hard error in a future release"
4891 fn err_dotdotdot_syntax(&self, span: Span) {
4892 self.diagnostic().struct_span_err(span, {
4893 "unexpected token: `...`"
4894 }).span_suggestion_with_applicability(
4895 span, "use `..` for an exclusive range", "..".to_owned(),
4896 Applicability::MaybeIncorrect
4897 ).span_suggestion_with_applicability(
4898 span, "or `..=` for an inclusive range", "..=".to_owned(),
4899 Applicability::MaybeIncorrect
4903 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4904 // BOUND = TY_BOUND | LT_BOUND
4905 // LT_BOUND = LIFETIME (e.g. `'a`)
4906 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4907 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4908 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4909 let mut bounds = Vec::new();
4911 // This needs to be synchronized with `Token::can_begin_bound`.
4912 let is_bound_start = self.check_path() || self.check_lifetime() ||
4913 self.check(&token::Question) ||
4914 self.check_keyword(keywords::For) ||
4915 self.check(&token::OpenDelim(token::Paren));
4918 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4919 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4920 if self.token.is_lifetime() {
4921 if let Some(question_span) = question {
4922 self.span_err(question_span,
4923 "`?` may only modify trait bounds, not lifetime bounds");
4925 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4927 self.expect(&token::CloseDelim(token::Paren))?;
4928 self.span_err(self.prev_span,
4929 "parenthesized lifetime bounds are not supported");
4932 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4933 let path = self.parse_path(PathStyle::Type)?;
4935 self.expect(&token::CloseDelim(token::Paren))?;
4937 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4938 let modifier = if question.is_some() {
4939 TraitBoundModifier::Maybe
4941 TraitBoundModifier::None
4943 bounds.push(GenericBound::Trait(poly_trait, modifier));
4949 if !allow_plus || !self.eat_plus() {
4957 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
4958 self.parse_generic_bounds_common(true)
4961 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4962 // BOUND = LT_BOUND (e.g. `'a`)
4963 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4964 let mut lifetimes = Vec::new();
4965 while self.check_lifetime() {
4966 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4968 if !self.eat_plus() {
4975 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4976 fn parse_ty_param(&mut self,
4977 preceding_attrs: Vec<Attribute>)
4978 -> PResult<'a, GenericParam> {
4979 let ident = self.parse_ident()?;
4981 // Parse optional colon and param bounds.
4982 let bounds = if self.eat(&token::Colon) {
4983 self.parse_generic_bounds()?
4988 let default = if self.eat(&token::Eq) {
4989 Some(self.parse_ty()?)
4996 id: ast::DUMMY_NODE_ID,
4997 attrs: preceding_attrs.into(),
4999 kind: GenericParamKind::Type {
5005 /// Parses the following grammar:
5006 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5007 fn parse_trait_item_assoc_ty(&mut self)
5008 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5009 let ident = self.parse_ident()?;
5010 let mut generics = self.parse_generics()?;
5012 // Parse optional colon and param bounds.
5013 let bounds = if self.eat(&token::Colon) {
5014 self.parse_generic_bounds()?
5018 generics.where_clause = self.parse_where_clause()?;
5020 let default = if self.eat(&token::Eq) {
5021 Some(self.parse_ty()?)
5025 self.expect(&token::Semi)?;
5027 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5030 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5031 /// trailing comma and erroneous trailing attributes.
5032 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5033 let mut params = Vec::new();
5034 let mut seen_ty_param = false;
5036 let attrs = self.parse_outer_attributes()?;
5037 if self.check_lifetime() {
5038 let lifetime = self.expect_lifetime();
5039 // Parse lifetime parameter.
5040 let bounds = if self.eat(&token::Colon) {
5041 self.parse_lt_param_bounds()
5045 params.push(ast::GenericParam {
5046 ident: lifetime.ident,
5048 attrs: attrs.into(),
5050 kind: ast::GenericParamKind::Lifetime,
5053 self.span_err(self.prev_span,
5054 "lifetime parameters must be declared prior to type parameters");
5056 } else if self.check_ident() {
5057 // Parse type parameter.
5058 params.push(self.parse_ty_param(attrs)?);
5059 seen_ty_param = true;
5061 // Check for trailing attributes and stop parsing.
5062 if !attrs.is_empty() {
5063 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
5064 self.span_err(attrs[0].span,
5065 &format!("trailing attribute after {} parameters", param_kind));
5070 if !self.eat(&token::Comma) {
5077 /// Parse a set of optional generic type parameter declarations. Where
5078 /// clauses are not parsed here, and must be added later via
5079 /// `parse_where_clause()`.
5081 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5082 /// | ( < lifetimes , typaramseq ( , )? > )
5083 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5084 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5085 maybe_whole!(self, NtGenerics, |x| x);
5087 let span_lo = self.span;
5089 let params = self.parse_generic_params()?;
5093 where_clause: WhereClause {
5094 id: ast::DUMMY_NODE_ID,
5095 predicates: Vec::new(),
5096 span: syntax_pos::DUMMY_SP,
5098 span: span_lo.to(self.prev_span),
5101 Ok(ast::Generics::default())
5105 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5106 /// possibly including trailing comma.
5107 fn parse_generic_args(&mut self)
5108 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5109 let mut args = Vec::new();
5110 let mut bindings = Vec::new();
5111 let mut seen_type = false;
5112 let mut seen_binding = false;
5114 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5115 // Parse lifetime argument.
5116 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5117 if seen_type || seen_binding {
5118 self.span_err(self.prev_span,
5119 "lifetime parameters must be declared prior to type parameters");
5121 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5122 // Parse associated type binding.
5124 let ident = self.parse_ident()?;
5126 let ty = self.parse_ty()?;
5127 bindings.push(TypeBinding {
5128 id: ast::DUMMY_NODE_ID,
5131 span: lo.to(self.prev_span),
5133 seen_binding = true;
5134 } else if self.check_type() {
5135 // Parse type argument.
5136 let ty_param = self.parse_ty()?;
5138 self.span_err(ty_param.span,
5139 "type parameters must be declared prior to associated type bindings");
5141 args.push(GenericArg::Type(ty_param));
5147 if !self.eat(&token::Comma) {
5151 Ok((args, bindings))
5154 /// Parses an optional `where` clause and places it in `generics`.
5156 /// ```ignore (only-for-syntax-highlight)
5157 /// where T : Trait<U, V> + 'b, 'a : 'b
5159 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5160 maybe_whole!(self, NtWhereClause, |x| x);
5162 let mut where_clause = WhereClause {
5163 id: ast::DUMMY_NODE_ID,
5164 predicates: Vec::new(),
5165 span: syntax_pos::DUMMY_SP,
5168 if !self.eat_keyword(keywords::Where) {
5169 return Ok(where_clause);
5171 let lo = self.prev_span;
5173 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5174 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5175 // change we parse those generics now, but report an error.
5176 if self.choose_generics_over_qpath() {
5177 let generics = self.parse_generics()?;
5178 self.span_err(generics.span,
5179 "generic parameters on `where` clauses are reserved for future use");
5184 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5185 let lifetime = self.expect_lifetime();
5186 // Bounds starting with a colon are mandatory, but possibly empty.
5187 self.expect(&token::Colon)?;
5188 let bounds = self.parse_lt_param_bounds();
5189 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5190 ast::WhereRegionPredicate {
5191 span: lo.to(self.prev_span),
5196 } else if self.check_type() {
5197 // Parse optional `for<'a, 'b>`.
5198 // This `for` is parsed greedily and applies to the whole predicate,
5199 // the bounded type can have its own `for` applying only to it.
5200 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5201 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5202 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5203 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5205 // Parse type with mandatory colon and (possibly empty) bounds,
5206 // or with mandatory equality sign and the second type.
5207 let ty = self.parse_ty()?;
5208 if self.eat(&token::Colon) {
5209 let bounds = self.parse_generic_bounds()?;
5210 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5211 ast::WhereBoundPredicate {
5212 span: lo.to(self.prev_span),
5213 bound_generic_params: lifetime_defs,
5218 // FIXME: Decide what should be used here, `=` or `==`.
5219 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5220 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5221 let rhs_ty = self.parse_ty()?;
5222 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5223 ast::WhereEqPredicate {
5224 span: lo.to(self.prev_span),
5227 id: ast::DUMMY_NODE_ID,
5231 return self.unexpected();
5237 if !self.eat(&token::Comma) {
5242 where_clause.span = lo.to(self.prev_span);
5246 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5247 -> PResult<'a, (Vec<Arg> , bool)> {
5249 let mut variadic = false;
5250 let args: Vec<Option<Arg>> =
5251 self.parse_unspanned_seq(
5252 &token::OpenDelim(token::Paren),
5253 &token::CloseDelim(token::Paren),
5254 SeqSep::trailing_allowed(token::Comma),
5256 if p.token == token::DotDotDot {
5260 if p.token != token::CloseDelim(token::Paren) {
5263 "`...` must be last in argument list for variadic function");
5267 let span = p.prev_span;
5268 if p.token == token::CloseDelim(token::Paren) {
5269 // continue parsing to present any further errors
5272 "only foreign functions are allowed to be variadic"
5274 Ok(Some(dummy_arg(span)))
5276 // this function definition looks beyond recovery, stop parsing
5278 "only foreign functions are allowed to be variadic");
5283 match p.parse_arg_general(named_args) {
5284 Ok(arg) => Ok(Some(arg)),
5287 let lo = p.prev_span;
5288 // Skip every token until next possible arg or end.
5289 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5290 // Create a placeholder argument for proper arg count (#34264).
5291 let span = lo.to(p.prev_span);
5292 Ok(Some(dummy_arg(span)))
5299 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5301 if variadic && args.is_empty() {
5303 "variadic function must be declared with at least one named argument");
5306 Ok((args, variadic))
5309 /// Parse the argument list and result type of a function declaration
5310 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5312 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5313 let ret_ty = self.parse_ret_ty(true)?;
5322 /// Returns the parsed optional self argument and whether a self shortcut was used.
5323 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5324 let expect_ident = |this: &mut Self| match this.token {
5325 // Preserve hygienic context.
5326 token::Ident(ident, _) =>
5327 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5330 let isolated_self = |this: &mut Self, n| {
5331 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5332 this.look_ahead(n + 1, |t| t != &token::ModSep)
5335 // Parse optional self parameter of a method.
5336 // Only a limited set of initial token sequences is considered self parameters, anything
5337 // else is parsed as a normal function parameter list, so some lookahead is required.
5338 let eself_lo = self.span;
5339 let (eself, eself_ident, eself_hi) = match self.token {
5340 token::BinOp(token::And) => {
5346 (if isolated_self(self, 1) {
5348 SelfKind::Region(None, Mutability::Immutable)
5349 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5350 isolated_self(self, 2) {
5353 SelfKind::Region(None, Mutability::Mutable)
5354 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5355 isolated_self(self, 2) {
5357 let lt = self.expect_lifetime();
5358 SelfKind::Region(Some(lt), Mutability::Immutable)
5359 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5360 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5361 isolated_self(self, 3) {
5363 let lt = self.expect_lifetime();
5365 SelfKind::Region(Some(lt), Mutability::Mutable)
5368 }, expect_ident(self), self.prev_span)
5370 token::BinOp(token::Star) => {
5375 // Emit special error for `self` cases.
5376 (if isolated_self(self, 1) {
5378 self.span_err(self.span, "cannot pass `self` by raw pointer");
5379 SelfKind::Value(Mutability::Immutable)
5380 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5381 isolated_self(self, 2) {
5384 self.span_err(self.span, "cannot pass `self` by raw pointer");
5385 SelfKind::Value(Mutability::Immutable)
5388 }, expect_ident(self), self.prev_span)
5390 token::Ident(..) => {
5391 if isolated_self(self, 0) {
5394 let eself_ident = expect_ident(self);
5395 let eself_hi = self.prev_span;
5396 (if self.eat(&token::Colon) {
5397 let ty = self.parse_ty()?;
5398 SelfKind::Explicit(ty, Mutability::Immutable)
5400 SelfKind::Value(Mutability::Immutable)
5401 }, eself_ident, eself_hi)
5402 } else if self.token.is_keyword(keywords::Mut) &&
5403 isolated_self(self, 1) {
5407 let eself_ident = expect_ident(self);
5408 let eself_hi = self.prev_span;
5409 (if self.eat(&token::Colon) {
5410 let ty = self.parse_ty()?;
5411 SelfKind::Explicit(ty, Mutability::Mutable)
5413 SelfKind::Value(Mutability::Mutable)
5414 }, eself_ident, eself_hi)
5419 _ => return Ok(None),
5422 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5423 Ok(Some(Arg::from_self(eself, eself_ident)))
5426 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5427 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5428 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5430 self.expect(&token::OpenDelim(token::Paren))?;
5432 // Parse optional self argument
5433 let self_arg = self.parse_self_arg()?;
5435 // Parse the rest of the function parameter list.
5436 let sep = SeqSep::trailing_allowed(token::Comma);
5437 let fn_inputs = if let Some(self_arg) = self_arg {
5438 if self.check(&token::CloseDelim(token::Paren)) {
5440 } else if self.eat(&token::Comma) {
5441 let mut fn_inputs = vec![self_arg];
5442 fn_inputs.append(&mut self.parse_seq_to_before_end(
5443 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5447 return self.unexpected();
5450 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5453 // Parse closing paren and return type.
5454 self.expect(&token::CloseDelim(token::Paren))?;
5457 output: self.parse_ret_ty(true)?,
5462 // parse the |arg, arg| header on a lambda
5463 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5464 let inputs_captures = {
5465 if self.eat(&token::OrOr) {
5468 self.expect(&token::BinOp(token::Or))?;
5469 let args = self.parse_seq_to_before_tokens(
5470 &[&token::BinOp(token::Or), &token::OrOr],
5471 SeqSep::trailing_allowed(token::Comma),
5472 TokenExpectType::NoExpect,
5473 |p| p.parse_fn_block_arg()
5479 let output = self.parse_ret_ty(true)?;
5482 inputs: inputs_captures,
5488 /// Parse the name and optional generic types of a function header.
5489 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5490 let id = self.parse_ident()?;
5491 let generics = self.parse_generics()?;
5495 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5496 attrs: Vec<Attribute>) -> P<Item> {
5500 id: ast::DUMMY_NODE_ID,
5508 /// Parse an item-position function declaration.
5509 fn parse_item_fn(&mut self,
5512 constness: Spanned<Constness>,
5514 -> PResult<'a, ItemInfo> {
5515 let (ident, mut generics) = self.parse_fn_header()?;
5516 let decl = self.parse_fn_decl(false)?;
5517 generics.where_clause = self.parse_where_clause()?;
5518 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5519 let header = FnHeader { unsafety, asyncness, constness, abi };
5520 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5523 /// true if we are looking at `const ID`, false for things like `const fn` etc
5524 fn is_const_item(&mut self) -> bool {
5525 self.token.is_keyword(keywords::Const) &&
5526 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5527 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5530 /// parses all the "front matter" for a `fn` declaration, up to
5531 /// and including the `fn` keyword:
5535 /// - `const unsafe fn`
5538 fn parse_fn_front_matter(&mut self)
5546 let is_const_fn = self.eat_keyword(keywords::Const);
5547 let const_span = self.prev_span;
5548 let unsafety = self.parse_unsafety();
5549 let asyncness = self.parse_asyncness();
5550 let (constness, unsafety, abi) = if is_const_fn {
5551 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5553 let abi = if self.eat_keyword(keywords::Extern) {
5554 self.parse_opt_abi()?.unwrap_or(Abi::C)
5558 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5560 self.expect_keyword(keywords::Fn)?;
5561 Ok((constness, unsafety, asyncness, abi))
5564 /// Parse an impl item.
5565 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5566 maybe_whole!(self, NtImplItem, |x| x);
5567 let attrs = self.parse_outer_attributes()?;
5568 let (mut item, tokens) = self.collect_tokens(|this| {
5569 this.parse_impl_item_(at_end, attrs)
5572 // See `parse_item` for why this clause is here.
5573 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5574 item.tokens = Some(tokens);
5579 fn parse_impl_item_(&mut self,
5581 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5583 let vis = self.parse_visibility(false)?;
5584 let defaultness = self.parse_defaultness();
5585 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5586 let (name, alias, generics) = type_?;
5587 let kind = match alias {
5588 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5589 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5591 (name, kind, generics)
5592 } else if self.is_const_item() {
5593 // This parses the grammar:
5594 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5595 self.expect_keyword(keywords::Const)?;
5596 let name = self.parse_ident()?;
5597 self.expect(&token::Colon)?;
5598 let typ = self.parse_ty()?;
5599 self.expect(&token::Eq)?;
5600 let expr = self.parse_expr()?;
5601 self.expect(&token::Semi)?;
5602 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5604 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5605 attrs.extend(inner_attrs);
5606 (name, node, generics)
5610 id: ast::DUMMY_NODE_ID,
5611 span: lo.to(self.prev_span),
5622 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5623 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5628 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5630 VisibilityKind::Inherited => Ok(()),
5632 let is_macro_rules: bool = match self.token {
5633 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5637 let mut err = self.diagnostic()
5638 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5639 err.span_suggestion_with_applicability(
5641 "try exporting the macro",
5642 "#[macro_export]".to_owned(),
5643 Applicability::MaybeIncorrect // speculative
5647 let mut err = self.diagnostic()
5648 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5649 err.help("try adjusting the macro to put `pub` inside the invocation");
5656 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5657 -> DiagnosticBuilder<'a>
5659 let expected_kinds = if item_type == "extern" {
5660 "missing `fn`, `type`, or `static`"
5662 "missing `fn`, `type`, or `const`"
5665 // Given this code `path(`, it seems like this is not
5666 // setting the visibility of a macro invocation, but rather
5667 // a mistyped method declaration.
5668 // Create a diagnostic pointing out that `fn` is missing.
5670 // x | pub path(&self) {
5671 // | ^ missing `fn`, `type`, or `const`
5673 // ^^ `sp` below will point to this
5674 let sp = prev_span.between(self.prev_span);
5675 let mut err = self.diagnostic().struct_span_err(
5677 &format!("{} for {}-item declaration",
5678 expected_kinds, item_type));
5679 err.span_label(sp, expected_kinds);
5683 /// Parse a method or a macro invocation in a trait impl.
5684 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5685 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5686 ast::ImplItemKind)> {
5687 // code copied from parse_macro_use_or_failure... abstraction!
5688 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5690 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5691 ast::ImplItemKind::Macro(mac)))
5693 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5694 let ident = self.parse_ident()?;
5695 let mut generics = self.parse_generics()?;
5696 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5697 generics.where_clause = self.parse_where_clause()?;
5699 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5700 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5701 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5702 ast::MethodSig { header, decl },
5708 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5709 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5710 let ident = self.parse_ident()?;
5711 let mut tps = self.parse_generics()?;
5713 // Parse optional colon and supertrait bounds.
5714 let bounds = if self.eat(&token::Colon) {
5715 self.parse_generic_bounds()?
5720 if self.eat(&token::Eq) {
5721 // it's a trait alias
5722 let bounds = self.parse_generic_bounds()?;
5723 tps.where_clause = self.parse_where_clause()?;
5724 self.expect(&token::Semi)?;
5725 if unsafety != Unsafety::Normal {
5726 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5728 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5730 // it's a normal trait
5731 tps.where_clause = self.parse_where_clause()?;
5732 self.expect(&token::OpenDelim(token::Brace))?;
5733 let mut trait_items = vec![];
5734 while !self.eat(&token::CloseDelim(token::Brace)) {
5735 let mut at_end = false;
5736 match self.parse_trait_item(&mut at_end) {
5737 Ok(item) => trait_items.push(item),
5741 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5746 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5750 fn choose_generics_over_qpath(&self) -> bool {
5751 // There's an ambiguity between generic parameters and qualified paths in impls.
5752 // If we see `<` it may start both, so we have to inspect some following tokens.
5753 // The following combinations can only start generics,
5754 // but not qualified paths (with one exception):
5755 // `<` `>` - empty generic parameters
5756 // `<` `#` - generic parameters with attributes
5757 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5758 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5759 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5760 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5761 // The only truly ambiguous case is
5762 // `<` IDENT `>` `::` IDENT ...
5763 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5764 // because this is what almost always expected in practice, qualified paths in impls
5765 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5766 self.token == token::Lt &&
5767 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5768 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5769 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5770 t == &token::Colon || t == &token::Eq))
5773 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5774 self.expect(&token::OpenDelim(token::Brace))?;
5775 let attrs = self.parse_inner_attributes()?;
5777 let mut impl_items = Vec::new();
5778 while !self.eat(&token::CloseDelim(token::Brace)) {
5779 let mut at_end = false;
5780 match self.parse_impl_item(&mut at_end) {
5781 Ok(impl_item) => impl_items.push(impl_item),
5785 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5790 Ok((impl_items, attrs))
5793 /// Parses an implementation item, `impl` keyword is already parsed.
5794 /// impl<'a, T> TYPE { /* impl items */ }
5795 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5796 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5797 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5798 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5799 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5800 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5801 -> PResult<'a, ItemInfo> {
5802 // First, parse generic parameters if necessary.
5803 let mut generics = if self.choose_generics_over_qpath() {
5804 self.parse_generics()?
5806 ast::Generics::default()
5809 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5810 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5812 ast::ImplPolarity::Negative
5814 ast::ImplPolarity::Positive
5817 // Parse both types and traits as a type, then reinterpret if necessary.
5818 let ty_first = self.parse_ty()?;
5820 // If `for` is missing we try to recover.
5821 let has_for = self.eat_keyword(keywords::For);
5822 let missing_for_span = self.prev_span.between(self.span);
5824 let ty_second = if self.token == token::DotDot {
5825 // We need to report this error after `cfg` expansion for compatibility reasons
5826 self.bump(); // `..`, do not add it to expected tokens
5827 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5828 } else if has_for || self.token.can_begin_type() {
5829 Some(self.parse_ty()?)
5834 generics.where_clause = self.parse_where_clause()?;
5836 let (impl_items, attrs) = self.parse_impl_body()?;
5838 let item_kind = match ty_second {
5839 Some(ty_second) => {
5840 // impl Trait for Type
5842 self.span_err(missing_for_span, "missing `for` in a trait impl");
5845 let ty_first = ty_first.into_inner();
5846 let path = match ty_first.node {
5847 // This notably includes paths passed through `ty` macro fragments (#46438).
5848 TyKind::Path(None, path) => path,
5850 self.span_err(ty_first.span, "expected a trait, found type");
5851 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5854 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5856 ItemKind::Impl(unsafety, polarity, defaultness,
5857 generics, Some(trait_ref), ty_second, impl_items)
5861 ItemKind::Impl(unsafety, polarity, defaultness,
5862 generics, None, ty_first, impl_items)
5866 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5869 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5870 if self.eat_keyword(keywords::For) {
5872 let params = self.parse_generic_params()?;
5874 // We rely on AST validation to rule out invalid cases: There must not be type
5875 // parameters, and the lifetime parameters must not have bounds.
5882 /// Parse struct Foo { ... }
5883 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5884 let class_name = self.parse_ident()?;
5886 let mut generics = self.parse_generics()?;
5888 // There is a special case worth noting here, as reported in issue #17904.
5889 // If we are parsing a tuple struct it is the case that the where clause
5890 // should follow the field list. Like so:
5892 // struct Foo<T>(T) where T: Copy;
5894 // If we are parsing a normal record-style struct it is the case
5895 // that the where clause comes before the body, and after the generics.
5896 // So if we look ahead and see a brace or a where-clause we begin
5897 // parsing a record style struct.
5899 // Otherwise if we look ahead and see a paren we parse a tuple-style
5902 let vdata = if self.token.is_keyword(keywords::Where) {
5903 generics.where_clause = self.parse_where_clause()?;
5904 if self.eat(&token::Semi) {
5905 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5906 VariantData::Unit(ast::DUMMY_NODE_ID)
5908 // If we see: `struct Foo<T> where T: Copy { ... }`
5909 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5911 // No `where` so: `struct Foo<T>;`
5912 } else if self.eat(&token::Semi) {
5913 VariantData::Unit(ast::DUMMY_NODE_ID)
5914 // Record-style struct definition
5915 } else if self.token == token::OpenDelim(token::Brace) {
5916 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5917 // Tuple-style struct definition with optional where-clause.
5918 } else if self.token == token::OpenDelim(token::Paren) {
5919 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5920 generics.where_clause = self.parse_where_clause()?;
5921 self.expect(&token::Semi)?;
5924 let token_str = self.this_token_to_string();
5925 let mut err = self.fatal(&format!(
5926 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5929 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5933 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5936 /// Parse union Foo { ... }
5937 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5938 let class_name = self.parse_ident()?;
5940 let mut generics = self.parse_generics()?;
5942 let vdata = if self.token.is_keyword(keywords::Where) {
5943 generics.where_clause = self.parse_where_clause()?;
5944 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5945 } else if self.token == token::OpenDelim(token::Brace) {
5946 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5948 let token_str = self.this_token_to_string();
5949 let mut err = self.fatal(&format!(
5950 "expected `where` or `{{` after union name, found `{}`", token_str));
5951 err.span_label(self.span, "expected `where` or `{` after union name");
5955 Ok((class_name, ItemKind::Union(vdata, generics), None))
5958 fn consume_block(&mut self, delim: token::DelimToken) {
5959 let mut brace_depth = 0;
5960 if !self.eat(&token::OpenDelim(delim)) {
5964 if self.eat(&token::OpenDelim(delim)) {
5966 } else if self.eat(&token::CloseDelim(delim)) {
5967 if brace_depth == 0 {
5973 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5981 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5982 let mut fields = Vec::new();
5983 if self.eat(&token::OpenDelim(token::Brace)) {
5984 while self.token != token::CloseDelim(token::Brace) {
5985 let field = self.parse_struct_decl_field().map_err(|e| {
5986 self.recover_stmt();
5990 Ok(field) => fields.push(field),
5996 self.eat(&token::CloseDelim(token::Brace));
5998 let token_str = self.this_token_to_string();
5999 let mut err = self.fatal(&format!(
6000 "expected `where`, or `{{` after struct name, found `{}`", token_str));
6001 err.span_label(self.span, "expected `where`, or `{` after struct name");
6008 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6009 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6010 // Unit like structs are handled in parse_item_struct function
6011 let fields = self.parse_unspanned_seq(
6012 &token::OpenDelim(token::Paren),
6013 &token::CloseDelim(token::Paren),
6014 SeqSep::trailing_allowed(token::Comma),
6016 let attrs = p.parse_outer_attributes()?;
6018 let vis = p.parse_visibility(true)?;
6019 let ty = p.parse_ty()?;
6021 span: lo.to(ty.span),
6024 id: ast::DUMMY_NODE_ID,
6033 /// Parse a structure field declaration
6034 fn parse_single_struct_field(&mut self,
6037 attrs: Vec<Attribute> )
6038 -> PResult<'a, StructField> {
6039 let mut seen_comma: bool = false;
6040 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6041 if self.token == token::Comma {
6048 token::CloseDelim(token::Brace) => {}
6049 token::DocComment(_) => {
6050 let previous_span = self.prev_span;
6051 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6052 self.bump(); // consume the doc comment
6053 let comma_after_doc_seen = self.eat(&token::Comma);
6054 // `seen_comma` is always false, because we are inside doc block
6055 // condition is here to make code more readable
6056 if seen_comma == false && comma_after_doc_seen == true {
6059 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6062 if seen_comma == false {
6063 let sp = self.sess.source_map().next_point(previous_span);
6064 err.span_suggestion_with_applicability(
6066 "missing comma here",
6068 Applicability::MachineApplicable
6075 let sp = self.sess.source_map().next_point(self.prev_span);
6076 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
6077 self.this_token_to_string()));
6078 if self.token.is_ident() {
6079 // This is likely another field; emit the diagnostic and keep going
6080 err.span_suggestion(sp, "try adding a comma", ",".into());
6090 /// Parse an element of a struct definition
6091 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6092 let attrs = self.parse_outer_attributes()?;
6094 let vis = self.parse_visibility(false)?;
6095 self.parse_single_struct_field(lo, vis, attrs)
6098 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6099 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6100 /// a function definition, it's not a tuple struct field) and the contents within the parens
6101 /// isn't valid, emit a proper diagnostic.
6102 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6103 maybe_whole!(self, NtVis, |x| x);
6105 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6106 if self.is_crate_vis() {
6107 self.bump(); // `crate`
6108 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6111 if !self.eat_keyword(keywords::Pub) {
6112 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6113 // keyword to grab a span from for inherited visibility; an empty span at the
6114 // beginning of the current token would seem to be the "Schelling span".
6115 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6117 let lo = self.prev_span;
6119 if self.check(&token::OpenDelim(token::Paren)) {
6120 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6121 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6122 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6123 // by the following tokens.
6124 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6127 self.bump(); // `crate`
6128 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6130 lo.to(self.prev_span),
6131 VisibilityKind::Crate(CrateSugar::PubCrate),
6134 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6137 self.bump(); // `in`
6138 let path = self.parse_path(PathStyle::Mod)?; // `path`
6139 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6140 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6142 id: ast::DUMMY_NODE_ID,
6145 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6146 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6147 t.is_keyword(keywords::SelfValue))
6149 // `pub(self)` or `pub(super)`
6151 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6152 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6153 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6155 id: ast::DUMMY_NODE_ID,
6158 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6159 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6161 let msg = "incorrect visibility restriction";
6162 let suggestion = r##"some possible visibility restrictions are:
6163 `pub(crate)`: visible only on the current crate
6164 `pub(super)`: visible only in the current module's parent
6165 `pub(in path::to::module)`: visible only on the specified path"##;
6166 let path = self.parse_path(PathStyle::Mod)?;
6167 let sp = self.prev_span;
6168 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6169 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6170 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6171 err.help(suggestion);
6172 err.span_suggestion_with_applicability(
6173 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6175 err.emit(); // emit diagnostic, but continue with public visibility
6179 Ok(respan(lo, VisibilityKind::Public))
6182 /// Parse defaultness: `default` or nothing.
6183 fn parse_defaultness(&mut self) -> Defaultness {
6184 // `pub` is included for better error messages
6185 if self.check_keyword(keywords::Default) &&
6186 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6187 t.is_keyword(keywords::Const) ||
6188 t.is_keyword(keywords::Fn) ||
6189 t.is_keyword(keywords::Unsafe) ||
6190 t.is_keyword(keywords::Extern) ||
6191 t.is_keyword(keywords::Type) ||
6192 t.is_keyword(keywords::Pub)) {
6193 self.bump(); // `default`
6194 Defaultness::Default
6200 /// Given a termination token, parse all of the items in a module
6201 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6202 let mut items = vec![];
6203 while let Some(item) = self.parse_item()? {
6207 if !self.eat(term) {
6208 let token_str = self.this_token_to_string();
6209 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6210 if token_str == ";" {
6211 let msg = "consider removing this semicolon";
6212 err.span_suggestion_short_with_applicability(
6213 self.span, msg, String::new(), Applicability::MachineApplicable
6215 if !items.is_empty() { // Issue #51603
6216 let previous_item = &items[items.len()-1];
6217 let previous_item_kind_name = match previous_item.node {
6218 // say "braced struct" because tuple-structs and
6219 // braceless-empty-struct declarations do take a semicolon
6220 ItemKind::Struct(..) => Some("braced struct"),
6221 ItemKind::Enum(..) => Some("enum"),
6222 ItemKind::Trait(..) => Some("trait"),
6223 ItemKind::Union(..) => Some("union"),
6226 if let Some(name) = previous_item_kind_name {
6227 err.help(&format!("{} declarations are not followed by a semicolon",
6232 err.span_label(self.span, "expected item");
6237 let hi = if self.span.is_dummy() {
6244 inner: inner_lo.to(hi),
6249 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6250 let id = self.parse_ident()?;
6251 self.expect(&token::Colon)?;
6252 let ty = self.parse_ty()?;
6253 self.expect(&token::Eq)?;
6254 let e = self.parse_expr()?;
6255 self.expect(&token::Semi)?;
6256 let item = match m {
6257 Some(m) => ItemKind::Static(ty, m, e),
6258 None => ItemKind::Const(ty, e),
6260 Ok((id, item, None))
6263 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6264 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6265 let (in_cfg, outer_attrs) = {
6266 let mut strip_unconfigured = ::config::StripUnconfigured {
6268 should_test: false, // irrelevant
6269 features: None, // don't perform gated feature checking
6271 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6272 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6275 let id_span = self.span;
6276 let id = self.parse_ident()?;
6277 if self.check(&token::Semi) {
6279 if in_cfg && self.recurse_into_file_modules {
6280 // This mod is in an external file. Let's go get it!
6281 let ModulePathSuccess { path, directory_ownership, warn } =
6282 self.submod_path(id, &outer_attrs, id_span)?;
6283 let (module, mut attrs) =
6284 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6286 let attr = Attribute {
6287 id: attr::mk_attr_id(),
6288 style: ast::AttrStyle::Outer,
6289 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6290 tokens: TokenStream::empty(),
6291 is_sugared_doc: false,
6292 span: syntax_pos::DUMMY_SP,
6294 attr::mark_known(&attr);
6297 Ok((id, module, Some(attrs)))
6299 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6300 Ok((id, ItemKind::Mod(placeholder), None))
6303 let old_directory = self.directory.clone();
6304 self.push_directory(id, &outer_attrs);
6306 self.expect(&token::OpenDelim(token::Brace))?;
6307 let mod_inner_lo = self.span;
6308 let attrs = self.parse_inner_attributes()?;
6309 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6311 self.directory = old_directory;
6312 Ok((id, ItemKind::Mod(module), Some(attrs)))
6316 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6317 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6318 self.directory.path.to_mut().push(&path.as_str());
6319 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6321 self.directory.path.to_mut().push(&id.as_str());
6325 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6326 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6329 // On windows, the base path might have the form
6330 // `\\?\foo\bar` in which case it does not tolerate
6331 // mixed `/` and `\` separators, so canonicalize
6334 let s = s.replace("/", "\\");
6335 Some(dir_path.join(s))
6341 /// Returns either a path to a module, or .
6342 pub fn default_submod_path(
6344 relative: Option<ast::Ident>,
6346 source_map: &SourceMap) -> ModulePath
6348 // If we're in a foo.rs file instead of a mod.rs file,
6349 // we need to look for submodules in
6350 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6351 // `./<id>.rs` and `./<id>/mod.rs`.
6352 let relative_prefix_string;
6353 let relative_prefix = if let Some(ident) = relative {
6354 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6355 &relative_prefix_string
6360 let mod_name = id.to_string();
6361 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6362 let secondary_path_str = format!("{}{}{}mod.rs",
6363 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6364 let default_path = dir_path.join(&default_path_str);
6365 let secondary_path = dir_path.join(&secondary_path_str);
6366 let default_exists = source_map.file_exists(&default_path);
6367 let secondary_exists = source_map.file_exists(&secondary_path);
6369 let result = match (default_exists, secondary_exists) {
6370 (true, false) => Ok(ModulePathSuccess {
6372 directory_ownership: DirectoryOwnership::Owned {
6377 (false, true) => Ok(ModulePathSuccess {
6378 path: secondary_path,
6379 directory_ownership: DirectoryOwnership::Owned {
6384 (false, false) => Err(Error::FileNotFoundForModule {
6385 mod_name: mod_name.clone(),
6386 default_path: default_path_str,
6387 secondary_path: secondary_path_str,
6388 dir_path: dir_path.display().to_string(),
6390 (true, true) => Err(Error::DuplicatePaths {
6391 mod_name: mod_name.clone(),
6392 default_path: default_path_str,
6393 secondary_path: secondary_path_str,
6399 path_exists: default_exists || secondary_exists,
6404 fn submod_path(&mut self,
6406 outer_attrs: &[Attribute],
6408 -> PResult<'a, ModulePathSuccess> {
6409 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6410 return Ok(ModulePathSuccess {
6411 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6412 // All `#[path]` files are treated as though they are a `mod.rs` file.
6413 // This means that `mod foo;` declarations inside `#[path]`-included
6414 // files are siblings,
6416 // Note that this will produce weirdness when a file named `foo.rs` is
6417 // `#[path]` included and contains a `mod foo;` declaration.
6418 // If you encounter this, it's your own darn fault :P
6419 Some(_) => DirectoryOwnership::Owned { relative: None },
6420 _ => DirectoryOwnership::UnownedViaMod(true),
6427 let relative = match self.directory.ownership {
6428 DirectoryOwnership::Owned { relative } => {
6429 // Push the usage onto the list of non-mod.rs mod uses.
6430 // This is used later for feature-gate error reporting.
6431 if let Some(cur_file_ident) = relative {
6433 .non_modrs_mods.borrow_mut()
6434 .push((cur_file_ident, id_sp));
6438 DirectoryOwnership::UnownedViaBlock |
6439 DirectoryOwnership::UnownedViaMod(_) => None,
6441 let paths = Parser::default_submod_path(
6442 id, relative, &self.directory.path, self.sess.source_map());
6444 match self.directory.ownership {
6445 DirectoryOwnership::Owned { .. } => {
6446 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6448 DirectoryOwnership::UnownedViaBlock => {
6450 "Cannot declare a non-inline module inside a block \
6451 unless it has a path attribute";
6452 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6453 if paths.path_exists {
6454 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6456 err.span_note(id_sp, &msg);
6460 DirectoryOwnership::UnownedViaMod(warn) => {
6462 if let Ok(result) = paths.result {
6463 return Ok(ModulePathSuccess { warn: true, ..result });
6466 let mut err = self.diagnostic().struct_span_err(id_sp,
6467 "cannot declare a new module at this location");
6468 if !id_sp.is_dummy() {
6469 let src_path = self.sess.source_map().span_to_filename(id_sp);
6470 if let FileName::Real(src_path) = src_path {
6471 if let Some(stem) = src_path.file_stem() {
6472 let mut dest_path = src_path.clone();
6473 dest_path.set_file_name(stem);
6474 dest_path.push("mod.rs");
6475 err.span_note(id_sp,
6476 &format!("maybe move this module `{}` to its own \
6477 directory via `{}`", src_path.display(),
6478 dest_path.display()));
6482 if paths.path_exists {
6483 err.span_note(id_sp,
6484 &format!("... or maybe `use` the module `{}` instead \
6485 of possibly redeclaring it",
6493 /// Read a module from a source file.
6494 fn eval_src_mod(&mut self,
6496 directory_ownership: DirectoryOwnership,
6499 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6500 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6501 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6502 let mut err = String::from("circular modules: ");
6503 let len = included_mod_stack.len();
6504 for p in &included_mod_stack[i.. len] {
6505 err.push_str(&p.to_string_lossy());
6506 err.push_str(" -> ");
6508 err.push_str(&path.to_string_lossy());
6509 return Err(self.span_fatal(id_sp, &err[..]));
6511 included_mod_stack.push(path.clone());
6512 drop(included_mod_stack);
6515 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6516 p0.cfg_mods = self.cfg_mods;
6517 let mod_inner_lo = p0.span;
6518 let mod_attrs = p0.parse_inner_attributes()?;
6519 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6520 self.sess.included_mod_stack.borrow_mut().pop();
6521 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6524 /// Parse a function declaration from a foreign module
6525 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6526 -> PResult<'a, ForeignItem> {
6527 self.expect_keyword(keywords::Fn)?;
6529 let (ident, mut generics) = self.parse_fn_header()?;
6530 let decl = self.parse_fn_decl(true)?;
6531 generics.where_clause = self.parse_where_clause()?;
6533 self.expect(&token::Semi)?;
6534 Ok(ast::ForeignItem {
6537 node: ForeignItemKind::Fn(decl, generics),
6538 id: ast::DUMMY_NODE_ID,
6544 /// Parse a static item from a foreign module.
6545 /// Assumes that the `static` keyword is already parsed.
6546 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6547 -> PResult<'a, ForeignItem> {
6548 let mutbl = self.eat_keyword(keywords::Mut);
6549 let ident = self.parse_ident()?;
6550 self.expect(&token::Colon)?;
6551 let ty = self.parse_ty()?;
6553 self.expect(&token::Semi)?;
6557 node: ForeignItemKind::Static(ty, mutbl),
6558 id: ast::DUMMY_NODE_ID,
6564 /// Parse a type from a foreign module
6565 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6566 -> PResult<'a, ForeignItem> {
6567 self.expect_keyword(keywords::Type)?;
6569 let ident = self.parse_ident()?;
6571 self.expect(&token::Semi)?;
6572 Ok(ast::ForeignItem {
6575 node: ForeignItemKind::Ty,
6576 id: ast::DUMMY_NODE_ID,
6582 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6583 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6584 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6586 let mut ident = self.parse_ident()?;
6587 let mut idents = vec![];
6588 let mut replacement = vec![];
6589 let mut fixed_crate_name = false;
6590 // Accept `extern crate name-like-this` for better diagnostics
6591 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6592 if self.token == dash { // Do not include `-` as part of the expected tokens list
6593 while self.eat(&dash) {
6594 fixed_crate_name = true;
6595 replacement.push((self.prev_span, "_".to_string()));
6596 idents.push(self.parse_ident()?);
6599 if fixed_crate_name {
6600 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6601 let mut fixed_name = format!("{}", ident.name);
6602 for part in idents {
6603 fixed_name.push_str(&format!("_{}", part.name));
6605 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6607 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6608 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6609 err.multipart_suggestion(suggestion_msg, replacement);
6615 /// Parse extern crate links
6619 /// extern crate foo;
6620 /// extern crate bar as foo;
6621 fn parse_item_extern_crate(&mut self,
6623 visibility: Visibility,
6624 attrs: Vec<Attribute>)
6625 -> PResult<'a, P<Item>> {
6626 // Accept `extern crate name-like-this` for better diagnostics
6627 let orig_name = self.parse_crate_name_with_dashes()?;
6628 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6629 (rename, Some(orig_name.name))
6633 self.expect(&token::Semi)?;
6635 let span = lo.to(self.prev_span);
6636 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6639 /// Parse `extern` for foreign ABIs
6642 /// `extern` is expected to have been
6643 /// consumed before calling this method
6649 fn parse_item_foreign_mod(&mut self,
6651 opt_abi: Option<Abi>,
6652 visibility: Visibility,
6653 mut attrs: Vec<Attribute>)
6654 -> PResult<'a, P<Item>> {
6655 self.expect(&token::OpenDelim(token::Brace))?;
6657 let abi = opt_abi.unwrap_or(Abi::C);
6659 attrs.extend(self.parse_inner_attributes()?);
6661 let mut foreign_items = vec![];
6662 while let Some(item) = self.parse_foreign_item()? {
6663 foreign_items.push(item);
6665 self.expect(&token::CloseDelim(token::Brace))?;
6667 let prev_span = self.prev_span;
6668 let m = ast::ForeignMod {
6670 items: foreign_items
6672 let invalid = keywords::Invalid.ident();
6673 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6676 /// Parse type Foo = Bar;
6678 /// existential type Foo: Bar;
6680 /// return None without modifying the parser state
6681 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6682 // This parses the grammar:
6683 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6684 if self.check_keyword(keywords::Type) ||
6685 self.check_keyword(keywords::Existential) &&
6686 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6687 let existential = self.eat_keyword(keywords::Existential);
6688 assert!(self.eat_keyword(keywords::Type));
6689 Some(self.parse_existential_or_alias(existential))
6695 /// Parse type alias or existential type
6696 fn parse_existential_or_alias(
6699 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6700 let ident = self.parse_ident()?;
6701 let mut tps = self.parse_generics()?;
6702 tps.where_clause = self.parse_where_clause()?;
6703 let alias = if existential {
6704 self.expect(&token::Colon)?;
6705 let bounds = self.parse_generic_bounds()?;
6706 AliasKind::Existential(bounds)
6708 self.expect(&token::Eq)?;
6709 let ty = self.parse_ty()?;
6712 self.expect(&token::Semi)?;
6713 Ok((ident, alias, tps))
6716 /// Parse the part of an "enum" decl following the '{'
6717 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6718 let mut variants = Vec::new();
6719 let mut all_nullary = true;
6720 let mut any_disr = None;
6721 while self.token != token::CloseDelim(token::Brace) {
6722 let variant_attrs = self.parse_outer_attributes()?;
6723 let vlo = self.span;
6726 let mut disr_expr = None;
6727 let ident = self.parse_ident()?;
6728 if self.check(&token::OpenDelim(token::Brace)) {
6729 // Parse a struct variant.
6730 all_nullary = false;
6731 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6732 ast::DUMMY_NODE_ID);
6733 } else if self.check(&token::OpenDelim(token::Paren)) {
6734 all_nullary = false;
6735 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6736 ast::DUMMY_NODE_ID);
6737 } else if self.eat(&token::Eq) {
6738 disr_expr = Some(AnonConst {
6739 id: ast::DUMMY_NODE_ID,
6740 value: self.parse_expr()?,
6742 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6743 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6745 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6748 let vr = ast::Variant_ {
6750 attrs: variant_attrs,
6754 variants.push(respan(vlo.to(self.prev_span), vr));
6756 if !self.eat(&token::Comma) { break; }
6758 self.expect(&token::CloseDelim(token::Brace))?;
6760 Some(disr_span) if !all_nullary =>
6761 self.span_err(disr_span,
6762 "discriminator values can only be used with a field-less enum"),
6766 Ok(ast::EnumDef { variants: variants })
6769 /// Parse an "enum" declaration
6770 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6771 let id = self.parse_ident()?;
6772 let mut generics = self.parse_generics()?;
6773 generics.where_clause = self.parse_where_clause()?;
6774 self.expect(&token::OpenDelim(token::Brace))?;
6776 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6777 self.recover_stmt();
6778 self.eat(&token::CloseDelim(token::Brace));
6781 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6784 /// Parses a string as an ABI spec on an extern type or module. Consumes
6785 /// the `extern` keyword, if one is found.
6786 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6788 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6790 self.expect_no_suffix(sp, "ABI spec", suf);
6792 match abi::lookup(&s.as_str()) {
6793 Some(abi) => Ok(Some(abi)),
6795 let prev_span = self.prev_span;
6796 let mut err = struct_span_err!(
6797 self.sess.span_diagnostic,
6800 "invalid ABI: found `{}`",
6802 err.span_label(prev_span, "invalid ABI");
6803 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6814 fn is_static_global(&mut self) -> bool {
6815 if self.check_keyword(keywords::Static) {
6816 // Check if this could be a closure
6817 !self.look_ahead(1, |token| {
6818 if token.is_keyword(keywords::Move) {
6822 token::BinOp(token::Or) | token::OrOr => true,
6833 attrs: Vec<Attribute>,
6834 macros_allowed: bool,
6835 attributes_allowed: bool,
6836 ) -> PResult<'a, Option<P<Item>>> {
6837 let (ret, tokens) = self.collect_tokens(|this| {
6838 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
6841 // Once we've parsed an item and recorded the tokens we got while
6842 // parsing we may want to store `tokens` into the item we're about to
6843 // return. Note, though, that we specifically didn't capture tokens
6844 // related to outer attributes. The `tokens` field here may later be
6845 // used with procedural macros to convert this item back into a token
6846 // stream, but during expansion we may be removing attributes as we go
6849 // If we've got inner attributes then the `tokens` we've got above holds
6850 // these inner attributes. If an inner attribute is expanded we won't
6851 // actually remove it from the token stream, so we'll just keep yielding
6852 // it (bad!). To work around this case for now we just avoid recording
6853 // `tokens` if we detect any inner attributes. This should help keep
6854 // expansion correct, but we should fix this bug one day!
6857 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6858 i.tokens = Some(tokens);
6865 /// Parse one of the items allowed by the flags.
6866 fn parse_item_implementation(
6868 attrs: Vec<Attribute>,
6869 macros_allowed: bool,
6870 attributes_allowed: bool,
6871 ) -> PResult<'a, Option<P<Item>>> {
6872 maybe_whole!(self, NtItem, |item| {
6873 let mut item = item.into_inner();
6874 let mut attrs = attrs;
6875 mem::swap(&mut item.attrs, &mut attrs);
6876 item.attrs.extend(attrs);
6882 let visibility = self.parse_visibility(false)?;
6884 if self.eat_keyword(keywords::Use) {
6886 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6887 self.expect(&token::Semi)?;
6889 let span = lo.to(self.prev_span);
6890 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6891 return Ok(Some(item));
6894 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6895 self.bump(); // `extern`
6896 if self.eat_keyword(keywords::Crate) {
6897 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6900 let opt_abi = self.parse_opt_abi()?;
6902 if self.eat_keyword(keywords::Fn) {
6903 // EXTERN FUNCTION ITEM
6904 let fn_span = self.prev_span;
6905 let abi = opt_abi.unwrap_or(Abi::C);
6906 let (ident, item_, extra_attrs) =
6907 self.parse_item_fn(Unsafety::Normal,
6909 respan(fn_span, Constness::NotConst),
6911 let prev_span = self.prev_span;
6912 let item = self.mk_item(lo.to(prev_span),
6916 maybe_append(attrs, extra_attrs));
6917 return Ok(Some(item));
6918 } else if self.check(&token::OpenDelim(token::Brace)) {
6919 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6925 if self.is_static_global() {
6928 let m = if self.eat_keyword(keywords::Mut) {
6931 Mutability::Immutable
6933 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6934 let prev_span = self.prev_span;
6935 let item = self.mk_item(lo.to(prev_span),
6939 maybe_append(attrs, extra_attrs));
6940 return Ok(Some(item));
6942 if self.eat_keyword(keywords::Const) {
6943 let const_span = self.prev_span;
6944 if self.check_keyword(keywords::Fn)
6945 || (self.check_keyword(keywords::Unsafe)
6946 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6947 // CONST FUNCTION ITEM
6948 let unsafety = self.parse_unsafety();
6950 let (ident, item_, extra_attrs) =
6951 self.parse_item_fn(unsafety,
6953 respan(const_span, Constness::Const),
6955 let prev_span = self.prev_span;
6956 let item = self.mk_item(lo.to(prev_span),
6960 maybe_append(attrs, extra_attrs));
6961 return Ok(Some(item));
6965 if self.eat_keyword(keywords::Mut) {
6966 let prev_span = self.prev_span;
6967 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6968 .help("did you mean to declare a static?")
6971 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6972 let prev_span = self.prev_span;
6973 let item = self.mk_item(lo.to(prev_span),
6977 maybe_append(attrs, extra_attrs));
6978 return Ok(Some(item));
6981 // `unsafe async fn` or `async fn`
6983 self.check_keyword(keywords::Unsafe) &&
6984 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
6986 self.check_keyword(keywords::Async) &&
6987 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
6990 // ASYNC FUNCTION ITEM
6991 let unsafety = self.parse_unsafety();
6992 self.expect_keyword(keywords::Async)?;
6993 self.expect_keyword(keywords::Fn)?;
6994 let fn_span = self.prev_span;
6995 let (ident, item_, extra_attrs) =
6996 self.parse_item_fn(unsafety,
6998 closure_id: ast::DUMMY_NODE_ID,
6999 return_impl_trait_id: ast::DUMMY_NODE_ID,
7001 respan(fn_span, Constness::NotConst),
7003 let prev_span = self.prev_span;
7004 let item = self.mk_item(lo.to(prev_span),
7008 maybe_append(attrs, extra_attrs));
7009 return Ok(Some(item));
7011 if self.check_keyword(keywords::Unsafe) &&
7012 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7013 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7015 // UNSAFE TRAIT ITEM
7016 self.bump(); // `unsafe`
7017 let is_auto = if self.eat_keyword(keywords::Trait) {
7020 self.expect_keyword(keywords::Auto)?;
7021 self.expect_keyword(keywords::Trait)?;
7024 let (ident, item_, extra_attrs) =
7025 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7026 let prev_span = self.prev_span;
7027 let item = self.mk_item(lo.to(prev_span),
7031 maybe_append(attrs, extra_attrs));
7032 return Ok(Some(item));
7034 if self.check_keyword(keywords::Impl) ||
7035 self.check_keyword(keywords::Unsafe) &&
7036 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7037 self.check_keyword(keywords::Default) &&
7038 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7039 self.check_keyword(keywords::Default) &&
7040 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7042 let defaultness = self.parse_defaultness();
7043 let unsafety = self.parse_unsafety();
7044 self.expect_keyword(keywords::Impl)?;
7045 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7046 let span = lo.to(self.prev_span);
7047 return Ok(Some(self.mk_item(span, ident, item, visibility,
7048 maybe_append(attrs, extra_attrs))));
7050 if self.check_keyword(keywords::Fn) {
7053 let fn_span = self.prev_span;
7054 let (ident, item_, extra_attrs) =
7055 self.parse_item_fn(Unsafety::Normal,
7057 respan(fn_span, Constness::NotConst),
7059 let prev_span = self.prev_span;
7060 let item = self.mk_item(lo.to(prev_span),
7064 maybe_append(attrs, extra_attrs));
7065 return Ok(Some(item));
7067 if self.check_keyword(keywords::Unsafe)
7068 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7069 // UNSAFE FUNCTION ITEM
7070 self.bump(); // `unsafe`
7071 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7072 self.check(&token::OpenDelim(token::Brace));
7073 let abi = if self.eat_keyword(keywords::Extern) {
7074 self.parse_opt_abi()?.unwrap_or(Abi::C)
7078 self.expect_keyword(keywords::Fn)?;
7079 let fn_span = self.prev_span;
7080 let (ident, item_, extra_attrs) =
7081 self.parse_item_fn(Unsafety::Unsafe,
7083 respan(fn_span, Constness::NotConst),
7085 let prev_span = self.prev_span;
7086 let item = self.mk_item(lo.to(prev_span),
7090 maybe_append(attrs, extra_attrs));
7091 return Ok(Some(item));
7093 if self.eat_keyword(keywords::Mod) {
7095 let (ident, item_, extra_attrs) =
7096 self.parse_item_mod(&attrs[..])?;
7097 let prev_span = self.prev_span;
7098 let item = self.mk_item(lo.to(prev_span),
7102 maybe_append(attrs, extra_attrs));
7103 return Ok(Some(item));
7105 if let Some(type_) = self.eat_type() {
7106 let (ident, alias, generics) = type_?;
7108 let item_ = match alias {
7109 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7110 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7112 let prev_span = self.prev_span;
7113 let item = self.mk_item(lo.to(prev_span),
7118 return Ok(Some(item));
7120 if self.eat_keyword(keywords::Enum) {
7122 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7123 let prev_span = self.prev_span;
7124 let item = self.mk_item(lo.to(prev_span),
7128 maybe_append(attrs, extra_attrs));
7129 return Ok(Some(item));
7131 if self.check_keyword(keywords::Trait)
7132 || (self.check_keyword(keywords::Auto)
7133 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7135 let is_auto = if self.eat_keyword(keywords::Trait) {
7138 self.expect_keyword(keywords::Auto)?;
7139 self.expect_keyword(keywords::Trait)?;
7143 let (ident, item_, extra_attrs) =
7144 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7145 let prev_span = self.prev_span;
7146 let item = self.mk_item(lo.to(prev_span),
7150 maybe_append(attrs, extra_attrs));
7151 return Ok(Some(item));
7153 if self.eat_keyword(keywords::Struct) {
7155 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7156 let prev_span = self.prev_span;
7157 let item = self.mk_item(lo.to(prev_span),
7161 maybe_append(attrs, extra_attrs));
7162 return Ok(Some(item));
7164 if self.is_union_item() {
7167 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7168 let prev_span = self.prev_span;
7169 let item = self.mk_item(lo.to(prev_span),
7173 maybe_append(attrs, extra_attrs));
7174 return Ok(Some(item));
7176 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7177 return Ok(Some(macro_def));
7180 // Verify whether we have encountered a struct or method definition where the user forgot to
7181 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7182 if visibility.node.is_pub() &&
7183 self.check_ident() &&
7184 self.look_ahead(1, |t| *t != token::Not)
7186 // Space between `pub` keyword and the identifier
7189 // ^^^ `sp` points here
7190 let sp = self.prev_span.between(self.span);
7191 let full_sp = self.prev_span.to(self.span);
7192 let ident_sp = self.span;
7193 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7194 // possible public struct definition where `struct` was forgotten
7195 let ident = self.parse_ident().unwrap();
7196 let msg = format!("add `struct` here to parse `{}` as a public struct",
7198 let mut err = self.diagnostic()
7199 .struct_span_err(sp, "missing `struct` for struct definition");
7200 err.span_suggestion_short_with_applicability(
7201 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7204 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7205 let ident = self.parse_ident().unwrap();
7206 self.consume_block(token::Paren);
7207 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7208 self.check(&token::OpenDelim(token::Brace))
7210 ("fn", "method", false)
7211 } else if self.check(&token::Colon) {
7215 ("fn` or `struct", "method or struct", true)
7218 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7219 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7221 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7225 err.span_suggestion_short_with_applicability(
7226 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7229 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7230 err.span_suggestion_with_applicability(
7232 "if you meant to call a macro, try",
7233 format!("{}!", snippet),
7234 // this is the `ambiguous` conditional branch
7235 Applicability::MaybeIncorrect
7238 err.help("if you meant to call a macro, remove the `pub` \
7239 and add a trailing `!` after the identifier");
7245 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7248 /// Parse a foreign item.
7249 crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
7250 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
7252 let attrs = self.parse_outer_attributes()?;
7254 let visibility = self.parse_visibility(false)?;
7256 // FOREIGN STATIC ITEM
7257 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7258 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7259 if self.token.is_keyword(keywords::Const) {
7261 .struct_span_err(self.span, "extern items cannot be `const`")
7262 .span_suggestion_with_applicability(
7264 "try using a static value",
7265 "static".to_owned(),
7266 Applicability::MachineApplicable
7269 self.bump(); // `static` or `const`
7270 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
7272 // FOREIGN FUNCTION ITEM
7273 if self.check_keyword(keywords::Fn) {
7274 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
7276 // FOREIGN TYPE ITEM
7277 if self.check_keyword(keywords::Type) {
7278 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
7281 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7285 ident: keywords::Invalid.ident(),
7286 span: lo.to(self.prev_span),
7287 id: ast::DUMMY_NODE_ID,
7290 node: ForeignItemKind::Macro(mac),
7295 if !attrs.is_empty() {
7296 self.expected_item_err(&attrs);
7304 /// This is the fall-through for parsing items.
7305 fn parse_macro_use_or_failure(
7307 attrs: Vec<Attribute> ,
7308 macros_allowed: bool,
7309 attributes_allowed: bool,
7311 visibility: Visibility
7312 ) -> PResult<'a, Option<P<Item>>> {
7313 if macros_allowed && self.token.is_path_start() {
7314 // MACRO INVOCATION ITEM
7316 let prev_span = self.prev_span;
7317 self.complain_if_pub_macro(&visibility.node, prev_span);
7319 let mac_lo = self.span;
7322 let pth = self.parse_path(PathStyle::Mod)?;
7323 self.expect(&token::Not)?;
7325 // a 'special' identifier (like what `macro_rules!` uses)
7326 // is optional. We should eventually unify invoc syntax
7328 let id = if self.token.is_ident() {
7331 keywords::Invalid.ident() // no special identifier
7333 // eat a matched-delimiter token tree:
7334 let (delim, tts) = self.expect_delimited_token_tree()?;
7335 if delim != MacDelimiter::Brace {
7336 if !self.eat(&token::Semi) {
7337 self.span_err(self.prev_span,
7338 "macros that expand to items must either \
7339 be surrounded with braces or followed by \
7344 let hi = self.prev_span;
7345 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7346 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7347 return Ok(Some(item));
7350 // FAILURE TO PARSE ITEM
7351 match visibility.node {
7352 VisibilityKind::Inherited => {}
7354 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7358 if !attributes_allowed && !attrs.is_empty() {
7359 self.expected_item_err(&attrs);
7364 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7365 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7366 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7368 if self.token.is_path_start() && !self.is_extern_non_path() {
7369 let prev_span = self.prev_span;
7371 let pth = self.parse_path(PathStyle::Mod)?;
7373 if pth.segments.len() == 1 {
7374 if !self.eat(&token::Not) {
7375 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7378 self.expect(&token::Not)?;
7381 if let Some(vis) = vis {
7382 self.complain_if_pub_macro(&vis.node, prev_span);
7387 // eat a matched-delimiter token tree:
7388 let (delim, tts) = self.expect_delimited_token_tree()?;
7389 if delim != MacDelimiter::Brace {
7390 self.expect(&token::Semi)?
7393 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7399 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7400 where F: FnOnce(&mut Self) -> PResult<'a, R>
7402 // Record all tokens we parse when parsing this item.
7403 let mut tokens = Vec::new();
7404 let prev_collecting = match self.token_cursor.frame.last_token {
7405 LastToken::Collecting(ref mut list) => {
7406 Some(mem::replace(list, Vec::new()))
7408 LastToken::Was(ref mut last) => {
7409 tokens.extend(last.take());
7413 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7414 let prev = self.token_cursor.stack.len();
7416 let last_token = if self.token_cursor.stack.len() == prev {
7417 &mut self.token_cursor.frame.last_token
7419 &mut self.token_cursor.stack[prev].last_token
7422 // Pull our the toekns that we've collected from the call to `f` above
7423 let mut collected_tokens = match *last_token {
7424 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7425 LastToken::Was(_) => panic!("our vector went away?"),
7428 // If we're not at EOF our current token wasn't actually consumed by
7429 // `f`, but it'll still be in our list that we pulled out. In that case
7431 let extra_token = if self.token != token::Eof {
7432 collected_tokens.pop()
7437 // If we were previously collecting tokens, then this was a recursive
7438 // call. In that case we need to record all the tokens we collected in
7439 // our parent list as well. To do that we push a clone of our stream
7440 // onto the previous list.
7441 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7442 match prev_collecting {
7444 list.push(stream.clone());
7445 list.extend(extra_token);
7446 *last_token = LastToken::Collecting(list);
7449 *last_token = LastToken::Was(extra_token);
7456 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7457 let attrs = self.parse_outer_attributes()?;
7458 self.parse_item_(attrs, true, false)
7462 fn is_import_coupler(&mut self) -> bool {
7463 self.check(&token::ModSep) &&
7464 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7465 *t == token::BinOp(token::Star))
7470 /// USE_TREE = [`::`] `*` |
7471 /// [`::`] `{` USE_TREE_LIST `}` |
7473 /// PATH `::` `{` USE_TREE_LIST `}` |
7474 /// PATH [`as` IDENT]
7475 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7478 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7479 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7480 self.check(&token::BinOp(token::Star)) ||
7481 self.is_import_coupler() {
7482 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7483 if self.eat(&token::ModSep) {
7484 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7487 if self.eat(&token::BinOp(token::Star)) {
7490 UseTreeKind::Nested(self.parse_use_tree_list()?)
7493 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7494 prefix = self.parse_path(PathStyle::Mod)?;
7496 if self.eat(&token::ModSep) {
7497 if self.eat(&token::BinOp(token::Star)) {
7500 UseTreeKind::Nested(self.parse_use_tree_list()?)
7503 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7507 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7510 /// Parse UseTreeKind::Nested(list)
7512 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7513 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7514 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7515 &token::CloseDelim(token::Brace),
7516 SeqSep::trailing_allowed(token::Comma), |this| {
7517 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7521 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7522 if self.eat_keyword(keywords::As) {
7524 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7526 Ok(Some(ident.gensym()))
7528 _ => self.parse_ident().map(Some),
7535 /// Parses a source module as a crate. This is the main
7536 /// entry point for the parser.
7537 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7540 attrs: self.parse_inner_attributes()?,
7541 module: self.parse_mod_items(&token::Eof, lo)?,
7542 span: lo.to(self.span),
7546 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7547 let ret = match self.token {
7548 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7549 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7556 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7557 match self.parse_optional_str() {
7558 Some((s, style, suf)) => {
7559 let sp = self.prev_span;
7560 self.expect_no_suffix(sp, "string literal", suf);
7564 let msg = "expected string literal";
7565 let mut err = self.fatal(msg);
7566 err.span_label(self.span, msg);