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};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::{GenericParam, GenericParamKind};
26 use ast::{Ident, ImplItem, 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};
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 unsafety: `unsafe` or nothing.
1297 fn parse_unsafety(&mut self) -> Unsafety {
1298 if self.eat_keyword(keywords::Unsafe) {
1305 /// Parse the items in a trait declaration
1306 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1307 maybe_whole!(self, NtTraitItem, |x| x);
1308 let attrs = self.parse_outer_attributes()?;
1309 let (mut item, tokens) = self.collect_tokens(|this| {
1310 this.parse_trait_item_(at_end, attrs)
1312 // See `parse_item` for why this clause is here.
1313 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1314 item.tokens = Some(tokens);
1319 fn parse_trait_item_(&mut self,
1321 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1324 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1325 self.parse_trait_item_assoc_ty()?
1326 } else if self.is_const_item() {
1327 self.expect_keyword(keywords::Const)?;
1328 let ident = self.parse_ident()?;
1329 self.expect(&token::Colon)?;
1330 let ty = self.parse_ty()?;
1331 let default = if self.check(&token::Eq) {
1333 let expr = self.parse_expr()?;
1334 self.expect(&token::Semi)?;
1337 self.expect(&token::Semi)?;
1340 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1341 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1342 // trait item macro.
1343 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1345 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1347 let ident = self.parse_ident()?;
1348 let mut generics = self.parse_generics()?;
1350 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1351 // This is somewhat dubious; We don't want to allow
1352 // argument names to be left off if there is a
1354 p.parse_arg_general(false)
1356 generics.where_clause = self.parse_where_clause()?;
1358 let sig = ast::MethodSig {
1365 let body = match self.token {
1369 debug!("parse_trait_methods(): parsing required method");
1372 token::OpenDelim(token::Brace) => {
1373 debug!("parse_trait_methods(): parsing provided method");
1375 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1376 attrs.extend(inner_attrs.iter().cloned());
1380 let token_str = self.this_token_to_string();
1381 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1383 err.span_label(self.span, "expected `;` or `{`");
1387 (ident, ast::TraitItemKind::Method(sig, body), generics)
1391 id: ast::DUMMY_NODE_ID,
1396 span: lo.to(self.prev_span),
1401 /// Parse optional return type [ -> TY ] in function decl
1402 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1403 if self.eat(&token::RArrow) {
1404 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1406 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1411 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1412 self.parse_ty_common(true, true)
1415 /// Parse a type in restricted contexts where `+` is not permitted.
1416 /// Example 1: `&'a TYPE`
1417 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1418 /// Example 2: `value1 as TYPE + value2`
1419 /// `+` is prohibited to avoid interactions with expression grammar.
1420 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1421 self.parse_ty_common(false, true)
1424 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1425 -> PResult<'a, P<Ty>> {
1426 maybe_whole!(self, NtTy, |x| x);
1429 let mut impl_dyn_multi = false;
1430 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1431 // `(TYPE)` is a parenthesized type.
1432 // `(TYPE,)` is a tuple with a single field of type TYPE.
1433 let mut ts = vec![];
1434 let mut last_comma = false;
1435 while self.token != token::CloseDelim(token::Paren) {
1436 ts.push(self.parse_ty()?);
1437 if self.eat(&token::Comma) {
1444 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1445 self.expect(&token::CloseDelim(token::Paren))?;
1447 if ts.len() == 1 && !last_comma {
1448 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1449 let maybe_bounds = allow_plus && self.token.is_like_plus();
1451 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1452 TyKind::Path(None, ref path) if maybe_bounds => {
1453 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1455 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1456 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1457 let path = match bounds[0] {
1458 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1459 _ => self.bug("unexpected lifetime bound"),
1461 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1464 _ => TyKind::Paren(P(ty))
1469 } else if self.eat(&token::Not) {
1472 } else if self.eat(&token::BinOp(token::Star)) {
1474 TyKind::Ptr(self.parse_ptr()?)
1475 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1477 let t = self.parse_ty()?;
1478 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1479 let t = match self.maybe_parse_fixed_length_of_vec()? {
1480 None => TyKind::Slice(t),
1481 Some(length) => TyKind::Array(t, AnonConst {
1482 id: ast::DUMMY_NODE_ID,
1486 self.expect(&token::CloseDelim(token::Bracket))?;
1488 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1491 self.parse_borrowed_pointee()?
1492 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1494 // In order to not be ambiguous, the type must be surrounded by parens.
1495 self.expect(&token::OpenDelim(token::Paren))?;
1497 id: ast::DUMMY_NODE_ID,
1498 value: self.parse_expr()?,
1500 self.expect(&token::CloseDelim(token::Paren))?;
1502 } else if self.eat_keyword(keywords::Underscore) {
1503 // A type to be inferred `_`
1505 } else if self.token_is_bare_fn_keyword() {
1506 // Function pointer type
1507 self.parse_ty_bare_fn(Vec::new())?
1508 } else if self.check_keyword(keywords::For) {
1509 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1510 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1511 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1513 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1514 if self.token_is_bare_fn_keyword() {
1515 self.parse_ty_bare_fn(lifetime_defs)?
1517 let path = self.parse_path(PathStyle::Type)?;
1518 let parse_plus = allow_plus && self.check_plus();
1519 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1521 } else if self.eat_keyword(keywords::Impl) {
1522 // Always parse bounds greedily for better error recovery.
1523 let bounds = self.parse_generic_bounds()?;
1524 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1525 TyKind::ImplTrait(bounds)
1526 } else if self.check_keyword(keywords::Dyn) &&
1527 self.look_ahead(1, |t| t.can_begin_bound() &&
1528 !can_continue_type_after_non_fn_ident(t)) {
1529 self.bump(); // `dyn`
1530 // Always parse bounds greedily for better error recovery.
1531 let bounds = self.parse_generic_bounds()?;
1532 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1533 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1534 } else if self.check(&token::Question) ||
1535 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1536 // Bound list (trait object type)
1537 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1538 TraitObjectSyntax::None)
1539 } else if self.eat_lt() {
1541 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1542 TyKind::Path(Some(qself), path)
1543 } else if self.token.is_path_start() {
1545 let path = self.parse_path(PathStyle::Type)?;
1546 if self.eat(&token::Not) {
1547 // Macro invocation in type position
1548 let (delim, tts) = self.expect_delimited_token_tree()?;
1549 let node = Mac_ { path, tts, delim };
1550 TyKind::Mac(respan(lo.to(self.prev_span), node))
1552 // Just a type path or bound list (trait object type) starting with a trait.
1554 // `Trait1 + Trait2 + 'a`
1555 if allow_plus && self.check_plus() {
1556 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1558 TyKind::Path(None, path)
1562 let msg = format!("expected type, found {}", self.this_token_descr());
1563 return Err(self.fatal(&msg));
1566 let span = lo.to(self.prev_span);
1567 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1569 // Try to recover from use of `+` with incorrect priority.
1570 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1571 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1572 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1577 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1578 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1579 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1580 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1582 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1583 bounds.append(&mut self.parse_generic_bounds()?);
1585 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1588 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1589 if !allow_plus && impl_dyn_multi {
1590 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1591 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1592 .span_suggestion_with_applicability(
1594 "use parentheses to disambiguate",
1596 Applicability::MachineApplicable
1601 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1602 // Do not add `+` to expected tokens.
1603 if !allow_plus || !self.token.is_like_plus() {
1608 let bounds = self.parse_generic_bounds()?;
1609 let sum_span = ty.span.to(self.prev_span);
1611 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1612 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1615 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1616 let sum_with_parens = pprust::to_string(|s| {
1617 use print::pprust::PrintState;
1620 s.print_opt_lifetime(lifetime)?;
1621 s.print_mutability(mut_ty.mutbl)?;
1623 s.print_type(&mut_ty.ty)?;
1624 s.print_type_bounds(" +", &bounds)?;
1627 err.span_suggestion_with_applicability(
1629 "try adding parentheses",
1631 Applicability::MachineApplicable
1634 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1635 err.span_label(sum_span, "perhaps you forgot parentheses?");
1638 err.span_label(sum_span, "expected a path");
1645 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1646 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1648 // Do not add `::` to expected tokens.
1649 if !allow_recovery || self.token != token::ModSep {
1652 let ty = match base.to_ty() {
1654 None => return Ok(base),
1657 self.bump(); // `::`
1658 let mut segments = Vec::new();
1659 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1661 let span = ty.span.to(self.prev_span);
1662 let path_span = span.to(span); // use an empty path since `position` == 0
1663 let recovered = base.to_recovered(
1664 Some(QSelf { ty, path_span, position: 0 }),
1665 ast::Path { segments, span },
1669 .struct_span_err(span, "missing angle brackets in associated item path")
1670 .span_suggestion_with_applicability( // this is a best-effort recovery
1671 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1677 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1678 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1679 let mutbl = self.parse_mutability();
1680 let ty = self.parse_ty_no_plus()?;
1681 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1684 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1685 let mutbl = if self.eat_keyword(keywords::Mut) {
1687 } else if self.eat_keyword(keywords::Const) {
1688 Mutability::Immutable
1690 let span = self.prev_span;
1692 "expected mut or const in raw pointer type (use \
1693 `*mut T` or `*const T` as appropriate)");
1694 Mutability::Immutable
1696 let t = self.parse_ty_no_plus()?;
1697 Ok(MutTy { ty: t, mutbl: mutbl })
1700 fn is_named_argument(&mut self) -> bool {
1701 let offset = match self.token {
1702 token::Interpolated(ref nt) => match nt.0 {
1703 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1706 token::BinOp(token::And) | token::AndAnd => 1,
1707 _ if self.token.is_keyword(keywords::Mut) => 1,
1711 self.look_ahead(offset, |t| t.is_ident()) &&
1712 self.look_ahead(offset + 1, |t| t == &token::Colon)
1715 /// This version of parse arg doesn't necessarily require
1716 /// identifier names.
1717 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1718 maybe_whole!(self, NtArg, |x| x);
1720 let (pat, ty) = if require_name || self.is_named_argument() {
1721 debug!("parse_arg_general parse_pat (require_name:{})",
1723 let pat = self.parse_pat()?;
1725 self.expect(&token::Colon)?;
1726 (pat, self.parse_ty()?)
1728 debug!("parse_arg_general ident_to_pat");
1729 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1730 let ty = self.parse_ty()?;
1732 id: ast::DUMMY_NODE_ID,
1733 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
1742 id: ast::DUMMY_NODE_ID,
1746 /// Parse a single function argument
1747 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1748 self.parse_arg_general(true)
1751 /// Parse an argument in a lambda header e.g. |arg, arg|
1752 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1753 let pat = self.parse_pat()?;
1754 let t = if self.eat(&token::Colon) {
1758 id: ast::DUMMY_NODE_ID,
1759 node: TyKind::Infer,
1766 id: ast::DUMMY_NODE_ID
1770 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1771 if self.eat(&token::Semi) {
1772 Ok(Some(self.parse_expr()?))
1778 /// Matches token_lit = LIT_INTEGER | ...
1779 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1780 let out = match self.token {
1781 token::Interpolated(ref nt) => match nt.0 {
1782 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1783 ExprKind::Lit(ref lit) => { lit.node.clone() }
1784 _ => { return self.unexpected_last(&self.token); }
1786 _ => { return self.unexpected_last(&self.token); }
1788 token::Literal(lit, suf) => {
1789 let diag = Some((self.span, &self.sess.span_diagnostic));
1790 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1794 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1799 _ => { return self.unexpected_last(&self.token); }
1806 /// Matches lit = true | false | token_lit
1807 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1809 let lit = if self.eat_keyword(keywords::True) {
1811 } else if self.eat_keyword(keywords::False) {
1812 LitKind::Bool(false)
1814 let lit = self.parse_lit_token()?;
1817 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1820 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1821 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1822 maybe_whole_expr!(self);
1824 let minus_lo = self.span;
1825 let minus_present = self.eat(&token::BinOp(token::Minus));
1827 let literal = P(self.parse_lit()?);
1828 let hi = self.prev_span;
1829 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1832 let minus_hi = self.prev_span;
1833 let unary = self.mk_unary(UnOp::Neg, expr);
1834 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1840 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1842 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1843 let span = self.span;
1845 Ok(Ident::new(ident.name, span))
1847 _ => self.parse_ident(),
1851 /// Parses qualified path.
1852 /// Assumes that the leading `<` has been parsed already.
1854 /// `qualified_path = <type [as trait_ref]>::path`
1859 /// `<T as U>::F::a<S>` (without disambiguator)
1860 /// `<T as U>::F::a::<S>` (with disambiguator)
1861 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1862 let lo = self.prev_span;
1863 let ty = self.parse_ty()?;
1865 // `path` will contain the prefix of the path up to the `>`,
1866 // if any (e.g., `U` in the `<T as U>::*` examples
1867 // above). `path_span` has the span of that path, or an empty
1868 // span in the case of something like `<T>::Bar`.
1869 let (mut path, path_span);
1870 if self.eat_keyword(keywords::As) {
1871 let path_lo = self.span;
1872 path = self.parse_path(PathStyle::Type)?;
1873 path_span = path_lo.to(self.prev_span);
1875 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1876 path_span = self.span.to(self.span);
1879 self.expect(&token::Gt)?;
1880 self.expect(&token::ModSep)?;
1882 let qself = QSelf { ty, path_span, position: path.segments.len() };
1883 self.parse_path_segments(&mut path.segments, style, true)?;
1885 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1888 /// Parses simple paths.
1890 /// `path = [::] segment+`
1891 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1894 /// `a::b::C<D>` (without disambiguator)
1895 /// `a::b::C::<D>` (with disambiguator)
1896 /// `Fn(Args)` (without disambiguator)
1897 /// `Fn::(Args)` (with disambiguator)
1898 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1899 self.parse_path_common(style, true)
1902 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1903 -> PResult<'a, ast::Path> {
1904 maybe_whole!(self, NtPath, |path| {
1905 if style == PathStyle::Mod &&
1906 path.segments.iter().any(|segment| segment.args.is_some()) {
1907 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1912 let lo = self.meta_var_span.unwrap_or(self.span);
1913 let mut segments = Vec::new();
1914 if self.eat(&token::ModSep) {
1915 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1917 self.parse_path_segments(&mut segments, style, enable_warning)?;
1919 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1922 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1923 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1924 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1925 let meta_ident = match self.token {
1926 token::Interpolated(ref nt) => match nt.0 {
1927 token::NtMeta(ref meta) => match meta.node {
1928 ast::MetaItemKind::Word => Some(meta.ident.clone()),
1935 if let Some(path) = meta_ident {
1939 self.parse_path(style)
1942 fn parse_path_segments(&mut self,
1943 segments: &mut Vec<PathSegment>,
1945 enable_warning: bool)
1946 -> PResult<'a, ()> {
1948 segments.push(self.parse_path_segment(style, enable_warning)?);
1950 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1956 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1957 -> PResult<'a, PathSegment> {
1958 let ident = self.parse_path_segment_ident()?;
1960 let is_args_start = |token: &token::Token| match *token {
1961 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1964 let check_args_start = |this: &mut Self| {
1965 this.expected_tokens.extend_from_slice(
1966 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1968 is_args_start(&this.token)
1971 Ok(if style == PathStyle::Type && check_args_start(self) ||
1972 style != PathStyle::Mod && self.check(&token::ModSep)
1973 && self.look_ahead(1, |t| is_args_start(t)) {
1974 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1976 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1977 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1978 .span_label(self.prev_span, "try removing `::`").emit();
1981 let args = if self.eat_lt() {
1983 let (args, bindings) = self.parse_generic_args()?;
1985 let span = lo.to(self.prev_span);
1986 AngleBracketedArgs { args, bindings, span }.into()
1990 let inputs = self.parse_seq_to_before_tokens(
1991 &[&token::CloseDelim(token::Paren)],
1992 SeqSep::trailing_allowed(token::Comma),
1993 TokenExpectType::Expect,
1996 let output = if self.eat(&token::RArrow) {
1997 Some(self.parse_ty_common(false, false)?)
2001 let span = lo.to(self.prev_span);
2002 ParenthesisedArgs { inputs, output, span }.into()
2005 PathSegment { ident, args }
2007 // Generic arguments are not found.
2008 PathSegment::from_ident(ident)
2012 crate fn check_lifetime(&mut self) -> bool {
2013 self.expected_tokens.push(TokenType::Lifetime);
2014 self.token.is_lifetime()
2017 /// Parse single lifetime 'a or panic.
2018 crate fn expect_lifetime(&mut self) -> Lifetime {
2019 if let Some(ident) = self.token.lifetime() {
2020 let span = self.span;
2022 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2024 self.span_bug(self.span, "not a lifetime")
2028 fn eat_label(&mut self) -> Option<Label> {
2029 if let Some(ident) = self.token.lifetime() {
2030 let span = self.span;
2032 Some(Label { ident: Ident::new(ident.name, span) })
2038 /// Parse mutability (`mut` or nothing).
2039 fn parse_mutability(&mut self) -> Mutability {
2040 if self.eat_keyword(keywords::Mut) {
2043 Mutability::Immutable
2047 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2048 if let token::Literal(token::Integer(name), None) = self.token {
2050 Ok(Ident::new(name, self.prev_span))
2052 self.parse_ident_common(false)
2056 /// Parse ident (COLON expr)?
2057 fn parse_field(&mut self) -> PResult<'a, Field> {
2058 let attrs = self.parse_outer_attributes()?;
2061 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2062 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2063 let fieldname = self.parse_field_name()?;
2065 (fieldname, self.parse_expr()?, false)
2067 let fieldname = self.parse_ident_common(false)?;
2069 // Mimic `x: x` for the `x` field shorthand.
2070 let path = ast::Path::from_ident(fieldname);
2071 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2072 (fieldname, expr, true)
2076 span: lo.to(expr.span),
2079 attrs: attrs.into(),
2083 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2084 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2087 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2088 ExprKind::Unary(unop, expr)
2091 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2092 ExprKind::Binary(binop, lhs, rhs)
2095 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2096 ExprKind::Call(f, args)
2099 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2100 ExprKind::Index(expr, idx)
2103 fn mk_range(&mut self,
2104 start: Option<P<Expr>>,
2105 end: Option<P<Expr>>,
2106 limits: RangeLimits)
2107 -> PResult<'a, ast::ExprKind> {
2108 if end.is_none() && limits == RangeLimits::Closed {
2109 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2111 Ok(ExprKind::Range(start, end, limits))
2115 fn mk_assign_op(&mut self, binop: ast::BinOp,
2116 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2117 ExprKind::AssignOp(binop, lhs, rhs)
2120 fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2122 id: ast::DUMMY_NODE_ID,
2123 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2129 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2130 let delim = match self.token {
2131 token::OpenDelim(delim) => delim,
2133 let msg = "expected open delimiter";
2134 let mut err = self.fatal(msg);
2135 err.span_label(self.span, msg);
2139 let delimited = match self.parse_token_tree() {
2140 TokenTree::Delimited(_, delimited) => delimited,
2141 _ => unreachable!(),
2143 let delim = match delim {
2144 token::Paren => MacDelimiter::Parenthesis,
2145 token::Bracket => MacDelimiter::Bracket,
2146 token::Brace => MacDelimiter::Brace,
2147 token::NoDelim => self.bug("unexpected no delimiter"),
2149 Ok((delim, delimited.stream().into()))
2152 /// At the bottom (top?) of the precedence hierarchy,
2153 /// parse things like parenthesized exprs,
2154 /// macros, return, etc.
2156 /// NB: This does not parse outer attributes,
2157 /// and is private because it only works
2158 /// correctly if called from parse_dot_or_call_expr().
2159 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2160 maybe_whole_expr!(self);
2162 // Outer attributes are already parsed and will be
2163 // added to the return value after the fact.
2165 // Therefore, prevent sub-parser from parsing
2166 // attributes by giving them a empty "already parsed" list.
2167 let mut attrs = ThinVec::new();
2170 let mut hi = self.span;
2174 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2176 token::OpenDelim(token::Paren) => {
2179 attrs.extend(self.parse_inner_attributes()?);
2181 // (e) is parenthesized e
2182 // (e,) is a tuple with only one field, e
2183 let mut es = vec![];
2184 let mut trailing_comma = false;
2185 while self.token != token::CloseDelim(token::Paren) {
2186 es.push(self.parse_expr()?);
2187 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2188 if self.check(&token::Comma) {
2189 trailing_comma = true;
2193 trailing_comma = false;
2199 hi = self.prev_span;
2200 ex = if es.len() == 1 && !trailing_comma {
2201 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2206 token::OpenDelim(token::Brace) => {
2207 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2209 token::BinOp(token::Or) | token::OrOr => {
2210 return self.parse_lambda_expr(attrs);
2212 token::OpenDelim(token::Bracket) => {
2215 attrs.extend(self.parse_inner_attributes()?);
2217 if self.check(&token::CloseDelim(token::Bracket)) {
2220 ex = ExprKind::Array(Vec::new());
2223 let first_expr = self.parse_expr()?;
2224 if self.check(&token::Semi) {
2225 // Repeating array syntax: [ 0; 512 ]
2227 let count = AnonConst {
2228 id: ast::DUMMY_NODE_ID,
2229 value: self.parse_expr()?,
2231 self.expect(&token::CloseDelim(token::Bracket))?;
2232 ex = ExprKind::Repeat(first_expr, count);
2233 } else if self.check(&token::Comma) {
2234 // Vector with two or more elements.
2236 let remaining_exprs = self.parse_seq_to_end(
2237 &token::CloseDelim(token::Bracket),
2238 SeqSep::trailing_allowed(token::Comma),
2239 |p| Ok(p.parse_expr()?)
2241 let mut exprs = vec![first_expr];
2242 exprs.extend(remaining_exprs);
2243 ex = ExprKind::Array(exprs);
2245 // Vector with one element.
2246 self.expect(&token::CloseDelim(token::Bracket))?;
2247 ex = ExprKind::Array(vec![first_expr]);
2250 hi = self.prev_span;
2254 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2256 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2258 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2259 return self.parse_lambda_expr(attrs);
2261 if self.eat_keyword(keywords::If) {
2262 return self.parse_if_expr(attrs);
2264 if self.eat_keyword(keywords::For) {
2265 let lo = self.prev_span;
2266 return self.parse_for_expr(None, lo, attrs);
2268 if self.eat_keyword(keywords::While) {
2269 let lo = self.prev_span;
2270 return self.parse_while_expr(None, lo, attrs);
2272 if let Some(label) = self.eat_label() {
2273 let lo = label.ident.span;
2274 self.expect(&token::Colon)?;
2275 if self.eat_keyword(keywords::While) {
2276 return self.parse_while_expr(Some(label), lo, attrs)
2278 if self.eat_keyword(keywords::For) {
2279 return self.parse_for_expr(Some(label), lo, attrs)
2281 if self.eat_keyword(keywords::Loop) {
2282 return self.parse_loop_expr(Some(label), lo, attrs)
2284 if self.token == token::OpenDelim(token::Brace) {
2285 return self.parse_block_expr(Some(label),
2287 BlockCheckMode::Default,
2290 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2291 let mut err = self.fatal(msg);
2292 err.span_label(self.span, msg);
2295 if self.eat_keyword(keywords::Loop) {
2296 let lo = self.prev_span;
2297 return self.parse_loop_expr(None, lo, attrs);
2299 if self.eat_keyword(keywords::Continue) {
2300 let label = self.eat_label();
2301 let ex = ExprKind::Continue(label);
2302 let hi = self.prev_span;
2303 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2305 if self.eat_keyword(keywords::Match) {
2306 return self.parse_match_expr(attrs);
2308 if self.eat_keyword(keywords::Unsafe) {
2309 return self.parse_block_expr(
2312 BlockCheckMode::Unsafe(ast::UserProvided),
2315 if self.is_catch_expr() {
2317 assert!(self.eat_keyword(keywords::Do));
2318 assert!(self.eat_keyword(keywords::Catch));
2319 return self.parse_catch_expr(lo, attrs);
2321 if self.eat_keyword(keywords::Return) {
2322 if self.token.can_begin_expr() {
2323 let e = self.parse_expr()?;
2325 ex = ExprKind::Ret(Some(e));
2327 ex = ExprKind::Ret(None);
2329 } else if self.eat_keyword(keywords::Break) {
2330 let label = self.eat_label();
2331 let e = if self.token.can_begin_expr()
2332 && !(self.token == token::OpenDelim(token::Brace)
2333 && self.restrictions.contains(
2334 Restrictions::NO_STRUCT_LITERAL)) {
2335 Some(self.parse_expr()?)
2339 ex = ExprKind::Break(label, e);
2340 hi = self.prev_span;
2341 } else if self.eat_keyword(keywords::Yield) {
2342 if self.token.can_begin_expr() {
2343 let e = self.parse_expr()?;
2345 ex = ExprKind::Yield(Some(e));
2347 ex = ExprKind::Yield(None);
2349 } else if self.token.is_keyword(keywords::Let) {
2350 // Catch this syntax error here, instead of in `parse_ident`, so
2351 // that we can explicitly mention that let is not to be used as an expression
2352 let mut db = self.fatal("expected expression, found statement (`let`)");
2353 db.span_label(self.span, "expected expression");
2354 db.note("variable declaration using `let` is a statement");
2356 } else if self.token.is_path_start() {
2357 let pth = self.parse_path(PathStyle::Expr)?;
2359 // `!`, as an operator, is prefix, so we know this isn't that
2360 if self.eat(&token::Not) {
2361 // MACRO INVOCATION expression
2362 let (delim, tts) = self.expect_delimited_token_tree()?;
2363 let hi = self.prev_span;
2364 let node = Mac_ { path: pth, tts, delim };
2365 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2367 if self.check(&token::OpenDelim(token::Brace)) {
2368 // This is a struct literal, unless we're prohibited
2369 // from parsing struct literals here.
2370 let prohibited = self.restrictions.contains(
2371 Restrictions::NO_STRUCT_LITERAL
2374 return self.parse_struct_expr(lo, pth, attrs);
2379 ex = ExprKind::Path(None, pth);
2381 match self.parse_literal_maybe_minus() {
2384 ex = expr.node.clone();
2387 self.cancel(&mut err);
2388 let msg = format!("expected expression, found {}",
2389 self.this_token_descr());
2390 let mut err = self.fatal(&msg);
2391 err.span_label(self.span, "expected expression");
2399 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2400 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2405 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2406 -> PResult<'a, P<Expr>> {
2407 let struct_sp = lo.to(self.prev_span);
2409 let mut fields = Vec::new();
2410 let mut base = None;
2412 attrs.extend(self.parse_inner_attributes()?);
2414 while self.token != token::CloseDelim(token::Brace) {
2415 if self.eat(&token::DotDot) {
2416 let exp_span = self.prev_span;
2417 match self.parse_expr() {
2423 self.recover_stmt();
2426 if self.token == token::Comma {
2427 let mut err = self.sess.span_diagnostic.mut_span_err(
2428 exp_span.to(self.prev_span),
2429 "cannot use a comma after the base struct",
2431 err.span_suggestion_short_with_applicability(
2433 "remove this comma",
2435 Applicability::MachineApplicable
2437 err.note("the base struct must always be the last field");
2439 self.recover_stmt();
2444 match self.parse_field() {
2445 Ok(f) => fields.push(f),
2447 e.span_label(struct_sp, "while parsing this struct");
2449 self.recover_stmt();
2454 match self.expect_one_of(&[token::Comma],
2455 &[token::CloseDelim(token::Brace)]) {
2459 self.recover_stmt();
2465 let span = lo.to(self.span);
2466 self.expect(&token::CloseDelim(token::Brace))?;
2467 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2470 fn parse_or_use_outer_attributes(&mut self,
2471 already_parsed_attrs: Option<ThinVec<Attribute>>)
2472 -> PResult<'a, ThinVec<Attribute>> {
2473 if let Some(attrs) = already_parsed_attrs {
2476 self.parse_outer_attributes().map(|a| a.into())
2480 /// Parse a block or unsafe block
2481 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2482 lo: Span, blk_mode: BlockCheckMode,
2483 outer_attrs: ThinVec<Attribute>)
2484 -> PResult<'a, P<Expr>> {
2485 self.expect(&token::OpenDelim(token::Brace))?;
2487 let mut attrs = outer_attrs;
2488 attrs.extend(self.parse_inner_attributes()?);
2490 let blk = self.parse_block_tail(lo, blk_mode)?;
2491 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2494 /// parse a.b or a(13) or a[4] or just a
2495 fn parse_dot_or_call_expr(&mut self,
2496 already_parsed_attrs: Option<ThinVec<Attribute>>)
2497 -> PResult<'a, P<Expr>> {
2498 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2500 let b = self.parse_bottom_expr();
2501 let (span, b) = self.interpolated_or_expr_span(b)?;
2502 self.parse_dot_or_call_expr_with(b, span, attrs)
2505 fn parse_dot_or_call_expr_with(&mut self,
2508 mut attrs: ThinVec<Attribute>)
2509 -> PResult<'a, P<Expr>> {
2510 // Stitch the list of outer attributes onto the return value.
2511 // A little bit ugly, but the best way given the current code
2513 self.parse_dot_or_call_expr_with_(e0, lo)
2515 expr.map(|mut expr| {
2516 attrs.extend::<Vec<_>>(expr.attrs.into());
2519 ExprKind::If(..) | ExprKind::IfLet(..) => {
2520 if !expr.attrs.is_empty() {
2521 // Just point to the first attribute in there...
2522 let span = expr.attrs[0].span;
2525 "attributes are not yet allowed on `if` \
2536 // Assuming we have just parsed `.`, continue parsing into an expression.
2537 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2538 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2539 Ok(match self.token {
2540 token::OpenDelim(token::Paren) => {
2541 // Method call `expr.f()`
2542 let mut args = self.parse_unspanned_seq(
2543 &token::OpenDelim(token::Paren),
2544 &token::CloseDelim(token::Paren),
2545 SeqSep::trailing_allowed(token::Comma),
2546 |p| Ok(p.parse_expr()?)
2548 args.insert(0, self_arg);
2550 let span = lo.to(self.prev_span);
2551 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2554 // Field access `expr.f`
2555 if let Some(args) = segment.args {
2556 self.span_err(args.span(),
2557 "field expressions may not have generic arguments");
2560 let span = lo.to(self.prev_span);
2561 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2566 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2571 while self.eat(&token::Question) {
2572 let hi = self.prev_span;
2573 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2577 if self.eat(&token::Dot) {
2579 token::Ident(..) => {
2580 e = self.parse_dot_suffix(e, lo)?;
2582 token::Literal(token::Integer(name), _) => {
2583 let span = self.span;
2585 let field = ExprKind::Field(e, Ident::new(name, span));
2586 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2588 token::Literal(token::Float(n), _suf) => {
2590 let fstr = n.as_str();
2591 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2592 &format!("unexpected token: `{}`", n));
2593 err.span_label(self.prev_span, "unexpected token");
2594 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2595 let float = match fstr.parse::<f64>().ok() {
2599 let sugg = pprust::to_string(|s| {
2600 use print::pprust::PrintState;
2604 s.print_usize(float.trunc() as usize)?;
2607 s.s.word(fstr.splitn(2, ".").last().unwrap())
2609 err.span_suggestion_with_applicability(
2610 lo.to(self.prev_span),
2611 "try parenthesizing the first index",
2613 Applicability::MachineApplicable
2620 // FIXME Could factor this out into non_fatal_unexpected or something.
2621 let actual = self.this_token_to_string();
2622 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2627 if self.expr_is_complete(&e) { break; }
2630 token::OpenDelim(token::Paren) => {
2631 let es = self.parse_unspanned_seq(
2632 &token::OpenDelim(token::Paren),
2633 &token::CloseDelim(token::Paren),
2634 SeqSep::trailing_allowed(token::Comma),
2635 |p| Ok(p.parse_expr()?)
2637 hi = self.prev_span;
2639 let nd = self.mk_call(e, es);
2640 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2644 // Could be either an index expression or a slicing expression.
2645 token::OpenDelim(token::Bracket) => {
2647 let ix = self.parse_expr()?;
2649 self.expect(&token::CloseDelim(token::Bracket))?;
2650 let index = self.mk_index(e, ix);
2651 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2659 crate fn process_potential_macro_variable(&mut self) {
2660 let (token, span) = match self.token {
2661 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2662 self.look_ahead(1, |t| t.is_ident()) => {
2664 let name = match self.token {
2665 token::Ident(ident, _) => ident,
2668 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2669 err.span_label(self.span, "unknown macro variable");
2673 token::Interpolated(ref nt) => {
2674 self.meta_var_span = Some(self.span);
2675 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2676 // and lifetime tokens, so the former are never encountered during normal parsing.
2678 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2679 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2689 /// parse a single token tree from the input.
2690 crate fn parse_token_tree(&mut self) -> TokenTree {
2692 token::OpenDelim(..) => {
2693 let frame = mem::replace(&mut self.token_cursor.frame,
2694 self.token_cursor.stack.pop().unwrap());
2695 self.span = frame.span;
2697 TokenTree::Delimited(frame.span, Delimited {
2699 tts: frame.tree_cursor.original_stream().into(),
2702 token::CloseDelim(_) | token::Eof => unreachable!(),
2704 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2706 TokenTree::Token(span, token)
2711 // parse a stream of tokens into a list of TokenTree's,
2713 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2714 let mut tts = Vec::new();
2715 while self.token != token::Eof {
2716 tts.push(self.parse_token_tree());
2721 pub fn parse_tokens(&mut self) -> TokenStream {
2722 let mut result = Vec::new();
2725 token::Eof | token::CloseDelim(..) => break,
2726 _ => result.push(self.parse_token_tree().into()),
2729 TokenStream::concat(result)
2732 /// Parse a prefix-unary-operator expr
2733 fn parse_prefix_expr(&mut self,
2734 already_parsed_attrs: Option<ThinVec<Attribute>>)
2735 -> PResult<'a, P<Expr>> {
2736 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2738 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2739 let (hi, ex) = match self.token {
2742 let e = self.parse_prefix_expr(None);
2743 let (span, e) = self.interpolated_or_expr_span(e)?;
2744 (lo.to(span), self.mk_unary(UnOp::Not, e))
2746 // Suggest `!` for bitwise negation when encountering a `~`
2749 let e = self.parse_prefix_expr(None);
2750 let (span, e) = self.interpolated_or_expr_span(e)?;
2751 let span_of_tilde = lo;
2752 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2753 "`~` cannot be used as a unary operator");
2754 err.span_suggestion_short_with_applicability(
2756 "use `!` to perform bitwise negation",
2758 Applicability::MachineApplicable
2761 (lo.to(span), self.mk_unary(UnOp::Not, e))
2763 token::BinOp(token::Minus) => {
2765 let e = self.parse_prefix_expr(None);
2766 let (span, e) = self.interpolated_or_expr_span(e)?;
2767 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2769 token::BinOp(token::Star) => {
2771 let e = self.parse_prefix_expr(None);
2772 let (span, e) = self.interpolated_or_expr_span(e)?;
2773 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2775 token::BinOp(token::And) | token::AndAnd => {
2777 let m = self.parse_mutability();
2778 let e = self.parse_prefix_expr(None);
2779 let (span, e) = self.interpolated_or_expr_span(e)?;
2780 (lo.to(span), ExprKind::AddrOf(m, e))
2782 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2784 let place = self.parse_expr_res(
2785 Restrictions::NO_STRUCT_LITERAL,
2788 let blk = self.parse_block()?;
2789 let span = blk.span;
2790 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2791 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2793 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2795 let e = self.parse_prefix_expr(None);
2796 let (span, e) = self.interpolated_or_expr_span(e)?;
2797 (lo.to(span), ExprKind::Box(e))
2799 token::Ident(..) if self.token.is_ident_named("not") => {
2800 // `not` is just an ordinary identifier in Rust-the-language,
2801 // but as `rustc`-the-compiler, we can issue clever diagnostics
2802 // for confused users who really want to say `!`
2803 let token_cannot_continue_expr = |t: &token::Token| match *t {
2804 // These tokens can start an expression after `!`, but
2805 // can't continue an expression after an ident
2806 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2807 token::Literal(..) | token::Pound => true,
2808 token::Interpolated(ref nt) => match nt.0 {
2809 token::NtIdent(..) | token::NtExpr(..) |
2810 token::NtBlock(..) | token::NtPath(..) => true,
2815 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2816 if cannot_continue_expr {
2818 // Emit the error ...
2819 let mut err = self.diagnostic()
2820 .struct_span_err(self.span,
2821 &format!("unexpected {} after identifier",
2822 self.this_token_descr()));
2823 // span the `not` plus trailing whitespace to avoid
2824 // trailing whitespace after the `!` in our suggestion
2825 let to_replace = self.sess.codemap()
2826 .span_until_non_whitespace(lo.to(self.span));
2827 err.span_suggestion_short_with_applicability(
2829 "use `!` to perform logical negation",
2831 Applicability::MachineApplicable
2834 // —and recover! (just as if we were in the block
2835 // for the `token::Not` arm)
2836 let e = self.parse_prefix_expr(None);
2837 let (span, e) = self.interpolated_or_expr_span(e)?;
2838 (lo.to(span), self.mk_unary(UnOp::Not, e))
2840 return self.parse_dot_or_call_expr(Some(attrs));
2843 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2845 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2848 /// Parse an associative expression
2850 /// This parses an expression accounting for associativity and precedence of the operators in
2852 fn parse_assoc_expr(&mut self,
2853 already_parsed_attrs: Option<ThinVec<Attribute>>)
2854 -> PResult<'a, P<Expr>> {
2855 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2858 /// Parse an associative expression with operators of at least `min_prec` precedence
2859 fn parse_assoc_expr_with(&mut self,
2862 -> PResult<'a, P<Expr>> {
2863 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2866 let attrs = match lhs {
2867 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2870 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2871 return self.parse_prefix_range_expr(attrs);
2873 self.parse_prefix_expr(attrs)?
2877 if self.expr_is_complete(&lhs) {
2878 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2881 self.expected_tokens.push(TokenType::Operator);
2882 while let Some(op) = AssocOp::from_token(&self.token) {
2884 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2885 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2886 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2887 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2888 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2889 (PrevTokenKind::Interpolated, _) => self.prev_span,
2890 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2891 if path.segments.len() == 1 => self.prev_span,
2895 let cur_op_span = self.span;
2896 let restrictions = if op.is_assign_like() {
2897 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2901 if op.precedence() < min_prec {
2904 // Check for deprecated `...` syntax
2905 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2906 self.err_dotdotdot_syntax(self.span);
2910 if op.is_comparison() {
2911 self.check_no_chained_comparison(&lhs, &op);
2914 if op == AssocOp::As {
2915 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2917 } else if op == AssocOp::Colon {
2918 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2921 err.span_label(self.span,
2922 "expecting a type here because of type ascription");
2923 let cm = self.sess.codemap();
2924 let cur_pos = cm.lookup_char_pos(self.span.lo());
2925 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2926 if cur_pos.line != op_pos.line {
2927 err.span_suggestion_with_applicability(
2929 "try using a semicolon",
2931 Applicability::MaybeIncorrect // speculative
2938 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2939 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2940 // generalise it to the Fixity::None code.
2942 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2943 // two variants are handled with `parse_prefix_range_expr` call above.
2944 let rhs = if self.is_at_start_of_range_notation_rhs() {
2945 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2946 LhsExpr::NotYetParsed)?)
2950 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2955 let limits = if op == AssocOp::DotDot {
2956 RangeLimits::HalfOpen
2961 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2962 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2966 let rhs = match op.fixity() {
2967 Fixity::Right => self.with_res(
2968 restrictions - Restrictions::STMT_EXPR,
2970 this.parse_assoc_expr_with(op.precedence(),
2971 LhsExpr::NotYetParsed)
2973 Fixity::Left => self.with_res(
2974 restrictions - Restrictions::STMT_EXPR,
2976 this.parse_assoc_expr_with(op.precedence() + 1,
2977 LhsExpr::NotYetParsed)
2979 // We currently have no non-associative operators that are not handled above by
2980 // the special cases. The code is here only for future convenience.
2981 Fixity::None => self.with_res(
2982 restrictions - Restrictions::STMT_EXPR,
2984 this.parse_assoc_expr_with(op.precedence() + 1,
2985 LhsExpr::NotYetParsed)
2989 let span = lhs_span.to(rhs.span);
2991 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2992 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2993 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2994 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2995 AssocOp::Greater | AssocOp::GreaterEqual => {
2996 let ast_op = op.to_ast_binop().unwrap();
2997 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2998 self.mk_expr(span, binary, ThinVec::new())
3001 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3002 AssocOp::ObsoleteInPlace =>
3003 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3004 AssocOp::AssignOp(k) => {
3006 token::Plus => BinOpKind::Add,
3007 token::Minus => BinOpKind::Sub,
3008 token::Star => BinOpKind::Mul,
3009 token::Slash => BinOpKind::Div,
3010 token::Percent => BinOpKind::Rem,
3011 token::Caret => BinOpKind::BitXor,
3012 token::And => BinOpKind::BitAnd,
3013 token::Or => BinOpKind::BitOr,
3014 token::Shl => BinOpKind::Shl,
3015 token::Shr => BinOpKind::Shr,
3017 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3018 self.mk_expr(span, aopexpr, ThinVec::new())
3020 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3021 self.bug("AssocOp should have been handled by special case")
3025 if op.fixity() == Fixity::None { break }
3030 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3031 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3032 -> PResult<'a, P<Expr>> {
3033 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3034 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3037 // Save the state of the parser before parsing type normally, in case there is a
3038 // LessThan comparison after this cast.
3039 let parser_snapshot_before_type = self.clone();
3040 match self.parse_ty_no_plus() {
3042 Ok(mk_expr(self, rhs))
3044 Err(mut type_err) => {
3045 // Rewind to before attempting to parse the type with generics, to recover
3046 // from situations like `x as usize < y` in which we first tried to parse
3047 // `usize < y` as a type with generic arguments.
3048 let parser_snapshot_after_type = self.clone();
3049 mem::replace(self, parser_snapshot_before_type);
3051 match self.parse_path(PathStyle::Expr) {
3053 let (op_noun, op_verb) = match self.token {
3054 token::Lt => ("comparison", "comparing"),
3055 token::BinOp(token::Shl) => ("shift", "shifting"),
3057 // We can end up here even without `<` being the next token, for
3058 // example because `parse_ty_no_plus` returns `Err` on keywords,
3059 // but `parse_path` returns `Ok` on them due to error recovery.
3060 // Return original error and parser state.
3061 mem::replace(self, parser_snapshot_after_type);
3062 return Err(type_err);
3066 // Successfully parsed the type path leaving a `<` yet to parse.
3069 // Report non-fatal diagnostics, keep `x as usize` as an expression
3070 // in AST and continue parsing.
3071 let msg = format!("`<` is interpreted as a start of generic \
3072 arguments for `{}`, not a {}", path, op_noun);
3073 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3074 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3075 "interpreted as generic arguments");
3076 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3078 let expr = mk_expr(self, P(Ty {
3080 node: TyKind::Path(None, path),
3081 id: ast::DUMMY_NODE_ID
3084 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3085 .unwrap_or(pprust::expr_to_string(&expr));
3086 err.span_suggestion_with_applicability(
3088 &format!("try {} the cast value", op_verb),
3089 format!("({})", expr_str),
3090 Applicability::MachineApplicable
3096 Err(mut path_err) => {
3097 // Couldn't parse as a path, return original error and parser state.
3099 mem::replace(self, parser_snapshot_after_type);
3107 /// Produce an error if comparison operators are chained (RFC #558).
3108 /// We only need to check lhs, not rhs, because all comparison ops
3109 /// have same precedence and are left-associative
3110 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3111 debug_assert!(outer_op.is_comparison(),
3112 "check_no_chained_comparison: {:?} is not comparison",
3115 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3116 // respan to include both operators
3117 let op_span = op.span.to(self.span);
3118 let mut err = self.diagnostic().struct_span_err(op_span,
3119 "chained comparison operators require parentheses");
3120 if op.node == BinOpKind::Lt &&
3121 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3122 *outer_op == AssocOp::Greater // even in a case like the following:
3123 { // Foo<Bar<Baz<Qux, ()>>>
3125 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3126 err.help("or use `(...)` if you meant to specify fn arguments");
3134 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3135 fn parse_prefix_range_expr(&mut self,
3136 already_parsed_attrs: Option<ThinVec<Attribute>>)
3137 -> PResult<'a, P<Expr>> {
3138 // Check for deprecated `...` syntax
3139 if self.token == token::DotDotDot {
3140 self.err_dotdotdot_syntax(self.span);
3143 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3144 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3146 let tok = self.token.clone();
3147 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3149 let mut hi = self.span;
3151 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3152 // RHS must be parsed with more associativity than the dots.
3153 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3154 Some(self.parse_assoc_expr_with(next_prec,
3155 LhsExpr::NotYetParsed)
3163 let limits = if tok == token::DotDot {
3164 RangeLimits::HalfOpen
3169 let r = try!(self.mk_range(None,
3172 Ok(self.mk_expr(lo.to(hi), r, attrs))
3175 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3176 if self.token.can_begin_expr() {
3177 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3178 if self.token == token::OpenDelim(token::Brace) {
3179 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3187 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3188 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3189 if self.check_keyword(keywords::Let) {
3190 return self.parse_if_let_expr(attrs);
3192 let lo = self.prev_span;
3193 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3195 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3196 // verify that the last statement is either an implicit return (no `;`) or an explicit
3197 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3198 // the dead code lint.
3199 if self.eat_keyword(keywords::Else) || !cond.returns() {
3200 let sp = self.sess.codemap().next_point(lo);
3201 let mut err = self.diagnostic()
3202 .struct_span_err(sp, "missing condition for `if` statemement");
3203 err.span_label(sp, "expected if condition here");
3206 let not_block = self.token != token::OpenDelim(token::Brace);
3207 let thn = self.parse_block().map_err(|mut err| {
3209 err.span_label(lo, "this `if` statement has a condition, but no block");
3213 let mut els: Option<P<Expr>> = None;
3214 let mut hi = thn.span;
3215 if self.eat_keyword(keywords::Else) {
3216 let elexpr = self.parse_else_expr()?;
3220 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3223 /// Parse an 'if let' expression ('if' token already eaten)
3224 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3225 -> PResult<'a, P<Expr>> {
3226 let lo = self.prev_span;
3227 self.expect_keyword(keywords::Let)?;
3228 let pats = self.parse_pats()?;
3229 self.expect(&token::Eq)?;
3230 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3231 let thn = self.parse_block()?;
3232 let (hi, els) = if self.eat_keyword(keywords::Else) {
3233 let expr = self.parse_else_expr()?;
3234 (expr.span, Some(expr))
3238 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3241 // `move |args| expr`
3242 fn parse_lambda_expr(&mut self,
3243 attrs: ThinVec<Attribute>)
3244 -> PResult<'a, P<Expr>>
3247 let movability = if self.eat_keyword(keywords::Static) {
3252 let capture_clause = if self.eat_keyword(keywords::Move) {
3257 let decl = self.parse_fn_block_decl()?;
3258 let decl_hi = self.prev_span;
3259 let body = match decl.output {
3260 FunctionRetTy::Default(_) => {
3261 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3262 self.parse_expr_res(restrictions, None)?
3265 // If an explicit return type is given, require a
3266 // block to appear (RFC 968).
3267 let body_lo = self.span;
3268 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3274 ExprKind::Closure(capture_clause, movability, decl, body, lo.to(decl_hi)),
3278 // `else` token already eaten
3279 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3280 if self.eat_keyword(keywords::If) {
3281 return self.parse_if_expr(ThinVec::new());
3283 let blk = self.parse_block()?;
3284 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3288 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3289 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3291 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3292 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3294 let pat = self.parse_top_level_pat()?;
3295 if !self.eat_keyword(keywords::In) {
3296 let in_span = self.prev_span.between(self.span);
3297 let mut err = self.sess.span_diagnostic
3298 .struct_span_err(in_span, "missing `in` in `for` loop");
3299 err.span_suggestion_short_with_applicability(
3300 in_span, "try adding `in` here", " in ".into(),
3301 // has been misleading, at least in the past (closed Issue #48492)
3302 Applicability::MaybeIncorrect
3306 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3307 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3308 attrs.extend(iattrs);
3310 let hi = self.prev_span;
3311 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3314 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3315 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3317 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3318 if self.token.is_keyword(keywords::Let) {
3319 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3321 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3322 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3323 attrs.extend(iattrs);
3324 let span = span_lo.to(body.span);
3325 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3328 /// Parse a 'while let' expression ('while' token already eaten)
3329 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3331 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3332 self.expect_keyword(keywords::Let)?;
3333 let pats = self.parse_pats()?;
3334 self.expect(&token::Eq)?;
3335 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3336 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3337 attrs.extend(iattrs);
3338 let span = span_lo.to(body.span);
3339 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3342 // parse `loop {...}`, `loop` token already eaten
3343 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3345 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3346 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3347 attrs.extend(iattrs);
3348 let span = span_lo.to(body.span);
3349 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3352 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3353 fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3354 -> PResult<'a, P<Expr>>
3356 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3357 attrs.extend(iattrs);
3358 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3361 // `match` token already eaten
3362 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3363 let match_span = self.prev_span;
3364 let lo = self.prev_span;
3365 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3367 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3368 if self.token == token::Token::Semi {
3369 e.span_suggestion_short_with_applicability(
3371 "try removing this `match`",
3373 Applicability::MaybeIncorrect // speculative
3378 attrs.extend(self.parse_inner_attributes()?);
3380 let mut arms: Vec<Arm> = Vec::new();
3381 while self.token != token::CloseDelim(token::Brace) {
3382 match self.parse_arm() {
3383 Ok(arm) => arms.push(arm),
3385 // Recover by skipping to the end of the block.
3387 self.recover_stmt();
3388 let span = lo.to(self.span);
3389 if self.token == token::CloseDelim(token::Brace) {
3392 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3398 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3401 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3402 maybe_whole!(self, NtArm, |x| x);
3404 let attrs = self.parse_outer_attributes()?;
3405 // Allow a '|' before the pats (RFC 1925)
3406 self.eat(&token::BinOp(token::Or));
3407 let pats = self.parse_pats()?;
3408 let guard = if self.eat_keyword(keywords::If) {
3409 Some(self.parse_expr()?)
3413 let arrow_span = self.span;
3414 self.expect(&token::FatArrow)?;
3415 let arm_start_span = self.span;
3417 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3418 .map_err(|mut err| {
3419 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3423 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3424 && self.token != token::CloseDelim(token::Brace);
3427 let cm = self.sess.codemap();
3428 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3429 .map_err(|mut err| {
3430 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3431 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3432 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3433 && expr_lines.lines.len() == 2
3434 && self.token == token::FatArrow => {
3435 // We check wether there's any trailing code in the parse span, if there
3436 // isn't, we very likely have the following:
3439 // | -- - missing comma
3445 // | parsed until here as `"y" & X`
3446 err.span_suggestion_short_with_applicability(
3447 cm.next_point(arm_start_span),
3448 "missing a comma here to end this `match` arm",
3450 Applicability::MachineApplicable
3454 err.span_label(arrow_span,
3455 "while parsing the `match` arm starting here");
3461 self.eat(&token::Comma);
3472 /// Parse an expression
3473 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3474 self.parse_expr_res(Restrictions::empty(), None)
3477 /// Evaluate the closure with restrictions in place.
3479 /// After the closure is evaluated, restrictions are reset.
3480 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3481 where F: FnOnce(&mut Self) -> T
3483 let old = self.restrictions;
3484 self.restrictions = r;
3486 self.restrictions = old;
3491 /// Parse an expression, subject to the given restrictions
3492 fn parse_expr_res(&mut self, r: Restrictions,
3493 already_parsed_attrs: Option<ThinVec<Attribute>>)
3494 -> PResult<'a, P<Expr>> {
3495 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3498 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3499 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3500 if self.check(&token::Eq) {
3502 Ok(Some(self.parse_expr()?))
3504 Ok(Some(self.parse_expr()?))
3510 /// Parse patterns, separated by '|' s
3511 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3512 let mut pats = Vec::new();
3514 pats.push(self.parse_top_level_pat()?);
3516 if self.token == token::OrOr {
3517 let mut err = self.struct_span_err(self.span,
3518 "unexpected token `||` after pattern");
3519 err.span_suggestion_with_applicability(
3521 "use a single `|` to specify multiple patterns",
3523 Applicability::MachineApplicable
3527 } else if self.check(&token::BinOp(token::Or)) {
3535 // Parses a parenthesized list of patterns like
3536 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3537 // - a vector of the patterns that were parsed
3538 // - an option indicating the index of the `..` element
3539 // - a boolean indicating whether a trailing comma was present.
3540 // Trailing commas are significant because (p) and (p,) are different patterns.
3541 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3542 self.expect(&token::OpenDelim(token::Paren))?;
3543 let result = self.parse_pat_list()?;
3544 self.expect(&token::CloseDelim(token::Paren))?;
3548 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3549 let mut fields = Vec::new();
3550 let mut ddpos = None;
3551 let mut trailing_comma = false;
3553 if self.eat(&token::DotDot) {
3554 if ddpos.is_none() {
3555 ddpos = Some(fields.len());
3557 // Emit a friendly error, ignore `..` and continue parsing
3558 self.span_err(self.prev_span,
3559 "`..` can only be used once per tuple or tuple struct pattern");
3561 } else if !self.check(&token::CloseDelim(token::Paren)) {
3562 fields.push(self.parse_pat()?);
3567 trailing_comma = self.eat(&token::Comma);
3568 if !trailing_comma {
3573 if ddpos == Some(fields.len()) && trailing_comma {
3574 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3575 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3578 Ok((fields, ddpos, trailing_comma))
3581 fn parse_pat_vec_elements(
3583 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3584 let mut before = Vec::new();
3585 let mut slice = None;
3586 let mut after = Vec::new();
3587 let mut first = true;
3588 let mut before_slice = true;
3590 while self.token != token::CloseDelim(token::Bracket) {
3594 self.expect(&token::Comma)?;
3596 if self.token == token::CloseDelim(token::Bracket)
3597 && (before_slice || !after.is_empty()) {
3603 if self.eat(&token::DotDot) {
3605 if self.check(&token::Comma) ||
3606 self.check(&token::CloseDelim(token::Bracket)) {
3607 slice = Some(P(Pat {
3608 id: ast::DUMMY_NODE_ID,
3609 node: PatKind::Wild,
3610 span: self.prev_span,
3612 before_slice = false;
3618 let subpat = self.parse_pat()?;
3619 if before_slice && self.eat(&token::DotDot) {
3620 slice = Some(subpat);
3621 before_slice = false;
3622 } else if before_slice {
3623 before.push(subpat);
3629 Ok((before, slice, after))
3635 attrs: Vec<Attribute>
3636 ) -> PResult<'a, codemap::Spanned<ast::FieldPat>> {
3637 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3639 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3640 // Parsing a pattern of the form "fieldname: pat"
3641 let fieldname = self.parse_field_name()?;
3643 let pat = self.parse_pat()?;
3645 (pat, fieldname, false)
3647 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3648 let is_box = self.eat_keyword(keywords::Box);
3649 let boxed_span = self.span;
3650 let is_ref = self.eat_keyword(keywords::Ref);
3651 let is_mut = self.eat_keyword(keywords::Mut);
3652 let fieldname = self.parse_ident()?;
3653 hi = self.prev_span;
3655 let bind_type = match (is_ref, is_mut) {
3656 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3657 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3658 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3659 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3661 let fieldpat = P(Pat {
3662 id: ast::DUMMY_NODE_ID,
3663 node: PatKind::Ident(bind_type, fieldname, None),
3664 span: boxed_span.to(hi),
3667 let subpat = if is_box {
3669 id: ast::DUMMY_NODE_ID,
3670 node: PatKind::Box(fieldpat),
3676 (subpat, fieldname, true)
3679 Ok(codemap::Spanned {
3681 node: ast::FieldPat {
3685 attrs: attrs.into(),
3690 /// Parse the fields of a struct-like pattern
3691 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3692 let mut fields = Vec::new();
3693 let mut etc = false;
3694 let mut ate_comma = true;
3695 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3696 let mut etc_span = None;
3698 while self.token != token::CloseDelim(token::Brace) {
3699 let attrs = self.parse_outer_attributes()?;
3702 // check that a comma comes after every field
3704 let err = self.struct_span_err(self.prev_span, "expected `,`");
3709 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3711 let mut etc_sp = self.span;
3713 if self.token == token::DotDotDot { // Issue #46718
3714 // Accept `...` as if it were `..` to avoid further errors
3715 let mut err = self.struct_span_err(self.span,
3716 "expected field pattern, found `...`");
3717 err.span_suggestion_with_applicability(
3719 "to omit remaining fields, use one fewer `.`",
3721 Applicability::MachineApplicable
3725 self.bump(); // `..` || `...`:w
3727 if self.token == token::CloseDelim(token::Brace) {
3728 etc_span = Some(etc_sp);
3731 let token_str = self.this_token_to_string();
3732 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3734 err.span_label(self.span, "expected `}`");
3735 let mut comma_sp = None;
3736 if self.token == token::Comma { // Issue #49257
3737 etc_sp = etc_sp.to(self.sess.codemap().span_until_non_whitespace(self.span));
3738 err.span_label(etc_sp,
3739 "`..` must be at the end and cannot have a trailing comma");
3740 comma_sp = Some(self.span);
3745 etc_span = Some(etc_sp);
3746 if self.token == token::CloseDelim(token::Brace) {
3747 // If the struct looks otherwise well formed, recover and continue.
3748 if let Some(sp) = comma_sp {
3749 err.span_suggestion_short(sp, "remove this comma", "".into());
3753 } else if self.token.is_ident() && ate_comma {
3754 // Accept fields coming after `..,`.
3755 // This way we avoid "pattern missing fields" errors afterwards.
3756 // We delay this error until the end in order to have a span for a
3758 if let Some(mut delayed_err) = delayed_err {
3762 delayed_err = Some(err);
3765 if let Some(mut err) = delayed_err {
3772 fields.push(match self.parse_pat_field(lo, attrs) {
3775 if let Some(mut delayed_err) = delayed_err {
3781 ate_comma = self.eat(&token::Comma);
3784 if let Some(mut err) = delayed_err {
3785 if let Some(etc_span) = etc_span {
3786 err.multipart_suggestion(
3787 "move the `..` to the end of the field list",
3789 (etc_span, "".into()),
3790 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3796 return Ok((fields, etc));
3799 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3800 if self.token.is_path_start() {
3802 let (qself, path) = if self.eat_lt() {
3803 // Parse a qualified path
3804 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3807 // Parse an unqualified path
3808 (None, self.parse_path(PathStyle::Expr)?)
3810 let hi = self.prev_span;
3811 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3813 self.parse_literal_maybe_minus()
3817 // helper function to decide whether to parse as ident binding or to try to do
3818 // something more complex like range patterns
3819 fn parse_as_ident(&mut self) -> bool {
3820 self.look_ahead(1, |t| match *t {
3821 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3822 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3823 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3824 // range pattern branch
3825 token::DotDot => None,
3827 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3828 token::Comma | token::CloseDelim(token::Bracket) => true,
3833 /// A wrapper around `parse_pat` with some special error handling for the
3834 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contast
3835 /// to subpatterns within such).
3836 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3837 let pat = self.parse_pat()?;
3838 if self.token == token::Comma {
3839 // An unexpected comma after a top-level pattern is a clue that the
3840 // user (perhaps more accustomed to some other language) forgot the
3841 // parentheses in what should have been a tuple pattern; return a
3842 // suggestion-enhanced error here rather than choking on the comma
3844 let comma_span = self.span;
3846 if let Err(mut err) = self.parse_pat_list() {
3847 // We didn't expect this to work anyway; we just wanted
3848 // to advance to the end of the comma-sequence so we know
3849 // the span to suggest parenthesizing
3852 let seq_span = pat.span.to(self.prev_span);
3853 let mut err = self.struct_span_err(comma_span,
3854 "unexpected `,` in pattern");
3855 if let Ok(seq_snippet) = self.sess.codemap().span_to_snippet(seq_span) {
3856 err.span_suggestion_with_applicability(
3858 "try adding parentheses",
3859 format!("({})", seq_snippet),
3860 Applicability::MachineApplicable
3868 /// Parse a pattern.
3869 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3870 self.parse_pat_with_range_pat(true)
3873 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3875 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3876 maybe_whole!(self, NtPat, |x| x);
3881 token::BinOp(token::And) | token::AndAnd => {
3882 // Parse &pat / &mut pat
3884 let mutbl = self.parse_mutability();
3885 if let token::Lifetime(ident) = self.token {
3886 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3888 err.span_label(self.span, "unexpected lifetime");
3891 let subpat = self.parse_pat_with_range_pat(false)?;
3892 pat = PatKind::Ref(subpat, mutbl);
3894 token::OpenDelim(token::Paren) => {
3895 // Parse (pat,pat,pat,...) as tuple pattern
3896 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3897 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3898 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3900 PatKind::Tuple(fields, ddpos)
3903 token::OpenDelim(token::Bracket) => {
3904 // Parse [pat,pat,...] as slice pattern
3906 let (before, slice, after) = self.parse_pat_vec_elements()?;
3907 self.expect(&token::CloseDelim(token::Bracket))?;
3908 pat = PatKind::Slice(before, slice, after);
3910 // At this point, token != &, &&, (, [
3911 _ => if self.eat_keyword(keywords::Underscore) {
3913 pat = PatKind::Wild;
3914 } else if self.eat_keyword(keywords::Mut) {
3915 // Parse mut ident @ pat / mut ref ident @ pat
3916 let mutref_span = self.prev_span.to(self.span);
3917 let binding_mode = if self.eat_keyword(keywords::Ref) {
3919 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3920 .span_suggestion_with_applicability(
3922 "try switching the order",
3924 Applicability::MachineApplicable
3926 BindingMode::ByRef(Mutability::Mutable)
3928 BindingMode::ByValue(Mutability::Mutable)
3930 pat = self.parse_pat_ident(binding_mode)?;
3931 } else if self.eat_keyword(keywords::Ref) {
3932 // Parse ref ident @ pat / ref mut ident @ pat
3933 let mutbl = self.parse_mutability();
3934 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3935 } else if self.eat_keyword(keywords::Box) {
3937 let subpat = self.parse_pat_with_range_pat(false)?;
3938 pat = PatKind::Box(subpat);
3939 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3940 self.parse_as_ident() {
3941 // Parse ident @ pat
3942 // This can give false positives and parse nullary enums,
3943 // they are dealt with later in resolve
3944 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3945 pat = self.parse_pat_ident(binding_mode)?;
3946 } else if self.token.is_path_start() {
3947 // Parse pattern starting with a path
3948 let (qself, path) = if self.eat_lt() {
3949 // Parse a qualified path
3950 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3953 // Parse an unqualified path
3954 (None, self.parse_path(PathStyle::Expr)?)
3957 token::Not if qself.is_none() => {
3958 // Parse macro invocation
3960 let (delim, tts) = self.expect_delimited_token_tree()?;
3961 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
3962 pat = PatKind::Mac(mac);
3964 token::DotDotDot | token::DotDotEq | token::DotDot => {
3965 let end_kind = match self.token {
3966 token::DotDot => RangeEnd::Excluded,
3967 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3968 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3969 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3973 let span = lo.to(self.prev_span);
3974 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3976 let end = self.parse_pat_range_end()?;
3977 pat = PatKind::Range(begin, end, end_kind);
3979 token::OpenDelim(token::Brace) => {
3980 if qself.is_some() {
3981 let msg = "unexpected `{` after qualified path";
3982 let mut err = self.fatal(msg);
3983 err.span_label(self.span, msg);
3986 // Parse struct pattern
3988 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3990 self.recover_stmt();
3994 pat = PatKind::Struct(path, fields, etc);
3996 token::OpenDelim(token::Paren) => {
3997 if qself.is_some() {
3998 let msg = "unexpected `(` after qualified path";
3999 let mut err = self.fatal(msg);
4000 err.span_label(self.span, msg);
4003 // Parse tuple struct or enum pattern
4004 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4005 pat = PatKind::TupleStruct(path, fields, ddpos)
4007 _ => pat = PatKind::Path(qself, path),
4010 // Try to parse everything else as literal with optional minus
4011 match self.parse_literal_maybe_minus() {
4013 if self.eat(&token::DotDotDot) {
4014 let end = self.parse_pat_range_end()?;
4015 pat = PatKind::Range(begin, end,
4016 RangeEnd::Included(RangeSyntax::DotDotDot));
4017 } else if self.eat(&token::DotDotEq) {
4018 let end = self.parse_pat_range_end()?;
4019 pat = PatKind::Range(begin, end,
4020 RangeEnd::Included(RangeSyntax::DotDotEq));
4021 } else if self.eat(&token::DotDot) {
4022 let end = self.parse_pat_range_end()?;
4023 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
4025 pat = PatKind::Lit(begin);
4029 self.cancel(&mut err);
4030 let msg = format!("expected pattern, found {}", self.this_token_descr());
4031 let mut err = self.fatal(&msg);
4032 err.span_label(self.span, "expected pattern");
4039 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4040 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4042 if !allow_range_pat {
4044 PatKind::Range(_, _, RangeEnd::Included(RangeSyntax::DotDotDot)) => {}
4045 PatKind::Range(..) => {
4046 let mut err = self.struct_span_err(
4048 "the range pattern here has ambiguous interpretation",
4050 err.span_suggestion_with_applicability(
4052 "add parentheses to clarify the precedence",
4053 format!("({})", pprust::pat_to_string(&pat)),
4054 // "ambiguous interpretation" implies that we have to be guessing
4055 Applicability::MaybeIncorrect
4066 /// Parse ident or ident @ pat
4067 /// used by the copy foo and ref foo patterns to give a good
4068 /// error message when parsing mistakes like ref foo(a,b)
4069 fn parse_pat_ident(&mut self,
4070 binding_mode: ast::BindingMode)
4071 -> PResult<'a, PatKind> {
4072 let ident = self.parse_ident()?;
4073 let sub = if self.eat(&token::At) {
4074 Some(self.parse_pat()?)
4079 // just to be friendly, if they write something like
4081 // we end up here with ( as the current token. This shortly
4082 // leads to a parse error. Note that if there is no explicit
4083 // binding mode then we do not end up here, because the lookahead
4084 // will direct us over to parse_enum_variant()
4085 if self.token == token::OpenDelim(token::Paren) {
4086 return Err(self.span_fatal(
4088 "expected identifier, found enum pattern"))
4091 Ok(PatKind::Ident(binding_mode, ident, sub))
4094 /// Parse a local variable declaration
4095 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4096 let lo = self.prev_span;
4097 let pat = self.parse_top_level_pat()?;
4099 let (err, ty) = if self.eat(&token::Colon) {
4100 // Save the state of the parser before parsing type normally, in case there is a `:`
4101 // instead of an `=` typo.
4102 let parser_snapshot_before_type = self.clone();
4103 let colon_sp = self.prev_span;
4104 match self.parse_ty() {
4105 Ok(ty) => (None, Some(ty)),
4107 // Rewind to before attempting to parse the type and continue parsing
4108 let parser_snapshot_after_type = self.clone();
4109 mem::replace(self, parser_snapshot_before_type);
4111 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
4112 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4113 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4119 let init = match (self.parse_initializer(err.is_some()), err) {
4120 (Ok(init), None) => { // init parsed, ty parsed
4123 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4124 // Could parse the type as if it were the initializer, it is likely there was a
4125 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4126 err.span_suggestion_short_with_applicability(
4128 "use `=` if you meant to assign",
4130 Applicability::MachineApplicable
4133 // As this was parsed successfully, continue as if the code has been fixed for the
4134 // rest of the file. It will still fail due to the emitted error, but we avoid
4138 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4140 // Couldn't parse the type nor the initializer, only raise the type error and
4141 // return to the parser state before parsing the type as the initializer.
4142 // let x: <parse_error>;
4143 mem::replace(self, snapshot);
4146 (Err(err), None) => { // init error, ty parsed
4147 // Couldn't parse the initializer and we're not attempting to recover a failed
4148 // parse of the type, return the error.
4152 let hi = if self.token == token::Semi {
4161 id: ast::DUMMY_NODE_ID,
4167 /// Parse a structure field
4168 fn parse_name_and_ty(&mut self,
4171 attrs: Vec<Attribute>)
4172 -> PResult<'a, StructField> {
4173 let name = self.parse_ident()?;
4174 self.expect(&token::Colon)?;
4175 let ty = self.parse_ty()?;
4177 span: lo.to(self.prev_span),
4180 id: ast::DUMMY_NODE_ID,
4186 /// Emit an expected item after attributes error.
4187 fn expected_item_err(&self, attrs: &[Attribute]) {
4188 let message = match attrs.last() {
4189 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4190 _ => "expected item after attributes",
4193 self.span_err(self.prev_span, message);
4196 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4197 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4198 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4199 Ok(self.parse_stmt_(true))
4202 // Eat tokens until we can be relatively sure we reached the end of the
4203 // statement. This is something of a best-effort heuristic.
4205 // We terminate when we find an unmatched `}` (without consuming it).
4206 fn recover_stmt(&mut self) {
4207 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4210 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4211 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4212 // approximate - it can mean we break too early due to macros, but that
4213 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4215 // If `break_on_block` is `Break`, then we will stop consuming tokens
4216 // after finding (and consuming) a brace-delimited block.
4217 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4218 let mut brace_depth = 0;
4219 let mut bracket_depth = 0;
4220 let mut in_block = false;
4221 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4222 break_on_semi, break_on_block);
4224 debug!("recover_stmt_ loop {:?}", self.token);
4226 token::OpenDelim(token::DelimToken::Brace) => {
4229 if break_on_block == BlockMode::Break &&
4231 bracket_depth == 0 {
4235 token::OpenDelim(token::DelimToken::Bracket) => {
4239 token::CloseDelim(token::DelimToken::Brace) => {
4240 if brace_depth == 0 {
4241 debug!("recover_stmt_ return - close delim {:?}", self.token);
4246 if in_block && bracket_depth == 0 && brace_depth == 0 {
4247 debug!("recover_stmt_ return - block end {:?}", self.token);
4251 token::CloseDelim(token::DelimToken::Bracket) => {
4253 if bracket_depth < 0 {
4259 debug!("recover_stmt_ return - Eof");
4264 if break_on_semi == SemiColonMode::Break &&
4266 bracket_depth == 0 {
4267 debug!("recover_stmt_ return - Semi");
4278 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4279 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4281 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4286 fn is_catch_expr(&mut self) -> bool {
4287 self.token.is_keyword(keywords::Do) &&
4288 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4289 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4291 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4292 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4295 fn is_union_item(&self) -> bool {
4296 self.token.is_keyword(keywords::Union) &&
4297 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4300 fn is_crate_vis(&self) -> bool {
4301 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4304 fn is_extern_non_path(&self) -> bool {
4305 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4308 fn is_auto_trait_item(&mut self) -> bool {
4310 (self.token.is_keyword(keywords::Auto)
4311 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4312 || // unsafe auto trait
4313 (self.token.is_keyword(keywords::Unsafe) &&
4314 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4315 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4318 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4319 -> PResult<'a, Option<P<Item>>> {
4320 let token_lo = self.span;
4321 let (ident, def) = match self.token {
4322 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4324 let ident = self.parse_ident()?;
4325 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4326 match self.parse_token_tree() {
4327 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4328 _ => unreachable!(),
4330 } else if self.check(&token::OpenDelim(token::Paren)) {
4331 let args = self.parse_token_tree();
4332 let body = if self.check(&token::OpenDelim(token::Brace)) {
4333 self.parse_token_tree()
4338 TokenStream::concat(vec![
4340 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4348 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4350 token::Ident(ident, _) if ident.name == "macro_rules" &&
4351 self.look_ahead(1, |t| *t == token::Not) => {
4352 let prev_span = self.prev_span;
4353 self.complain_if_pub_macro(&vis.node, prev_span);
4357 let ident = self.parse_ident()?;
4358 let (delim, tokens) = self.expect_delimited_token_tree()?;
4359 if delim != MacDelimiter::Brace {
4360 if !self.eat(&token::Semi) {
4361 let msg = "macros that expand to items must either \
4362 be surrounded with braces or followed by a semicolon";
4363 self.span_err(self.prev_span, msg);
4367 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4369 _ => return Ok(None),
4372 let span = lo.to(self.prev_span);
4373 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4376 fn parse_stmt_without_recovery(&mut self,
4377 macro_legacy_warnings: bool)
4378 -> PResult<'a, Option<Stmt>> {
4379 maybe_whole!(self, NtStmt, |x| Some(x));
4381 let attrs = self.parse_outer_attributes()?;
4384 Ok(Some(if self.eat_keyword(keywords::Let) {
4386 id: ast::DUMMY_NODE_ID,
4387 node: StmtKind::Local(self.parse_local(attrs.into())?),
4388 span: lo.to(self.prev_span),
4390 } else if let Some(macro_def) = self.eat_macro_def(
4392 &codemap::respan(lo, VisibilityKind::Inherited),
4396 id: ast::DUMMY_NODE_ID,
4397 node: StmtKind::Item(macro_def),
4398 span: lo.to(self.prev_span),
4400 // Starts like a simple path, being careful to avoid contextual keywords
4401 // such as a union items, item with `crate` visibility or auto trait items.
4402 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4403 // like a path (1 token), but it fact not a path.
4404 // `union::b::c` - path, `union U { ... }` - not a path.
4405 // `crate::b::c` - path, `crate struct S;` - not a path.
4406 // `extern::b::c` - path, `extern crate c;` - not a path.
4407 } else if self.token.is_path_start() &&
4408 !self.token.is_qpath_start() &&
4409 !self.is_union_item() &&
4410 !self.is_crate_vis() &&
4411 !self.is_extern_non_path() &&
4412 !self.is_auto_trait_item() {
4413 let pth = self.parse_path(PathStyle::Expr)?;
4415 if !self.eat(&token::Not) {
4416 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4417 self.parse_struct_expr(lo, pth, ThinVec::new())?
4419 let hi = self.prev_span;
4420 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4423 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4424 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4425 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4428 return Ok(Some(Stmt {
4429 id: ast::DUMMY_NODE_ID,
4430 node: StmtKind::Expr(expr),
4431 span: lo.to(self.prev_span),
4435 // it's a macro invocation
4436 let id = match self.token {
4437 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4438 _ => self.parse_ident()?,
4441 // check that we're pointing at delimiters (need to check
4442 // again after the `if`, because of `parse_ident`
4443 // consuming more tokens).
4445 token::OpenDelim(_) => {}
4447 // we only expect an ident if we didn't parse one
4449 let ident_str = if id.name == keywords::Invalid.name() {
4454 let tok_str = self.this_token_to_string();
4455 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4458 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4463 let (delim, tts) = self.expect_delimited_token_tree()?;
4464 let hi = self.prev_span;
4466 let style = if delim == MacDelimiter::Brace {
4467 MacStmtStyle::Braces
4469 MacStmtStyle::NoBraces
4472 if id.name == keywords::Invalid.name() {
4473 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4474 let node = if delim == MacDelimiter::Brace ||
4475 self.token == token::Semi || self.token == token::Eof {
4476 StmtKind::Mac(P((mac, style, attrs.into())))
4478 // We used to incorrectly stop parsing macro-expanded statements here.
4479 // If the next token will be an error anyway but could have parsed with the
4480 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4481 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4482 // These can continue an expression, so we can't stop parsing and warn.
4483 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4484 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4485 token::BinOp(token::And) | token::BinOp(token::Or) |
4486 token::AndAnd | token::OrOr |
4487 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4490 self.warn_missing_semicolon();
4491 StmtKind::Mac(P((mac, style, attrs.into())))
4493 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4494 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4495 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4499 id: ast::DUMMY_NODE_ID,
4504 // if it has a special ident, it's definitely an item
4506 // Require a semicolon or braces.
4507 if style != MacStmtStyle::Braces {
4508 if !self.eat(&token::Semi) {
4509 self.span_err(self.prev_span,
4510 "macros that expand to items must \
4511 either be surrounded with braces or \
4512 followed by a semicolon");
4515 let span = lo.to(hi);
4517 id: ast::DUMMY_NODE_ID,
4519 node: StmtKind::Item({
4521 span, id /*id is good here*/,
4522 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4523 respan(lo, VisibilityKind::Inherited),
4529 // FIXME: Bad copy of attrs
4530 let old_directory_ownership =
4531 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4532 let item = self.parse_item_(attrs.clone(), false, true)?;
4533 self.directory.ownership = old_directory_ownership;
4537 id: ast::DUMMY_NODE_ID,
4538 span: lo.to(i.span),
4539 node: StmtKind::Item(i),
4542 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4543 if !attrs.is_empty() {
4544 if s.prev_token_kind == PrevTokenKind::DocComment {
4545 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4546 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4547 s.span_err(s.span, "expected statement after outer attribute");
4552 // Do not attempt to parse an expression if we're done here.
4553 if self.token == token::Semi {
4554 unused_attrs(&attrs, self);
4559 if self.token == token::CloseDelim(token::Brace) {
4560 unused_attrs(&attrs, self);
4564 // Remainder are line-expr stmts.
4565 let e = self.parse_expr_res(
4566 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4568 id: ast::DUMMY_NODE_ID,
4569 span: lo.to(e.span),
4570 node: StmtKind::Expr(e),
4577 /// Is this expression a successfully-parsed statement?
4578 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4579 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4580 !classify::expr_requires_semi_to_be_stmt(e)
4583 /// Parse a block. No inner attrs are allowed.
4584 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4585 maybe_whole!(self, NtBlock, |x| x);
4589 if !self.eat(&token::OpenDelim(token::Brace)) {
4591 let tok = self.this_token_to_string();
4592 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4594 // Check to see if the user has written something like
4599 // Which is valid in other languages, but not Rust.
4600 match self.parse_stmt_without_recovery(false) {
4602 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) {
4603 // if the next token is an open brace (e.g., `if a b {`), the place-
4604 // inside-a-block suggestion would be more likely wrong than right
4607 let mut stmt_span = stmt.span;
4608 // expand the span to include the semicolon, if it exists
4609 if self.eat(&token::Semi) {
4610 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4612 let sugg = pprust::to_string(|s| {
4613 use print::pprust::{PrintState, INDENT_UNIT};
4614 s.ibox(INDENT_UNIT)?;
4616 s.print_stmt(&stmt)?;
4617 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4619 e.span_suggestion_with_applicability(
4621 "try placing this code inside a block",
4623 // speculative, has been misleading in the past (closed Issue #46836)
4624 Applicability::MaybeIncorrect
4628 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4629 self.cancel(&mut e);
4636 self.parse_block_tail(lo, BlockCheckMode::Default)
4639 /// Parse a block. Inner attrs are allowed.
4640 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4641 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4644 self.expect(&token::OpenDelim(token::Brace))?;
4645 Ok((self.parse_inner_attributes()?,
4646 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4649 /// Parse the rest of a block expression or function body
4650 /// Precondition: already parsed the '{'.
4651 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4652 let mut stmts = vec![];
4653 let mut recovered = false;
4655 while !self.eat(&token::CloseDelim(token::Brace)) {
4656 let stmt = match self.parse_full_stmt(false) {
4659 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4660 self.eat(&token::CloseDelim(token::Brace));
4666 if let Some(stmt) = stmt {
4668 } else if self.token == token::Eof {
4671 // Found only `;` or `}`.
4677 id: ast::DUMMY_NODE_ID,
4679 span: lo.to(self.prev_span),
4684 /// Parse a statement, including the trailing semicolon.
4685 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4686 // skip looking for a trailing semicolon when we have an interpolated statement
4687 maybe_whole!(self, NtStmt, |x| Some(x));
4689 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4691 None => return Ok(None),
4695 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4696 // expression without semicolon
4697 if classify::expr_requires_semi_to_be_stmt(expr) {
4698 // Just check for errors and recover; do not eat semicolon yet.
4700 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4703 self.recover_stmt();
4707 StmtKind::Local(..) => {
4708 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4709 if macro_legacy_warnings && self.token != token::Semi {
4710 self.warn_missing_semicolon();
4712 self.expect_one_of(&[], &[token::Semi])?;
4718 if self.eat(&token::Semi) {
4719 stmt = stmt.add_trailing_semicolon();
4722 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4726 fn warn_missing_semicolon(&self) {
4727 self.diagnostic().struct_span_warn(self.span, {
4728 &format!("expected `;`, found `{}`", self.this_token_to_string())
4730 "This was erroneously allowed and will become a hard error in a future release"
4734 fn err_dotdotdot_syntax(&self, span: Span) {
4735 self.diagnostic().struct_span_err(span, {
4736 "`...` syntax cannot be used in expressions"
4738 "Use `..` if you need an exclusive range (a < b)"
4740 "or `..=` if you need an inclusive range (a <= b)"
4744 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4745 // BOUND = TY_BOUND | LT_BOUND
4746 // LT_BOUND = LIFETIME (e.g. `'a`)
4747 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4748 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4749 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4750 let mut bounds = Vec::new();
4752 // This needs to be syncronized with `Token::can_begin_bound`.
4753 let is_bound_start = self.check_path() || self.check_lifetime() ||
4754 self.check(&token::Question) ||
4755 self.check_keyword(keywords::For) ||
4756 self.check(&token::OpenDelim(token::Paren));
4759 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4760 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4761 if self.token.is_lifetime() {
4762 if let Some(question_span) = question {
4763 self.span_err(question_span,
4764 "`?` may only modify trait bounds, not lifetime bounds");
4766 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4768 self.expect(&token::CloseDelim(token::Paren))?;
4769 self.span_err(self.prev_span,
4770 "parenthesized lifetime bounds are not supported");
4773 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4774 let path = self.parse_path(PathStyle::Type)?;
4776 self.expect(&token::CloseDelim(token::Paren))?;
4778 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4779 let modifier = if question.is_some() {
4780 TraitBoundModifier::Maybe
4782 TraitBoundModifier::None
4784 bounds.push(GenericBound::Trait(poly_trait, modifier));
4790 if !allow_plus || !self.eat_plus() {
4798 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
4799 self.parse_generic_bounds_common(true)
4802 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4803 // BOUND = LT_BOUND (e.g. `'a`)
4804 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4805 let mut lifetimes = Vec::new();
4806 while self.check_lifetime() {
4807 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4809 if !self.eat_plus() {
4816 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4817 fn parse_ty_param(&mut self,
4818 preceding_attrs: Vec<Attribute>)
4819 -> PResult<'a, GenericParam> {
4820 let ident = self.parse_ident()?;
4822 // Parse optional colon and param bounds.
4823 let bounds = if self.eat(&token::Colon) {
4824 self.parse_generic_bounds()?
4829 let default = if self.eat(&token::Eq) {
4830 Some(self.parse_ty()?)
4837 id: ast::DUMMY_NODE_ID,
4838 attrs: preceding_attrs.into(),
4840 kind: GenericParamKind::Type {
4846 /// Parses the following grammar:
4847 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4848 fn parse_trait_item_assoc_ty(&mut self)
4849 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4850 let ident = self.parse_ident()?;
4851 let mut generics = self.parse_generics()?;
4853 // Parse optional colon and param bounds.
4854 let bounds = if self.eat(&token::Colon) {
4855 self.parse_generic_bounds()?
4859 generics.where_clause = self.parse_where_clause()?;
4861 let default = if self.eat(&token::Eq) {
4862 Some(self.parse_ty()?)
4866 self.expect(&token::Semi)?;
4868 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4871 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4872 /// trailing comma and erroneous trailing attributes.
4873 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4874 let mut params = Vec::new();
4875 let mut seen_ty_param = false;
4877 let attrs = self.parse_outer_attributes()?;
4878 if self.check_lifetime() {
4879 let lifetime = self.expect_lifetime();
4880 // Parse lifetime parameter.
4881 let bounds = if self.eat(&token::Colon) {
4882 self.parse_lt_param_bounds()
4886 params.push(ast::GenericParam {
4887 ident: lifetime.ident,
4889 attrs: attrs.into(),
4891 kind: ast::GenericParamKind::Lifetime,
4894 self.span_err(self.prev_span,
4895 "lifetime parameters must be declared prior to type parameters");
4897 } else if self.check_ident() {
4898 // Parse type parameter.
4899 params.push(self.parse_ty_param(attrs)?);
4900 seen_ty_param = true;
4902 // Check for trailing attributes and stop parsing.
4903 if !attrs.is_empty() {
4904 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4905 self.span_err(attrs[0].span,
4906 &format!("trailing attribute after {} parameters", param_kind));
4911 if !self.eat(&token::Comma) {
4918 /// Parse a set of optional generic type parameter declarations. Where
4919 /// clauses are not parsed here, and must be added later via
4920 /// `parse_where_clause()`.
4922 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4923 /// | ( < lifetimes , typaramseq ( , )? > )
4924 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4925 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4926 maybe_whole!(self, NtGenerics, |x| x);
4928 let span_lo = self.span;
4930 let params = self.parse_generic_params()?;
4934 where_clause: WhereClause {
4935 id: ast::DUMMY_NODE_ID,
4936 predicates: Vec::new(),
4937 span: syntax_pos::DUMMY_SP,
4939 span: span_lo.to(self.prev_span),
4942 Ok(ast::Generics::default())
4946 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4947 /// possibly including trailing comma.
4948 fn parse_generic_args(&mut self)
4949 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
4950 let mut args = Vec::new();
4951 let mut bindings = Vec::new();
4952 let mut seen_type = false;
4953 let mut seen_binding = false;
4955 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
4956 // Parse lifetime argument.
4957 args.push(GenericArg::Lifetime(self.expect_lifetime()));
4958 if seen_type || seen_binding {
4959 self.span_err(self.prev_span,
4960 "lifetime parameters must be declared prior to type parameters");
4962 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4963 // Parse associated type binding.
4965 let ident = self.parse_ident()?;
4967 let ty = self.parse_ty()?;
4968 bindings.push(TypeBinding {
4969 id: ast::DUMMY_NODE_ID,
4972 span: lo.to(self.prev_span),
4974 seen_binding = true;
4975 } else if self.check_type() {
4976 // Parse type argument.
4977 let ty_param = self.parse_ty()?;
4979 self.span_err(ty_param.span,
4980 "type parameters must be declared prior to associated type bindings");
4982 args.push(GenericArg::Type(ty_param));
4988 if !self.eat(&token::Comma) {
4992 Ok((args, bindings))
4995 /// Parses an optional `where` clause and places it in `generics`.
4997 /// ```ignore (only-for-syntax-highlight)
4998 /// where T : Trait<U, V> + 'b, 'a : 'b
5000 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5001 maybe_whole!(self, NtWhereClause, |x| x);
5003 let mut where_clause = WhereClause {
5004 id: ast::DUMMY_NODE_ID,
5005 predicates: Vec::new(),
5006 span: syntax_pos::DUMMY_SP,
5009 if !self.eat_keyword(keywords::Where) {
5010 return Ok(where_clause);
5012 let lo = self.prev_span;
5014 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5015 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5016 // change we parse those generics now, but report an error.
5017 if self.choose_generics_over_qpath() {
5018 let generics = self.parse_generics()?;
5019 self.span_err(generics.span,
5020 "generic parameters on `where` clauses are reserved for future use");
5025 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5026 let lifetime = self.expect_lifetime();
5027 // Bounds starting with a colon are mandatory, but possibly empty.
5028 self.expect(&token::Colon)?;
5029 let bounds = self.parse_lt_param_bounds();
5030 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5031 ast::WhereRegionPredicate {
5032 span: lo.to(self.prev_span),
5037 } else if self.check_type() {
5038 // Parse optional `for<'a, 'b>`.
5039 // This `for` is parsed greedily and applies to the whole predicate,
5040 // the bounded type can have its own `for` applying only to it.
5041 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5042 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5043 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5044 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5046 // Parse type with mandatory colon and (possibly empty) bounds,
5047 // or with mandatory equality sign and the second type.
5048 let ty = self.parse_ty()?;
5049 if self.eat(&token::Colon) {
5050 let bounds = self.parse_generic_bounds()?;
5051 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5052 ast::WhereBoundPredicate {
5053 span: lo.to(self.prev_span),
5054 bound_generic_params: lifetime_defs,
5059 // FIXME: Decide what should be used here, `=` or `==`.
5060 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5061 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5062 let rhs_ty = self.parse_ty()?;
5063 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5064 ast::WhereEqPredicate {
5065 span: lo.to(self.prev_span),
5068 id: ast::DUMMY_NODE_ID,
5072 return self.unexpected();
5078 if !self.eat(&token::Comma) {
5083 where_clause.span = lo.to(self.prev_span);
5087 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5088 -> PResult<'a, (Vec<Arg> , bool)> {
5090 let mut variadic = false;
5091 let args: Vec<Option<Arg>> =
5092 self.parse_unspanned_seq(
5093 &token::OpenDelim(token::Paren),
5094 &token::CloseDelim(token::Paren),
5095 SeqSep::trailing_allowed(token::Comma),
5097 if p.token == token::DotDotDot {
5101 if p.token != token::CloseDelim(token::Paren) {
5104 "`...` must be last in argument list for variadic function");
5108 let span = p.prev_span;
5109 if p.token == token::CloseDelim(token::Paren) {
5110 // continue parsing to present any further errors
5113 "only foreign functions are allowed to be variadic"
5115 Ok(Some(dummy_arg(span)))
5117 // this function definition looks beyond recovery, stop parsing
5119 "only foreign functions are allowed to be variadic");
5124 match p.parse_arg_general(named_args) {
5125 Ok(arg) => Ok(Some(arg)),
5128 let lo = p.prev_span;
5129 // Skip every token until next possible arg or end.
5130 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5131 // Create a placeholder argument for proper arg count (#34264).
5132 let span = lo.to(p.prev_span);
5133 Ok(Some(dummy_arg(span)))
5140 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5142 if variadic && args.is_empty() {
5144 "variadic function must be declared with at least one named argument");
5147 Ok((args, variadic))
5150 /// Parse the argument list and result type of a function declaration
5151 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5153 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5154 let ret_ty = self.parse_ret_ty(true)?;
5163 /// Returns the parsed optional self argument and whether a self shortcut was used.
5164 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5165 let expect_ident = |this: &mut Self| match this.token {
5166 // Preserve hygienic context.
5167 token::Ident(ident, _) =>
5168 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5171 let isolated_self = |this: &mut Self, n| {
5172 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5173 this.look_ahead(n + 1, |t| t != &token::ModSep)
5176 // Parse optional self parameter of a method.
5177 // Only a limited set of initial token sequences is considered self parameters, anything
5178 // else is parsed as a normal function parameter list, so some lookahead is required.
5179 let eself_lo = self.span;
5180 let (eself, eself_ident, eself_hi) = match self.token {
5181 token::BinOp(token::And) => {
5187 (if isolated_self(self, 1) {
5189 SelfKind::Region(None, Mutability::Immutable)
5190 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5191 isolated_self(self, 2) {
5194 SelfKind::Region(None, Mutability::Mutable)
5195 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5196 isolated_self(self, 2) {
5198 let lt = self.expect_lifetime();
5199 SelfKind::Region(Some(lt), Mutability::Immutable)
5200 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5201 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5202 isolated_self(self, 3) {
5204 let lt = self.expect_lifetime();
5206 SelfKind::Region(Some(lt), Mutability::Mutable)
5209 }, expect_ident(self), self.prev_span)
5211 token::BinOp(token::Star) => {
5216 // Emit special error for `self` cases.
5217 (if isolated_self(self, 1) {
5219 self.span_err(self.span, "cannot pass `self` by raw pointer");
5220 SelfKind::Value(Mutability::Immutable)
5221 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5222 isolated_self(self, 2) {
5225 self.span_err(self.span, "cannot pass `self` by raw pointer");
5226 SelfKind::Value(Mutability::Immutable)
5229 }, expect_ident(self), self.prev_span)
5231 token::Ident(..) => {
5232 if isolated_self(self, 0) {
5235 let eself_ident = expect_ident(self);
5236 let eself_hi = self.prev_span;
5237 (if self.eat(&token::Colon) {
5238 let ty = self.parse_ty()?;
5239 SelfKind::Explicit(ty, Mutability::Immutable)
5241 SelfKind::Value(Mutability::Immutable)
5242 }, eself_ident, eself_hi)
5243 } else if self.token.is_keyword(keywords::Mut) &&
5244 isolated_self(self, 1) {
5248 let eself_ident = expect_ident(self);
5249 let eself_hi = self.prev_span;
5250 (if self.eat(&token::Colon) {
5251 let ty = self.parse_ty()?;
5252 SelfKind::Explicit(ty, Mutability::Mutable)
5254 SelfKind::Value(Mutability::Mutable)
5255 }, eself_ident, eself_hi)
5260 _ => return Ok(None),
5263 let eself = codemap::respan(eself_lo.to(eself_hi), eself);
5264 Ok(Some(Arg::from_self(eself, eself_ident)))
5267 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5268 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5269 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5271 self.expect(&token::OpenDelim(token::Paren))?;
5273 // Parse optional self argument
5274 let self_arg = self.parse_self_arg()?;
5276 // Parse the rest of the function parameter list.
5277 let sep = SeqSep::trailing_allowed(token::Comma);
5278 let fn_inputs = if let Some(self_arg) = self_arg {
5279 if self.check(&token::CloseDelim(token::Paren)) {
5281 } else if self.eat(&token::Comma) {
5282 let mut fn_inputs = vec![self_arg];
5283 fn_inputs.append(&mut self.parse_seq_to_before_end(
5284 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5288 return self.unexpected();
5291 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5294 // Parse closing paren and return type.
5295 self.expect(&token::CloseDelim(token::Paren))?;
5298 output: self.parse_ret_ty(true)?,
5303 // parse the |arg, arg| header on a lambda
5304 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5305 let inputs_captures = {
5306 if self.eat(&token::OrOr) {
5309 self.expect(&token::BinOp(token::Or))?;
5310 let args = self.parse_seq_to_before_tokens(
5311 &[&token::BinOp(token::Or), &token::OrOr],
5312 SeqSep::trailing_allowed(token::Comma),
5313 TokenExpectType::NoExpect,
5314 |p| p.parse_fn_block_arg()
5320 let output = self.parse_ret_ty(true)?;
5323 inputs: inputs_captures,
5329 /// Parse the name and optional generic types of a function header.
5330 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5331 let id = self.parse_ident()?;
5332 let generics = self.parse_generics()?;
5336 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5337 attrs: Vec<Attribute>) -> P<Item> {
5341 id: ast::DUMMY_NODE_ID,
5349 /// Parse an item-position function declaration.
5350 fn parse_item_fn(&mut self,
5352 constness: Spanned<Constness>,
5354 -> PResult<'a, ItemInfo> {
5355 let (ident, mut generics) = self.parse_fn_header()?;
5356 let decl = self.parse_fn_decl(false)?;
5357 generics.where_clause = self.parse_where_clause()?;
5358 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5359 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
5362 /// true if we are looking at `const ID`, false for things like `const fn` etc
5363 fn is_const_item(&mut self) -> bool {
5364 self.token.is_keyword(keywords::Const) &&
5365 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5366 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5369 /// parses all the "front matter" for a `fn` declaration, up to
5370 /// and including the `fn` keyword:
5374 /// - `const unsafe fn`
5377 fn parse_fn_front_matter(&mut self) -> PResult<'a, (Spanned<Constness>, Unsafety, Abi)> {
5378 let is_const_fn = self.eat_keyword(keywords::Const);
5379 let const_span = self.prev_span;
5380 let unsafety = self.parse_unsafety();
5381 let (constness, unsafety, abi) = if is_const_fn {
5382 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5384 let abi = if self.eat_keyword(keywords::Extern) {
5385 self.parse_opt_abi()?.unwrap_or(Abi::C)
5389 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5391 self.expect_keyword(keywords::Fn)?;
5392 Ok((constness, unsafety, abi))
5395 /// Parse an impl item.
5396 crate fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5397 maybe_whole!(self, NtImplItem, |x| x);
5398 let attrs = self.parse_outer_attributes()?;
5399 let (mut item, tokens) = self.collect_tokens(|this| {
5400 this.parse_impl_item_(at_end, attrs)
5403 // See `parse_item` for why this clause is here.
5404 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5405 item.tokens = Some(tokens);
5410 fn parse_impl_item_(&mut self,
5412 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5414 let vis = self.parse_visibility(false)?;
5415 let defaultness = self.parse_defaultness();
5416 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5417 // This parses the grammar:
5418 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5419 let name = self.parse_ident()?;
5420 let mut generics = self.parse_generics()?;
5421 generics.where_clause = self.parse_where_clause()?;
5422 self.expect(&token::Eq)?;
5423 let typ = self.parse_ty()?;
5424 self.expect(&token::Semi)?;
5425 (name, ast::ImplItemKind::Type(typ), generics)
5426 } else if self.is_const_item() {
5427 // This parses the grammar:
5428 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5429 self.expect_keyword(keywords::Const)?;
5430 let name = self.parse_ident()?;
5431 self.expect(&token::Colon)?;
5432 let typ = self.parse_ty()?;
5433 self.expect(&token::Eq)?;
5434 let expr = self.parse_expr()?;
5435 self.expect(&token::Semi)?;
5436 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5438 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5439 attrs.extend(inner_attrs);
5440 (name, node, generics)
5444 id: ast::DUMMY_NODE_ID,
5445 span: lo.to(self.prev_span),
5456 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5457 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5462 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5464 VisibilityKind::Inherited => Ok(()),
5466 let is_macro_rules: bool = match self.token {
5467 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5471 let mut err = self.diagnostic()
5472 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5473 err.span_suggestion_with_applicability(
5475 "try exporting the macro",
5476 "#[macro_export]".to_owned(),
5477 Applicability::MaybeIncorrect // speculative
5481 let mut err = self.diagnostic()
5482 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5483 err.help("try adjusting the macro to put `pub` inside the invocation");
5490 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5491 -> DiagnosticBuilder<'a>
5493 let expected_kinds = if item_type == "extern" {
5494 "missing `fn`, `type`, or `static`"
5496 "missing `fn`, `type`, or `const`"
5499 // Given this code `path(`, it seems like this is not
5500 // setting the visibility of a macro invocation, but rather
5501 // a mistyped method declaration.
5502 // Create a diagnostic pointing out that `fn` is missing.
5504 // x | pub path(&self) {
5505 // | ^ missing `fn`, `type`, or `const`
5507 // ^^ `sp` below will point to this
5508 let sp = prev_span.between(self.prev_span);
5509 let mut err = self.diagnostic().struct_span_err(
5511 &format!("{} for {}-item declaration",
5512 expected_kinds, item_type));
5513 err.span_label(sp, expected_kinds);
5517 /// Parse a method or a macro invocation in a trait impl.
5518 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5519 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5520 ast::ImplItemKind)> {
5521 // code copied from parse_macro_use_or_failure... abstraction!
5522 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5524 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5525 ast::ImplItemKind::Macro(mac)))
5527 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5528 let ident = self.parse_ident()?;
5529 let mut generics = self.parse_generics()?;
5530 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5531 generics.where_clause = self.parse_where_clause()?;
5533 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5534 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5543 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5544 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5545 let ident = self.parse_ident()?;
5546 let mut tps = self.parse_generics()?;
5548 // Parse optional colon and supertrait bounds.
5549 let bounds = if self.eat(&token::Colon) {
5550 self.parse_generic_bounds()?
5555 if self.eat(&token::Eq) {
5556 // it's a trait alias
5557 let bounds = self.parse_generic_bounds()?;
5558 tps.where_clause = self.parse_where_clause()?;
5559 self.expect(&token::Semi)?;
5560 if unsafety != Unsafety::Normal {
5561 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5563 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5565 // it's a normal trait
5566 tps.where_clause = self.parse_where_clause()?;
5567 self.expect(&token::OpenDelim(token::Brace))?;
5568 let mut trait_items = vec![];
5569 while !self.eat(&token::CloseDelim(token::Brace)) {
5570 let mut at_end = false;
5571 match self.parse_trait_item(&mut at_end) {
5572 Ok(item) => trait_items.push(item),
5576 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5581 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5585 fn choose_generics_over_qpath(&self) -> bool {
5586 // There's an ambiguity between generic parameters and qualified paths in impls.
5587 // If we see `<` it may start both, so we have to inspect some following tokens.
5588 // The following combinations can only start generics,
5589 // but not qualified paths (with one exception):
5590 // `<` `>` - empty generic parameters
5591 // `<` `#` - generic parameters with attributes
5592 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5593 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5594 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5595 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5596 // The only truly ambiguous case is
5597 // `<` IDENT `>` `::` IDENT ...
5598 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5599 // because this is what almost always expected in practice, qualified paths in impls
5600 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5601 self.token == token::Lt &&
5602 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5603 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5604 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5605 t == &token::Colon || t == &token::Eq))
5608 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5609 self.expect(&token::OpenDelim(token::Brace))?;
5610 let attrs = self.parse_inner_attributes()?;
5612 let mut impl_items = Vec::new();
5613 while !self.eat(&token::CloseDelim(token::Brace)) {
5614 let mut at_end = false;
5615 match self.parse_impl_item(&mut at_end) {
5616 Ok(impl_item) => impl_items.push(impl_item),
5620 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5625 Ok((impl_items, attrs))
5628 /// Parses an implementation item, `impl` keyword is already parsed.
5629 /// impl<'a, T> TYPE { /* impl items */ }
5630 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5631 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5632 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5633 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5634 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5635 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5636 -> PResult<'a, ItemInfo> {
5637 // First, parse generic parameters if necessary.
5638 let mut generics = if self.choose_generics_over_qpath() {
5639 self.parse_generics()?
5641 ast::Generics::default()
5644 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5645 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5647 ast::ImplPolarity::Negative
5649 ast::ImplPolarity::Positive
5652 // Parse both types and traits as a type, then reinterpret if necessary.
5653 let ty_first = self.parse_ty()?;
5655 // If `for` is missing we try to recover.
5656 let has_for = self.eat_keyword(keywords::For);
5657 let missing_for_span = self.prev_span.between(self.span);
5659 let ty_second = if self.token == token::DotDot {
5660 // We need to report this error after `cfg` expansion for compatibility reasons
5661 self.bump(); // `..`, do not add it to expected tokens
5662 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5663 } else if has_for || self.token.can_begin_type() {
5664 Some(self.parse_ty()?)
5669 generics.where_clause = self.parse_where_clause()?;
5671 let (impl_items, attrs) = self.parse_impl_body()?;
5673 let item_kind = match ty_second {
5674 Some(ty_second) => {
5675 // impl Trait for Type
5677 self.span_err(missing_for_span, "missing `for` in a trait impl");
5680 let ty_first = ty_first.into_inner();
5681 let path = match ty_first.node {
5682 // This notably includes paths passed through `ty` macro fragments (#46438).
5683 TyKind::Path(None, path) => path,
5685 self.span_err(ty_first.span, "expected a trait, found type");
5686 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5689 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5691 ItemKind::Impl(unsafety, polarity, defaultness,
5692 generics, Some(trait_ref), ty_second, impl_items)
5696 ItemKind::Impl(unsafety, polarity, defaultness,
5697 generics, None, ty_first, impl_items)
5701 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5704 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5705 if self.eat_keyword(keywords::For) {
5707 let params = self.parse_generic_params()?;
5709 // We rely on AST validation to rule out invalid cases: There must not be type
5710 // parameters, and the lifetime parameters must not have bounds.
5717 /// Parse struct Foo { ... }
5718 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5719 let class_name = self.parse_ident()?;
5721 let mut generics = self.parse_generics()?;
5723 // There is a special case worth noting here, as reported in issue #17904.
5724 // If we are parsing a tuple struct it is the case that the where clause
5725 // should follow the field list. Like so:
5727 // struct Foo<T>(T) where T: Copy;
5729 // If we are parsing a normal record-style struct it is the case
5730 // that the where clause comes before the body, and after the generics.
5731 // So if we look ahead and see a brace or a where-clause we begin
5732 // parsing a record style struct.
5734 // Otherwise if we look ahead and see a paren we parse a tuple-style
5737 let vdata = if self.token.is_keyword(keywords::Where) {
5738 generics.where_clause = self.parse_where_clause()?;
5739 if self.eat(&token::Semi) {
5740 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5741 VariantData::Unit(ast::DUMMY_NODE_ID)
5743 // If we see: `struct Foo<T> where T: Copy { ... }`
5744 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5746 // No `where` so: `struct Foo<T>;`
5747 } else if self.eat(&token::Semi) {
5748 VariantData::Unit(ast::DUMMY_NODE_ID)
5749 // Record-style struct definition
5750 } else if self.token == token::OpenDelim(token::Brace) {
5751 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5752 // Tuple-style struct definition with optional where-clause.
5753 } else if self.token == token::OpenDelim(token::Paren) {
5754 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5755 generics.where_clause = self.parse_where_clause()?;
5756 self.expect(&token::Semi)?;
5759 let token_str = self.this_token_to_string();
5760 let mut err = self.fatal(&format!(
5761 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5764 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5768 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5771 /// Parse union Foo { ... }
5772 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5773 let class_name = self.parse_ident()?;
5775 let mut generics = self.parse_generics()?;
5777 let vdata = if self.token.is_keyword(keywords::Where) {
5778 generics.where_clause = self.parse_where_clause()?;
5779 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5780 } else if self.token == token::OpenDelim(token::Brace) {
5781 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5783 let token_str = self.this_token_to_string();
5784 let mut err = self.fatal(&format!(
5785 "expected `where` or `{{` after union name, found `{}`", token_str));
5786 err.span_label(self.span, "expected `where` or `{` after union name");
5790 Ok((class_name, ItemKind::Union(vdata, generics), None))
5793 fn consume_block(&mut self, delim: token::DelimToken) {
5794 let mut brace_depth = 0;
5795 if !self.eat(&token::OpenDelim(delim)) {
5799 if self.eat(&token::OpenDelim(delim)) {
5801 } else if self.eat(&token::CloseDelim(delim)) {
5802 if brace_depth == 0 {
5808 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5816 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5817 let mut fields = Vec::new();
5818 if self.eat(&token::OpenDelim(token::Brace)) {
5819 while self.token != token::CloseDelim(token::Brace) {
5820 let field = self.parse_struct_decl_field().map_err(|e| {
5821 self.recover_stmt();
5825 Ok(field) => fields.push(field),
5831 self.eat(&token::CloseDelim(token::Brace));
5833 let token_str = self.this_token_to_string();
5834 let mut err = self.fatal(&format!(
5835 "expected `where`, or `{{` after struct name, found `{}`", token_str));
5836 err.span_label(self.span, "expected `where`, or `{` after struct name");
5843 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5844 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5845 // Unit like structs are handled in parse_item_struct function
5846 let fields = self.parse_unspanned_seq(
5847 &token::OpenDelim(token::Paren),
5848 &token::CloseDelim(token::Paren),
5849 SeqSep::trailing_allowed(token::Comma),
5851 let attrs = p.parse_outer_attributes()?;
5853 let vis = p.parse_visibility(true)?;
5854 let ty = p.parse_ty()?;
5856 span: lo.to(ty.span),
5859 id: ast::DUMMY_NODE_ID,
5868 /// Parse a structure field declaration
5869 fn parse_single_struct_field(&mut self,
5872 attrs: Vec<Attribute> )
5873 -> PResult<'a, StructField> {
5874 let mut seen_comma: bool = false;
5875 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5876 if self.token == token::Comma {
5883 token::CloseDelim(token::Brace) => {}
5884 token::DocComment(_) => {
5885 let previous_span = self.prev_span;
5886 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5887 self.bump(); // consume the doc comment
5888 let comma_after_doc_seen = self.eat(&token::Comma);
5889 // `seen_comma` is always false, because we are inside doc block
5890 // condition is here to make code more readable
5891 if seen_comma == false && comma_after_doc_seen == true {
5894 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
5897 if seen_comma == false {
5898 let sp = self.sess.codemap().next_point(previous_span);
5899 err.span_suggestion_with_applicability(
5901 "missing comma here",
5903 Applicability::MachineApplicable
5910 let sp = self.sess.codemap().next_point(self.prev_span);
5911 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
5912 self.this_token_to_string()));
5913 if self.token.is_ident() {
5914 // This is likely another field; emit the diagnostic and keep going
5915 err.span_suggestion(sp, "try adding a comma", ",".into());
5925 /// Parse an element of a struct definition
5926 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5927 let attrs = self.parse_outer_attributes()?;
5929 let vis = self.parse_visibility(false)?;
5930 self.parse_single_struct_field(lo, vis, attrs)
5933 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5934 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5935 /// a function definition, it's not a tuple struct field) and the contents within the parens
5936 /// isn't valid, emit a proper diagnostic.
5937 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5938 maybe_whole!(self, NtVis, |x| x);
5940 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
5941 if self.is_crate_vis() {
5942 self.bump(); // `crate`
5943 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
5946 if !self.eat_keyword(keywords::Pub) {
5947 return Ok(respan(self.prev_span, VisibilityKind::Inherited))
5949 let lo = self.prev_span;
5951 if self.check(&token::OpenDelim(token::Paren)) {
5952 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5953 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5954 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5955 // by the following tokens.
5956 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5959 self.bump(); // `crate`
5960 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5962 lo.to(self.prev_span),
5963 VisibilityKind::Crate(CrateSugar::PubCrate),
5966 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5969 self.bump(); // `in`
5970 let path = self.parse_path(PathStyle::Mod)?; // `path`
5971 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5972 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5974 id: ast::DUMMY_NODE_ID,
5977 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5978 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5979 t.is_keyword(keywords::SelfValue))
5981 // `pub(self)` or `pub(super)`
5983 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
5984 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5985 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5987 id: ast::DUMMY_NODE_ID,
5990 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5991 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5993 let msg = "incorrect visibility restriction";
5994 let suggestion = r##"some possible visibility restrictions are:
5995 `pub(crate)`: visible only on the current crate
5996 `pub(super)`: visible only in the current module's parent
5997 `pub(in path::to::module)`: visible only on the specified path"##;
5998 let path = self.parse_path(PathStyle::Mod)?;
5999 let sp = self.prev_span;
6000 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6001 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6002 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6003 err.help(suggestion);
6004 err.span_suggestion_with_applicability(
6005 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6007 err.emit(); // emit diagnostic, but continue with public visibility
6011 Ok(respan(lo, VisibilityKind::Public))
6014 /// Parse defaultness: `default` or nothing.
6015 fn parse_defaultness(&mut self) -> Defaultness {
6016 // `pub` is included for better error messages
6017 if self.check_keyword(keywords::Default) &&
6018 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6019 t.is_keyword(keywords::Const) ||
6020 t.is_keyword(keywords::Fn) ||
6021 t.is_keyword(keywords::Unsafe) ||
6022 t.is_keyword(keywords::Extern) ||
6023 t.is_keyword(keywords::Type) ||
6024 t.is_keyword(keywords::Pub)) {
6025 self.bump(); // `default`
6026 Defaultness::Default
6032 /// Given a termination token, parse all of the items in a module
6033 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6034 let mut items = vec![];
6035 while let Some(item) = self.parse_item()? {
6039 if !self.eat(term) {
6040 let token_str = self.this_token_to_string();
6041 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6042 if token_str == ";" {
6043 let msg = "consider removing this semicolon";
6044 err.span_suggestion_short_with_applicability(
6045 self.span, msg, "".to_string(), Applicability::MachineApplicable
6048 err.span_label(self.span, "expected item");
6053 let hi = if self.span == syntax_pos::DUMMY_SP {
6060 inner: inner_lo.to(hi),
6065 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6066 let id = self.parse_ident()?;
6067 self.expect(&token::Colon)?;
6068 let ty = self.parse_ty()?;
6069 self.expect(&token::Eq)?;
6070 let e = self.parse_expr()?;
6071 self.expect(&token::Semi)?;
6072 let item = match m {
6073 Some(m) => ItemKind::Static(ty, m, e),
6074 None => ItemKind::Const(ty, e),
6076 Ok((id, item, None))
6079 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6080 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6081 let (in_cfg, outer_attrs) = {
6082 let mut strip_unconfigured = ::config::StripUnconfigured {
6084 should_test: false, // irrelevant
6085 features: None, // don't perform gated feature checking
6087 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6088 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6091 let id_span = self.span;
6092 let id = self.parse_ident()?;
6093 if self.check(&token::Semi) {
6095 if in_cfg && self.recurse_into_file_modules {
6096 // This mod is in an external file. Let's go get it!
6097 let ModulePathSuccess { path, directory_ownership, warn } =
6098 self.submod_path(id, &outer_attrs, id_span)?;
6099 let (module, mut attrs) =
6100 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6102 let attr = Attribute {
6103 id: attr::mk_attr_id(),
6104 style: ast::AttrStyle::Outer,
6105 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6106 tokens: TokenStream::empty(),
6107 is_sugared_doc: false,
6108 span: syntax_pos::DUMMY_SP,
6110 attr::mark_known(&attr);
6113 Ok((id, module, Some(attrs)))
6115 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6116 Ok((id, ItemKind::Mod(placeholder), None))
6119 let old_directory = self.directory.clone();
6120 self.push_directory(id, &outer_attrs);
6122 self.expect(&token::OpenDelim(token::Brace))?;
6123 let mod_inner_lo = self.span;
6124 let attrs = self.parse_inner_attributes()?;
6125 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6127 self.directory = old_directory;
6128 Ok((id, ItemKind::Mod(module), Some(attrs)))
6132 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6133 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6134 self.directory.path.to_mut().push(&path.as_str());
6135 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6137 self.directory.path.to_mut().push(&id.as_str());
6141 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6142 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6145 // On windows, the base path might have the form
6146 // `\\?\foo\bar` in which case it does not tolerate
6147 // mixed `/` and `\` separators, so canonicalize
6150 let s = s.replace("/", "\\");
6151 Some(dir_path.join(s))
6157 /// Returns either a path to a module, or .
6158 pub fn default_submod_path(
6160 relative: Option<ast::Ident>,
6162 codemap: &CodeMap) -> ModulePath
6164 // If we're in a foo.rs file instead of a mod.rs file,
6165 // we need to look for submodules in
6166 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6167 // `./<id>.rs` and `./<id>/mod.rs`.
6168 let relative_prefix_string;
6169 let relative_prefix = if let Some(ident) = relative {
6170 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6171 &relative_prefix_string
6176 let mod_name = id.to_string();
6177 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6178 let secondary_path_str = format!("{}{}{}mod.rs",
6179 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6180 let default_path = dir_path.join(&default_path_str);
6181 let secondary_path = dir_path.join(&secondary_path_str);
6182 let default_exists = codemap.file_exists(&default_path);
6183 let secondary_exists = codemap.file_exists(&secondary_path);
6185 let result = match (default_exists, secondary_exists) {
6186 (true, false) => Ok(ModulePathSuccess {
6188 directory_ownership: DirectoryOwnership::Owned {
6193 (false, true) => Ok(ModulePathSuccess {
6194 path: secondary_path,
6195 directory_ownership: DirectoryOwnership::Owned {
6200 (false, false) => Err(Error::FileNotFoundForModule {
6201 mod_name: mod_name.clone(),
6202 default_path: default_path_str,
6203 secondary_path: secondary_path_str,
6204 dir_path: format!("{}", dir_path.display()),
6206 (true, true) => Err(Error::DuplicatePaths {
6207 mod_name: mod_name.clone(),
6208 default_path: default_path_str,
6209 secondary_path: secondary_path_str,
6215 path_exists: default_exists || secondary_exists,
6220 fn submod_path(&mut self,
6222 outer_attrs: &[Attribute],
6224 -> PResult<'a, ModulePathSuccess> {
6225 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6226 return Ok(ModulePathSuccess {
6227 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6228 // All `#[path]` files are treated as though they are a `mod.rs` file.
6229 // This means that `mod foo;` declarations inside `#[path]`-included
6230 // files are siblings,
6232 // Note that this will produce weirdness when a file named `foo.rs` is
6233 // `#[path]` included and contains a `mod foo;` declaration.
6234 // If you encounter this, it's your own darn fault :P
6235 Some(_) => DirectoryOwnership::Owned { relative: None },
6236 _ => DirectoryOwnership::UnownedViaMod(true),
6243 let relative = match self.directory.ownership {
6244 DirectoryOwnership::Owned { relative } => {
6245 // Push the usage onto the list of non-mod.rs mod uses.
6246 // This is used later for feature-gate error reporting.
6247 if let Some(cur_file_ident) = relative {
6249 .non_modrs_mods.borrow_mut()
6250 .push((cur_file_ident, id_sp));
6254 DirectoryOwnership::UnownedViaBlock |
6255 DirectoryOwnership::UnownedViaMod(_) => None,
6257 let paths = Parser::default_submod_path(
6258 id, relative, &self.directory.path, self.sess.codemap());
6260 match self.directory.ownership {
6261 DirectoryOwnership::Owned { .. } => {
6262 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6264 DirectoryOwnership::UnownedViaBlock => {
6266 "Cannot declare a non-inline module inside a block \
6267 unless it has a path attribute";
6268 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6269 if paths.path_exists {
6270 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6272 err.span_note(id_sp, &msg);
6276 DirectoryOwnership::UnownedViaMod(warn) => {
6278 if let Ok(result) = paths.result {
6279 return Ok(ModulePathSuccess { warn: true, ..result });
6282 let mut err = self.diagnostic().struct_span_err(id_sp,
6283 "cannot declare a new module at this location");
6284 if id_sp != syntax_pos::DUMMY_SP {
6285 let src_path = self.sess.codemap().span_to_filename(id_sp);
6286 if let FileName::Real(src_path) = src_path {
6287 if let Some(stem) = src_path.file_stem() {
6288 let mut dest_path = src_path.clone();
6289 dest_path.set_file_name(stem);
6290 dest_path.push("mod.rs");
6291 err.span_note(id_sp,
6292 &format!("maybe move this module `{}` to its own \
6293 directory via `{}`", src_path.display(),
6294 dest_path.display()));
6298 if paths.path_exists {
6299 err.span_note(id_sp,
6300 &format!("... or maybe `use` the module `{}` instead \
6301 of possibly redeclaring it",
6309 /// Read a module from a source file.
6310 fn eval_src_mod(&mut self,
6312 directory_ownership: DirectoryOwnership,
6315 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6316 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6317 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6318 let mut err = String::from("circular modules: ");
6319 let len = included_mod_stack.len();
6320 for p in &included_mod_stack[i.. len] {
6321 err.push_str(&p.to_string_lossy());
6322 err.push_str(" -> ");
6324 err.push_str(&path.to_string_lossy());
6325 return Err(self.span_fatal(id_sp, &err[..]));
6327 included_mod_stack.push(path.clone());
6328 drop(included_mod_stack);
6331 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6332 p0.cfg_mods = self.cfg_mods;
6333 let mod_inner_lo = p0.span;
6334 let mod_attrs = p0.parse_inner_attributes()?;
6335 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6336 self.sess.included_mod_stack.borrow_mut().pop();
6337 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6340 /// Parse a function declaration from a foreign module
6341 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6342 -> PResult<'a, ForeignItem> {
6343 self.expect_keyword(keywords::Fn)?;
6345 let (ident, mut generics) = self.parse_fn_header()?;
6346 let decl = self.parse_fn_decl(true)?;
6347 generics.where_clause = self.parse_where_clause()?;
6349 self.expect(&token::Semi)?;
6350 Ok(ast::ForeignItem {
6353 node: ForeignItemKind::Fn(decl, generics),
6354 id: ast::DUMMY_NODE_ID,
6360 /// Parse a static item from a foreign module.
6361 /// Assumes that the `static` keyword is already parsed.
6362 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6363 -> PResult<'a, ForeignItem> {
6364 let mutbl = self.eat_keyword(keywords::Mut);
6365 let ident = self.parse_ident()?;
6366 self.expect(&token::Colon)?;
6367 let ty = self.parse_ty()?;
6369 self.expect(&token::Semi)?;
6373 node: ForeignItemKind::Static(ty, mutbl),
6374 id: ast::DUMMY_NODE_ID,
6380 /// Parse a type from a foreign module
6381 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6382 -> PResult<'a, ForeignItem> {
6383 self.expect_keyword(keywords::Type)?;
6385 let ident = self.parse_ident()?;
6387 self.expect(&token::Semi)?;
6388 Ok(ast::ForeignItem {
6391 node: ForeignItemKind::Ty,
6392 id: ast::DUMMY_NODE_ID,
6398 /// Parse extern crate links
6402 /// extern crate foo;
6403 /// extern crate bar as foo;
6404 fn parse_item_extern_crate(&mut self,
6406 visibility: Visibility,
6407 attrs: Vec<Attribute>)
6408 -> PResult<'a, P<Item>> {
6409 let orig_name = self.parse_ident()?;
6410 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6411 (rename, Some(orig_name.name))
6415 self.expect(&token::Semi)?;
6417 let span = lo.to(self.prev_span);
6418 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6421 /// Parse `extern` for foreign ABIs
6424 /// `extern` is expected to have been
6425 /// consumed before calling this method
6431 fn parse_item_foreign_mod(&mut self,
6433 opt_abi: Option<Abi>,
6434 visibility: Visibility,
6435 mut attrs: Vec<Attribute>)
6436 -> PResult<'a, P<Item>> {
6437 self.expect(&token::OpenDelim(token::Brace))?;
6439 let abi = opt_abi.unwrap_or(Abi::C);
6441 attrs.extend(self.parse_inner_attributes()?);
6443 let mut foreign_items = vec![];
6444 while let Some(item) = self.parse_foreign_item()? {
6445 foreign_items.push(item);
6447 self.expect(&token::CloseDelim(token::Brace))?;
6449 let prev_span = self.prev_span;
6450 let m = ast::ForeignMod {
6452 items: foreign_items
6454 let invalid = keywords::Invalid.ident();
6455 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6458 /// Parse type Foo = Bar;
6459 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6460 let ident = self.parse_ident()?;
6461 let mut tps = self.parse_generics()?;
6462 tps.where_clause = self.parse_where_clause()?;
6463 self.expect(&token::Eq)?;
6464 let ty = self.parse_ty()?;
6465 self.expect(&token::Semi)?;
6466 Ok((ident, ItemKind::Ty(ty, tps), None))
6469 /// Parse the part of an "enum" decl following the '{'
6470 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6471 let mut variants = Vec::new();
6472 let mut all_nullary = true;
6473 let mut any_disr = None;
6474 while self.token != token::CloseDelim(token::Brace) {
6475 let variant_attrs = self.parse_outer_attributes()?;
6476 let vlo = self.span;
6479 let mut disr_expr = None;
6480 let ident = self.parse_ident()?;
6481 if self.check(&token::OpenDelim(token::Brace)) {
6482 // Parse a struct variant.
6483 all_nullary = false;
6484 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6485 ast::DUMMY_NODE_ID);
6486 } else if self.check(&token::OpenDelim(token::Paren)) {
6487 all_nullary = false;
6488 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6489 ast::DUMMY_NODE_ID);
6490 } else if self.eat(&token::Eq) {
6491 disr_expr = Some(AnonConst {
6492 id: ast::DUMMY_NODE_ID,
6493 value: self.parse_expr()?,
6495 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6496 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6498 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6501 let vr = ast::Variant_ {
6503 attrs: variant_attrs,
6507 variants.push(respan(vlo.to(self.prev_span), vr));
6509 if !self.eat(&token::Comma) { break; }
6511 self.expect(&token::CloseDelim(token::Brace))?;
6513 Some(disr_span) if !all_nullary =>
6514 self.span_err(disr_span,
6515 "discriminator values can only be used with a field-less enum"),
6519 Ok(ast::EnumDef { variants: variants })
6522 /// Parse an "enum" declaration
6523 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6524 let id = self.parse_ident()?;
6525 let mut generics = self.parse_generics()?;
6526 generics.where_clause = self.parse_where_clause()?;
6527 self.expect(&token::OpenDelim(token::Brace))?;
6529 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6530 self.recover_stmt();
6531 self.eat(&token::CloseDelim(token::Brace));
6534 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6537 /// Parses a string as an ABI spec on an extern type or module. Consumes
6538 /// the `extern` keyword, if one is found.
6539 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6541 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6543 self.expect_no_suffix(sp, "ABI spec", suf);
6545 match abi::lookup(&s.as_str()) {
6546 Some(abi) => Ok(Some(abi)),
6548 let prev_span = self.prev_span;
6549 let mut err = struct_span_err!(
6550 self.sess.span_diagnostic,
6553 "invalid ABI: found `{}`",
6555 err.span_label(prev_span, "invalid ABI");
6556 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6567 fn is_static_global(&mut self) -> bool {
6568 if self.check_keyword(keywords::Static) {
6569 // Check if this could be a closure
6570 !self.look_ahead(1, |token| {
6571 if token.is_keyword(keywords::Move) {
6575 token::BinOp(token::Or) | token::OrOr => true,
6584 /// Parse one of the items allowed by the flags.
6585 /// NB: this function no longer parses the items inside an
6587 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6588 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6589 maybe_whole!(self, NtItem, |item| {
6590 let mut item = item.into_inner();
6591 let mut attrs = attrs;
6592 mem::swap(&mut item.attrs, &mut attrs);
6593 item.attrs.extend(attrs);
6599 let visibility = self.parse_visibility(false)?;
6601 if self.eat_keyword(keywords::Use) {
6603 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6604 self.expect(&token::Semi)?;
6606 let span = lo.to(self.prev_span);
6607 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6608 return Ok(Some(item));
6611 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6612 self.bump(); // `extern`
6613 if self.eat_keyword(keywords::Crate) {
6614 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6617 let opt_abi = self.parse_opt_abi()?;
6619 if self.eat_keyword(keywords::Fn) {
6620 // EXTERN FUNCTION ITEM
6621 let fn_span = self.prev_span;
6622 let abi = opt_abi.unwrap_or(Abi::C);
6623 let (ident, item_, extra_attrs) =
6624 self.parse_item_fn(Unsafety::Normal,
6625 respan(fn_span, Constness::NotConst),
6627 let prev_span = self.prev_span;
6628 let item = self.mk_item(lo.to(prev_span),
6632 maybe_append(attrs, extra_attrs));
6633 return Ok(Some(item));
6634 } else if self.check(&token::OpenDelim(token::Brace)) {
6635 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6641 if self.is_static_global() {
6644 let m = if self.eat_keyword(keywords::Mut) {
6647 Mutability::Immutable
6649 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6650 let prev_span = self.prev_span;
6651 let item = self.mk_item(lo.to(prev_span),
6655 maybe_append(attrs, extra_attrs));
6656 return Ok(Some(item));
6658 if self.eat_keyword(keywords::Const) {
6659 let const_span = self.prev_span;
6660 if self.check_keyword(keywords::Fn)
6661 || (self.check_keyword(keywords::Unsafe)
6662 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6663 // CONST FUNCTION ITEM
6664 let unsafety = self.parse_unsafety();
6666 let (ident, item_, extra_attrs) =
6667 self.parse_item_fn(unsafety,
6668 respan(const_span, Constness::Const),
6670 let prev_span = self.prev_span;
6671 let item = self.mk_item(lo.to(prev_span),
6675 maybe_append(attrs, extra_attrs));
6676 return Ok(Some(item));
6680 if self.eat_keyword(keywords::Mut) {
6681 let prev_span = self.prev_span;
6682 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6683 .help("did you mean to declare a static?")
6686 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6687 let prev_span = self.prev_span;
6688 let item = self.mk_item(lo.to(prev_span),
6692 maybe_append(attrs, extra_attrs));
6693 return Ok(Some(item));
6695 if self.check_keyword(keywords::Unsafe) &&
6696 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6697 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6699 // UNSAFE TRAIT ITEM
6700 self.bump(); // `unsafe`
6701 let is_auto = if self.eat_keyword(keywords::Trait) {
6704 self.expect_keyword(keywords::Auto)?;
6705 self.expect_keyword(keywords::Trait)?;
6708 let (ident, item_, extra_attrs) =
6709 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
6710 let prev_span = self.prev_span;
6711 let item = self.mk_item(lo.to(prev_span),
6715 maybe_append(attrs, extra_attrs));
6716 return Ok(Some(item));
6718 if self.check_keyword(keywords::Impl) ||
6719 self.check_keyword(keywords::Unsafe) &&
6720 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6721 self.check_keyword(keywords::Default) &&
6722 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6723 self.check_keyword(keywords::Default) &&
6724 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6726 let defaultness = self.parse_defaultness();
6727 let unsafety = self.parse_unsafety();
6728 self.expect_keyword(keywords::Impl)?;
6729 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6730 let span = lo.to(self.prev_span);
6731 return Ok(Some(self.mk_item(span, ident, item, visibility,
6732 maybe_append(attrs, extra_attrs))));
6734 if self.check_keyword(keywords::Fn) {
6737 let fn_span = self.prev_span;
6738 let (ident, item_, extra_attrs) =
6739 self.parse_item_fn(Unsafety::Normal,
6740 respan(fn_span, Constness::NotConst),
6742 let prev_span = self.prev_span;
6743 let item = self.mk_item(lo.to(prev_span),
6747 maybe_append(attrs, extra_attrs));
6748 return Ok(Some(item));
6750 if self.check_keyword(keywords::Unsafe)
6751 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6752 // UNSAFE FUNCTION ITEM
6753 self.bump(); // `unsafe`
6754 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
6755 self.check(&token::OpenDelim(token::Brace));
6756 let abi = if self.eat_keyword(keywords::Extern) {
6757 self.parse_opt_abi()?.unwrap_or(Abi::C)
6761 self.expect_keyword(keywords::Fn)?;
6762 let fn_span = self.prev_span;
6763 let (ident, item_, extra_attrs) =
6764 self.parse_item_fn(Unsafety::Unsafe,
6765 respan(fn_span, Constness::NotConst),
6767 let prev_span = self.prev_span;
6768 let item = self.mk_item(lo.to(prev_span),
6772 maybe_append(attrs, extra_attrs));
6773 return Ok(Some(item));
6775 if self.eat_keyword(keywords::Mod) {
6777 let (ident, item_, extra_attrs) =
6778 self.parse_item_mod(&attrs[..])?;
6779 let prev_span = self.prev_span;
6780 let item = self.mk_item(lo.to(prev_span),
6784 maybe_append(attrs, extra_attrs));
6785 return Ok(Some(item));
6787 if self.eat_keyword(keywords::Type) {
6789 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6790 let prev_span = self.prev_span;
6791 let item = self.mk_item(lo.to(prev_span),
6795 maybe_append(attrs, extra_attrs));
6796 return Ok(Some(item));
6798 if self.eat_keyword(keywords::Enum) {
6800 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6801 let prev_span = self.prev_span;
6802 let item = self.mk_item(lo.to(prev_span),
6806 maybe_append(attrs, extra_attrs));
6807 return Ok(Some(item));
6809 if self.check_keyword(keywords::Trait)
6810 || (self.check_keyword(keywords::Auto)
6811 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6813 let is_auto = if self.eat_keyword(keywords::Trait) {
6816 self.expect_keyword(keywords::Auto)?;
6817 self.expect_keyword(keywords::Trait)?;
6821 let (ident, item_, extra_attrs) =
6822 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6823 let prev_span = self.prev_span;
6824 let item = self.mk_item(lo.to(prev_span),
6828 maybe_append(attrs, extra_attrs));
6829 return Ok(Some(item));
6831 if self.eat_keyword(keywords::Struct) {
6833 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6834 let prev_span = self.prev_span;
6835 let item = self.mk_item(lo.to(prev_span),
6839 maybe_append(attrs, extra_attrs));
6840 return Ok(Some(item));
6842 if self.is_union_item() {
6845 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6846 let prev_span = self.prev_span;
6847 let item = self.mk_item(lo.to(prev_span),
6851 maybe_append(attrs, extra_attrs));
6852 return Ok(Some(item));
6854 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6855 return Ok(Some(macro_def));
6858 // Verify whether we have encountered a struct or method definition where the user forgot to
6859 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6860 if visibility.node == VisibilityKind::Public &&
6861 self.check_ident() &&
6862 self.look_ahead(1, |t| *t != token::Not)
6864 // Space between `pub` keyword and the identifier
6867 // ^^^ `sp` points here
6868 let sp = self.prev_span.between(self.span);
6869 let full_sp = self.prev_span.to(self.span);
6870 let ident_sp = self.span;
6871 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6872 // possible public struct definition where `struct` was forgotten
6873 let ident = self.parse_ident().unwrap();
6874 let msg = format!("add `struct` here to parse `{}` as a public struct",
6876 let mut err = self.diagnostic()
6877 .struct_span_err(sp, "missing `struct` for struct definition");
6878 err.span_suggestion_short_with_applicability(
6879 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
6882 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6883 let ident = self.parse_ident().unwrap();
6884 self.consume_block(token::Paren);
6885 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6886 self.check(&token::OpenDelim(token::Brace))
6888 ("fn", "method", false)
6889 } else if self.check(&token::Colon) {
6893 ("fn` or `struct", "method or struct", true)
6896 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6897 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6899 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
6903 err.span_suggestion_short_with_applicability(
6904 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
6907 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
6908 err.span_suggestion_with_applicability(
6910 "if you meant to call a macro, try",
6911 format!("{}!", snippet),
6912 // this is the `ambiguous` conditional branch
6913 Applicability::MaybeIncorrect
6916 err.help("if you meant to call a macro, remove the `pub` \
6917 and add a trailing `!` after the identifier");
6923 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
6926 /// Parse a foreign item.
6927 crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6928 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
6930 let attrs = self.parse_outer_attributes()?;
6932 let visibility = self.parse_visibility(false)?;
6934 // FOREIGN STATIC ITEM
6935 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6936 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6937 if self.token.is_keyword(keywords::Const) {
6939 .struct_span_err(self.span, "extern items cannot be `const`")
6940 .span_suggestion_with_applicability(
6942 "try using a static value",
6943 "static".to_owned(),
6944 Applicability::MachineApplicable
6947 self.bump(); // `static` or `const`
6948 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6950 // FOREIGN FUNCTION ITEM
6951 if self.check_keyword(keywords::Fn) {
6952 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6954 // FOREIGN TYPE ITEM
6955 if self.check_keyword(keywords::Type) {
6956 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6959 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
6963 ident: keywords::Invalid.ident(),
6964 span: lo.to(self.prev_span),
6965 id: ast::DUMMY_NODE_ID,
6968 node: ForeignItemKind::Macro(mac),
6973 if !attrs.is_empty() {
6974 self.expected_item_err(&attrs);
6982 /// This is the fall-through for parsing items.
6983 fn parse_macro_use_or_failure(
6985 attrs: Vec<Attribute> ,
6986 macros_allowed: bool,
6987 attributes_allowed: bool,
6989 visibility: Visibility
6990 ) -> PResult<'a, Option<P<Item>>> {
6991 if macros_allowed && self.token.is_path_start() {
6992 // MACRO INVOCATION ITEM
6994 let prev_span = self.prev_span;
6995 self.complain_if_pub_macro(&visibility.node, prev_span);
6997 let mac_lo = self.span;
7000 let pth = self.parse_path(PathStyle::Mod)?;
7001 self.expect(&token::Not)?;
7003 // a 'special' identifier (like what `macro_rules!` uses)
7004 // is optional. We should eventually unify invoc syntax
7006 let id = if self.token.is_ident() {
7009 keywords::Invalid.ident() // no special identifier
7011 // eat a matched-delimiter token tree:
7012 let (delim, tts) = self.expect_delimited_token_tree()?;
7013 if delim != MacDelimiter::Brace {
7014 if !self.eat(&token::Semi) {
7015 self.span_err(self.prev_span,
7016 "macros that expand to items must either \
7017 be surrounded with braces or followed by \
7022 let hi = self.prev_span;
7023 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7024 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7025 return Ok(Some(item));
7028 // FAILURE TO PARSE ITEM
7029 match visibility.node {
7030 VisibilityKind::Inherited => {}
7032 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7036 if !attributes_allowed && !attrs.is_empty() {
7037 self.expected_item_err(&attrs);
7042 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7043 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7044 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7046 if self.token.is_path_start() && !self.is_extern_non_path() {
7047 let prev_span = self.prev_span;
7049 let pth = self.parse_path(PathStyle::Mod)?;
7051 if pth.segments.len() == 1 {
7052 if !self.eat(&token::Not) {
7053 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7056 self.expect(&token::Not)?;
7059 if let Some(vis) = vis {
7060 self.complain_if_pub_macro(&vis.node, prev_span);
7065 // eat a matched-delimiter token tree:
7066 let (delim, tts) = self.expect_delimited_token_tree()?;
7067 if delim != MacDelimiter::Brace {
7068 self.expect(&token::Semi)?
7071 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7077 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7078 where F: FnOnce(&mut Self) -> PResult<'a, R>
7080 // Record all tokens we parse when parsing this item.
7081 let mut tokens = Vec::new();
7082 match self.token_cursor.frame.last_token {
7083 LastToken::Collecting(_) => {
7084 panic!("cannot collect tokens recursively yet")
7086 LastToken::Was(ref mut last) => tokens.extend(last.take()),
7088 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7089 let prev = self.token_cursor.stack.len();
7091 let last_token = if self.token_cursor.stack.len() == prev {
7092 &mut self.token_cursor.frame.last_token
7094 &mut self.token_cursor.stack[prev].last_token
7096 let mut tokens = match *last_token {
7097 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7098 LastToken::Was(_) => panic!("our vector went away?"),
7101 // If we're not at EOF our current token wasn't actually consumed by
7102 // `f`, but it'll still be in our list that we pulled out. In that case
7104 if self.token == token::Eof {
7105 *last_token = LastToken::Was(None);
7107 *last_token = LastToken::Was(tokens.pop());
7110 Ok((ret?, tokens.into_iter().collect()))
7113 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7114 let attrs = self.parse_outer_attributes()?;
7116 let (ret, tokens) = self.collect_tokens(|this| {
7117 this.parse_item_(attrs, true, false)
7120 // Once we've parsed an item and recorded the tokens we got while
7121 // parsing we may want to store `tokens` into the item we're about to
7122 // return. Note, though, that we specifically didn't capture tokens
7123 // related to outer attributes. The `tokens` field here may later be
7124 // used with procedural macros to convert this item back into a token
7125 // stream, but during expansion we may be removing attributes as we go
7128 // If we've got inner attributes then the `tokens` we've got above holds
7129 // these inner attributes. If an inner attribute is expanded we won't
7130 // actually remove it from the token stream, so we'll just keep yielding
7131 // it (bad!). To work around this case for now we just avoid recording
7132 // `tokens` if we detect any inner attributes. This should help keep
7133 // expansion correct, but we should fix this bug one day!
7136 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7137 i.tokens = Some(tokens);
7145 fn is_import_coupler(&mut self) -> bool {
7146 self.check(&token::ModSep) &&
7147 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7148 *t == token::BinOp(token::Star))
7153 /// USE_TREE = [`::`] `*` |
7154 /// [`::`] `{` USE_TREE_LIST `}` |
7156 /// PATH `::` `{` USE_TREE_LIST `}` |
7157 /// PATH [`as` IDENT]
7158 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7161 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7162 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7163 self.check(&token::BinOp(token::Star)) ||
7164 self.is_import_coupler() {
7165 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7166 if self.eat(&token::ModSep) {
7167 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7170 if self.eat(&token::BinOp(token::Star)) {
7173 UseTreeKind::Nested(self.parse_use_tree_list()?)
7176 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7177 prefix = self.parse_path(PathStyle::Mod)?;
7179 if self.eat(&token::ModSep) {
7180 if self.eat(&token::BinOp(token::Star)) {
7183 UseTreeKind::Nested(self.parse_use_tree_list()?)
7186 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7190 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7193 /// Parse UseTreeKind::Nested(list)
7195 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7196 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7197 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7198 &token::CloseDelim(token::Brace),
7199 SeqSep::trailing_allowed(token::Comma), |this| {
7200 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7204 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7205 if self.eat_keyword(keywords::As) {
7207 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7209 Ok(Some(Ident::new(ident.name.gensymed(), ident.span)))
7211 _ => self.parse_ident().map(Some),
7218 /// Parses a source module as a crate. This is the main
7219 /// entry point for the parser.
7220 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7223 attrs: self.parse_inner_attributes()?,
7224 module: self.parse_mod_items(&token::Eof, lo)?,
7225 span: lo.to(self.span),
7229 fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7230 let ret = match self.token {
7231 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7232 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7239 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7240 match self.parse_optional_str() {
7241 Some((s, style, suf)) => {
7242 let sp = self.prev_span;
7243 self.expect_no_suffix(sp, "string literal", suf);
7247 let msg = "expected string literal";
7248 let mut err = self.fatal(msg);
7249 err.span_label(self.span, msg);