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 codemap::{self, CodeMap, Spanned, respan};
46 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName, DUMMY_SP, edition::Edition};
47 use errors::{self, Applicability, DiagnosticBuilder};
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};
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
63 use std::path::{self, Path, PathBuf};
67 struct Restrictions: u8 {
68 const STMT_EXPR = 1 << 0;
69 const NO_STRUCT_LITERAL = 1 << 1;
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
75 /// How to parse a path.
76 #[derive(Copy, Clone, PartialEq)]
78 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
79 /// with something else. For example, in expressions `segment < ....` can be interpreted
80 /// as a comparison and `segment ( ....` can be interpreted as a function call.
81 /// In all such contexts the non-path interpretation is preferred by default for practical
82 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
83 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
85 /// In other contexts, notably in types, no ambiguity exists and paths can be written
86 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
87 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
89 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
90 /// visibilities or attributes.
91 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
92 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
93 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
94 /// tokens when something goes wrong.
98 #[derive(Clone, Copy, Debug, PartialEq)]
104 #[derive(Clone, Copy, Debug, PartialEq)]
110 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
111 /// dropped into the token stream, which happens while parsing the result of
112 /// macro expansion). Placement of these is not as complex as I feared it would
113 /// be. The important thing is to make sure that lookahead doesn't balk at
114 /// `token::Interpolated` tokens.
115 macro_rules! maybe_whole_expr {
117 if let token::Interpolated(nt) = $p.token.clone() {
119 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
121 return Ok((*e).clone());
123 token::NtPath(ref path) => {
126 let kind = ExprKind::Path(None, (*path).clone());
127 return Ok($p.mk_expr(span, kind, ThinVec::new()));
129 token::NtBlock(ref block) => {
132 let kind = ExprKind::Block((*block).clone(), None);
133 return Ok($p.mk_expr(span, kind, ThinVec::new()));
141 /// As maybe_whole_expr, but for things other than expressions
142 macro_rules! maybe_whole {
143 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
144 if let token::Interpolated(nt) = $p.token.clone() {
145 if let token::$constructor($x) = nt.0.clone() {
153 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
154 if let Some(ref mut rhs) = rhs {
160 #[derive(Debug, Clone, Copy, PartialEq)]
171 trait RecoverQPath: Sized {
172 const PATH_STYLE: PathStyle = PathStyle::Expr;
173 fn to_ty(&self) -> Option<P<Ty>>;
174 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
175 fn to_string(&self) -> String;
178 impl RecoverQPath for Ty {
179 const PATH_STYLE: PathStyle = PathStyle::Type;
180 fn to_ty(&self) -> Option<P<Ty>> {
181 Some(P(self.clone()))
183 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
184 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
186 fn to_string(&self) -> String {
187 pprust::ty_to_string(self)
191 impl RecoverQPath for Pat {
192 fn to_ty(&self) -> Option<P<Ty>> {
195 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
196 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
198 fn to_string(&self) -> String {
199 pprust::pat_to_string(self)
203 impl RecoverQPath for Expr {
204 fn to_ty(&self) -> Option<P<Ty>> {
207 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
208 Self { span: path.span, node: ExprKind::Path(qself, path),
209 id: self.id, attrs: self.attrs.clone() }
211 fn to_string(&self) -> String {
212 pprust::expr_to_string(self)
216 /* ident is handled by common.rs */
219 pub struct Parser<'a> {
220 pub sess: &'a ParseSess,
221 /// the current token:
222 pub token: token::Token,
223 /// the span of the current token:
225 /// the span of the previous token:
226 meta_var_span: Option<Span>,
228 /// the previous token kind
229 prev_token_kind: PrevTokenKind,
230 restrictions: Restrictions,
231 /// Used to determine the path to externally loaded source files
232 crate directory: Directory<'a>,
233 /// Whether to parse sub-modules in other files.
234 pub recurse_into_file_modules: bool,
235 /// Name of the root module this parser originated from. If `None`, then the
236 /// name is not known. This does not change while the parser is descending
237 /// into modules, and sub-parsers have new values for this name.
238 pub root_module_name: Option<String>,
239 crate expected_tokens: Vec<TokenType>,
240 token_cursor: TokenCursor,
241 desugar_doc_comments: bool,
242 /// Whether we should configure out of line modules as we parse.
249 frame: TokenCursorFrame,
250 stack: Vec<TokenCursorFrame>,
254 struct TokenCursorFrame {
255 delim: token::DelimToken,
258 tree_cursor: tokenstream::Cursor,
260 last_token: LastToken,
263 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
264 /// by the parser, and then that's transitively used to record the tokens that
265 /// each parse AST item is created with.
267 /// Right now this has two states, either collecting tokens or not collecting
268 /// tokens. If we're collecting tokens we just save everything off into a local
269 /// `Vec`. This should eventually though likely save tokens from the original
270 /// token stream and just use slicing of token streams to avoid creation of a
271 /// whole new vector.
273 /// The second state is where we're passively not recording tokens, but the last
274 /// token is still tracked for when we want to start recording tokens. This
275 /// "last token" means that when we start recording tokens we'll want to ensure
276 /// that this, the first token, is included in the output.
278 /// You can find some more example usage of this in the `collect_tokens` method
282 Collecting(Vec<TokenTree>),
283 Was(Option<TokenTree>),
286 impl TokenCursorFrame {
287 fn new(sp: Span, delimited: &Delimited) -> Self {
289 delim: delimited.delim,
291 open_delim: delimited.delim == token::NoDelim,
292 tree_cursor: delimited.stream().into_trees(),
293 close_delim: delimited.delim == token::NoDelim,
294 last_token: LastToken::Was(None),
300 fn next(&mut self) -> TokenAndSpan {
302 let tree = if !self.frame.open_delim {
303 self.frame.open_delim = true;
304 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
305 .open_tt(self.frame.span)
306 } else if let Some(tree) = self.frame.tree_cursor.next() {
308 } else if !self.frame.close_delim {
309 self.frame.close_delim = true;
310 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
311 .close_tt(self.frame.span)
312 } else if let Some(frame) = self.stack.pop() {
316 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
319 match self.frame.last_token {
320 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
321 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
325 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
326 TokenTree::Delimited(sp, ref delimited) => {
327 let frame = TokenCursorFrame::new(sp, delimited);
328 self.stack.push(mem::replace(&mut self.frame, frame));
334 fn next_desugared(&mut self) -> TokenAndSpan {
335 let (sp, name) = match self.next() {
336 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
340 let stripped = strip_doc_comment_decoration(&name.as_str());
342 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
343 // required to wrap the text.
344 let mut num_of_hashes = 0;
346 for ch in stripped.chars() {
349 '#' if count > 0 => count + 1,
352 num_of_hashes = cmp::max(num_of_hashes, count);
355 let body = TokenTree::Delimited(sp, Delimited {
356 delim: token::Bracket,
357 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
358 TokenTree::Token(sp, token::Eq),
359 TokenTree::Token(sp, token::Literal(
360 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
361 .iter().cloned().collect::<TokenStream>().into(),
364 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
365 delim: token::NoDelim,
366 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
367 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
368 .iter().cloned().collect::<TokenStream>().into()
370 [TokenTree::Token(sp, token::Pound), body]
371 .iter().cloned().collect::<TokenStream>().into()
379 #[derive(PartialEq, Eq, Clone)]
380 crate enum TokenType {
382 Keyword(keywords::Keyword),
391 fn to_string(&self) -> String {
393 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
394 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
395 TokenType::Operator => "an operator".to_string(),
396 TokenType::Lifetime => "lifetime".to_string(),
397 TokenType::Ident => "identifier".to_string(),
398 TokenType::Path => "path".to_string(),
399 TokenType::Type => "type".to_string(),
404 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
405 /// `IDENT<<u8 as Trait>::AssocTy>`.
407 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
408 /// that IDENT is not the ident of a fn trait
409 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
410 t == &token::ModSep || t == &token::Lt ||
411 t == &token::BinOp(token::Shl)
414 /// Information about the path to a module.
415 pub struct ModulePath {
418 pub result: Result<ModulePathSuccess, Error>,
421 pub struct ModulePathSuccess {
423 pub directory_ownership: DirectoryOwnership,
428 FileNotFoundForModule {
430 default_path: String,
431 secondary_path: String,
436 default_path: String,
437 secondary_path: String,
440 InclusiveRangeWithNoEnd,
444 fn span_err<S: Into<MultiSpan>>(self,
446 handler: &errors::Handler) -> DiagnosticBuilder {
448 Error::FileNotFoundForModule { ref mod_name,
452 let mut err = struct_span_err!(handler, sp, E0583,
453 "file not found for module `{}`", mod_name);
454 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
460 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
461 let mut err = struct_span_err!(handler, sp, E0584,
462 "file for module `{}` found at both {} and {}",
466 err.help("delete or rename one of them to remove the ambiguity");
469 Error::UselessDocComment => {
470 let mut err = struct_span_err!(handler, sp, E0585,
471 "found a documentation comment that doesn't document anything");
472 err.help("doc comments must come before what they document, maybe a comment was \
473 intended with `//`?");
476 Error::InclusiveRangeWithNoEnd => {
477 let mut err = struct_span_err!(handler, sp, E0586,
478 "inclusive range with no end");
479 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
489 AttributesParsed(ThinVec<Attribute>),
490 AlreadyParsed(P<Expr>),
493 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
494 fn from(o: Option<ThinVec<Attribute>>) -> Self {
495 if let Some(attrs) = o {
496 LhsExpr::AttributesParsed(attrs)
498 LhsExpr::NotYetParsed
503 impl From<P<Expr>> for LhsExpr {
504 fn from(expr: P<Expr>) -> Self {
505 LhsExpr::AlreadyParsed(expr)
509 /// Create a placeholder argument.
510 fn dummy_arg(span: Span) -> Arg {
511 let ident = Ident::new(keywords::Invalid.name(), span);
513 id: ast::DUMMY_NODE_ID,
514 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
520 id: ast::DUMMY_NODE_ID
522 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
525 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
526 enum TokenExpectType {
531 impl<'a> Parser<'a> {
532 pub fn new(sess: &'a ParseSess,
534 directory: Option<Directory<'a>>,
535 recurse_into_file_modules: bool,
536 desugar_doc_comments: bool)
538 let mut parser = Parser {
540 token: token::Whitespace,
541 span: syntax_pos::DUMMY_SP,
542 prev_span: syntax_pos::DUMMY_SP,
544 prev_token_kind: PrevTokenKind::Other,
545 restrictions: Restrictions::empty(),
546 recurse_into_file_modules,
547 directory: Directory {
548 path: Cow::from(PathBuf::new()),
549 ownership: DirectoryOwnership::Owned { relative: None }
551 root_module_name: None,
552 expected_tokens: Vec::new(),
553 token_cursor: TokenCursor {
554 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
555 delim: token::NoDelim,
560 desugar_doc_comments,
564 let tok = parser.next_tok();
565 parser.token = tok.tok;
566 parser.span = tok.sp;
568 if let Some(directory) = directory {
569 parser.directory = directory;
570 } else if !parser.span.source_equal(&DUMMY_SP) {
571 if let FileName::Real(mut path) = sess.codemap().span_to_unmapped_path(parser.span) {
573 parser.directory.path = Cow::from(path);
577 parser.process_potential_macro_variable();
581 fn next_tok(&mut self) -> TokenAndSpan {
582 let mut next = if self.desugar_doc_comments {
583 self.token_cursor.next_desugared()
585 self.token_cursor.next()
587 if next.sp == syntax_pos::DUMMY_SP {
588 // Tweak the location for better diagnostics, but keep syntactic context intact.
589 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
594 /// Convert the current token to a string using self's reader
595 pub fn this_token_to_string(&self) -> String {
596 pprust::token_to_string(&self.token)
599 fn token_descr(&self) -> Option<&'static str> {
600 Some(match &self.token {
601 t if t.is_special_ident() => "reserved identifier",
602 t if t.is_used_keyword() => "keyword",
603 t if t.is_unused_keyword() => "reserved keyword",
608 fn this_token_descr(&self) -> String {
609 if let Some(prefix) = self.token_descr() {
610 format!("{} `{}`", prefix, self.this_token_to_string())
612 format!("`{}`", self.this_token_to_string())
616 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
617 let token_str = pprust::token_to_string(t);
618 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
621 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
622 match self.expect_one_of(&[], &[]) {
624 Ok(_) => unreachable!(),
628 /// Expect and consume the token t. Signal an error if
629 /// the next token is not t.
630 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
631 if self.expected_tokens.is_empty() {
632 if self.token == *t {
636 let token_str = pprust::token_to_string(t);
637 let this_token_str = self.this_token_to_string();
638 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
642 let sp = if self.token == token::Token::Eof {
643 // EOF, don't want to point at the following char, but rather the last token
646 self.sess.codemap().next_point(self.prev_span)
648 let label_exp = format!("expected `{}`", token_str);
649 let cm = self.sess.codemap();
650 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
651 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
652 // When the spans are in the same line, it means that the only content
653 // between them is whitespace, point only at the found token.
654 err.span_label(self.span, label_exp);
657 err.span_label(sp, label_exp);
658 err.span_label(self.span, "unexpected token");
664 self.expect_one_of(slice::from_ref(t), &[])
668 /// Expect next token to be edible or inedible token. If edible,
669 /// then consume it; if inedible, then return without consuming
670 /// anything. Signal a fatal error if next token is unexpected.
671 fn expect_one_of(&mut self,
672 edible: &[token::Token],
673 inedible: &[token::Token]) -> PResult<'a, ()>{
674 fn tokens_to_string(tokens: &[TokenType]) -> String {
675 let mut i = tokens.iter();
676 // This might be a sign we need a connect method on Iterator.
678 .map_or("".to_string(), |t| t.to_string());
679 i.enumerate().fold(b, |mut b, (i, a)| {
680 if tokens.len() > 2 && i == tokens.len() - 2 {
682 } else if tokens.len() == 2 && i == tokens.len() - 2 {
687 b.push_str(&a.to_string());
691 if edible.contains(&self.token) {
694 } else if inedible.contains(&self.token) {
695 // leave it in the input
698 let mut expected = edible.iter()
699 .map(|x| TokenType::Token(x.clone()))
700 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
701 .chain(self.expected_tokens.iter().cloned())
702 .collect::<Vec<_>>();
703 expected.sort_by_cached_key(|x| x.to_string());
705 let expect = tokens_to_string(&expected[..]);
706 let actual = self.this_token_to_string();
707 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
708 let short_expect = if expected.len() > 6 {
709 format!("{} possible tokens", expected.len())
713 (format!("expected one of {}, found `{}`", expect, actual),
714 (self.sess.codemap().next_point(self.prev_span),
715 format!("expected one of {} here", short_expect)))
716 } else if expected.is_empty() {
717 (format!("unexpected token: `{}`", actual),
718 (self.prev_span, "unexpected token after this".to_string()))
720 (format!("expected {}, found `{}`", expect, actual),
721 (self.sess.codemap().next_point(self.prev_span),
722 format!("expected {} here", expect)))
724 let mut err = self.fatal(&msg_exp);
725 let sp = if self.token == token::Token::Eof {
726 // This is EOF, don't want to point at the following char, but rather the last token
732 let cm = self.sess.codemap();
733 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
734 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
735 // When the spans are in the same line, it means that the only content between
736 // them is whitespace, point at the found token in that case:
738 // X | () => { syntax error };
739 // | ^^^^^ expected one of 8 possible tokens here
741 // instead of having:
743 // X | () => { syntax error };
744 // | -^^^^^ unexpected token
746 // | expected one of 8 possible tokens here
747 err.span_label(self.span, label_exp);
750 err.span_label(sp, label_exp);
751 err.span_label(self.span, "unexpected token");
758 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
759 fn interpolated_or_expr_span(&self,
760 expr: PResult<'a, P<Expr>>)
761 -> PResult<'a, (Span, P<Expr>)> {
763 if self.prev_token_kind == PrevTokenKind::Interpolated {
771 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
772 let mut err = self.struct_span_err(self.span,
773 &format!("expected identifier, found {}",
774 self.this_token_descr()));
775 if let Some(token_descr) = self.token_descr() {
776 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
778 err.span_label(self.span, "expected identifier");
783 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
784 self.parse_ident_common(true)
787 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
789 token::Ident(ident, _) => {
790 if self.token.is_reserved_ident() {
791 let mut err = self.expected_ident_found();
798 let span = self.span;
800 Ok(Ident::new(ident.name, span))
803 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
804 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
806 self.expected_ident_found()
812 /// Check if the next token is `tok`, and return `true` if so.
814 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
816 fn check(&mut self, tok: &token::Token) -> bool {
817 let is_present = self.token == *tok;
818 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
822 /// Consume token 'tok' if it exists. Returns true if the given
823 /// token was present, false otherwise.
824 pub fn eat(&mut self, tok: &token::Token) -> bool {
825 let is_present = self.check(tok);
826 if is_present { self.bump() }
830 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
831 self.expected_tokens.push(TokenType::Keyword(kw));
832 self.token.is_keyword(kw)
835 /// If the next token is the given keyword, eat it and return
836 /// true. Otherwise, return false.
837 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
838 if self.check_keyword(kw) {
846 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
847 if self.token.is_keyword(kw) {
855 /// If the given word is not a keyword, signal an error.
856 /// If the next token is not the given word, signal an error.
857 /// Otherwise, eat it.
858 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
859 if !self.eat_keyword(kw) {
866 fn check_ident(&mut self) -> bool {
867 if self.token.is_ident() {
870 self.expected_tokens.push(TokenType::Ident);
875 fn check_path(&mut self) -> bool {
876 if self.token.is_path_start() {
879 self.expected_tokens.push(TokenType::Path);
884 fn check_type(&mut self) -> bool {
885 if self.token.can_begin_type() {
888 self.expected_tokens.push(TokenType::Type);
893 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
894 /// and continue. If a `+` is not seen, return false.
896 /// This is using when token splitting += into +.
897 /// See issue 47856 for an example of when this may occur.
898 fn eat_plus(&mut self) -> bool {
899 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
901 token::BinOp(token::Plus) => {
905 token::BinOpEq(token::Plus) => {
906 let span = self.span.with_lo(self.span.lo() + BytePos(1));
907 self.bump_with(token::Eq, span);
915 /// Checks to see if the next token is either `+` or `+=`.
916 /// Otherwise returns false.
917 fn check_plus(&mut self) -> bool {
918 if self.token.is_like_plus() {
922 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
927 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
928 /// `&` and continue. If an `&` is not seen, signal an error.
929 fn expect_and(&mut self) -> PResult<'a, ()> {
930 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
932 token::BinOp(token::And) => {
937 let span = self.span.with_lo(self.span.lo() + BytePos(1));
938 Ok(self.bump_with(token::BinOp(token::And), span))
940 _ => self.unexpected()
944 /// Expect and consume an `|`. If `||` is seen, replace it with a single
945 /// `|` and continue. If an `|` is not seen, signal an error.
946 fn expect_or(&mut self) -> PResult<'a, ()> {
947 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
949 token::BinOp(token::Or) => {
954 let span = self.span.with_lo(self.span.lo() + BytePos(1));
955 Ok(self.bump_with(token::BinOp(token::Or), span))
957 _ => self.unexpected()
961 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
963 None => {/* everything ok */}
965 let text = suf.as_str();
967 self.span_bug(sp, "found empty literal suffix in Some")
969 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
974 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
975 /// `<` and continue. If a `<` is not seen, return false.
977 /// This is meant to be used when parsing generics on a path to get the
979 fn eat_lt(&mut self) -> bool {
980 self.expected_tokens.push(TokenType::Token(token::Lt));
986 token::BinOp(token::Shl) => {
987 let span = self.span.with_lo(self.span.lo() + BytePos(1));
988 self.bump_with(token::Lt, span);
995 fn expect_lt(&mut self) -> PResult<'a, ()> {
1003 /// Expect and consume a GT. if a >> is seen, replace it
1004 /// with a single > and continue. If a GT is not seen,
1005 /// signal an error.
1006 fn expect_gt(&mut self) -> PResult<'a, ()> {
1007 self.expected_tokens.push(TokenType::Token(token::Gt));
1013 token::BinOp(token::Shr) => {
1014 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1015 Ok(self.bump_with(token::Gt, span))
1017 token::BinOpEq(token::Shr) => {
1018 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1019 Ok(self.bump_with(token::Ge, span))
1022 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1023 Ok(self.bump_with(token::Eq, span))
1025 _ => self.unexpected()
1029 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1030 /// passes through any errors encountered. Used for error recovery.
1031 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1032 let handler = self.diagnostic();
1034 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1036 TokenExpectType::Expect,
1037 |p| Ok(p.parse_token_tree())) {
1038 handler.cancel(err);
1042 /// Parse a sequence, including the closing delimiter. The function
1043 /// f must consume tokens until reaching the next separator or
1044 /// closing bracket.
1045 pub fn parse_seq_to_end<T, F>(&mut self,
1049 -> PResult<'a, Vec<T>> where
1050 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1052 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1057 /// Parse a sequence, not including the closing delimiter. The function
1058 /// f must consume tokens until reaching the next separator or
1059 /// closing bracket.
1060 fn parse_seq_to_before_end<T, F>(&mut self,
1064 -> PResult<'a, Vec<T>>
1065 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1067 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1070 fn parse_seq_to_before_tokens<T, F>(&mut self,
1071 kets: &[&token::Token],
1073 expect: TokenExpectType,
1075 -> PResult<'a, Vec<T>>
1076 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1078 let mut first: bool = true;
1080 while !kets.iter().any(|k| {
1082 TokenExpectType::Expect => self.check(k),
1083 TokenExpectType::NoExpect => self.token == **k,
1087 token::CloseDelim(..) | token::Eof => break,
1090 if let Some(ref t) = sep.sep {
1094 if let Err(mut e) = self.expect(t) {
1095 // Attempt to keep parsing if it was a similar separator
1096 if let Some(ref tokens) = t.similar_tokens() {
1097 if tokens.contains(&self.token) {
1102 // Attempt to keep parsing if it was an omitted separator
1116 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1118 TokenExpectType::Expect => self.check(k),
1119 TokenExpectType::NoExpect => self.token == **k,
1132 /// Parse a sequence, including the closing delimiter. The function
1133 /// f must consume tokens until reaching the next separator or
1134 /// closing bracket.
1135 fn parse_unspanned_seq<T, F>(&mut self,
1140 -> PResult<'a, Vec<T>> where
1141 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1144 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1145 if self.token == *ket {
1151 /// Advance the parser by one token
1152 pub fn bump(&mut self) {
1153 if self.prev_token_kind == PrevTokenKind::Eof {
1154 // Bumping after EOF is a bad sign, usually an infinite loop.
1155 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1158 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1160 // Record last token kind for possible error recovery.
1161 self.prev_token_kind = match self.token {
1162 token::DocComment(..) => PrevTokenKind::DocComment,
1163 token::Comma => PrevTokenKind::Comma,
1164 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1165 token::Interpolated(..) => PrevTokenKind::Interpolated,
1166 token::Eof => PrevTokenKind::Eof,
1167 token::Ident(..) => PrevTokenKind::Ident,
1168 _ => PrevTokenKind::Other,
1171 let next = self.next_tok();
1172 self.span = next.sp;
1173 self.token = next.tok;
1174 self.expected_tokens.clear();
1175 // check after each token
1176 self.process_potential_macro_variable();
1179 /// Advance the parser using provided token as a next one. Use this when
1180 /// consuming a part of a token. For example a single `<` from `<<`.
1181 fn bump_with(&mut self, next: token::Token, span: Span) {
1182 self.prev_span = self.span.with_hi(span.lo());
1183 // It would be incorrect to record the kind of the current token, but
1184 // fortunately for tokens currently using `bump_with`, the
1185 // prev_token_kind will be of no use anyway.
1186 self.prev_token_kind = PrevTokenKind::Other;
1189 self.expected_tokens.clear();
1192 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1193 F: FnOnce(&token::Token) -> R,
1196 return f(&self.token)
1199 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1200 Some(tree) => match tree {
1201 TokenTree::Token(_, tok) => tok,
1202 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1204 None => token::CloseDelim(self.token_cursor.frame.delim),
1208 fn look_ahead_span(&self, dist: usize) -> Span {
1213 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1214 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1215 None => self.look_ahead_span(dist - 1),
1218 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1219 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1221 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1222 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1224 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1225 err.span_err(sp, self.diagnostic())
1227 fn bug(&self, m: &str) -> ! {
1228 self.sess.span_diagnostic.span_bug(self.span, m)
1230 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1231 self.sess.span_diagnostic.span_err(sp, m)
1233 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1234 self.sess.span_diagnostic.struct_span_err(sp, m)
1236 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1237 self.sess.span_diagnostic.span_bug(sp, m)
1239 crate fn abort_if_errors(&self) {
1240 self.sess.span_diagnostic.abort_if_errors();
1243 fn cancel(&self, err: &mut DiagnosticBuilder) {
1244 self.sess.span_diagnostic.cancel(err)
1247 crate fn diagnostic(&self) -> &'a errors::Handler {
1248 &self.sess.span_diagnostic
1251 /// Is the current token one of the keywords that signals a bare function
1253 fn token_is_bare_fn_keyword(&mut self) -> bool {
1254 self.check_keyword(keywords::Fn) ||
1255 self.check_keyword(keywords::Unsafe) ||
1256 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1259 /// parse a TyKind::BareFn type:
1260 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1263 [unsafe] [extern "ABI"] fn (S) -> T
1273 let unsafety = self.parse_unsafety();
1274 let abi = if self.eat_keyword(keywords::Extern) {
1275 self.parse_opt_abi()?.unwrap_or(Abi::C)
1280 self.expect_keyword(keywords::Fn)?;
1281 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1282 let ret_ty = self.parse_ret_ty(false)?;
1283 let decl = P(FnDecl {
1288 Ok(TyKind::BareFn(P(BareFnTy {
1296 /// Parse asyncness: `async` or nothing
1297 fn parse_asyncness(&mut self) -> IsAsync {
1298 if self.eat_keyword(keywords::Async) {
1299 IsAsync::Async(ast::DUMMY_NODE_ID)
1305 /// Parse unsafety: `unsafe` or nothing.
1306 fn parse_unsafety(&mut self) -> Unsafety {
1307 if self.eat_keyword(keywords::Unsafe) {
1314 /// Parse the items in a trait declaration
1315 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1316 maybe_whole!(self, NtTraitItem, |x| x);
1317 let attrs = self.parse_outer_attributes()?;
1318 let (mut item, tokens) = self.collect_tokens(|this| {
1319 this.parse_trait_item_(at_end, attrs)
1321 // See `parse_item` for why this clause is here.
1322 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1323 item.tokens = Some(tokens);
1328 fn parse_trait_item_(&mut self,
1330 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1333 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1334 self.parse_trait_item_assoc_ty()?
1335 } else if self.is_const_item() {
1336 self.expect_keyword(keywords::Const)?;
1337 let ident = self.parse_ident()?;
1338 self.expect(&token::Colon)?;
1339 let ty = self.parse_ty()?;
1340 let default = if self.check(&token::Eq) {
1342 let expr = self.parse_expr()?;
1343 self.expect(&token::Semi)?;
1346 self.expect(&token::Semi)?;
1349 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1350 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1351 // trait item macro.
1352 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1354 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1356 let ident = self.parse_ident()?;
1357 let mut generics = self.parse_generics()?;
1359 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1360 // This is somewhat dubious; We don't want to allow
1361 // argument names to be left off if there is a
1363 p.parse_arg_general(false)
1365 generics.where_clause = self.parse_where_clause()?;
1367 let sig = ast::MethodSig {
1377 let body = match self.token {
1381 debug!("parse_trait_methods(): parsing required method");
1384 token::OpenDelim(token::Brace) => {
1385 debug!("parse_trait_methods(): parsing provided method");
1387 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1388 attrs.extend(inner_attrs.iter().cloned());
1392 let token_str = self.this_token_to_string();
1393 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1395 err.span_label(self.span, "expected `;` or `{`");
1399 (ident, ast::TraitItemKind::Method(sig, body), generics)
1403 id: ast::DUMMY_NODE_ID,
1408 span: lo.to(self.prev_span),
1413 /// Parse optional return type [ -> TY ] in function decl
1414 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1415 if self.eat(&token::RArrow) {
1416 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1418 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1423 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1424 self.parse_ty_common(true, true)
1427 /// Parse a type in restricted contexts where `+` is not permitted.
1428 /// Example 1: `&'a TYPE`
1429 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1430 /// Example 2: `value1 as TYPE + value2`
1431 /// `+` is prohibited to avoid interactions with expression grammar.
1432 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1433 self.parse_ty_common(false, true)
1436 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1437 -> PResult<'a, P<Ty>> {
1438 maybe_whole!(self, NtTy, |x| x);
1441 let mut impl_dyn_multi = false;
1442 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1443 // `(TYPE)` is a parenthesized type.
1444 // `(TYPE,)` is a tuple with a single field of type TYPE.
1445 let mut ts = vec![];
1446 let mut last_comma = false;
1447 while self.token != token::CloseDelim(token::Paren) {
1448 ts.push(self.parse_ty()?);
1449 if self.eat(&token::Comma) {
1456 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1457 self.expect(&token::CloseDelim(token::Paren))?;
1459 if ts.len() == 1 && !last_comma {
1460 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1461 let maybe_bounds = allow_plus && self.token.is_like_plus();
1463 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1464 TyKind::Path(None, ref path) if maybe_bounds => {
1465 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1467 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1468 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1469 let path = match bounds[0] {
1470 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1471 _ => self.bug("unexpected lifetime bound"),
1473 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1476 _ => TyKind::Paren(P(ty))
1481 } else if self.eat(&token::Not) {
1484 } else if self.eat(&token::BinOp(token::Star)) {
1486 TyKind::Ptr(self.parse_ptr()?)
1487 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1489 let t = self.parse_ty()?;
1490 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1491 let t = match self.maybe_parse_fixed_length_of_vec()? {
1492 None => TyKind::Slice(t),
1493 Some(length) => TyKind::Array(t, AnonConst {
1494 id: ast::DUMMY_NODE_ID,
1498 self.expect(&token::CloseDelim(token::Bracket))?;
1500 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1503 self.parse_borrowed_pointee()?
1504 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1506 // In order to not be ambiguous, the type must be surrounded by parens.
1507 self.expect(&token::OpenDelim(token::Paren))?;
1509 id: ast::DUMMY_NODE_ID,
1510 value: self.parse_expr()?,
1512 self.expect(&token::CloseDelim(token::Paren))?;
1514 } else if self.eat_keyword(keywords::Underscore) {
1515 // A type to be inferred `_`
1517 } else if self.token_is_bare_fn_keyword() {
1518 // Function pointer type
1519 self.parse_ty_bare_fn(Vec::new())?
1520 } else if self.check_keyword(keywords::For) {
1521 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1522 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1523 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1525 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1526 if self.token_is_bare_fn_keyword() {
1527 self.parse_ty_bare_fn(lifetime_defs)?
1529 let path = self.parse_path(PathStyle::Type)?;
1530 let parse_plus = allow_plus && self.check_plus();
1531 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1533 } else if self.eat_keyword(keywords::Impl) {
1534 // Always parse bounds greedily for better error recovery.
1535 let bounds = self.parse_generic_bounds()?;
1536 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1537 TyKind::ImplTrait(bounds)
1538 } else if self.check_keyword(keywords::Dyn) &&
1539 self.look_ahead(1, |t| t.can_begin_bound() &&
1540 !can_continue_type_after_non_fn_ident(t)) {
1541 self.bump(); // `dyn`
1542 // Always parse bounds greedily for better error recovery.
1543 let bounds = self.parse_generic_bounds()?;
1544 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1545 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1546 } else if self.check(&token::Question) ||
1547 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1548 // Bound list (trait object type)
1549 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1550 TraitObjectSyntax::None)
1551 } else if self.eat_lt() {
1553 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1554 TyKind::Path(Some(qself), path)
1555 } else if self.token.is_path_start() {
1557 let path = self.parse_path(PathStyle::Type)?;
1558 if self.eat(&token::Not) {
1559 // Macro invocation in type position
1560 let (delim, tts) = self.expect_delimited_token_tree()?;
1561 let node = Mac_ { path, tts, delim };
1562 TyKind::Mac(respan(lo.to(self.prev_span), node))
1564 // Just a type path or bound list (trait object type) starting with a trait.
1566 // `Trait1 + Trait2 + 'a`
1567 if allow_plus && self.check_plus() {
1568 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1570 TyKind::Path(None, path)
1574 let msg = format!("expected type, found {}", self.this_token_descr());
1575 return Err(self.fatal(&msg));
1578 let span = lo.to(self.prev_span);
1579 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1581 // Try to recover from use of `+` with incorrect priority.
1582 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1583 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1584 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1589 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1590 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1591 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1592 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1594 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1595 bounds.append(&mut self.parse_generic_bounds()?);
1597 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1600 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1601 if !allow_plus && impl_dyn_multi {
1602 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1603 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1604 .span_suggestion_with_applicability(
1606 "use parentheses to disambiguate",
1608 Applicability::MachineApplicable
1613 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1614 // Do not add `+` to expected tokens.
1615 if !allow_plus || !self.token.is_like_plus() {
1620 let bounds = self.parse_generic_bounds()?;
1621 let sum_span = ty.span.to(self.prev_span);
1623 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1624 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1627 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1628 let sum_with_parens = pprust::to_string(|s| {
1629 use print::pprust::PrintState;
1632 s.print_opt_lifetime(lifetime)?;
1633 s.print_mutability(mut_ty.mutbl)?;
1635 s.print_type(&mut_ty.ty)?;
1636 s.print_type_bounds(" +", &bounds)?;
1639 err.span_suggestion_with_applicability(
1641 "try adding parentheses",
1643 Applicability::MachineApplicable
1646 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1647 err.span_label(sum_span, "perhaps you forgot parentheses?");
1650 err.span_label(sum_span, "expected a path");
1657 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1658 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1660 // Do not add `::` to expected tokens.
1661 if !allow_recovery || self.token != token::ModSep {
1664 let ty = match base.to_ty() {
1666 None => return Ok(base),
1669 self.bump(); // `::`
1670 let mut segments = Vec::new();
1671 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1673 let span = ty.span.to(self.prev_span);
1674 let path_span = span.to(span); // use an empty path since `position` == 0
1675 let recovered = base.to_recovered(
1676 Some(QSelf { ty, path_span, position: 0 }),
1677 ast::Path { segments, span },
1681 .struct_span_err(span, "missing angle brackets in associated item path")
1682 .span_suggestion_with_applicability( // this is a best-effort recovery
1683 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1689 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1690 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1691 let mutbl = self.parse_mutability();
1692 let ty = self.parse_ty_no_plus()?;
1693 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1696 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1697 let mutbl = if self.eat_keyword(keywords::Mut) {
1699 } else if self.eat_keyword(keywords::Const) {
1700 Mutability::Immutable
1702 let span = self.prev_span;
1704 "expected mut or const in raw pointer type (use \
1705 `*mut T` or `*const T` as appropriate)");
1706 Mutability::Immutable
1708 let t = self.parse_ty_no_plus()?;
1709 Ok(MutTy { ty: t, mutbl: mutbl })
1712 fn is_named_argument(&mut self) -> bool {
1713 let offset = match self.token {
1714 token::Interpolated(ref nt) => match nt.0 {
1715 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1718 token::BinOp(token::And) | token::AndAnd => 1,
1719 _ if self.token.is_keyword(keywords::Mut) => 1,
1723 self.look_ahead(offset, |t| t.is_ident()) &&
1724 self.look_ahead(offset + 1, |t| t == &token::Colon)
1727 /// This version of parse arg doesn't necessarily require
1728 /// identifier names.
1729 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1730 maybe_whole!(self, NtArg, |x| x);
1732 let (pat, ty) = if require_name || self.is_named_argument() {
1733 debug!("parse_arg_general parse_pat (require_name:{})",
1735 let pat = self.parse_pat()?;
1737 self.expect(&token::Colon)?;
1738 (pat, self.parse_ty()?)
1740 debug!("parse_arg_general ident_to_pat");
1741 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1742 let ty = self.parse_ty()?;
1744 id: ast::DUMMY_NODE_ID,
1745 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
1754 id: ast::DUMMY_NODE_ID,
1758 /// Parse a single function argument
1759 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1760 self.parse_arg_general(true)
1763 /// Parse an argument in a lambda header e.g. |arg, arg|
1764 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1765 let pat = self.parse_pat()?;
1766 let t = if self.eat(&token::Colon) {
1770 id: ast::DUMMY_NODE_ID,
1771 node: TyKind::Infer,
1778 id: ast::DUMMY_NODE_ID
1782 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1783 if self.eat(&token::Semi) {
1784 Ok(Some(self.parse_expr()?))
1790 /// Matches token_lit = LIT_INTEGER | ...
1791 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1792 let out = match self.token {
1793 token::Interpolated(ref nt) => match nt.0 {
1794 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1795 ExprKind::Lit(ref lit) => { lit.node.clone() }
1796 _ => { return self.unexpected_last(&self.token); }
1798 _ => { return self.unexpected_last(&self.token); }
1800 token::Literal(lit, suf) => {
1801 let diag = Some((self.span, &self.sess.span_diagnostic));
1802 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1806 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1811 _ => { return self.unexpected_last(&self.token); }
1818 /// Matches lit = true | false | token_lit
1819 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1821 let lit = if self.eat_keyword(keywords::True) {
1823 } else if self.eat_keyword(keywords::False) {
1824 LitKind::Bool(false)
1826 let lit = self.parse_lit_token()?;
1829 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1832 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1833 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1834 maybe_whole_expr!(self);
1836 let minus_lo = self.span;
1837 let minus_present = self.eat(&token::BinOp(token::Minus));
1839 let literal = P(self.parse_lit()?);
1840 let hi = self.prev_span;
1841 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1844 let minus_hi = self.prev_span;
1845 let unary = self.mk_unary(UnOp::Neg, expr);
1846 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1852 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1854 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1855 let span = self.span;
1857 Ok(Ident::new(ident.name, span))
1859 _ => self.parse_ident(),
1863 /// Parses qualified path.
1864 /// Assumes that the leading `<` has been parsed already.
1866 /// `qualified_path = <type [as trait_ref]>::path`
1871 /// `<T as U>::F::a<S>` (without disambiguator)
1872 /// `<T as U>::F::a::<S>` (with disambiguator)
1873 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1874 let lo = self.prev_span;
1875 let ty = self.parse_ty()?;
1877 // `path` will contain the prefix of the path up to the `>`,
1878 // if any (e.g., `U` in the `<T as U>::*` examples
1879 // above). `path_span` has the span of that path, or an empty
1880 // span in the case of something like `<T>::Bar`.
1881 let (mut path, path_span);
1882 if self.eat_keyword(keywords::As) {
1883 let path_lo = self.span;
1884 path = self.parse_path(PathStyle::Type)?;
1885 path_span = path_lo.to(self.prev_span);
1887 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1888 path_span = self.span.to(self.span);
1891 self.expect(&token::Gt)?;
1892 self.expect(&token::ModSep)?;
1894 let qself = QSelf { ty, path_span, position: path.segments.len() };
1895 self.parse_path_segments(&mut path.segments, style, true)?;
1897 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1900 /// Parses simple paths.
1902 /// `path = [::] segment+`
1903 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1906 /// `a::b::C<D>` (without disambiguator)
1907 /// `a::b::C::<D>` (with disambiguator)
1908 /// `Fn(Args)` (without disambiguator)
1909 /// `Fn::(Args)` (with disambiguator)
1910 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1911 self.parse_path_common(style, true)
1914 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1915 -> PResult<'a, ast::Path> {
1916 maybe_whole!(self, NtPath, |path| {
1917 if style == PathStyle::Mod &&
1918 path.segments.iter().any(|segment| segment.args.is_some()) {
1919 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1924 let lo = self.meta_var_span.unwrap_or(self.span);
1925 let mut segments = Vec::new();
1926 if self.eat(&token::ModSep) {
1927 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1929 self.parse_path_segments(&mut segments, style, enable_warning)?;
1931 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1934 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1935 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1936 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1937 let meta_ident = match self.token {
1938 token::Interpolated(ref nt) => match nt.0 {
1939 token::NtMeta(ref meta) => match meta.node {
1940 ast::MetaItemKind::Word => Some(meta.ident.clone()),
1947 if let Some(path) = meta_ident {
1951 self.parse_path(style)
1954 fn parse_path_segments(&mut self,
1955 segments: &mut Vec<PathSegment>,
1957 enable_warning: bool)
1958 -> PResult<'a, ()> {
1960 segments.push(self.parse_path_segment(style, enable_warning)?);
1962 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1968 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1969 -> PResult<'a, PathSegment> {
1970 let ident = self.parse_path_segment_ident()?;
1972 let is_args_start = |token: &token::Token| match *token {
1973 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1976 let check_args_start = |this: &mut Self| {
1977 this.expected_tokens.extend_from_slice(
1978 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1980 is_args_start(&this.token)
1983 Ok(if style == PathStyle::Type && check_args_start(self) ||
1984 style != PathStyle::Mod && self.check(&token::ModSep)
1985 && self.look_ahead(1, |t| is_args_start(t)) {
1986 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1988 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1989 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1990 .span_label(self.prev_span, "try removing `::`").emit();
1993 let args = if self.eat_lt() {
1995 let (args, bindings) = self.parse_generic_args()?;
1997 let span = lo.to(self.prev_span);
1998 AngleBracketedArgs { args, bindings, span }.into()
2002 let inputs = self.parse_seq_to_before_tokens(
2003 &[&token::CloseDelim(token::Paren)],
2004 SeqSep::trailing_allowed(token::Comma),
2005 TokenExpectType::Expect,
2008 let output = if self.eat(&token::RArrow) {
2009 Some(self.parse_ty_common(false, false)?)
2013 let span = lo.to(self.prev_span);
2014 ParenthesisedArgs { inputs, output, span }.into()
2017 PathSegment { ident, args }
2019 // Generic arguments are not found.
2020 PathSegment::from_ident(ident)
2024 crate fn check_lifetime(&mut self) -> bool {
2025 self.expected_tokens.push(TokenType::Lifetime);
2026 self.token.is_lifetime()
2029 /// Parse single lifetime 'a or panic.
2030 crate fn expect_lifetime(&mut self) -> Lifetime {
2031 if let Some(ident) = self.token.lifetime() {
2032 let span = self.span;
2034 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2036 self.span_bug(self.span, "not a lifetime")
2040 fn eat_label(&mut self) -> Option<Label> {
2041 if let Some(ident) = self.token.lifetime() {
2042 let span = self.span;
2044 Some(Label { ident: Ident::new(ident.name, span) })
2050 /// Parse mutability (`mut` or nothing).
2051 fn parse_mutability(&mut self) -> Mutability {
2052 if self.eat_keyword(keywords::Mut) {
2055 Mutability::Immutable
2059 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2060 if let token::Literal(token::Integer(name), None) = self.token {
2062 Ok(Ident::new(name, self.prev_span))
2064 self.parse_ident_common(false)
2068 /// Parse ident (COLON expr)?
2069 fn parse_field(&mut self) -> PResult<'a, Field> {
2070 let attrs = self.parse_outer_attributes()?;
2073 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2074 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2075 let fieldname = self.parse_field_name()?;
2077 (fieldname, self.parse_expr()?, false)
2079 let fieldname = self.parse_ident_common(false)?;
2081 // Mimic `x: x` for the `x` field shorthand.
2082 let path = ast::Path::from_ident(fieldname);
2083 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2084 (fieldname, expr, true)
2088 span: lo.to(expr.span),
2091 attrs: attrs.into(),
2095 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2096 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2099 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2100 ExprKind::Unary(unop, expr)
2103 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2104 ExprKind::Binary(binop, lhs, rhs)
2107 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2108 ExprKind::Call(f, args)
2111 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2112 ExprKind::Index(expr, idx)
2115 fn mk_range(&mut self,
2116 start: Option<P<Expr>>,
2117 end: Option<P<Expr>>,
2118 limits: RangeLimits)
2119 -> PResult<'a, ast::ExprKind> {
2120 if end.is_none() && limits == RangeLimits::Closed {
2121 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2123 Ok(ExprKind::Range(start, end, limits))
2127 fn mk_assign_op(&mut self, binop: ast::BinOp,
2128 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2129 ExprKind::AssignOp(binop, lhs, rhs)
2132 fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2134 id: ast::DUMMY_NODE_ID,
2135 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2141 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2142 let delim = match self.token {
2143 token::OpenDelim(delim) => delim,
2145 let msg = "expected open delimiter";
2146 let mut err = self.fatal(msg);
2147 err.span_label(self.span, msg);
2151 let delimited = match self.parse_token_tree() {
2152 TokenTree::Delimited(_, delimited) => delimited,
2153 _ => unreachable!(),
2155 let delim = match delim {
2156 token::Paren => MacDelimiter::Parenthesis,
2157 token::Bracket => MacDelimiter::Bracket,
2158 token::Brace => MacDelimiter::Brace,
2159 token::NoDelim => self.bug("unexpected no delimiter"),
2161 Ok((delim, delimited.stream().into()))
2164 /// At the bottom (top?) of the precedence hierarchy,
2165 /// parse things like parenthesized exprs,
2166 /// macros, return, etc.
2168 /// NB: This does not parse outer attributes,
2169 /// and is private because it only works
2170 /// correctly if called from parse_dot_or_call_expr().
2171 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2172 maybe_whole_expr!(self);
2174 // Outer attributes are already parsed and will be
2175 // added to the return value after the fact.
2177 // Therefore, prevent sub-parser from parsing
2178 // attributes by giving them a empty "already parsed" list.
2179 let mut attrs = ThinVec::new();
2182 let mut hi = self.span;
2186 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2188 token::OpenDelim(token::Paren) => {
2191 attrs.extend(self.parse_inner_attributes()?);
2193 // (e) is parenthesized e
2194 // (e,) is a tuple with only one field, e
2195 let mut es = vec![];
2196 let mut trailing_comma = false;
2197 while self.token != token::CloseDelim(token::Paren) {
2198 es.push(self.parse_expr()?);
2199 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2200 if self.check(&token::Comma) {
2201 trailing_comma = true;
2205 trailing_comma = false;
2211 hi = self.prev_span;
2212 ex = if es.len() == 1 && !trailing_comma {
2213 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2218 token::OpenDelim(token::Brace) => {
2219 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2221 token::BinOp(token::Or) | token::OrOr => {
2222 return self.parse_lambda_expr(attrs);
2224 token::OpenDelim(token::Bracket) => {
2227 attrs.extend(self.parse_inner_attributes()?);
2229 if self.check(&token::CloseDelim(token::Bracket)) {
2232 ex = ExprKind::Array(Vec::new());
2235 let first_expr = self.parse_expr()?;
2236 if self.check(&token::Semi) {
2237 // Repeating array syntax: [ 0; 512 ]
2239 let count = AnonConst {
2240 id: ast::DUMMY_NODE_ID,
2241 value: self.parse_expr()?,
2243 self.expect(&token::CloseDelim(token::Bracket))?;
2244 ex = ExprKind::Repeat(first_expr, count);
2245 } else if self.check(&token::Comma) {
2246 // Vector with two or more elements.
2248 let remaining_exprs = self.parse_seq_to_end(
2249 &token::CloseDelim(token::Bracket),
2250 SeqSep::trailing_allowed(token::Comma),
2251 |p| Ok(p.parse_expr()?)
2253 let mut exprs = vec![first_expr];
2254 exprs.extend(remaining_exprs);
2255 ex = ExprKind::Array(exprs);
2257 // Vector with one element.
2258 self.expect(&token::CloseDelim(token::Bracket))?;
2259 ex = ExprKind::Array(vec![first_expr]);
2262 hi = self.prev_span;
2266 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2268 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2270 if syntax_pos::hygiene::default_edition() >= Edition::Edition2018 &&
2271 self.check_keyword(keywords::Async)
2273 if self.is_async_block() { // check for `async {` and `async move {`
2274 return self.parse_async_block(attrs);
2276 return self.parse_lambda_expr(attrs);
2279 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2280 return self.parse_lambda_expr(attrs);
2282 if self.eat_keyword(keywords::If) {
2283 return self.parse_if_expr(attrs);
2285 if self.eat_keyword(keywords::For) {
2286 let lo = self.prev_span;
2287 return self.parse_for_expr(None, lo, attrs);
2289 if self.eat_keyword(keywords::While) {
2290 let lo = self.prev_span;
2291 return self.parse_while_expr(None, lo, attrs);
2293 if let Some(label) = self.eat_label() {
2294 let lo = label.ident.span;
2295 self.expect(&token::Colon)?;
2296 if self.eat_keyword(keywords::While) {
2297 return self.parse_while_expr(Some(label), lo, attrs)
2299 if self.eat_keyword(keywords::For) {
2300 return self.parse_for_expr(Some(label), lo, attrs)
2302 if self.eat_keyword(keywords::Loop) {
2303 return self.parse_loop_expr(Some(label), lo, attrs)
2305 if self.token == token::OpenDelim(token::Brace) {
2306 return self.parse_block_expr(Some(label),
2308 BlockCheckMode::Default,
2311 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2312 let mut err = self.fatal(msg);
2313 err.span_label(self.span, msg);
2316 if self.eat_keyword(keywords::Loop) {
2317 let lo = self.prev_span;
2318 return self.parse_loop_expr(None, lo, attrs);
2320 if self.eat_keyword(keywords::Continue) {
2321 let label = self.eat_label();
2322 let ex = ExprKind::Continue(label);
2323 let hi = self.prev_span;
2324 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2326 if self.eat_keyword(keywords::Match) {
2327 return self.parse_match_expr(attrs);
2329 if self.eat_keyword(keywords::Unsafe) {
2330 return self.parse_block_expr(
2333 BlockCheckMode::Unsafe(ast::UserProvided),
2336 if self.is_catch_expr() {
2338 assert!(self.eat_keyword(keywords::Do));
2339 assert!(self.eat_keyword(keywords::Catch));
2340 return self.parse_catch_expr(lo, attrs);
2342 if self.eat_keyword(keywords::Return) {
2343 if self.token.can_begin_expr() {
2344 let e = self.parse_expr()?;
2346 ex = ExprKind::Ret(Some(e));
2348 ex = ExprKind::Ret(None);
2350 } else if self.eat_keyword(keywords::Break) {
2351 let label = self.eat_label();
2352 let e = if self.token.can_begin_expr()
2353 && !(self.token == token::OpenDelim(token::Brace)
2354 && self.restrictions.contains(
2355 Restrictions::NO_STRUCT_LITERAL)) {
2356 Some(self.parse_expr()?)
2360 ex = ExprKind::Break(label, e);
2361 hi = self.prev_span;
2362 } else if self.eat_keyword(keywords::Yield) {
2363 if self.token.can_begin_expr() {
2364 let e = self.parse_expr()?;
2366 ex = ExprKind::Yield(Some(e));
2368 ex = ExprKind::Yield(None);
2370 } else if self.token.is_keyword(keywords::Let) {
2371 // Catch this syntax error here, instead of in `parse_ident`, so
2372 // that we can explicitly mention that let is not to be used as an expression
2373 let mut db = self.fatal("expected expression, found statement (`let`)");
2374 db.span_label(self.span, "expected expression");
2375 db.note("variable declaration using `let` is a statement");
2377 } else if self.token.is_path_start() {
2378 let pth = self.parse_path(PathStyle::Expr)?;
2380 // `!`, as an operator, is prefix, so we know this isn't that
2381 if self.eat(&token::Not) {
2382 // MACRO INVOCATION expression
2383 let (delim, tts) = self.expect_delimited_token_tree()?;
2384 let hi = self.prev_span;
2385 let node = Mac_ { path: pth, tts, delim };
2386 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2388 if self.check(&token::OpenDelim(token::Brace)) {
2389 // This is a struct literal, unless we're prohibited
2390 // from parsing struct literals here.
2391 let prohibited = self.restrictions.contains(
2392 Restrictions::NO_STRUCT_LITERAL
2395 return self.parse_struct_expr(lo, pth, attrs);
2400 ex = ExprKind::Path(None, pth);
2402 match self.parse_literal_maybe_minus() {
2405 ex = expr.node.clone();
2408 self.cancel(&mut err);
2409 let msg = format!("expected expression, found {}",
2410 self.this_token_descr());
2411 let mut err = self.fatal(&msg);
2412 err.span_label(self.span, "expected expression");
2420 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2421 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2426 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2427 -> PResult<'a, P<Expr>> {
2428 let struct_sp = lo.to(self.prev_span);
2430 let mut fields = Vec::new();
2431 let mut base = None;
2433 attrs.extend(self.parse_inner_attributes()?);
2435 while self.token != token::CloseDelim(token::Brace) {
2436 if self.eat(&token::DotDot) {
2437 let exp_span = self.prev_span;
2438 match self.parse_expr() {
2444 self.recover_stmt();
2447 if self.token == token::Comma {
2448 let mut err = self.sess.span_diagnostic.mut_span_err(
2449 exp_span.to(self.prev_span),
2450 "cannot use a comma after the base struct",
2452 err.span_suggestion_short_with_applicability(
2454 "remove this comma",
2456 Applicability::MachineApplicable
2458 err.note("the base struct must always be the last field");
2460 self.recover_stmt();
2465 match self.parse_field() {
2466 Ok(f) => fields.push(f),
2468 e.span_label(struct_sp, "while parsing this struct");
2470 self.recover_stmt();
2475 match self.expect_one_of(&[token::Comma],
2476 &[token::CloseDelim(token::Brace)]) {
2480 self.recover_stmt();
2486 let span = lo.to(self.span);
2487 self.expect(&token::CloseDelim(token::Brace))?;
2488 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2491 fn parse_or_use_outer_attributes(&mut self,
2492 already_parsed_attrs: Option<ThinVec<Attribute>>)
2493 -> PResult<'a, ThinVec<Attribute>> {
2494 if let Some(attrs) = already_parsed_attrs {
2497 self.parse_outer_attributes().map(|a| a.into())
2501 /// Parse a block or unsafe block
2502 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2503 lo: Span, blk_mode: BlockCheckMode,
2504 outer_attrs: ThinVec<Attribute>)
2505 -> PResult<'a, P<Expr>> {
2506 self.expect(&token::OpenDelim(token::Brace))?;
2508 let mut attrs = outer_attrs;
2509 attrs.extend(self.parse_inner_attributes()?);
2511 let blk = self.parse_block_tail(lo, blk_mode)?;
2512 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2515 /// parse a.b or a(13) or a[4] or just a
2516 fn parse_dot_or_call_expr(&mut self,
2517 already_parsed_attrs: Option<ThinVec<Attribute>>)
2518 -> PResult<'a, P<Expr>> {
2519 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2521 let b = self.parse_bottom_expr();
2522 let (span, b) = self.interpolated_or_expr_span(b)?;
2523 self.parse_dot_or_call_expr_with(b, span, attrs)
2526 fn parse_dot_or_call_expr_with(&mut self,
2529 mut attrs: ThinVec<Attribute>)
2530 -> PResult<'a, P<Expr>> {
2531 // Stitch the list of outer attributes onto the return value.
2532 // A little bit ugly, but the best way given the current code
2534 self.parse_dot_or_call_expr_with_(e0, lo)
2536 expr.map(|mut expr| {
2537 attrs.extend::<Vec<_>>(expr.attrs.into());
2540 ExprKind::If(..) | ExprKind::IfLet(..) => {
2541 if !expr.attrs.is_empty() {
2542 // Just point to the first attribute in there...
2543 let span = expr.attrs[0].span;
2546 "attributes are not yet allowed on `if` \
2557 // Assuming we have just parsed `.`, continue parsing into an expression.
2558 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2559 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2560 Ok(match self.token {
2561 token::OpenDelim(token::Paren) => {
2562 // Method call `expr.f()`
2563 let mut args = self.parse_unspanned_seq(
2564 &token::OpenDelim(token::Paren),
2565 &token::CloseDelim(token::Paren),
2566 SeqSep::trailing_allowed(token::Comma),
2567 |p| Ok(p.parse_expr()?)
2569 args.insert(0, self_arg);
2571 let span = lo.to(self.prev_span);
2572 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2575 // Field access `expr.f`
2576 if let Some(args) = segment.args {
2577 self.span_err(args.span(),
2578 "field expressions may not have generic arguments");
2581 let span = lo.to(self.prev_span);
2582 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2587 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2592 while self.eat(&token::Question) {
2593 let hi = self.prev_span;
2594 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2598 if self.eat(&token::Dot) {
2600 token::Ident(..) => {
2601 e = self.parse_dot_suffix(e, lo)?;
2603 token::Literal(token::Integer(name), _) => {
2604 let span = self.span;
2606 let field = ExprKind::Field(e, Ident::new(name, span));
2607 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2609 token::Literal(token::Float(n), _suf) => {
2611 let fstr = n.as_str();
2612 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2613 &format!("unexpected token: `{}`", n));
2614 err.span_label(self.prev_span, "unexpected token");
2615 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2616 let float = match fstr.parse::<f64>().ok() {
2620 let sugg = pprust::to_string(|s| {
2621 use print::pprust::PrintState;
2625 s.print_usize(float.trunc() as usize)?;
2628 s.s.word(fstr.splitn(2, ".").last().unwrap())
2630 err.span_suggestion_with_applicability(
2631 lo.to(self.prev_span),
2632 "try parenthesizing the first index",
2634 Applicability::MachineApplicable
2641 // FIXME Could factor this out into non_fatal_unexpected or something.
2642 let actual = self.this_token_to_string();
2643 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2648 if self.expr_is_complete(&e) { break; }
2651 token::OpenDelim(token::Paren) => {
2652 let es = self.parse_unspanned_seq(
2653 &token::OpenDelim(token::Paren),
2654 &token::CloseDelim(token::Paren),
2655 SeqSep::trailing_allowed(token::Comma),
2656 |p| Ok(p.parse_expr()?)
2658 hi = self.prev_span;
2660 let nd = self.mk_call(e, es);
2661 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2665 // Could be either an index expression or a slicing expression.
2666 token::OpenDelim(token::Bracket) => {
2668 let ix = self.parse_expr()?;
2670 self.expect(&token::CloseDelim(token::Bracket))?;
2671 let index = self.mk_index(e, ix);
2672 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2680 crate fn process_potential_macro_variable(&mut self) {
2681 let (token, span) = match self.token {
2682 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2683 self.look_ahead(1, |t| t.is_ident()) => {
2685 let name = match self.token {
2686 token::Ident(ident, _) => ident,
2689 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2690 err.span_label(self.span, "unknown macro variable");
2694 token::Interpolated(ref nt) => {
2695 self.meta_var_span = Some(self.span);
2696 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2697 // and lifetime tokens, so the former are never encountered during normal parsing.
2699 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2700 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2710 /// parse a single token tree from the input.
2711 crate fn parse_token_tree(&mut self) -> TokenTree {
2713 token::OpenDelim(..) => {
2714 let frame = mem::replace(&mut self.token_cursor.frame,
2715 self.token_cursor.stack.pop().unwrap());
2716 self.span = frame.span;
2718 TokenTree::Delimited(frame.span, Delimited {
2720 tts: frame.tree_cursor.original_stream().into(),
2723 token::CloseDelim(_) | token::Eof => unreachable!(),
2725 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2727 TokenTree::Token(span, token)
2732 // parse a stream of tokens into a list of TokenTree's,
2734 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2735 let mut tts = Vec::new();
2736 while self.token != token::Eof {
2737 tts.push(self.parse_token_tree());
2742 pub fn parse_tokens(&mut self) -> TokenStream {
2743 let mut result = Vec::new();
2746 token::Eof | token::CloseDelim(..) => break,
2747 _ => result.push(self.parse_token_tree().into()),
2750 TokenStream::concat(result)
2753 /// Parse a prefix-unary-operator expr
2754 fn parse_prefix_expr(&mut self,
2755 already_parsed_attrs: Option<ThinVec<Attribute>>)
2756 -> PResult<'a, P<Expr>> {
2757 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2759 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2760 let (hi, ex) = match self.token {
2763 let e = self.parse_prefix_expr(None);
2764 let (span, e) = self.interpolated_or_expr_span(e)?;
2765 (lo.to(span), self.mk_unary(UnOp::Not, e))
2767 // Suggest `!` for bitwise negation when encountering a `~`
2770 let e = self.parse_prefix_expr(None);
2771 let (span, e) = self.interpolated_or_expr_span(e)?;
2772 let span_of_tilde = lo;
2773 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2774 "`~` cannot be used as a unary operator");
2775 err.span_suggestion_short_with_applicability(
2777 "use `!` to perform bitwise negation",
2779 Applicability::MachineApplicable
2782 (lo.to(span), self.mk_unary(UnOp::Not, e))
2784 token::BinOp(token::Minus) => {
2786 let e = self.parse_prefix_expr(None);
2787 let (span, e) = self.interpolated_or_expr_span(e)?;
2788 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2790 token::BinOp(token::Star) => {
2792 let e = self.parse_prefix_expr(None);
2793 let (span, e) = self.interpolated_or_expr_span(e)?;
2794 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2796 token::BinOp(token::And) | token::AndAnd => {
2798 let m = self.parse_mutability();
2799 let e = self.parse_prefix_expr(None);
2800 let (span, e) = self.interpolated_or_expr_span(e)?;
2801 (lo.to(span), ExprKind::AddrOf(m, e))
2803 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2805 let place = self.parse_expr_res(
2806 Restrictions::NO_STRUCT_LITERAL,
2809 let blk = self.parse_block()?;
2810 let span = blk.span;
2811 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2812 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2814 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2816 let e = self.parse_prefix_expr(None);
2817 let (span, e) = self.interpolated_or_expr_span(e)?;
2818 (lo.to(span), ExprKind::Box(e))
2820 token::Ident(..) if self.token.is_ident_named("not") => {
2821 // `not` is just an ordinary identifier in Rust-the-language,
2822 // but as `rustc`-the-compiler, we can issue clever diagnostics
2823 // for confused users who really want to say `!`
2824 let token_cannot_continue_expr = |t: &token::Token| match *t {
2825 // These tokens can start an expression after `!`, but
2826 // can't continue an expression after an ident
2827 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2828 token::Literal(..) | token::Pound => true,
2829 token::Interpolated(ref nt) => match nt.0 {
2830 token::NtIdent(..) | token::NtExpr(..) |
2831 token::NtBlock(..) | token::NtPath(..) => true,
2836 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2837 if cannot_continue_expr {
2839 // Emit the error ...
2840 let mut err = self.diagnostic()
2841 .struct_span_err(self.span,
2842 &format!("unexpected {} after identifier",
2843 self.this_token_descr()));
2844 // span the `not` plus trailing whitespace to avoid
2845 // trailing whitespace after the `!` in our suggestion
2846 let to_replace = self.sess.codemap()
2847 .span_until_non_whitespace(lo.to(self.span));
2848 err.span_suggestion_short_with_applicability(
2850 "use `!` to perform logical negation",
2852 Applicability::MachineApplicable
2855 // —and recover! (just as if we were in the block
2856 // for the `token::Not` arm)
2857 let e = self.parse_prefix_expr(None);
2858 let (span, e) = self.interpolated_or_expr_span(e)?;
2859 (lo.to(span), self.mk_unary(UnOp::Not, e))
2861 return self.parse_dot_or_call_expr(Some(attrs));
2864 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2866 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2869 /// Parse an associative expression
2871 /// This parses an expression accounting for associativity and precedence of the operators in
2873 fn parse_assoc_expr(&mut self,
2874 already_parsed_attrs: Option<ThinVec<Attribute>>)
2875 -> PResult<'a, P<Expr>> {
2876 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2879 /// Parse an associative expression with operators of at least `min_prec` precedence
2880 fn parse_assoc_expr_with(&mut self,
2883 -> PResult<'a, P<Expr>> {
2884 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2887 let attrs = match lhs {
2888 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2891 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2892 return self.parse_prefix_range_expr(attrs);
2894 self.parse_prefix_expr(attrs)?
2898 if self.expr_is_complete(&lhs) {
2899 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2902 self.expected_tokens.push(TokenType::Operator);
2903 while let Some(op) = AssocOp::from_token(&self.token) {
2905 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2906 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2907 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2908 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2909 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2910 (PrevTokenKind::Interpolated, _) => self.prev_span,
2911 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2912 if path.segments.len() == 1 => self.prev_span,
2916 let cur_op_span = self.span;
2917 let restrictions = if op.is_assign_like() {
2918 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2922 if op.precedence() < min_prec {
2925 // Check for deprecated `...` syntax
2926 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2927 self.err_dotdotdot_syntax(self.span);
2931 if op.is_comparison() {
2932 self.check_no_chained_comparison(&lhs, &op);
2935 if op == AssocOp::As {
2936 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2938 } else if op == AssocOp::Colon {
2939 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2942 err.span_label(self.span,
2943 "expecting a type here because of type ascription");
2944 let cm = self.sess.codemap();
2945 let cur_pos = cm.lookup_char_pos(self.span.lo());
2946 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2947 if cur_pos.line != op_pos.line {
2948 err.span_suggestion_with_applicability(
2950 "try using a semicolon",
2952 Applicability::MaybeIncorrect // speculative
2959 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2960 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2961 // generalise it to the Fixity::None code.
2963 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2964 // two variants are handled with `parse_prefix_range_expr` call above.
2965 let rhs = if self.is_at_start_of_range_notation_rhs() {
2966 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2967 LhsExpr::NotYetParsed)?)
2971 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2976 let limits = if op == AssocOp::DotDot {
2977 RangeLimits::HalfOpen
2982 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2983 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2987 let rhs = match op.fixity() {
2988 Fixity::Right => self.with_res(
2989 restrictions - Restrictions::STMT_EXPR,
2991 this.parse_assoc_expr_with(op.precedence(),
2992 LhsExpr::NotYetParsed)
2994 Fixity::Left => self.with_res(
2995 restrictions - Restrictions::STMT_EXPR,
2997 this.parse_assoc_expr_with(op.precedence() + 1,
2998 LhsExpr::NotYetParsed)
3000 // We currently have no non-associative operators that are not handled above by
3001 // the special cases. The code is here only for future convenience.
3002 Fixity::None => self.with_res(
3003 restrictions - Restrictions::STMT_EXPR,
3005 this.parse_assoc_expr_with(op.precedence() + 1,
3006 LhsExpr::NotYetParsed)
3010 let span = lhs_span.to(rhs.span);
3012 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3013 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3014 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3015 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3016 AssocOp::Greater | AssocOp::GreaterEqual => {
3017 let ast_op = op.to_ast_binop().unwrap();
3018 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
3019 self.mk_expr(span, binary, ThinVec::new())
3022 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3023 AssocOp::ObsoleteInPlace =>
3024 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3025 AssocOp::AssignOp(k) => {
3027 token::Plus => BinOpKind::Add,
3028 token::Minus => BinOpKind::Sub,
3029 token::Star => BinOpKind::Mul,
3030 token::Slash => BinOpKind::Div,
3031 token::Percent => BinOpKind::Rem,
3032 token::Caret => BinOpKind::BitXor,
3033 token::And => BinOpKind::BitAnd,
3034 token::Or => BinOpKind::BitOr,
3035 token::Shl => BinOpKind::Shl,
3036 token::Shr => BinOpKind::Shr,
3038 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3039 self.mk_expr(span, aopexpr, ThinVec::new())
3041 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3042 self.bug("AssocOp should have been handled by special case")
3046 if op.fixity() == Fixity::None { break }
3051 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3052 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3053 -> PResult<'a, P<Expr>> {
3054 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3055 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3058 // Save the state of the parser before parsing type normally, in case there is a
3059 // LessThan comparison after this cast.
3060 let parser_snapshot_before_type = self.clone();
3061 match self.parse_ty_no_plus() {
3063 Ok(mk_expr(self, rhs))
3065 Err(mut type_err) => {
3066 // Rewind to before attempting to parse the type with generics, to recover
3067 // from situations like `x as usize < y` in which we first tried to parse
3068 // `usize < y` as a type with generic arguments.
3069 let parser_snapshot_after_type = self.clone();
3070 mem::replace(self, parser_snapshot_before_type);
3072 match self.parse_path(PathStyle::Expr) {
3074 let (op_noun, op_verb) = match self.token {
3075 token::Lt => ("comparison", "comparing"),
3076 token::BinOp(token::Shl) => ("shift", "shifting"),
3078 // We can end up here even without `<` being the next token, for
3079 // example because `parse_ty_no_plus` returns `Err` on keywords,
3080 // but `parse_path` returns `Ok` on them due to error recovery.
3081 // Return original error and parser state.
3082 mem::replace(self, parser_snapshot_after_type);
3083 return Err(type_err);
3087 // Successfully parsed the type path leaving a `<` yet to parse.
3090 // Report non-fatal diagnostics, keep `x as usize` as an expression
3091 // in AST and continue parsing.
3092 let msg = format!("`<` is interpreted as a start of generic \
3093 arguments for `{}`, not a {}", path, op_noun);
3094 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3095 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3096 "interpreted as generic arguments");
3097 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3099 let expr = mk_expr(self, P(Ty {
3101 node: TyKind::Path(None, path),
3102 id: ast::DUMMY_NODE_ID
3105 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3106 .unwrap_or(pprust::expr_to_string(&expr));
3107 err.span_suggestion_with_applicability(
3109 &format!("try {} the cast value", op_verb),
3110 format!("({})", expr_str),
3111 Applicability::MachineApplicable
3117 Err(mut path_err) => {
3118 // Couldn't parse as a path, return original error and parser state.
3120 mem::replace(self, parser_snapshot_after_type);
3128 /// Produce an error if comparison operators are chained (RFC #558).
3129 /// We only need to check lhs, not rhs, because all comparison ops
3130 /// have same precedence and are left-associative
3131 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3132 debug_assert!(outer_op.is_comparison(),
3133 "check_no_chained_comparison: {:?} is not comparison",
3136 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3137 // respan to include both operators
3138 let op_span = op.span.to(self.span);
3139 let mut err = self.diagnostic().struct_span_err(op_span,
3140 "chained comparison operators require parentheses");
3141 if op.node == BinOpKind::Lt &&
3142 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3143 *outer_op == AssocOp::Greater // even in a case like the following:
3144 { // Foo<Bar<Baz<Qux, ()>>>
3146 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3147 err.help("or use `(...)` if you meant to specify fn arguments");
3155 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3156 fn parse_prefix_range_expr(&mut self,
3157 already_parsed_attrs: Option<ThinVec<Attribute>>)
3158 -> PResult<'a, P<Expr>> {
3159 // Check for deprecated `...` syntax
3160 if self.token == token::DotDotDot {
3161 self.err_dotdotdot_syntax(self.span);
3164 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3165 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3167 let tok = self.token.clone();
3168 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3170 let mut hi = self.span;
3172 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3173 // RHS must be parsed with more associativity than the dots.
3174 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3175 Some(self.parse_assoc_expr_with(next_prec,
3176 LhsExpr::NotYetParsed)
3184 let limits = if tok == token::DotDot {
3185 RangeLimits::HalfOpen
3190 let r = try!(self.mk_range(None,
3193 Ok(self.mk_expr(lo.to(hi), r, attrs))
3196 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3197 if self.token.can_begin_expr() {
3198 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3199 if self.token == token::OpenDelim(token::Brace) {
3200 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3208 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3209 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3210 if self.check_keyword(keywords::Let) {
3211 return self.parse_if_let_expr(attrs);
3213 let lo = self.prev_span;
3214 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3216 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3217 // verify that the last statement is either an implicit return (no `;`) or an explicit
3218 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3219 // the dead code lint.
3220 if self.eat_keyword(keywords::Else) || !cond.returns() {
3221 let sp = self.sess.codemap().next_point(lo);
3222 let mut err = self.diagnostic()
3223 .struct_span_err(sp, "missing condition for `if` statemement");
3224 err.span_label(sp, "expected if condition here");
3227 let not_block = self.token != token::OpenDelim(token::Brace);
3228 let thn = self.parse_block().map_err(|mut err| {
3230 err.span_label(lo, "this `if` statement has a condition, but no block");
3234 let mut els: Option<P<Expr>> = None;
3235 let mut hi = thn.span;
3236 if self.eat_keyword(keywords::Else) {
3237 let elexpr = self.parse_else_expr()?;
3241 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3244 /// Parse an 'if let' expression ('if' token already eaten)
3245 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3246 -> PResult<'a, P<Expr>> {
3247 let lo = self.prev_span;
3248 self.expect_keyword(keywords::Let)?;
3249 let pats = self.parse_pats()?;
3250 self.expect(&token::Eq)?;
3251 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3252 let thn = self.parse_block()?;
3253 let (hi, els) = if self.eat_keyword(keywords::Else) {
3254 let expr = self.parse_else_expr()?;
3255 (expr.span, Some(expr))
3259 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3262 // `move |args| expr`
3263 fn parse_lambda_expr(&mut self,
3264 attrs: ThinVec<Attribute>)
3265 -> PResult<'a, P<Expr>>
3268 let movability = if self.eat_keyword(keywords::Static) {
3273 let asyncness = if syntax_pos::hygiene::default_edition() >= Edition::Edition2018
3274 && self.eat_keyword(keywords::Async)
3276 IsAsync::Async(ast::DUMMY_NODE_ID)
3280 let capture_clause = if self.eat_keyword(keywords::Move) {
3285 let decl = self.parse_fn_block_decl()?;
3286 let decl_hi = self.prev_span;
3287 let body = match decl.output {
3288 FunctionRetTy::Default(_) => {
3289 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3290 self.parse_expr_res(restrictions, None)?
3293 // If an explicit return type is given, require a
3294 // block to appear (RFC 968).
3295 let body_lo = self.span;
3296 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3302 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3306 // `else` token already eaten
3307 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3308 if self.eat_keyword(keywords::If) {
3309 return self.parse_if_expr(ThinVec::new());
3311 let blk = self.parse_block()?;
3312 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3316 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3317 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3319 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3320 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3322 let pat = self.parse_top_level_pat()?;
3323 if !self.eat_keyword(keywords::In) {
3324 let in_span = self.prev_span.between(self.span);
3325 let mut err = self.sess.span_diagnostic
3326 .struct_span_err(in_span, "missing `in` in `for` loop");
3327 err.span_suggestion_short_with_applicability(
3328 in_span, "try adding `in` here", " in ".into(),
3329 // has been misleading, at least in the past (closed Issue #48492)
3330 Applicability::MaybeIncorrect
3334 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3335 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3336 attrs.extend(iattrs);
3338 let hi = self.prev_span;
3339 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3342 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3343 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3345 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3346 if self.token.is_keyword(keywords::Let) {
3347 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3349 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3350 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3351 attrs.extend(iattrs);
3352 let span = span_lo.to(body.span);
3353 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3356 /// Parse a 'while let' expression ('while' token already eaten)
3357 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3359 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3360 self.expect_keyword(keywords::Let)?;
3361 let pats = self.parse_pats()?;
3362 self.expect(&token::Eq)?;
3363 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3364 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3365 attrs.extend(iattrs);
3366 let span = span_lo.to(body.span);
3367 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3370 // parse `loop {...}`, `loop` token already eaten
3371 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3373 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3374 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3375 attrs.extend(iattrs);
3376 let span = span_lo.to(body.span);
3377 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3380 /// Parse an `async move {...}` expression
3381 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3382 -> PResult<'a, P<Expr>>
3384 let span_lo = self.span;
3385 self.expect_keyword(keywords::Async)?;
3386 let capture_clause = if self.eat_keyword(keywords::Move) {
3391 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3392 attrs.extend(iattrs);
3394 span_lo.to(body.span),
3395 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3398 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3399 fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3400 -> PResult<'a, P<Expr>>
3402 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3403 attrs.extend(iattrs);
3404 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3407 // `match` token already eaten
3408 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3409 let match_span = self.prev_span;
3410 let lo = self.prev_span;
3411 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3413 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3414 if self.token == token::Token::Semi {
3415 e.span_suggestion_short_with_applicability(
3417 "try removing this `match`",
3419 Applicability::MaybeIncorrect // speculative
3424 attrs.extend(self.parse_inner_attributes()?);
3426 let mut arms: Vec<Arm> = Vec::new();
3427 while self.token != token::CloseDelim(token::Brace) {
3428 match self.parse_arm() {
3429 Ok(arm) => arms.push(arm),
3431 // Recover by skipping to the end of the block.
3433 self.recover_stmt();
3434 let span = lo.to(self.span);
3435 if self.token == token::CloseDelim(token::Brace) {
3438 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3444 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3447 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3448 maybe_whole!(self, NtArm, |x| x);
3450 let attrs = self.parse_outer_attributes()?;
3451 // Allow a '|' before the pats (RFC 1925)
3452 self.eat(&token::BinOp(token::Or));
3453 let pats = self.parse_pats()?;
3454 let guard = if self.eat_keyword(keywords::If) {
3455 Some(self.parse_expr()?)
3459 let arrow_span = self.span;
3460 self.expect(&token::FatArrow)?;
3461 let arm_start_span = self.span;
3463 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3464 .map_err(|mut err| {
3465 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3469 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3470 && self.token != token::CloseDelim(token::Brace);
3473 let cm = self.sess.codemap();
3474 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3475 .map_err(|mut err| {
3476 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3477 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3478 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3479 && expr_lines.lines.len() == 2
3480 && self.token == token::FatArrow => {
3481 // We check wether there's any trailing code in the parse span, if there
3482 // isn't, we very likely have the following:
3485 // | -- - missing comma
3491 // | parsed until here as `"y" & X`
3492 err.span_suggestion_short_with_applicability(
3493 cm.next_point(arm_start_span),
3494 "missing a comma here to end this `match` arm",
3496 Applicability::MachineApplicable
3500 err.span_label(arrow_span,
3501 "while parsing the `match` arm starting here");
3507 self.eat(&token::Comma);
3518 /// Parse an expression
3519 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3520 self.parse_expr_res(Restrictions::empty(), None)
3523 /// Evaluate the closure with restrictions in place.
3525 /// After the closure is evaluated, restrictions are reset.
3526 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3527 where F: FnOnce(&mut Self) -> T
3529 let old = self.restrictions;
3530 self.restrictions = r;
3532 self.restrictions = old;
3537 /// Parse an expression, subject to the given restrictions
3538 fn parse_expr_res(&mut self, r: Restrictions,
3539 already_parsed_attrs: Option<ThinVec<Attribute>>)
3540 -> PResult<'a, P<Expr>> {
3541 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3544 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3545 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3546 if self.check(&token::Eq) {
3548 Ok(Some(self.parse_expr()?))
3550 Ok(Some(self.parse_expr()?))
3556 /// Parse patterns, separated by '|' s
3557 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3558 let mut pats = Vec::new();
3560 pats.push(self.parse_top_level_pat()?);
3562 if self.token == token::OrOr {
3563 let mut err = self.struct_span_err(self.span,
3564 "unexpected token `||` after pattern");
3565 err.span_suggestion_with_applicability(
3567 "use a single `|` to specify multiple patterns",
3569 Applicability::MachineApplicable
3573 } else if self.check(&token::BinOp(token::Or)) {
3581 // Parses a parenthesized list of patterns like
3582 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3583 // - a vector of the patterns that were parsed
3584 // - an option indicating the index of the `..` element
3585 // - a boolean indicating whether a trailing comma was present.
3586 // Trailing commas are significant because (p) and (p,) are different patterns.
3587 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3588 self.expect(&token::OpenDelim(token::Paren))?;
3589 let result = self.parse_pat_list()?;
3590 self.expect(&token::CloseDelim(token::Paren))?;
3594 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3595 let mut fields = Vec::new();
3596 let mut ddpos = None;
3597 let mut trailing_comma = false;
3599 if self.eat(&token::DotDot) {
3600 if ddpos.is_none() {
3601 ddpos = Some(fields.len());
3603 // Emit a friendly error, ignore `..` and continue parsing
3604 self.span_err(self.prev_span,
3605 "`..` can only be used once per tuple or tuple struct pattern");
3607 } else if !self.check(&token::CloseDelim(token::Paren)) {
3608 fields.push(self.parse_pat()?);
3613 trailing_comma = self.eat(&token::Comma);
3614 if !trailing_comma {
3619 if ddpos == Some(fields.len()) && trailing_comma {
3620 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3621 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3624 Ok((fields, ddpos, trailing_comma))
3627 fn parse_pat_vec_elements(
3629 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3630 let mut before = Vec::new();
3631 let mut slice = None;
3632 let mut after = Vec::new();
3633 let mut first = true;
3634 let mut before_slice = true;
3636 while self.token != token::CloseDelim(token::Bracket) {
3640 self.expect(&token::Comma)?;
3642 if self.token == token::CloseDelim(token::Bracket)
3643 && (before_slice || !after.is_empty()) {
3649 if self.eat(&token::DotDot) {
3651 if self.check(&token::Comma) ||
3652 self.check(&token::CloseDelim(token::Bracket)) {
3653 slice = Some(P(Pat {
3654 id: ast::DUMMY_NODE_ID,
3655 node: PatKind::Wild,
3656 span: self.prev_span,
3658 before_slice = false;
3664 let subpat = self.parse_pat()?;
3665 if before_slice && self.eat(&token::DotDot) {
3666 slice = Some(subpat);
3667 before_slice = false;
3668 } else if before_slice {
3669 before.push(subpat);
3675 Ok((before, slice, after))
3681 attrs: Vec<Attribute>
3682 ) -> PResult<'a, codemap::Spanned<ast::FieldPat>> {
3683 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3685 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3686 // Parsing a pattern of the form "fieldname: pat"
3687 let fieldname = self.parse_field_name()?;
3689 let pat = self.parse_pat()?;
3691 (pat, fieldname, false)
3693 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3694 let is_box = self.eat_keyword(keywords::Box);
3695 let boxed_span = self.span;
3696 let is_ref = self.eat_keyword(keywords::Ref);
3697 let is_mut = self.eat_keyword(keywords::Mut);
3698 let fieldname = self.parse_ident()?;
3699 hi = self.prev_span;
3701 let bind_type = match (is_ref, is_mut) {
3702 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3703 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3704 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3705 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3707 let fieldpat = P(Pat {
3708 id: ast::DUMMY_NODE_ID,
3709 node: PatKind::Ident(bind_type, fieldname, None),
3710 span: boxed_span.to(hi),
3713 let subpat = if is_box {
3715 id: ast::DUMMY_NODE_ID,
3716 node: PatKind::Box(fieldpat),
3722 (subpat, fieldname, true)
3725 Ok(codemap::Spanned {
3727 node: ast::FieldPat {
3731 attrs: attrs.into(),
3736 /// Parse the fields of a struct-like pattern
3737 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3738 let mut fields = Vec::new();
3739 let mut etc = false;
3740 let mut ate_comma = true;
3741 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3742 let mut etc_span = None;
3744 while self.token != token::CloseDelim(token::Brace) {
3745 let attrs = self.parse_outer_attributes()?;
3748 // check that a comma comes after every field
3750 let err = self.struct_span_err(self.prev_span, "expected `,`");
3755 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3757 let mut etc_sp = self.span;
3759 if self.token == token::DotDotDot { // Issue #46718
3760 // Accept `...` as if it were `..` to avoid further errors
3761 let mut err = self.struct_span_err(self.span,
3762 "expected field pattern, found `...`");
3763 err.span_suggestion_with_applicability(
3765 "to omit remaining fields, use one fewer `.`",
3767 Applicability::MachineApplicable
3771 self.bump(); // `..` || `...`:w
3773 if self.token == token::CloseDelim(token::Brace) {
3774 etc_span = Some(etc_sp);
3777 let token_str = self.this_token_to_string();
3778 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3780 err.span_label(self.span, "expected `}`");
3781 let mut comma_sp = None;
3782 if self.token == token::Comma { // Issue #49257
3783 etc_sp = etc_sp.to(self.sess.codemap().span_until_non_whitespace(self.span));
3784 err.span_label(etc_sp,
3785 "`..` must be at the end and cannot have a trailing comma");
3786 comma_sp = Some(self.span);
3791 etc_span = Some(etc_sp);
3792 if self.token == token::CloseDelim(token::Brace) {
3793 // If the struct looks otherwise well formed, recover and continue.
3794 if let Some(sp) = comma_sp {
3795 err.span_suggestion_short(sp, "remove this comma", "".into());
3799 } else if self.token.is_ident() && ate_comma {
3800 // Accept fields coming after `..,`.
3801 // This way we avoid "pattern missing fields" errors afterwards.
3802 // We delay this error until the end in order to have a span for a
3804 if let Some(mut delayed_err) = delayed_err {
3808 delayed_err = Some(err);
3811 if let Some(mut err) = delayed_err {
3818 fields.push(match self.parse_pat_field(lo, attrs) {
3821 if let Some(mut delayed_err) = delayed_err {
3827 ate_comma = self.eat(&token::Comma);
3830 if let Some(mut err) = delayed_err {
3831 if let Some(etc_span) = etc_span {
3832 err.multipart_suggestion(
3833 "move the `..` to the end of the field list",
3835 (etc_span, "".into()),
3836 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3842 return Ok((fields, etc));
3845 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3846 if self.token.is_path_start() {
3848 let (qself, path) = if self.eat_lt() {
3849 // Parse a qualified path
3850 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3853 // Parse an unqualified path
3854 (None, self.parse_path(PathStyle::Expr)?)
3856 let hi = self.prev_span;
3857 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3859 self.parse_literal_maybe_minus()
3863 // helper function to decide whether to parse as ident binding or to try to do
3864 // something more complex like range patterns
3865 fn parse_as_ident(&mut self) -> bool {
3866 self.look_ahead(1, |t| match *t {
3867 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3868 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3869 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3870 // range pattern branch
3871 token::DotDot => None,
3873 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3874 token::Comma | token::CloseDelim(token::Bracket) => true,
3879 /// A wrapper around `parse_pat` with some special error handling for the
3880 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contast
3881 /// to subpatterns within such).
3882 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3883 let pat = self.parse_pat()?;
3884 if self.token == token::Comma {
3885 // An unexpected comma after a top-level pattern is a clue that the
3886 // user (perhaps more accustomed to some other language) forgot the
3887 // parentheses in what should have been a tuple pattern; return a
3888 // suggestion-enhanced error here rather than choking on the comma
3890 let comma_span = self.span;
3892 if let Err(mut err) = self.parse_pat_list() {
3893 // We didn't expect this to work anyway; we just wanted
3894 // to advance to the end of the comma-sequence so we know
3895 // the span to suggest parenthesizing
3898 let seq_span = pat.span.to(self.prev_span);
3899 let mut err = self.struct_span_err(comma_span,
3900 "unexpected `,` in pattern");
3901 if let Ok(seq_snippet) = self.sess.codemap().span_to_snippet(seq_span) {
3902 err.span_suggestion_with_applicability(
3904 "try adding parentheses",
3905 format!("({})", seq_snippet),
3906 Applicability::MachineApplicable
3914 /// Parse a pattern.
3915 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3916 self.parse_pat_with_range_pat(true)
3919 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3921 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3922 maybe_whole!(self, NtPat, |x| x);
3927 token::BinOp(token::And) | token::AndAnd => {
3928 // Parse &pat / &mut pat
3930 let mutbl = self.parse_mutability();
3931 if let token::Lifetime(ident) = self.token {
3932 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3934 err.span_label(self.span, "unexpected lifetime");
3937 let subpat = self.parse_pat_with_range_pat(false)?;
3938 pat = PatKind::Ref(subpat, mutbl);
3940 token::OpenDelim(token::Paren) => {
3941 // Parse (pat,pat,pat,...) as tuple pattern
3942 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3943 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3944 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3946 PatKind::Tuple(fields, ddpos)
3949 token::OpenDelim(token::Bracket) => {
3950 // Parse [pat,pat,...] as slice pattern
3952 let (before, slice, after) = self.parse_pat_vec_elements()?;
3953 self.expect(&token::CloseDelim(token::Bracket))?;
3954 pat = PatKind::Slice(before, slice, after);
3956 // At this point, token != &, &&, (, [
3957 _ => if self.eat_keyword(keywords::Underscore) {
3959 pat = PatKind::Wild;
3960 } else if self.eat_keyword(keywords::Mut) {
3961 // Parse mut ident @ pat / mut ref ident @ pat
3962 let mutref_span = self.prev_span.to(self.span);
3963 let binding_mode = if self.eat_keyword(keywords::Ref) {
3965 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3966 .span_suggestion_with_applicability(
3968 "try switching the order",
3970 Applicability::MachineApplicable
3972 BindingMode::ByRef(Mutability::Mutable)
3974 BindingMode::ByValue(Mutability::Mutable)
3976 pat = self.parse_pat_ident(binding_mode)?;
3977 } else if self.eat_keyword(keywords::Ref) {
3978 // Parse ref ident @ pat / ref mut ident @ pat
3979 let mutbl = self.parse_mutability();
3980 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3981 } else if self.eat_keyword(keywords::Box) {
3983 let subpat = self.parse_pat_with_range_pat(false)?;
3984 pat = PatKind::Box(subpat);
3985 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3986 self.parse_as_ident() {
3987 // Parse ident @ pat
3988 // This can give false positives and parse nullary enums,
3989 // they are dealt with later in resolve
3990 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3991 pat = self.parse_pat_ident(binding_mode)?;
3992 } else if self.token.is_path_start() {
3993 // Parse pattern starting with a path
3994 let (qself, path) = if self.eat_lt() {
3995 // Parse a qualified path
3996 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3999 // Parse an unqualified path
4000 (None, self.parse_path(PathStyle::Expr)?)
4003 token::Not if qself.is_none() => {
4004 // Parse macro invocation
4006 let (delim, tts) = self.expect_delimited_token_tree()?;
4007 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4008 pat = PatKind::Mac(mac);
4010 token::DotDotDot | token::DotDotEq | token::DotDot => {
4011 let end_kind = match self.token {
4012 token::DotDot => RangeEnd::Excluded,
4013 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4014 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4015 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4019 let span = lo.to(self.prev_span);
4020 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4022 let end = self.parse_pat_range_end()?;
4023 pat = PatKind::Range(begin, end, end_kind);
4025 token::OpenDelim(token::Brace) => {
4026 if qself.is_some() {
4027 let msg = "unexpected `{` after qualified path";
4028 let mut err = self.fatal(msg);
4029 err.span_label(self.span, msg);
4032 // Parse struct pattern
4034 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4036 self.recover_stmt();
4040 pat = PatKind::Struct(path, fields, etc);
4042 token::OpenDelim(token::Paren) => {
4043 if qself.is_some() {
4044 let msg = "unexpected `(` after qualified path";
4045 let mut err = self.fatal(msg);
4046 err.span_label(self.span, msg);
4049 // Parse tuple struct or enum pattern
4050 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4051 pat = PatKind::TupleStruct(path, fields, ddpos)
4053 _ => pat = PatKind::Path(qself, path),
4056 // Try to parse everything else as literal with optional minus
4057 match self.parse_literal_maybe_minus() {
4059 if self.eat(&token::DotDotDot) {
4060 let end = self.parse_pat_range_end()?;
4061 pat = PatKind::Range(begin, end,
4062 RangeEnd::Included(RangeSyntax::DotDotDot));
4063 } else if self.eat(&token::DotDotEq) {
4064 let end = self.parse_pat_range_end()?;
4065 pat = PatKind::Range(begin, end,
4066 RangeEnd::Included(RangeSyntax::DotDotEq));
4067 } else if self.eat(&token::DotDot) {
4068 let end = self.parse_pat_range_end()?;
4069 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
4071 pat = PatKind::Lit(begin);
4075 self.cancel(&mut err);
4076 let msg = format!("expected pattern, found {}", self.this_token_descr());
4077 let mut err = self.fatal(&msg);
4078 err.span_label(self.span, "expected pattern");
4085 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4086 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4088 if !allow_range_pat {
4090 PatKind::Range(_, _, RangeEnd::Included(RangeSyntax::DotDotDot)) => {}
4091 PatKind::Range(..) => {
4092 let mut err = self.struct_span_err(
4094 "the range pattern here has ambiguous interpretation",
4096 err.span_suggestion_with_applicability(
4098 "add parentheses to clarify the precedence",
4099 format!("({})", pprust::pat_to_string(&pat)),
4100 // "ambiguous interpretation" implies that we have to be guessing
4101 Applicability::MaybeIncorrect
4112 /// Parse ident or ident @ pat
4113 /// used by the copy foo and ref foo patterns to give a good
4114 /// error message when parsing mistakes like ref foo(a,b)
4115 fn parse_pat_ident(&mut self,
4116 binding_mode: ast::BindingMode)
4117 -> PResult<'a, PatKind> {
4118 let ident = self.parse_ident()?;
4119 let sub = if self.eat(&token::At) {
4120 Some(self.parse_pat()?)
4125 // just to be friendly, if they write something like
4127 // we end up here with ( as the current token. This shortly
4128 // leads to a parse error. Note that if there is no explicit
4129 // binding mode then we do not end up here, because the lookahead
4130 // will direct us over to parse_enum_variant()
4131 if self.token == token::OpenDelim(token::Paren) {
4132 return Err(self.span_fatal(
4134 "expected identifier, found enum pattern"))
4137 Ok(PatKind::Ident(binding_mode, ident, sub))
4140 /// Parse a local variable declaration
4141 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4142 let lo = self.prev_span;
4143 let pat = self.parse_top_level_pat()?;
4145 let (err, ty) = if self.eat(&token::Colon) {
4146 // Save the state of the parser before parsing type normally, in case there is a `:`
4147 // instead of an `=` typo.
4148 let parser_snapshot_before_type = self.clone();
4149 let colon_sp = self.prev_span;
4150 match self.parse_ty() {
4151 Ok(ty) => (None, Some(ty)),
4153 // Rewind to before attempting to parse the type and continue parsing
4154 let parser_snapshot_after_type = self.clone();
4155 mem::replace(self, parser_snapshot_before_type);
4157 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
4158 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4159 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4165 let init = match (self.parse_initializer(err.is_some()), err) {
4166 (Ok(init), None) => { // init parsed, ty parsed
4169 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4170 // Could parse the type as if it were the initializer, it is likely there was a
4171 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4172 err.span_suggestion_short_with_applicability(
4174 "use `=` if you meant to assign",
4176 Applicability::MachineApplicable
4179 // As this was parsed successfully, continue as if the code has been fixed for the
4180 // rest of the file. It will still fail due to the emitted error, but we avoid
4184 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4186 // Couldn't parse the type nor the initializer, only raise the type error and
4187 // return to the parser state before parsing the type as the initializer.
4188 // let x: <parse_error>;
4189 mem::replace(self, snapshot);
4192 (Err(err), None) => { // init error, ty parsed
4193 // Couldn't parse the initializer and we're not attempting to recover a failed
4194 // parse of the type, return the error.
4198 let hi = if self.token == token::Semi {
4207 id: ast::DUMMY_NODE_ID,
4213 /// Parse a structure field
4214 fn parse_name_and_ty(&mut self,
4217 attrs: Vec<Attribute>)
4218 -> PResult<'a, StructField> {
4219 let name = self.parse_ident()?;
4220 self.expect(&token::Colon)?;
4221 let ty = self.parse_ty()?;
4223 span: lo.to(self.prev_span),
4226 id: ast::DUMMY_NODE_ID,
4232 /// Emit an expected item after attributes error.
4233 fn expected_item_err(&self, attrs: &[Attribute]) {
4234 let message = match attrs.last() {
4235 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4236 _ => "expected item after attributes",
4239 self.span_err(self.prev_span, message);
4242 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4243 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4244 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4245 Ok(self.parse_stmt_(true))
4248 // Eat tokens until we can be relatively sure we reached the end of the
4249 // statement. This is something of a best-effort heuristic.
4251 // We terminate when we find an unmatched `}` (without consuming it).
4252 fn recover_stmt(&mut self) {
4253 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4256 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4257 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4258 // approximate - it can mean we break too early due to macros, but that
4259 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4261 // If `break_on_block` is `Break`, then we will stop consuming tokens
4262 // after finding (and consuming) a brace-delimited block.
4263 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4264 let mut brace_depth = 0;
4265 let mut bracket_depth = 0;
4266 let mut in_block = false;
4267 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4268 break_on_semi, break_on_block);
4270 debug!("recover_stmt_ loop {:?}", self.token);
4272 token::OpenDelim(token::DelimToken::Brace) => {
4275 if break_on_block == BlockMode::Break &&
4277 bracket_depth == 0 {
4281 token::OpenDelim(token::DelimToken::Bracket) => {
4285 token::CloseDelim(token::DelimToken::Brace) => {
4286 if brace_depth == 0 {
4287 debug!("recover_stmt_ return - close delim {:?}", self.token);
4292 if in_block && bracket_depth == 0 && brace_depth == 0 {
4293 debug!("recover_stmt_ return - block end {:?}", self.token);
4297 token::CloseDelim(token::DelimToken::Bracket) => {
4299 if bracket_depth < 0 {
4305 debug!("recover_stmt_ return - Eof");
4310 if break_on_semi == SemiColonMode::Break &&
4312 bracket_depth == 0 {
4313 debug!("recover_stmt_ return - Semi");
4324 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4325 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4327 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4332 fn is_async_block(&mut self) -> bool {
4333 self.token.is_keyword(keywords::Async) &&
4336 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4337 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4339 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4344 fn is_catch_expr(&mut self) -> bool {
4345 self.token.is_keyword(keywords::Do) &&
4346 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4347 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4349 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4350 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4353 fn is_union_item(&self) -> bool {
4354 self.token.is_keyword(keywords::Union) &&
4355 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4358 fn is_crate_vis(&self) -> bool {
4359 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4362 fn is_extern_non_path(&self) -> bool {
4363 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4366 fn is_auto_trait_item(&mut self) -> bool {
4368 (self.token.is_keyword(keywords::Auto)
4369 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4370 || // unsafe auto trait
4371 (self.token.is_keyword(keywords::Unsafe) &&
4372 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4373 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4376 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4377 -> PResult<'a, Option<P<Item>>> {
4378 let token_lo = self.span;
4379 let (ident, def) = match self.token {
4380 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4382 let ident = self.parse_ident()?;
4383 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4384 match self.parse_token_tree() {
4385 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4386 _ => unreachable!(),
4388 } else if self.check(&token::OpenDelim(token::Paren)) {
4389 let args = self.parse_token_tree();
4390 let body = if self.check(&token::OpenDelim(token::Brace)) {
4391 self.parse_token_tree()
4396 TokenStream::concat(vec![
4398 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4406 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4408 token::Ident(ident, _) if ident.name == "macro_rules" &&
4409 self.look_ahead(1, |t| *t == token::Not) => {
4410 let prev_span = self.prev_span;
4411 self.complain_if_pub_macro(&vis.node, prev_span);
4415 let ident = self.parse_ident()?;
4416 let (delim, tokens) = self.expect_delimited_token_tree()?;
4417 if delim != MacDelimiter::Brace {
4418 if !self.eat(&token::Semi) {
4419 let msg = "macros that expand to items must either \
4420 be surrounded with braces or followed by a semicolon";
4421 self.span_err(self.prev_span, msg);
4425 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4427 _ => return Ok(None),
4430 let span = lo.to(self.prev_span);
4431 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4434 fn parse_stmt_without_recovery(&mut self,
4435 macro_legacy_warnings: bool)
4436 -> PResult<'a, Option<Stmt>> {
4437 maybe_whole!(self, NtStmt, |x| Some(x));
4439 let attrs = self.parse_outer_attributes()?;
4442 Ok(Some(if self.eat_keyword(keywords::Let) {
4444 id: ast::DUMMY_NODE_ID,
4445 node: StmtKind::Local(self.parse_local(attrs.into())?),
4446 span: lo.to(self.prev_span),
4448 } else if let Some(macro_def) = self.eat_macro_def(
4450 &codemap::respan(lo, VisibilityKind::Inherited),
4454 id: ast::DUMMY_NODE_ID,
4455 node: StmtKind::Item(macro_def),
4456 span: lo.to(self.prev_span),
4458 // Starts like a simple path, being careful to avoid contextual keywords
4459 // such as a union items, item with `crate` visibility or auto trait items.
4460 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4461 // like a path (1 token), but it fact not a path.
4462 // `union::b::c` - path, `union U { ... }` - not a path.
4463 // `crate::b::c` - path, `crate struct S;` - not a path.
4464 // `extern::b::c` - path, `extern crate c;` - not a path.
4465 } else if self.token.is_path_start() &&
4466 !self.token.is_qpath_start() &&
4467 !self.is_union_item() &&
4468 !self.is_crate_vis() &&
4469 !self.is_extern_non_path() &&
4470 !self.is_auto_trait_item() {
4471 let pth = self.parse_path(PathStyle::Expr)?;
4473 if !self.eat(&token::Not) {
4474 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4475 self.parse_struct_expr(lo, pth, ThinVec::new())?
4477 let hi = self.prev_span;
4478 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4481 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4482 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4483 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4486 return Ok(Some(Stmt {
4487 id: ast::DUMMY_NODE_ID,
4488 node: StmtKind::Expr(expr),
4489 span: lo.to(self.prev_span),
4493 // it's a macro invocation
4494 let id = match self.token {
4495 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4496 _ => self.parse_ident()?,
4499 // check that we're pointing at delimiters (need to check
4500 // again after the `if`, because of `parse_ident`
4501 // consuming more tokens).
4503 token::OpenDelim(_) => {}
4505 // we only expect an ident if we didn't parse one
4507 let ident_str = if id.name == keywords::Invalid.name() {
4512 let tok_str = self.this_token_to_string();
4513 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4516 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4521 let (delim, tts) = self.expect_delimited_token_tree()?;
4522 let hi = self.prev_span;
4524 let style = if delim == MacDelimiter::Brace {
4525 MacStmtStyle::Braces
4527 MacStmtStyle::NoBraces
4530 if id.name == keywords::Invalid.name() {
4531 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4532 let node = if delim == MacDelimiter::Brace ||
4533 self.token == token::Semi || self.token == token::Eof {
4534 StmtKind::Mac(P((mac, style, attrs.into())))
4536 // We used to incorrectly stop parsing macro-expanded statements here.
4537 // If the next token will be an error anyway but could have parsed with the
4538 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4539 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4540 // These can continue an expression, so we can't stop parsing and warn.
4541 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4542 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4543 token::BinOp(token::And) | token::BinOp(token::Or) |
4544 token::AndAnd | token::OrOr |
4545 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4548 self.warn_missing_semicolon();
4549 StmtKind::Mac(P((mac, style, attrs.into())))
4551 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4552 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4553 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4557 id: ast::DUMMY_NODE_ID,
4562 // if it has a special ident, it's definitely an item
4564 // Require a semicolon or braces.
4565 if style != MacStmtStyle::Braces {
4566 if !self.eat(&token::Semi) {
4567 self.span_err(self.prev_span,
4568 "macros that expand to items must \
4569 either be surrounded with braces or \
4570 followed by a semicolon");
4573 let span = lo.to(hi);
4575 id: ast::DUMMY_NODE_ID,
4577 node: StmtKind::Item({
4579 span, id /*id is good here*/,
4580 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4581 respan(lo, VisibilityKind::Inherited),
4587 // FIXME: Bad copy of attrs
4588 let old_directory_ownership =
4589 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4590 let item = self.parse_item_(attrs.clone(), false, true)?;
4591 self.directory.ownership = old_directory_ownership;
4595 id: ast::DUMMY_NODE_ID,
4596 span: lo.to(i.span),
4597 node: StmtKind::Item(i),
4600 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4601 if !attrs.is_empty() {
4602 if s.prev_token_kind == PrevTokenKind::DocComment {
4603 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4604 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4605 s.span_err(s.span, "expected statement after outer attribute");
4610 // Do not attempt to parse an expression if we're done here.
4611 if self.token == token::Semi {
4612 unused_attrs(&attrs, self);
4617 if self.token == token::CloseDelim(token::Brace) {
4618 unused_attrs(&attrs, self);
4622 // Remainder are line-expr stmts.
4623 let e = self.parse_expr_res(
4624 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4626 id: ast::DUMMY_NODE_ID,
4627 span: lo.to(e.span),
4628 node: StmtKind::Expr(e),
4635 /// Is this expression a successfully-parsed statement?
4636 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4637 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4638 !classify::expr_requires_semi_to_be_stmt(e)
4641 /// Parse a block. No inner attrs are allowed.
4642 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4643 maybe_whole!(self, NtBlock, |x| x);
4647 if !self.eat(&token::OpenDelim(token::Brace)) {
4649 let tok = self.this_token_to_string();
4650 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4652 // Check to see if the user has written something like
4657 // Which is valid in other languages, but not Rust.
4658 match self.parse_stmt_without_recovery(false) {
4660 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) {
4661 // if the next token is an open brace (e.g., `if a b {`), the place-
4662 // inside-a-block suggestion would be more likely wrong than right
4665 let mut stmt_span = stmt.span;
4666 // expand the span to include the semicolon, if it exists
4667 if self.eat(&token::Semi) {
4668 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4670 let sugg = pprust::to_string(|s| {
4671 use print::pprust::{PrintState, INDENT_UNIT};
4672 s.ibox(INDENT_UNIT)?;
4674 s.print_stmt(&stmt)?;
4675 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4677 e.span_suggestion_with_applicability(
4679 "try placing this code inside a block",
4681 // speculative, has been misleading in the past (closed Issue #46836)
4682 Applicability::MaybeIncorrect
4686 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4687 self.cancel(&mut e);
4694 self.parse_block_tail(lo, BlockCheckMode::Default)
4697 /// Parse a block. Inner attrs are allowed.
4698 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4699 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4702 self.expect(&token::OpenDelim(token::Brace))?;
4703 Ok((self.parse_inner_attributes()?,
4704 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4707 /// Parse the rest of a block expression or function body
4708 /// Precondition: already parsed the '{'.
4709 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4710 let mut stmts = vec![];
4711 let mut recovered = false;
4713 while !self.eat(&token::CloseDelim(token::Brace)) {
4714 let stmt = match self.parse_full_stmt(false) {
4717 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4718 self.eat(&token::CloseDelim(token::Brace));
4724 if let Some(stmt) = stmt {
4726 } else if self.token == token::Eof {
4729 // Found only `;` or `}`.
4735 id: ast::DUMMY_NODE_ID,
4737 span: lo.to(self.prev_span),
4742 /// Parse a statement, including the trailing semicolon.
4743 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4744 // skip looking for a trailing semicolon when we have an interpolated statement
4745 maybe_whole!(self, NtStmt, |x| Some(x));
4747 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4749 None => return Ok(None),
4753 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4754 // expression without semicolon
4755 if classify::expr_requires_semi_to_be_stmt(expr) {
4756 // Just check for errors and recover; do not eat semicolon yet.
4758 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4761 self.recover_stmt();
4765 StmtKind::Local(..) => {
4766 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4767 if macro_legacy_warnings && self.token != token::Semi {
4768 self.warn_missing_semicolon();
4770 self.expect_one_of(&[token::Semi], &[])?;
4776 if self.eat(&token::Semi) {
4777 stmt = stmt.add_trailing_semicolon();
4780 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4784 fn warn_missing_semicolon(&self) {
4785 self.diagnostic().struct_span_warn(self.span, {
4786 &format!("expected `;`, found `{}`", self.this_token_to_string())
4788 "This was erroneously allowed and will become a hard error in a future release"
4792 fn err_dotdotdot_syntax(&self, span: Span) {
4793 self.diagnostic().struct_span_err(span, {
4794 "`...` syntax cannot be used in expressions"
4796 "Use `..` if you need an exclusive range (a < b)"
4798 "or `..=` if you need an inclusive range (a <= b)"
4802 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4803 // BOUND = TY_BOUND | LT_BOUND
4804 // LT_BOUND = LIFETIME (e.g. `'a`)
4805 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4806 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4807 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4808 let mut bounds = Vec::new();
4810 // This needs to be syncronized with `Token::can_begin_bound`.
4811 let is_bound_start = self.check_path() || self.check_lifetime() ||
4812 self.check(&token::Question) ||
4813 self.check_keyword(keywords::For) ||
4814 self.check(&token::OpenDelim(token::Paren));
4817 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4818 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4819 if self.token.is_lifetime() {
4820 if let Some(question_span) = question {
4821 self.span_err(question_span,
4822 "`?` may only modify trait bounds, not lifetime bounds");
4824 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4826 self.expect(&token::CloseDelim(token::Paren))?;
4827 self.span_err(self.prev_span,
4828 "parenthesized lifetime bounds are not supported");
4831 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4832 let path = self.parse_path(PathStyle::Type)?;
4834 self.expect(&token::CloseDelim(token::Paren))?;
4836 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4837 let modifier = if question.is_some() {
4838 TraitBoundModifier::Maybe
4840 TraitBoundModifier::None
4842 bounds.push(GenericBound::Trait(poly_trait, modifier));
4848 if !allow_plus || !self.eat_plus() {
4856 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
4857 self.parse_generic_bounds_common(true)
4860 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4861 // BOUND = LT_BOUND (e.g. `'a`)
4862 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4863 let mut lifetimes = Vec::new();
4864 while self.check_lifetime() {
4865 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4867 if !self.eat_plus() {
4874 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4875 fn parse_ty_param(&mut self,
4876 preceding_attrs: Vec<Attribute>)
4877 -> PResult<'a, GenericParam> {
4878 let ident = self.parse_ident()?;
4880 // Parse optional colon and param bounds.
4881 let bounds = if self.eat(&token::Colon) {
4882 self.parse_generic_bounds()?
4887 let default = if self.eat(&token::Eq) {
4888 Some(self.parse_ty()?)
4895 id: ast::DUMMY_NODE_ID,
4896 attrs: preceding_attrs.into(),
4898 kind: GenericParamKind::Type {
4904 /// Parses the following grammar:
4905 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4906 fn parse_trait_item_assoc_ty(&mut self)
4907 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4908 let ident = self.parse_ident()?;
4909 let mut generics = self.parse_generics()?;
4911 // Parse optional colon and param bounds.
4912 let bounds = if self.eat(&token::Colon) {
4913 self.parse_generic_bounds()?
4917 generics.where_clause = self.parse_where_clause()?;
4919 let default = if self.eat(&token::Eq) {
4920 Some(self.parse_ty()?)
4924 self.expect(&token::Semi)?;
4926 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4929 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4930 /// trailing comma and erroneous trailing attributes.
4931 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4932 let mut params = Vec::new();
4933 let mut seen_ty_param = false;
4935 let attrs = self.parse_outer_attributes()?;
4936 if self.check_lifetime() {
4937 let lifetime = self.expect_lifetime();
4938 // Parse lifetime parameter.
4939 let bounds = if self.eat(&token::Colon) {
4940 self.parse_lt_param_bounds()
4944 params.push(ast::GenericParam {
4945 ident: lifetime.ident,
4947 attrs: attrs.into(),
4949 kind: ast::GenericParamKind::Lifetime,
4952 self.span_err(self.prev_span,
4953 "lifetime parameters must be declared prior to type parameters");
4955 } else if self.check_ident() {
4956 // Parse type parameter.
4957 params.push(self.parse_ty_param(attrs)?);
4958 seen_ty_param = true;
4960 // Check for trailing attributes and stop parsing.
4961 if !attrs.is_empty() {
4962 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4963 self.span_err(attrs[0].span,
4964 &format!("trailing attribute after {} parameters", param_kind));
4969 if !self.eat(&token::Comma) {
4976 /// Parse a set of optional generic type parameter declarations. Where
4977 /// clauses are not parsed here, and must be added later via
4978 /// `parse_where_clause()`.
4980 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4981 /// | ( < lifetimes , typaramseq ( , )? > )
4982 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4983 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4984 maybe_whole!(self, NtGenerics, |x| x);
4986 let span_lo = self.span;
4988 let params = self.parse_generic_params()?;
4992 where_clause: WhereClause {
4993 id: ast::DUMMY_NODE_ID,
4994 predicates: Vec::new(),
4995 span: syntax_pos::DUMMY_SP,
4997 span: span_lo.to(self.prev_span),
5000 Ok(ast::Generics::default())
5004 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5005 /// possibly including trailing comma.
5006 fn parse_generic_args(&mut self)
5007 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5008 let mut args = Vec::new();
5009 let mut bindings = Vec::new();
5010 let mut seen_type = false;
5011 let mut seen_binding = false;
5013 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5014 // Parse lifetime argument.
5015 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5016 if seen_type || seen_binding {
5017 self.span_err(self.prev_span,
5018 "lifetime parameters must be declared prior to type parameters");
5020 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5021 // Parse associated type binding.
5023 let ident = self.parse_ident()?;
5025 let ty = self.parse_ty()?;
5026 bindings.push(TypeBinding {
5027 id: ast::DUMMY_NODE_ID,
5030 span: lo.to(self.prev_span),
5032 seen_binding = true;
5033 } else if self.check_type() {
5034 // Parse type argument.
5035 let ty_param = self.parse_ty()?;
5037 self.span_err(ty_param.span,
5038 "type parameters must be declared prior to associated type bindings");
5040 args.push(GenericArg::Type(ty_param));
5046 if !self.eat(&token::Comma) {
5050 Ok((args, bindings))
5053 /// Parses an optional `where` clause and places it in `generics`.
5055 /// ```ignore (only-for-syntax-highlight)
5056 /// where T : Trait<U, V> + 'b, 'a : 'b
5058 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5059 maybe_whole!(self, NtWhereClause, |x| x);
5061 let mut where_clause = WhereClause {
5062 id: ast::DUMMY_NODE_ID,
5063 predicates: Vec::new(),
5064 span: syntax_pos::DUMMY_SP,
5067 if !self.eat_keyword(keywords::Where) {
5068 return Ok(where_clause);
5070 let lo = self.prev_span;
5072 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5073 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5074 // change we parse those generics now, but report an error.
5075 if self.choose_generics_over_qpath() {
5076 let generics = self.parse_generics()?;
5077 self.span_err(generics.span,
5078 "generic parameters on `where` clauses are reserved for future use");
5083 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5084 let lifetime = self.expect_lifetime();
5085 // Bounds starting with a colon are mandatory, but possibly empty.
5086 self.expect(&token::Colon)?;
5087 let bounds = self.parse_lt_param_bounds();
5088 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5089 ast::WhereRegionPredicate {
5090 span: lo.to(self.prev_span),
5095 } else if self.check_type() {
5096 // Parse optional `for<'a, 'b>`.
5097 // This `for` is parsed greedily and applies to the whole predicate,
5098 // the bounded type can have its own `for` applying only to it.
5099 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5100 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5101 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5102 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5104 // Parse type with mandatory colon and (possibly empty) bounds,
5105 // or with mandatory equality sign and the second type.
5106 let ty = self.parse_ty()?;
5107 if self.eat(&token::Colon) {
5108 let bounds = self.parse_generic_bounds()?;
5109 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5110 ast::WhereBoundPredicate {
5111 span: lo.to(self.prev_span),
5112 bound_generic_params: lifetime_defs,
5117 // FIXME: Decide what should be used here, `=` or `==`.
5118 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5119 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5120 let rhs_ty = self.parse_ty()?;
5121 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5122 ast::WhereEqPredicate {
5123 span: lo.to(self.prev_span),
5126 id: ast::DUMMY_NODE_ID,
5130 return self.unexpected();
5136 if !self.eat(&token::Comma) {
5141 where_clause.span = lo.to(self.prev_span);
5145 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5146 -> PResult<'a, (Vec<Arg> , bool)> {
5148 let mut variadic = false;
5149 let args: Vec<Option<Arg>> =
5150 self.parse_unspanned_seq(
5151 &token::OpenDelim(token::Paren),
5152 &token::CloseDelim(token::Paren),
5153 SeqSep::trailing_allowed(token::Comma),
5155 if p.token == token::DotDotDot {
5159 if p.token != token::CloseDelim(token::Paren) {
5162 "`...` must be last in argument list for variadic function");
5166 let span = p.prev_span;
5167 if p.token == token::CloseDelim(token::Paren) {
5168 // continue parsing to present any further errors
5171 "only foreign functions are allowed to be variadic"
5173 Ok(Some(dummy_arg(span)))
5175 // this function definition looks beyond recovery, stop parsing
5177 "only foreign functions are allowed to be variadic");
5182 match p.parse_arg_general(named_args) {
5183 Ok(arg) => Ok(Some(arg)),
5186 let lo = p.prev_span;
5187 // Skip every token until next possible arg or end.
5188 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5189 // Create a placeholder argument for proper arg count (#34264).
5190 let span = lo.to(p.prev_span);
5191 Ok(Some(dummy_arg(span)))
5198 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5200 if variadic && args.is_empty() {
5202 "variadic function must be declared with at least one named argument");
5205 Ok((args, variadic))
5208 /// Parse the argument list and result type of a function declaration
5209 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5211 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5212 let ret_ty = self.parse_ret_ty(true)?;
5221 /// Returns the parsed optional self argument and whether a self shortcut was used.
5222 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5223 let expect_ident = |this: &mut Self| match this.token {
5224 // Preserve hygienic context.
5225 token::Ident(ident, _) =>
5226 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5229 let isolated_self = |this: &mut Self, n| {
5230 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5231 this.look_ahead(n + 1, |t| t != &token::ModSep)
5234 // Parse optional self parameter of a method.
5235 // Only a limited set of initial token sequences is considered self parameters, anything
5236 // else is parsed as a normal function parameter list, so some lookahead is required.
5237 let eself_lo = self.span;
5238 let (eself, eself_ident, eself_hi) = match self.token {
5239 token::BinOp(token::And) => {
5245 (if isolated_self(self, 1) {
5247 SelfKind::Region(None, Mutability::Immutable)
5248 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5249 isolated_self(self, 2) {
5252 SelfKind::Region(None, Mutability::Mutable)
5253 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5254 isolated_self(self, 2) {
5256 let lt = self.expect_lifetime();
5257 SelfKind::Region(Some(lt), Mutability::Immutable)
5258 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5259 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5260 isolated_self(self, 3) {
5262 let lt = self.expect_lifetime();
5264 SelfKind::Region(Some(lt), Mutability::Mutable)
5267 }, expect_ident(self), self.prev_span)
5269 token::BinOp(token::Star) => {
5274 // Emit special error for `self` cases.
5275 (if isolated_self(self, 1) {
5277 self.span_err(self.span, "cannot pass `self` by raw pointer");
5278 SelfKind::Value(Mutability::Immutable)
5279 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5280 isolated_self(self, 2) {
5283 self.span_err(self.span, "cannot pass `self` by raw pointer");
5284 SelfKind::Value(Mutability::Immutable)
5287 }, expect_ident(self), self.prev_span)
5289 token::Ident(..) => {
5290 if isolated_self(self, 0) {
5293 let eself_ident = expect_ident(self);
5294 let eself_hi = self.prev_span;
5295 (if self.eat(&token::Colon) {
5296 let ty = self.parse_ty()?;
5297 SelfKind::Explicit(ty, Mutability::Immutable)
5299 SelfKind::Value(Mutability::Immutable)
5300 }, eself_ident, eself_hi)
5301 } else if self.token.is_keyword(keywords::Mut) &&
5302 isolated_self(self, 1) {
5306 let eself_ident = expect_ident(self);
5307 let eself_hi = self.prev_span;
5308 (if self.eat(&token::Colon) {
5309 let ty = self.parse_ty()?;
5310 SelfKind::Explicit(ty, Mutability::Mutable)
5312 SelfKind::Value(Mutability::Mutable)
5313 }, eself_ident, eself_hi)
5318 _ => return Ok(None),
5321 let eself = codemap::respan(eself_lo.to(eself_hi), eself);
5322 Ok(Some(Arg::from_self(eself, eself_ident)))
5325 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5326 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5327 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5329 self.expect(&token::OpenDelim(token::Paren))?;
5331 // Parse optional self argument
5332 let self_arg = self.parse_self_arg()?;
5334 // Parse the rest of the function parameter list.
5335 let sep = SeqSep::trailing_allowed(token::Comma);
5336 let fn_inputs = if let Some(self_arg) = self_arg {
5337 if self.check(&token::CloseDelim(token::Paren)) {
5339 } else if self.eat(&token::Comma) {
5340 let mut fn_inputs = vec![self_arg];
5341 fn_inputs.append(&mut self.parse_seq_to_before_end(
5342 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5346 return self.unexpected();
5349 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5352 // Parse closing paren and return type.
5353 self.expect(&token::CloseDelim(token::Paren))?;
5356 output: self.parse_ret_ty(true)?,
5361 // parse the |arg, arg| header on a lambda
5362 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5363 let inputs_captures = {
5364 if self.eat(&token::OrOr) {
5367 self.expect(&token::BinOp(token::Or))?;
5368 let args = self.parse_seq_to_before_tokens(
5369 &[&token::BinOp(token::Or), &token::OrOr],
5370 SeqSep::trailing_allowed(token::Comma),
5371 TokenExpectType::NoExpect,
5372 |p| p.parse_fn_block_arg()
5378 let output = self.parse_ret_ty(true)?;
5381 inputs: inputs_captures,
5387 /// Parse the name and optional generic types of a function header.
5388 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5389 let id = self.parse_ident()?;
5390 let generics = self.parse_generics()?;
5394 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5395 attrs: Vec<Attribute>) -> P<Item> {
5399 id: ast::DUMMY_NODE_ID,
5407 /// Parse an item-position function declaration.
5408 fn parse_item_fn(&mut self,
5411 constness: Spanned<Constness>,
5413 -> PResult<'a, ItemInfo> {
5414 let (ident, mut generics) = self.parse_fn_header()?;
5415 let decl = self.parse_fn_decl(false)?;
5416 generics.where_clause = self.parse_where_clause()?;
5417 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5418 let header = FnHeader { unsafety, asyncness, constness, abi };
5419 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5422 /// true if we are looking at `const ID`, false for things like `const fn` etc
5423 fn is_const_item(&mut self) -> bool {
5424 self.token.is_keyword(keywords::Const) &&
5425 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5426 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5429 /// parses all the "front matter" for a `fn` declaration, up to
5430 /// and including the `fn` keyword:
5434 /// - `const unsafe fn`
5437 fn parse_fn_front_matter(&mut self)
5445 let is_const_fn = self.eat_keyword(keywords::Const);
5446 let const_span = self.prev_span;
5447 let unsafety = self.parse_unsafety();
5448 let asyncness = self.parse_asyncness();
5449 let (constness, unsafety, abi) = if is_const_fn {
5450 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5452 let abi = if self.eat_keyword(keywords::Extern) {
5453 self.parse_opt_abi()?.unwrap_or(Abi::C)
5457 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5459 self.expect_keyword(keywords::Fn)?;
5460 Ok((constness, unsafety, asyncness, abi))
5463 /// Parse an impl item.
5464 crate fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5465 maybe_whole!(self, NtImplItem, |x| x);
5466 let attrs = self.parse_outer_attributes()?;
5467 let (mut item, tokens) = self.collect_tokens(|this| {
5468 this.parse_impl_item_(at_end, attrs)
5471 // See `parse_item` for why this clause is here.
5472 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5473 item.tokens = Some(tokens);
5478 fn parse_impl_item_(&mut self,
5480 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5482 let vis = self.parse_visibility(false)?;
5483 let defaultness = self.parse_defaultness();
5484 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5485 // This parses the grammar:
5486 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5487 let name = self.parse_ident()?;
5488 let mut generics = self.parse_generics()?;
5489 generics.where_clause = self.parse_where_clause()?;
5490 self.expect(&token::Eq)?;
5491 let typ = self.parse_ty()?;
5492 self.expect(&token::Semi)?;
5493 (name, ast::ImplItemKind::Type(typ), generics)
5494 } else if self.is_const_item() {
5495 // This parses the grammar:
5496 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5497 self.expect_keyword(keywords::Const)?;
5498 let name = self.parse_ident()?;
5499 self.expect(&token::Colon)?;
5500 let typ = self.parse_ty()?;
5501 self.expect(&token::Eq)?;
5502 let expr = self.parse_expr()?;
5503 self.expect(&token::Semi)?;
5504 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5506 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5507 attrs.extend(inner_attrs);
5508 (name, node, generics)
5512 id: ast::DUMMY_NODE_ID,
5513 span: lo.to(self.prev_span),
5524 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5525 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5530 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5532 VisibilityKind::Inherited => Ok(()),
5534 let is_macro_rules: bool = match self.token {
5535 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5539 let mut err = self.diagnostic()
5540 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5541 err.span_suggestion_with_applicability(
5543 "try exporting the macro",
5544 "#[macro_export]".to_owned(),
5545 Applicability::MaybeIncorrect // speculative
5549 let mut err = self.diagnostic()
5550 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5551 err.help("try adjusting the macro to put `pub` inside the invocation");
5558 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5559 -> DiagnosticBuilder<'a>
5561 let expected_kinds = if item_type == "extern" {
5562 "missing `fn`, `type`, or `static`"
5564 "missing `fn`, `type`, or `const`"
5567 // Given this code `path(`, it seems like this is not
5568 // setting the visibility of a macro invocation, but rather
5569 // a mistyped method declaration.
5570 // Create a diagnostic pointing out that `fn` is missing.
5572 // x | pub path(&self) {
5573 // | ^ missing `fn`, `type`, or `const`
5575 // ^^ `sp` below will point to this
5576 let sp = prev_span.between(self.prev_span);
5577 let mut err = self.diagnostic().struct_span_err(
5579 &format!("{} for {}-item declaration",
5580 expected_kinds, item_type));
5581 err.span_label(sp, expected_kinds);
5585 /// Parse a method or a macro invocation in a trait impl.
5586 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5587 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5588 ast::ImplItemKind)> {
5589 // code copied from parse_macro_use_or_failure... abstraction!
5590 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5592 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5593 ast::ImplItemKind::Macro(mac)))
5595 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5596 let ident = self.parse_ident()?;
5597 let mut generics = self.parse_generics()?;
5598 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5599 generics.where_clause = self.parse_where_clause()?;
5601 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5602 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5603 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5604 ast::MethodSig { header, decl },
5610 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5611 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5612 let ident = self.parse_ident()?;
5613 let mut tps = self.parse_generics()?;
5615 // Parse optional colon and supertrait bounds.
5616 let bounds = if self.eat(&token::Colon) {
5617 self.parse_generic_bounds()?
5622 if self.eat(&token::Eq) {
5623 // it's a trait alias
5624 let bounds = self.parse_generic_bounds()?;
5625 tps.where_clause = self.parse_where_clause()?;
5626 self.expect(&token::Semi)?;
5627 if unsafety != Unsafety::Normal {
5628 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5630 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5632 // it's a normal trait
5633 tps.where_clause = self.parse_where_clause()?;
5634 self.expect(&token::OpenDelim(token::Brace))?;
5635 let mut trait_items = vec![];
5636 while !self.eat(&token::CloseDelim(token::Brace)) {
5637 let mut at_end = false;
5638 match self.parse_trait_item(&mut at_end) {
5639 Ok(item) => trait_items.push(item),
5643 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5648 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5652 fn choose_generics_over_qpath(&self) -> bool {
5653 // There's an ambiguity between generic parameters and qualified paths in impls.
5654 // If we see `<` it may start both, so we have to inspect some following tokens.
5655 // The following combinations can only start generics,
5656 // but not qualified paths (with one exception):
5657 // `<` `>` - empty generic parameters
5658 // `<` `#` - generic parameters with attributes
5659 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5660 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5661 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5662 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5663 // The only truly ambiguous case is
5664 // `<` IDENT `>` `::` IDENT ...
5665 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5666 // because this is what almost always expected in practice, qualified paths in impls
5667 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5668 self.token == token::Lt &&
5669 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5670 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5671 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5672 t == &token::Colon || t == &token::Eq))
5675 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5676 self.expect(&token::OpenDelim(token::Brace))?;
5677 let attrs = self.parse_inner_attributes()?;
5679 let mut impl_items = Vec::new();
5680 while !self.eat(&token::CloseDelim(token::Brace)) {
5681 let mut at_end = false;
5682 match self.parse_impl_item(&mut at_end) {
5683 Ok(impl_item) => impl_items.push(impl_item),
5687 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5692 Ok((impl_items, attrs))
5695 /// Parses an implementation item, `impl` keyword is already parsed.
5696 /// impl<'a, T> TYPE { /* impl items */ }
5697 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5698 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5699 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5700 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5701 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5702 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5703 -> PResult<'a, ItemInfo> {
5704 // First, parse generic parameters if necessary.
5705 let mut generics = if self.choose_generics_over_qpath() {
5706 self.parse_generics()?
5708 ast::Generics::default()
5711 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5712 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5714 ast::ImplPolarity::Negative
5716 ast::ImplPolarity::Positive
5719 // Parse both types and traits as a type, then reinterpret if necessary.
5720 let ty_first = self.parse_ty()?;
5722 // If `for` is missing we try to recover.
5723 let has_for = self.eat_keyword(keywords::For);
5724 let missing_for_span = self.prev_span.between(self.span);
5726 let ty_second = if self.token == token::DotDot {
5727 // We need to report this error after `cfg` expansion for compatibility reasons
5728 self.bump(); // `..`, do not add it to expected tokens
5729 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5730 } else if has_for || self.token.can_begin_type() {
5731 Some(self.parse_ty()?)
5736 generics.where_clause = self.parse_where_clause()?;
5738 let (impl_items, attrs) = self.parse_impl_body()?;
5740 let item_kind = match ty_second {
5741 Some(ty_second) => {
5742 // impl Trait for Type
5744 self.span_err(missing_for_span, "missing `for` in a trait impl");
5747 let ty_first = ty_first.into_inner();
5748 let path = match ty_first.node {
5749 // This notably includes paths passed through `ty` macro fragments (#46438).
5750 TyKind::Path(None, path) => path,
5752 self.span_err(ty_first.span, "expected a trait, found type");
5753 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5756 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5758 ItemKind::Impl(unsafety, polarity, defaultness,
5759 generics, Some(trait_ref), ty_second, impl_items)
5763 ItemKind::Impl(unsafety, polarity, defaultness,
5764 generics, None, ty_first, impl_items)
5768 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5771 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5772 if self.eat_keyword(keywords::For) {
5774 let params = self.parse_generic_params()?;
5776 // We rely on AST validation to rule out invalid cases: There must not be type
5777 // parameters, and the lifetime parameters must not have bounds.
5784 /// Parse struct Foo { ... }
5785 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5786 let class_name = self.parse_ident()?;
5788 let mut generics = self.parse_generics()?;
5790 // There is a special case worth noting here, as reported in issue #17904.
5791 // If we are parsing a tuple struct it is the case that the where clause
5792 // should follow the field list. Like so:
5794 // struct Foo<T>(T) where T: Copy;
5796 // If we are parsing a normal record-style struct it is the case
5797 // that the where clause comes before the body, and after the generics.
5798 // So if we look ahead and see a brace or a where-clause we begin
5799 // parsing a record style struct.
5801 // Otherwise if we look ahead and see a paren we parse a tuple-style
5804 let vdata = if self.token.is_keyword(keywords::Where) {
5805 generics.where_clause = self.parse_where_clause()?;
5806 if self.eat(&token::Semi) {
5807 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5808 VariantData::Unit(ast::DUMMY_NODE_ID)
5810 // If we see: `struct Foo<T> where T: Copy { ... }`
5811 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5813 // No `where` so: `struct Foo<T>;`
5814 } else if self.eat(&token::Semi) {
5815 VariantData::Unit(ast::DUMMY_NODE_ID)
5816 // Record-style struct definition
5817 } else if self.token == token::OpenDelim(token::Brace) {
5818 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5819 // Tuple-style struct definition with optional where-clause.
5820 } else if self.token == token::OpenDelim(token::Paren) {
5821 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5822 generics.where_clause = self.parse_where_clause()?;
5823 self.expect(&token::Semi)?;
5826 let token_str = self.this_token_to_string();
5827 let mut err = self.fatal(&format!(
5828 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5831 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5835 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5838 /// Parse union Foo { ... }
5839 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5840 let class_name = self.parse_ident()?;
5842 let mut generics = self.parse_generics()?;
5844 let vdata = if self.token.is_keyword(keywords::Where) {
5845 generics.where_clause = self.parse_where_clause()?;
5846 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5847 } else if self.token == token::OpenDelim(token::Brace) {
5848 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5850 let token_str = self.this_token_to_string();
5851 let mut err = self.fatal(&format!(
5852 "expected `where` or `{{` after union name, found `{}`", token_str));
5853 err.span_label(self.span, "expected `where` or `{` after union name");
5857 Ok((class_name, ItemKind::Union(vdata, generics), None))
5860 fn consume_block(&mut self, delim: token::DelimToken) {
5861 let mut brace_depth = 0;
5862 if !self.eat(&token::OpenDelim(delim)) {
5866 if self.eat(&token::OpenDelim(delim)) {
5868 } else if self.eat(&token::CloseDelim(delim)) {
5869 if brace_depth == 0 {
5875 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5883 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5884 let mut fields = Vec::new();
5885 if self.eat(&token::OpenDelim(token::Brace)) {
5886 while self.token != token::CloseDelim(token::Brace) {
5887 let field = self.parse_struct_decl_field().map_err(|e| {
5888 self.recover_stmt();
5892 Ok(field) => fields.push(field),
5898 self.eat(&token::CloseDelim(token::Brace));
5900 let token_str = self.this_token_to_string();
5901 let mut err = self.fatal(&format!(
5902 "expected `where`, or `{{` after struct name, found `{}`", token_str));
5903 err.span_label(self.span, "expected `where`, or `{` after struct name");
5910 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5911 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5912 // Unit like structs are handled in parse_item_struct function
5913 let fields = self.parse_unspanned_seq(
5914 &token::OpenDelim(token::Paren),
5915 &token::CloseDelim(token::Paren),
5916 SeqSep::trailing_allowed(token::Comma),
5918 let attrs = p.parse_outer_attributes()?;
5920 let vis = p.parse_visibility(true)?;
5921 let ty = p.parse_ty()?;
5923 span: lo.to(ty.span),
5926 id: ast::DUMMY_NODE_ID,
5935 /// Parse a structure field declaration
5936 fn parse_single_struct_field(&mut self,
5939 attrs: Vec<Attribute> )
5940 -> PResult<'a, StructField> {
5941 let mut seen_comma: bool = false;
5942 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5943 if self.token == token::Comma {
5950 token::CloseDelim(token::Brace) => {}
5951 token::DocComment(_) => {
5952 let previous_span = self.prev_span;
5953 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5954 self.bump(); // consume the doc comment
5955 let comma_after_doc_seen = self.eat(&token::Comma);
5956 // `seen_comma` is always false, because we are inside doc block
5957 // condition is here to make code more readable
5958 if seen_comma == false && comma_after_doc_seen == true {
5961 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
5964 if seen_comma == false {
5965 let sp = self.sess.codemap().next_point(previous_span);
5966 err.span_suggestion_with_applicability(
5968 "missing comma here",
5970 Applicability::MachineApplicable
5977 let sp = self.sess.codemap().next_point(self.prev_span);
5978 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
5979 self.this_token_to_string()));
5980 if self.token.is_ident() {
5981 // This is likely another field; emit the diagnostic and keep going
5982 err.span_suggestion(sp, "try adding a comma", ",".into());
5992 /// Parse an element of a struct definition
5993 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5994 let attrs = self.parse_outer_attributes()?;
5996 let vis = self.parse_visibility(false)?;
5997 self.parse_single_struct_field(lo, vis, attrs)
6000 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6001 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6002 /// a function definition, it's not a tuple struct field) and the contents within the parens
6003 /// isn't valid, emit a proper diagnostic.
6004 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6005 maybe_whole!(self, NtVis, |x| x);
6007 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6008 if self.is_crate_vis() {
6009 self.bump(); // `crate`
6010 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6013 if !self.eat_keyword(keywords::Pub) {
6014 return Ok(respan(self.prev_span, VisibilityKind::Inherited))
6016 let lo = self.prev_span;
6018 if self.check(&token::OpenDelim(token::Paren)) {
6019 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6020 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6021 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6022 // by the following tokens.
6023 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6026 self.bump(); // `crate`
6027 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6029 lo.to(self.prev_span),
6030 VisibilityKind::Crate(CrateSugar::PubCrate),
6033 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6036 self.bump(); // `in`
6037 let path = self.parse_path(PathStyle::Mod)?; // `path`
6038 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6039 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6041 id: ast::DUMMY_NODE_ID,
6044 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6045 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6046 t.is_keyword(keywords::SelfValue))
6048 // `pub(self)` or `pub(super)`
6050 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6051 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6052 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6054 id: ast::DUMMY_NODE_ID,
6057 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6058 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6060 let msg = "incorrect visibility restriction";
6061 let suggestion = r##"some possible visibility restrictions are:
6062 `pub(crate)`: visible only on the current crate
6063 `pub(super)`: visible only in the current module's parent
6064 `pub(in path::to::module)`: visible only on the specified path"##;
6065 let path = self.parse_path(PathStyle::Mod)?;
6066 let sp = self.prev_span;
6067 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6068 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6069 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6070 err.help(suggestion);
6071 err.span_suggestion_with_applicability(
6072 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6074 err.emit(); // emit diagnostic, but continue with public visibility
6078 Ok(respan(lo, VisibilityKind::Public))
6081 /// Parse defaultness: `default` or nothing.
6082 fn parse_defaultness(&mut self) -> Defaultness {
6083 // `pub` is included for better error messages
6084 if self.check_keyword(keywords::Default) &&
6085 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6086 t.is_keyword(keywords::Const) ||
6087 t.is_keyword(keywords::Fn) ||
6088 t.is_keyword(keywords::Unsafe) ||
6089 t.is_keyword(keywords::Extern) ||
6090 t.is_keyword(keywords::Type) ||
6091 t.is_keyword(keywords::Pub)) {
6092 self.bump(); // `default`
6093 Defaultness::Default
6099 /// Given a termination token, parse all of the items in a module
6100 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6101 let mut items = vec![];
6102 while let Some(item) = self.parse_item()? {
6106 if !self.eat(term) {
6107 let token_str = self.this_token_to_string();
6108 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6109 if token_str == ";" {
6110 let msg = "consider removing this semicolon";
6111 err.span_suggestion_short_with_applicability(
6112 self.span, msg, "".to_string(), Applicability::MachineApplicable
6115 err.span_label(self.span, "expected item");
6120 let hi = if self.span == syntax_pos::DUMMY_SP {
6127 inner: inner_lo.to(hi),
6132 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6133 let id = self.parse_ident()?;
6134 self.expect(&token::Colon)?;
6135 let ty = self.parse_ty()?;
6136 self.expect(&token::Eq)?;
6137 let e = self.parse_expr()?;
6138 self.expect(&token::Semi)?;
6139 let item = match m {
6140 Some(m) => ItemKind::Static(ty, m, e),
6141 None => ItemKind::Const(ty, e),
6143 Ok((id, item, None))
6146 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6147 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6148 let (in_cfg, outer_attrs) = {
6149 let mut strip_unconfigured = ::config::StripUnconfigured {
6151 should_test: false, // irrelevant
6152 features: None, // don't perform gated feature checking
6154 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6155 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6158 let id_span = self.span;
6159 let id = self.parse_ident()?;
6160 if self.check(&token::Semi) {
6162 if in_cfg && self.recurse_into_file_modules {
6163 // This mod is in an external file. Let's go get it!
6164 let ModulePathSuccess { path, directory_ownership, warn } =
6165 self.submod_path(id, &outer_attrs, id_span)?;
6166 let (module, mut attrs) =
6167 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6169 let attr = Attribute {
6170 id: attr::mk_attr_id(),
6171 style: ast::AttrStyle::Outer,
6172 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6173 tokens: TokenStream::empty(),
6174 is_sugared_doc: false,
6175 span: syntax_pos::DUMMY_SP,
6177 attr::mark_known(&attr);
6180 Ok((id, module, Some(attrs)))
6182 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6183 Ok((id, ItemKind::Mod(placeholder), None))
6186 let old_directory = self.directory.clone();
6187 self.push_directory(id, &outer_attrs);
6189 self.expect(&token::OpenDelim(token::Brace))?;
6190 let mod_inner_lo = self.span;
6191 let attrs = self.parse_inner_attributes()?;
6192 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6194 self.directory = old_directory;
6195 Ok((id, ItemKind::Mod(module), Some(attrs)))
6199 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6200 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6201 self.directory.path.to_mut().push(&path.as_str());
6202 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6204 self.directory.path.to_mut().push(&id.as_str());
6208 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6209 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6212 // On windows, the base path might have the form
6213 // `\\?\foo\bar` in which case it does not tolerate
6214 // mixed `/` and `\` separators, so canonicalize
6217 let s = s.replace("/", "\\");
6218 Some(dir_path.join(s))
6224 /// Returns either a path to a module, or .
6225 pub fn default_submod_path(
6227 relative: Option<ast::Ident>,
6229 codemap: &CodeMap) -> ModulePath
6231 // If we're in a foo.rs file instead of a mod.rs file,
6232 // we need to look for submodules in
6233 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6234 // `./<id>.rs` and `./<id>/mod.rs`.
6235 let relative_prefix_string;
6236 let relative_prefix = if let Some(ident) = relative {
6237 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6238 &relative_prefix_string
6243 let mod_name = id.to_string();
6244 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6245 let secondary_path_str = format!("{}{}{}mod.rs",
6246 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6247 let default_path = dir_path.join(&default_path_str);
6248 let secondary_path = dir_path.join(&secondary_path_str);
6249 let default_exists = codemap.file_exists(&default_path);
6250 let secondary_exists = codemap.file_exists(&secondary_path);
6252 let result = match (default_exists, secondary_exists) {
6253 (true, false) => Ok(ModulePathSuccess {
6255 directory_ownership: DirectoryOwnership::Owned {
6260 (false, true) => Ok(ModulePathSuccess {
6261 path: secondary_path,
6262 directory_ownership: DirectoryOwnership::Owned {
6267 (false, false) => Err(Error::FileNotFoundForModule {
6268 mod_name: mod_name.clone(),
6269 default_path: default_path_str,
6270 secondary_path: secondary_path_str,
6271 dir_path: format!("{}", dir_path.display()),
6273 (true, true) => Err(Error::DuplicatePaths {
6274 mod_name: mod_name.clone(),
6275 default_path: default_path_str,
6276 secondary_path: secondary_path_str,
6282 path_exists: default_exists || secondary_exists,
6287 fn submod_path(&mut self,
6289 outer_attrs: &[Attribute],
6291 -> PResult<'a, ModulePathSuccess> {
6292 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6293 return Ok(ModulePathSuccess {
6294 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6295 // All `#[path]` files are treated as though they are a `mod.rs` file.
6296 // This means that `mod foo;` declarations inside `#[path]`-included
6297 // files are siblings,
6299 // Note that this will produce weirdness when a file named `foo.rs` is
6300 // `#[path]` included and contains a `mod foo;` declaration.
6301 // If you encounter this, it's your own darn fault :P
6302 Some(_) => DirectoryOwnership::Owned { relative: None },
6303 _ => DirectoryOwnership::UnownedViaMod(true),
6310 let relative = match self.directory.ownership {
6311 DirectoryOwnership::Owned { relative } => {
6312 // Push the usage onto the list of non-mod.rs mod uses.
6313 // This is used later for feature-gate error reporting.
6314 if let Some(cur_file_ident) = relative {
6316 .non_modrs_mods.borrow_mut()
6317 .push((cur_file_ident, id_sp));
6321 DirectoryOwnership::UnownedViaBlock |
6322 DirectoryOwnership::UnownedViaMod(_) => None,
6324 let paths = Parser::default_submod_path(
6325 id, relative, &self.directory.path, self.sess.codemap());
6327 match self.directory.ownership {
6328 DirectoryOwnership::Owned { .. } => {
6329 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6331 DirectoryOwnership::UnownedViaBlock => {
6333 "Cannot declare a non-inline module inside a block \
6334 unless it has a path attribute";
6335 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6336 if paths.path_exists {
6337 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6339 err.span_note(id_sp, &msg);
6343 DirectoryOwnership::UnownedViaMod(warn) => {
6345 if let Ok(result) = paths.result {
6346 return Ok(ModulePathSuccess { warn: true, ..result });
6349 let mut err = self.diagnostic().struct_span_err(id_sp,
6350 "cannot declare a new module at this location");
6351 if id_sp != syntax_pos::DUMMY_SP {
6352 let src_path = self.sess.codemap().span_to_filename(id_sp);
6353 if let FileName::Real(src_path) = src_path {
6354 if let Some(stem) = src_path.file_stem() {
6355 let mut dest_path = src_path.clone();
6356 dest_path.set_file_name(stem);
6357 dest_path.push("mod.rs");
6358 err.span_note(id_sp,
6359 &format!("maybe move this module `{}` to its own \
6360 directory via `{}`", src_path.display(),
6361 dest_path.display()));
6365 if paths.path_exists {
6366 err.span_note(id_sp,
6367 &format!("... or maybe `use` the module `{}` instead \
6368 of possibly redeclaring it",
6376 /// Read a module from a source file.
6377 fn eval_src_mod(&mut self,
6379 directory_ownership: DirectoryOwnership,
6382 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6383 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6384 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6385 let mut err = String::from("circular modules: ");
6386 let len = included_mod_stack.len();
6387 for p in &included_mod_stack[i.. len] {
6388 err.push_str(&p.to_string_lossy());
6389 err.push_str(" -> ");
6391 err.push_str(&path.to_string_lossy());
6392 return Err(self.span_fatal(id_sp, &err[..]));
6394 included_mod_stack.push(path.clone());
6395 drop(included_mod_stack);
6398 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6399 p0.cfg_mods = self.cfg_mods;
6400 let mod_inner_lo = p0.span;
6401 let mod_attrs = p0.parse_inner_attributes()?;
6402 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6403 self.sess.included_mod_stack.borrow_mut().pop();
6404 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6407 /// Parse a function declaration from a foreign module
6408 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6409 -> PResult<'a, ForeignItem> {
6410 self.expect_keyword(keywords::Fn)?;
6412 let (ident, mut generics) = self.parse_fn_header()?;
6413 let decl = self.parse_fn_decl(true)?;
6414 generics.where_clause = self.parse_where_clause()?;
6416 self.expect(&token::Semi)?;
6417 Ok(ast::ForeignItem {
6420 node: ForeignItemKind::Fn(decl, generics),
6421 id: ast::DUMMY_NODE_ID,
6427 /// Parse a static item from a foreign module.
6428 /// Assumes that the `static` keyword is already parsed.
6429 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6430 -> PResult<'a, ForeignItem> {
6431 let mutbl = self.eat_keyword(keywords::Mut);
6432 let ident = self.parse_ident()?;
6433 self.expect(&token::Colon)?;
6434 let ty = self.parse_ty()?;
6436 self.expect(&token::Semi)?;
6440 node: ForeignItemKind::Static(ty, mutbl),
6441 id: ast::DUMMY_NODE_ID,
6447 /// Parse a type from a foreign module
6448 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6449 -> PResult<'a, ForeignItem> {
6450 self.expect_keyword(keywords::Type)?;
6452 let ident = self.parse_ident()?;
6454 self.expect(&token::Semi)?;
6455 Ok(ast::ForeignItem {
6458 node: ForeignItemKind::Ty,
6459 id: ast::DUMMY_NODE_ID,
6465 /// Parse extern crate links
6469 /// extern crate foo;
6470 /// extern crate bar as foo;
6471 fn parse_item_extern_crate(&mut self,
6473 visibility: Visibility,
6474 attrs: Vec<Attribute>)
6475 -> PResult<'a, P<Item>> {
6476 let orig_name = self.parse_ident()?;
6477 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6478 (rename, Some(orig_name.name))
6482 self.expect(&token::Semi)?;
6484 let span = lo.to(self.prev_span);
6485 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6488 /// Parse `extern` for foreign ABIs
6491 /// `extern` is expected to have been
6492 /// consumed before calling this method
6498 fn parse_item_foreign_mod(&mut self,
6500 opt_abi: Option<Abi>,
6501 visibility: Visibility,
6502 mut attrs: Vec<Attribute>)
6503 -> PResult<'a, P<Item>> {
6504 self.expect(&token::OpenDelim(token::Brace))?;
6506 let abi = opt_abi.unwrap_or(Abi::C);
6508 attrs.extend(self.parse_inner_attributes()?);
6510 let mut foreign_items = vec![];
6511 while let Some(item) = self.parse_foreign_item()? {
6512 foreign_items.push(item);
6514 self.expect(&token::CloseDelim(token::Brace))?;
6516 let prev_span = self.prev_span;
6517 let m = ast::ForeignMod {
6519 items: foreign_items
6521 let invalid = keywords::Invalid.ident();
6522 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6525 /// Parse type Foo = Bar;
6526 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6527 let ident = self.parse_ident()?;
6528 let mut tps = self.parse_generics()?;
6529 tps.where_clause = self.parse_where_clause()?;
6530 self.expect(&token::Eq)?;
6531 let ty = self.parse_ty()?;
6532 self.expect(&token::Semi)?;
6533 Ok((ident, ItemKind::Ty(ty, tps), None))
6536 /// Parse the part of an "enum" decl following the '{'
6537 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6538 let mut variants = Vec::new();
6539 let mut all_nullary = true;
6540 let mut any_disr = None;
6541 while self.token != token::CloseDelim(token::Brace) {
6542 let variant_attrs = self.parse_outer_attributes()?;
6543 let vlo = self.span;
6546 let mut disr_expr = None;
6547 let ident = self.parse_ident()?;
6548 if self.check(&token::OpenDelim(token::Brace)) {
6549 // Parse a struct variant.
6550 all_nullary = false;
6551 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6552 ast::DUMMY_NODE_ID);
6553 } else if self.check(&token::OpenDelim(token::Paren)) {
6554 all_nullary = false;
6555 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6556 ast::DUMMY_NODE_ID);
6557 } else if self.eat(&token::Eq) {
6558 disr_expr = Some(AnonConst {
6559 id: ast::DUMMY_NODE_ID,
6560 value: self.parse_expr()?,
6562 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6563 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6565 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6568 let vr = ast::Variant_ {
6570 attrs: variant_attrs,
6574 variants.push(respan(vlo.to(self.prev_span), vr));
6576 if !self.eat(&token::Comma) { break; }
6578 self.expect(&token::CloseDelim(token::Brace))?;
6580 Some(disr_span) if !all_nullary =>
6581 self.span_err(disr_span,
6582 "discriminator values can only be used with a field-less enum"),
6586 Ok(ast::EnumDef { variants: variants })
6589 /// Parse an "enum" declaration
6590 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6591 let id = self.parse_ident()?;
6592 let mut generics = self.parse_generics()?;
6593 generics.where_clause = self.parse_where_clause()?;
6594 self.expect(&token::OpenDelim(token::Brace))?;
6596 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6597 self.recover_stmt();
6598 self.eat(&token::CloseDelim(token::Brace));
6601 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6604 /// Parses a string as an ABI spec on an extern type or module. Consumes
6605 /// the `extern` keyword, if one is found.
6606 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6608 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6610 self.expect_no_suffix(sp, "ABI spec", suf);
6612 match abi::lookup(&s.as_str()) {
6613 Some(abi) => Ok(Some(abi)),
6615 let prev_span = self.prev_span;
6616 let mut err = struct_span_err!(
6617 self.sess.span_diagnostic,
6620 "invalid ABI: found `{}`",
6622 err.span_label(prev_span, "invalid ABI");
6623 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6634 fn is_static_global(&mut self) -> bool {
6635 if self.check_keyword(keywords::Static) {
6636 // Check if this could be a closure
6637 !self.look_ahead(1, |token| {
6638 if token.is_keyword(keywords::Move) {
6642 token::BinOp(token::Or) | token::OrOr => true,
6651 /// Parse one of the items allowed by the flags.
6652 /// NB: this function no longer parses the items inside an
6654 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6655 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6656 maybe_whole!(self, NtItem, |item| {
6657 let mut item = item.into_inner();
6658 let mut attrs = attrs;
6659 mem::swap(&mut item.attrs, &mut attrs);
6660 item.attrs.extend(attrs);
6666 let visibility = self.parse_visibility(false)?;
6668 if self.eat_keyword(keywords::Use) {
6670 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6671 self.expect(&token::Semi)?;
6673 let span = lo.to(self.prev_span);
6674 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6675 return Ok(Some(item));
6678 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6679 self.bump(); // `extern`
6680 if self.eat_keyword(keywords::Crate) {
6681 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6684 let opt_abi = self.parse_opt_abi()?;
6686 if self.eat_keyword(keywords::Fn) {
6687 // EXTERN FUNCTION ITEM
6688 let fn_span = self.prev_span;
6689 let abi = opt_abi.unwrap_or(Abi::C);
6690 let (ident, item_, extra_attrs) =
6691 self.parse_item_fn(Unsafety::Normal,
6693 respan(fn_span, Constness::NotConst),
6695 let prev_span = self.prev_span;
6696 let item = self.mk_item(lo.to(prev_span),
6700 maybe_append(attrs, extra_attrs));
6701 return Ok(Some(item));
6702 } else if self.check(&token::OpenDelim(token::Brace)) {
6703 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6709 if self.is_static_global() {
6712 let m = if self.eat_keyword(keywords::Mut) {
6715 Mutability::Immutable
6717 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6718 let prev_span = self.prev_span;
6719 let item = self.mk_item(lo.to(prev_span),
6723 maybe_append(attrs, extra_attrs));
6724 return Ok(Some(item));
6726 if self.eat_keyword(keywords::Const) {
6727 let const_span = self.prev_span;
6728 if self.check_keyword(keywords::Fn)
6729 || (self.check_keyword(keywords::Unsafe)
6730 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6731 // CONST FUNCTION ITEM
6732 let unsafety = self.parse_unsafety();
6734 let (ident, item_, extra_attrs) =
6735 self.parse_item_fn(unsafety,
6737 respan(const_span, Constness::Const),
6739 let prev_span = self.prev_span;
6740 let item = self.mk_item(lo.to(prev_span),
6744 maybe_append(attrs, extra_attrs));
6745 return Ok(Some(item));
6749 if self.eat_keyword(keywords::Mut) {
6750 let prev_span = self.prev_span;
6751 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6752 .help("did you mean to declare a static?")
6755 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6756 let prev_span = self.prev_span;
6757 let item = self.mk_item(lo.to(prev_span),
6761 maybe_append(attrs, extra_attrs));
6762 return Ok(Some(item));
6765 // `unsafe async fn` or `async fn`
6767 self.check_keyword(keywords::Unsafe) &&
6768 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
6770 self.check_keyword(keywords::Async) &&
6771 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
6774 // ASYNC FUNCTION ITEM
6775 let unsafety = self.parse_unsafety();
6776 self.expect_keyword(keywords::Async)?;
6777 self.expect_keyword(keywords::Fn)?;
6778 let fn_span = self.prev_span;
6779 let (ident, item_, extra_attrs) =
6780 self.parse_item_fn(unsafety,
6781 IsAsync::Async(ast::DUMMY_NODE_ID),
6782 respan(fn_span, Constness::NotConst),
6784 let prev_span = self.prev_span;
6785 let item = self.mk_item(lo.to(prev_span),
6789 maybe_append(attrs, extra_attrs));
6790 return Ok(Some(item));
6792 if self.check_keyword(keywords::Unsafe) &&
6793 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6794 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6796 // UNSAFE TRAIT ITEM
6797 self.bump(); // `unsafe`
6798 let is_auto = if self.eat_keyword(keywords::Trait) {
6801 self.expect_keyword(keywords::Auto)?;
6802 self.expect_keyword(keywords::Trait)?;
6805 let (ident, item_, extra_attrs) =
6806 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
6807 let prev_span = self.prev_span;
6808 let item = self.mk_item(lo.to(prev_span),
6812 maybe_append(attrs, extra_attrs));
6813 return Ok(Some(item));
6815 if self.check_keyword(keywords::Impl) ||
6816 self.check_keyword(keywords::Unsafe) &&
6817 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6818 self.check_keyword(keywords::Default) &&
6819 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6820 self.check_keyword(keywords::Default) &&
6821 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6823 let defaultness = self.parse_defaultness();
6824 let unsafety = self.parse_unsafety();
6825 self.expect_keyword(keywords::Impl)?;
6826 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6827 let span = lo.to(self.prev_span);
6828 return Ok(Some(self.mk_item(span, ident, item, visibility,
6829 maybe_append(attrs, extra_attrs))));
6831 if self.check_keyword(keywords::Fn) {
6834 let fn_span = self.prev_span;
6835 let (ident, item_, extra_attrs) =
6836 self.parse_item_fn(Unsafety::Normal,
6838 respan(fn_span, Constness::NotConst),
6840 let prev_span = self.prev_span;
6841 let item = self.mk_item(lo.to(prev_span),
6845 maybe_append(attrs, extra_attrs));
6846 return Ok(Some(item));
6848 if self.check_keyword(keywords::Unsafe)
6849 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6850 // UNSAFE FUNCTION ITEM
6851 self.bump(); // `unsafe`
6852 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
6853 self.check(&token::OpenDelim(token::Brace));
6854 let abi = if self.eat_keyword(keywords::Extern) {
6855 self.parse_opt_abi()?.unwrap_or(Abi::C)
6859 self.expect_keyword(keywords::Fn)?;
6860 let fn_span = self.prev_span;
6861 let (ident, item_, extra_attrs) =
6862 self.parse_item_fn(Unsafety::Unsafe,
6864 respan(fn_span, Constness::NotConst),
6866 let prev_span = self.prev_span;
6867 let item = self.mk_item(lo.to(prev_span),
6871 maybe_append(attrs, extra_attrs));
6872 return Ok(Some(item));
6874 if self.eat_keyword(keywords::Mod) {
6876 let (ident, item_, extra_attrs) =
6877 self.parse_item_mod(&attrs[..])?;
6878 let prev_span = self.prev_span;
6879 let item = self.mk_item(lo.to(prev_span),
6883 maybe_append(attrs, extra_attrs));
6884 return Ok(Some(item));
6886 if self.eat_keyword(keywords::Type) {
6888 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6889 let prev_span = self.prev_span;
6890 let item = self.mk_item(lo.to(prev_span),
6894 maybe_append(attrs, extra_attrs));
6895 return Ok(Some(item));
6897 if self.eat_keyword(keywords::Enum) {
6899 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6900 let prev_span = self.prev_span;
6901 let item = self.mk_item(lo.to(prev_span),
6905 maybe_append(attrs, extra_attrs));
6906 return Ok(Some(item));
6908 if self.check_keyword(keywords::Trait)
6909 || (self.check_keyword(keywords::Auto)
6910 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6912 let is_auto = if self.eat_keyword(keywords::Trait) {
6915 self.expect_keyword(keywords::Auto)?;
6916 self.expect_keyword(keywords::Trait)?;
6920 let (ident, item_, extra_attrs) =
6921 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6922 let prev_span = self.prev_span;
6923 let item = self.mk_item(lo.to(prev_span),
6927 maybe_append(attrs, extra_attrs));
6928 return Ok(Some(item));
6930 if self.eat_keyword(keywords::Struct) {
6932 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6933 let prev_span = self.prev_span;
6934 let item = self.mk_item(lo.to(prev_span),
6938 maybe_append(attrs, extra_attrs));
6939 return Ok(Some(item));
6941 if self.is_union_item() {
6944 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6945 let prev_span = self.prev_span;
6946 let item = self.mk_item(lo.to(prev_span),
6950 maybe_append(attrs, extra_attrs));
6951 return Ok(Some(item));
6953 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6954 return Ok(Some(macro_def));
6957 // Verify whether we have encountered a struct or method definition where the user forgot to
6958 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6959 if visibility.node == VisibilityKind::Public &&
6960 self.check_ident() &&
6961 self.look_ahead(1, |t| *t != token::Not)
6963 // Space between `pub` keyword and the identifier
6966 // ^^^ `sp` points here
6967 let sp = self.prev_span.between(self.span);
6968 let full_sp = self.prev_span.to(self.span);
6969 let ident_sp = self.span;
6970 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6971 // possible public struct definition where `struct` was forgotten
6972 let ident = self.parse_ident().unwrap();
6973 let msg = format!("add `struct` here to parse `{}` as a public struct",
6975 let mut err = self.diagnostic()
6976 .struct_span_err(sp, "missing `struct` for struct definition");
6977 err.span_suggestion_short_with_applicability(
6978 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
6981 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6982 let ident = self.parse_ident().unwrap();
6983 self.consume_block(token::Paren);
6984 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6985 self.check(&token::OpenDelim(token::Brace))
6987 ("fn", "method", false)
6988 } else if self.check(&token::Colon) {
6992 ("fn` or `struct", "method or struct", true)
6995 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6996 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6998 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7002 err.span_suggestion_short_with_applicability(
7003 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7006 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
7007 err.span_suggestion_with_applicability(
7009 "if you meant to call a macro, try",
7010 format!("{}!", snippet),
7011 // this is the `ambiguous` conditional branch
7012 Applicability::MaybeIncorrect
7015 err.help("if you meant to call a macro, remove the `pub` \
7016 and add a trailing `!` after the identifier");
7022 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7025 /// Parse a foreign item.
7026 crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
7027 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
7029 let attrs = self.parse_outer_attributes()?;
7031 let visibility = self.parse_visibility(false)?;
7033 // FOREIGN STATIC ITEM
7034 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7035 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7036 if self.token.is_keyword(keywords::Const) {
7038 .struct_span_err(self.span, "extern items cannot be `const`")
7039 .span_suggestion_with_applicability(
7041 "try using a static value",
7042 "static".to_owned(),
7043 Applicability::MachineApplicable
7046 self.bump(); // `static` or `const`
7047 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
7049 // FOREIGN FUNCTION ITEM
7050 if self.check_keyword(keywords::Fn) {
7051 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
7053 // FOREIGN TYPE ITEM
7054 if self.check_keyword(keywords::Type) {
7055 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
7058 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7062 ident: keywords::Invalid.ident(),
7063 span: lo.to(self.prev_span),
7064 id: ast::DUMMY_NODE_ID,
7067 node: ForeignItemKind::Macro(mac),
7072 if !attrs.is_empty() {
7073 self.expected_item_err(&attrs);
7081 /// This is the fall-through for parsing items.
7082 fn parse_macro_use_or_failure(
7084 attrs: Vec<Attribute> ,
7085 macros_allowed: bool,
7086 attributes_allowed: bool,
7088 visibility: Visibility
7089 ) -> PResult<'a, Option<P<Item>>> {
7090 if macros_allowed && self.token.is_path_start() {
7091 // MACRO INVOCATION ITEM
7093 let prev_span = self.prev_span;
7094 self.complain_if_pub_macro(&visibility.node, prev_span);
7096 let mac_lo = self.span;
7099 let pth = self.parse_path(PathStyle::Mod)?;
7100 self.expect(&token::Not)?;
7102 // a 'special' identifier (like what `macro_rules!` uses)
7103 // is optional. We should eventually unify invoc syntax
7105 let id = if self.token.is_ident() {
7108 keywords::Invalid.ident() // no special identifier
7110 // eat a matched-delimiter token tree:
7111 let (delim, tts) = self.expect_delimited_token_tree()?;
7112 if delim != MacDelimiter::Brace {
7113 if !self.eat(&token::Semi) {
7114 self.span_err(self.prev_span,
7115 "macros that expand to items must either \
7116 be surrounded with braces or followed by \
7121 let hi = self.prev_span;
7122 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7123 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7124 return Ok(Some(item));
7127 // FAILURE TO PARSE ITEM
7128 match visibility.node {
7129 VisibilityKind::Inherited => {}
7131 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7135 if !attributes_allowed && !attrs.is_empty() {
7136 self.expected_item_err(&attrs);
7141 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7142 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7143 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7145 if self.token.is_path_start() && !self.is_extern_non_path() {
7146 let prev_span = self.prev_span;
7148 let pth = self.parse_path(PathStyle::Mod)?;
7150 if pth.segments.len() == 1 {
7151 if !self.eat(&token::Not) {
7152 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7155 self.expect(&token::Not)?;
7158 if let Some(vis) = vis {
7159 self.complain_if_pub_macro(&vis.node, prev_span);
7164 // eat a matched-delimiter token tree:
7165 let (delim, tts) = self.expect_delimited_token_tree()?;
7166 if delim != MacDelimiter::Brace {
7167 self.expect(&token::Semi)?
7170 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7176 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7177 where F: FnOnce(&mut Self) -> PResult<'a, R>
7179 // Record all tokens we parse when parsing this item.
7180 let mut tokens = Vec::new();
7181 match self.token_cursor.frame.last_token {
7182 LastToken::Collecting(_) => {
7183 panic!("cannot collect tokens recursively yet")
7185 LastToken::Was(ref mut last) => tokens.extend(last.take()),
7187 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7188 let prev = self.token_cursor.stack.len();
7190 let last_token = if self.token_cursor.stack.len() == prev {
7191 &mut self.token_cursor.frame.last_token
7193 &mut self.token_cursor.stack[prev].last_token
7195 let mut tokens = match *last_token {
7196 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7197 LastToken::Was(_) => panic!("our vector went away?"),
7200 // If we're not at EOF our current token wasn't actually consumed by
7201 // `f`, but it'll still be in our list that we pulled out. In that case
7203 if self.token == token::Eof {
7204 *last_token = LastToken::Was(None);
7206 *last_token = LastToken::Was(tokens.pop());
7209 Ok((ret?, tokens.into_iter().collect()))
7212 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7213 let attrs = self.parse_outer_attributes()?;
7215 let (ret, tokens) = self.collect_tokens(|this| {
7216 this.parse_item_(attrs, true, false)
7219 // Once we've parsed an item and recorded the tokens we got while
7220 // parsing we may want to store `tokens` into the item we're about to
7221 // return. Note, though, that we specifically didn't capture tokens
7222 // related to outer attributes. The `tokens` field here may later be
7223 // used with procedural macros to convert this item back into a token
7224 // stream, but during expansion we may be removing attributes as we go
7227 // If we've got inner attributes then the `tokens` we've got above holds
7228 // these inner attributes. If an inner attribute is expanded we won't
7229 // actually remove it from the token stream, so we'll just keep yielding
7230 // it (bad!). To work around this case for now we just avoid recording
7231 // `tokens` if we detect any inner attributes. This should help keep
7232 // expansion correct, but we should fix this bug one day!
7235 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7236 i.tokens = Some(tokens);
7244 fn is_import_coupler(&mut self) -> bool {
7245 self.check(&token::ModSep) &&
7246 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7247 *t == token::BinOp(token::Star))
7252 /// USE_TREE = [`::`] `*` |
7253 /// [`::`] `{` USE_TREE_LIST `}` |
7255 /// PATH `::` `{` USE_TREE_LIST `}` |
7256 /// PATH [`as` IDENT]
7257 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7260 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7261 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7262 self.check(&token::BinOp(token::Star)) ||
7263 self.is_import_coupler() {
7264 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7265 if self.eat(&token::ModSep) {
7266 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7269 if self.eat(&token::BinOp(token::Star)) {
7272 UseTreeKind::Nested(self.parse_use_tree_list()?)
7275 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7276 prefix = self.parse_path(PathStyle::Mod)?;
7278 if self.eat(&token::ModSep) {
7279 if self.eat(&token::BinOp(token::Star)) {
7282 UseTreeKind::Nested(self.parse_use_tree_list()?)
7285 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7289 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7292 /// Parse UseTreeKind::Nested(list)
7294 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7295 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7296 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7297 &token::CloseDelim(token::Brace),
7298 SeqSep::trailing_allowed(token::Comma), |this| {
7299 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7303 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7304 if self.eat_keyword(keywords::As) {
7306 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7308 Ok(Some(Ident::new(ident.name.gensymed(), ident.span)))
7310 _ => self.parse_ident().map(Some),
7317 /// Parses a source module as a crate. This is the main
7318 /// entry point for the parser.
7319 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7322 attrs: self.parse_inner_attributes()?,
7323 module: self.parse_mod_items(&token::Eof, lo)?,
7324 span: lo.to(self.span),
7328 fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7329 let ret = match self.token {
7330 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7331 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7338 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7339 match self.parse_optional_str() {
7340 Some((s, style, suf)) => {
7341 let sp = self.prev_span;
7342 self.expect_no_suffix(sp, "string literal", suf);
7346 let msg = "expected string literal";
7347 let mut err = self.fatal(msg);
7348 err.span_label(self.span, msg);