1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc_target::spec::abi::{self, Abi};
12 use ast::{AngleBracketedArgs, ParenthesisedArgs, AttrStyle, BareFnTy};
13 use ast::{GenericBound, TraitBoundModifier};
15 use ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy, Movability};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl, FnHeader};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::{GenericParam, GenericParamKind};
26 use ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
27 use ast::{Label, Lifetime, Lit, LitKind};
29 use ast::MacStmtStyle;
30 use ast::{Mac, Mac_, MacDelimiter};
31 use ast::{MutTy, Mutability};
32 use ast::{Pat, PatKind, PathSegment};
33 use ast::{PolyTraitRef, QSelf};
34 use ast::{Stmt, StmtKind};
35 use ast::{VariantData, StructField};
38 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
39 use ast::{Ty, TyKind, TypeBinding, GenericBounds};
40 use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
41 use ast::{UseTree, UseTreeKind};
42 use ast::{BinOpKind, UnOp};
43 use ast::{RangeEnd, RangeSyntax};
45 use codemap::{self, CodeMap, Spanned, respan};
46 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName, DUMMY_SP, edition::Edition};
47 use errors::{self, Applicability, DiagnosticBuilder};
48 use parse::{self, SeqSep, classify, token};
49 use parse::lexer::TokenAndSpan;
50 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
63 use std::path::{self, Path, PathBuf};
67 struct Restrictions: u8 {
68 const STMT_EXPR = 1 << 0;
69 const NO_STRUCT_LITERAL = 1 << 1;
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
75 /// How to parse a path.
76 #[derive(Copy, Clone, PartialEq)]
78 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
79 /// with something else. For example, in expressions `segment < ....` can be interpreted
80 /// as a comparison and `segment ( ....` can be interpreted as a function call.
81 /// In all such contexts the non-path interpretation is preferred by default for practical
82 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
83 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
85 /// In other contexts, notably in types, no ambiguity exists and paths can be written
86 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
87 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
89 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
90 /// visibilities or attributes.
91 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
92 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
93 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
94 /// tokens when something goes wrong.
98 #[derive(Clone, Copy, Debug, PartialEq)]
104 #[derive(Clone, Copy, Debug, PartialEq)]
110 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
111 /// dropped into the token stream, which happens while parsing the result of
112 /// macro expansion). Placement of these is not as complex as I feared it would
113 /// be. The important thing is to make sure that lookahead doesn't balk at
114 /// `token::Interpolated` tokens.
115 macro_rules! maybe_whole_expr {
117 if let token::Interpolated(nt) = $p.token.clone() {
119 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
121 return Ok((*e).clone());
123 token::NtPath(ref path) => {
126 let kind = ExprKind::Path(None, (*path).clone());
127 return Ok($p.mk_expr(span, kind, ThinVec::new()));
129 token::NtBlock(ref block) => {
132 let kind = ExprKind::Block((*block).clone(), None);
133 return Ok($p.mk_expr(span, kind, ThinVec::new()));
141 /// As maybe_whole_expr, but for things other than expressions
142 macro_rules! maybe_whole {
143 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
144 if let token::Interpolated(nt) = $p.token.clone() {
145 if let token::$constructor($x) = nt.0.clone() {
153 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
154 if let Some(ref mut rhs) = rhs {
160 #[derive(Debug, Clone, Copy, PartialEq)]
171 trait RecoverQPath: Sized {
172 const PATH_STYLE: PathStyle = PathStyle::Expr;
173 fn to_ty(&self) -> Option<P<Ty>>;
174 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
175 fn to_string(&self) -> String;
178 impl RecoverQPath for Ty {
179 const PATH_STYLE: PathStyle = PathStyle::Type;
180 fn to_ty(&self) -> Option<P<Ty>> {
181 Some(P(self.clone()))
183 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
184 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
186 fn to_string(&self) -> String {
187 pprust::ty_to_string(self)
191 impl RecoverQPath for Pat {
192 fn to_ty(&self) -> Option<P<Ty>> {
195 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
196 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
198 fn to_string(&self) -> String {
199 pprust::pat_to_string(self)
203 impl RecoverQPath for Expr {
204 fn to_ty(&self) -> Option<P<Ty>> {
207 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
208 Self { span: path.span, node: ExprKind::Path(qself, path),
209 id: self.id, attrs: self.attrs.clone() }
211 fn to_string(&self) -> String {
212 pprust::expr_to_string(self)
216 /* ident is handled by common.rs */
219 pub struct Parser<'a> {
220 pub sess: &'a ParseSess,
221 /// the current token:
222 pub token: token::Token,
223 /// the span of the current token:
225 /// the span of the previous token:
226 meta_var_span: Option<Span>,
228 /// the previous token kind
229 prev_token_kind: PrevTokenKind,
230 restrictions: Restrictions,
231 /// Used to determine the path to externally loaded source files
232 crate directory: Directory<'a>,
233 /// Whether to parse sub-modules in other files.
234 pub recurse_into_file_modules: bool,
235 /// Name of the root module this parser originated from. If `None`, then the
236 /// name is not known. This does not change while the parser is descending
237 /// into modules, and sub-parsers have new values for this name.
238 pub root_module_name: Option<String>,
239 crate expected_tokens: Vec<TokenType>,
240 token_cursor: TokenCursor,
241 desugar_doc_comments: bool,
242 /// Whether we should configure out of line modules as we parse.
249 frame: TokenCursorFrame,
250 stack: Vec<TokenCursorFrame>,
254 struct TokenCursorFrame {
255 delim: token::DelimToken,
258 tree_cursor: tokenstream::Cursor,
260 last_token: LastToken,
263 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
264 /// by the parser, and then that's transitively used to record the tokens that
265 /// each parse AST item is created with.
267 /// Right now this has two states, either collecting tokens or not collecting
268 /// tokens. If we're collecting tokens we just save everything off into a local
269 /// `Vec`. This should eventually though likely save tokens from the original
270 /// token stream and just use slicing of token streams to avoid creation of a
271 /// whole new vector.
273 /// The second state is where we're passively not recording tokens, but the last
274 /// token is still tracked for when we want to start recording tokens. This
275 /// "last token" means that when we start recording tokens we'll want to ensure
276 /// that this, the first token, is included in the output.
278 /// You can find some more example usage of this in the `collect_tokens` method
282 Collecting(Vec<TokenTree>),
283 Was(Option<TokenTree>),
286 impl TokenCursorFrame {
287 fn new(sp: Span, delimited: &Delimited) -> Self {
289 delim: delimited.delim,
291 open_delim: delimited.delim == token::NoDelim,
292 tree_cursor: delimited.stream().into_trees(),
293 close_delim: delimited.delim == token::NoDelim,
294 last_token: LastToken::Was(None),
300 fn next(&mut self) -> TokenAndSpan {
302 let tree = if !self.frame.open_delim {
303 self.frame.open_delim = true;
304 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
305 .open_tt(self.frame.span)
306 } else if let Some(tree) = self.frame.tree_cursor.next() {
308 } else if !self.frame.close_delim {
309 self.frame.close_delim = true;
310 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
311 .close_tt(self.frame.span)
312 } else if let Some(frame) = self.stack.pop() {
316 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
319 match self.frame.last_token {
320 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
321 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
325 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
326 TokenTree::Delimited(sp, ref delimited) => {
327 let frame = TokenCursorFrame::new(sp, delimited);
328 self.stack.push(mem::replace(&mut self.frame, frame));
334 fn next_desugared(&mut self) -> TokenAndSpan {
335 let (sp, name) = match self.next() {
336 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
340 let stripped = strip_doc_comment_decoration(&name.as_str());
342 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
343 // required to wrap the text.
344 let mut num_of_hashes = 0;
346 for ch in stripped.chars() {
349 '#' if count > 0 => count + 1,
352 num_of_hashes = cmp::max(num_of_hashes, count);
355 let body = TokenTree::Delimited(sp, Delimited {
356 delim: token::Bracket,
357 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
358 TokenTree::Token(sp, token::Eq),
359 TokenTree::Token(sp, token::Literal(
360 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
361 .iter().cloned().collect::<TokenStream>().into(),
364 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
365 delim: token::NoDelim,
366 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
367 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
368 .iter().cloned().collect::<TokenStream>().into()
370 [TokenTree::Token(sp, token::Pound), body]
371 .iter().cloned().collect::<TokenStream>().into()
379 #[derive(PartialEq, Eq, Clone)]
380 crate enum TokenType {
382 Keyword(keywords::Keyword),
391 fn to_string(&self) -> String {
393 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
394 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
395 TokenType::Operator => "an operator".to_string(),
396 TokenType::Lifetime => "lifetime".to_string(),
397 TokenType::Ident => "identifier".to_string(),
398 TokenType::Path => "path".to_string(),
399 TokenType::Type => "type".to_string(),
404 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
405 /// `IDENT<<u8 as Trait>::AssocTy>`.
407 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
408 /// that IDENT is not the ident of a fn trait
409 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
410 t == &token::ModSep || t == &token::Lt ||
411 t == &token::BinOp(token::Shl)
414 /// Information about the path to a module.
415 pub struct ModulePath {
418 pub result: Result<ModulePathSuccess, Error>,
421 pub struct ModulePathSuccess {
423 pub directory_ownership: DirectoryOwnership,
428 FileNotFoundForModule {
430 default_path: String,
431 secondary_path: String,
436 default_path: String,
437 secondary_path: String,
440 InclusiveRangeWithNoEnd,
444 fn span_err<S: Into<MultiSpan>>(self,
446 handler: &errors::Handler) -> DiagnosticBuilder {
448 Error::FileNotFoundForModule { ref mod_name,
452 let mut err = struct_span_err!(handler, sp, E0583,
453 "file not found for module `{}`", mod_name);
454 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
460 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
461 let mut err = struct_span_err!(handler, sp, E0584,
462 "file for module `{}` found at both {} and {}",
466 err.help("delete or rename one of them to remove the ambiguity");
469 Error::UselessDocComment => {
470 let mut err = struct_span_err!(handler, sp, E0585,
471 "found a documentation comment that doesn't document anything");
472 err.help("doc comments must come before what they document, maybe a comment was \
473 intended with `//`?");
476 Error::InclusiveRangeWithNoEnd => {
477 let mut err = struct_span_err!(handler, sp, E0586,
478 "inclusive range with no end");
479 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
489 AttributesParsed(ThinVec<Attribute>),
490 AlreadyParsed(P<Expr>),
493 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
494 fn from(o: Option<ThinVec<Attribute>>) -> Self {
495 if let Some(attrs) = o {
496 LhsExpr::AttributesParsed(attrs)
498 LhsExpr::NotYetParsed
503 impl From<P<Expr>> for LhsExpr {
504 fn from(expr: P<Expr>) -> Self {
505 LhsExpr::AlreadyParsed(expr)
509 /// Create a placeholder argument.
510 fn dummy_arg(span: Span) -> Arg {
511 let ident = Ident::new(keywords::Invalid.name(), span);
513 id: ast::DUMMY_NODE_ID,
514 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
520 id: ast::DUMMY_NODE_ID
522 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
525 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
526 enum TokenExpectType {
531 impl<'a> Parser<'a> {
532 pub fn new(sess: &'a ParseSess,
534 directory: Option<Directory<'a>>,
535 recurse_into_file_modules: bool,
536 desugar_doc_comments: bool)
538 let mut parser = Parser {
540 token: token::Whitespace,
541 span: syntax_pos::DUMMY_SP,
542 prev_span: syntax_pos::DUMMY_SP,
544 prev_token_kind: PrevTokenKind::Other,
545 restrictions: Restrictions::empty(),
546 recurse_into_file_modules,
547 directory: Directory {
548 path: Cow::from(PathBuf::new()),
549 ownership: DirectoryOwnership::Owned { relative: None }
551 root_module_name: None,
552 expected_tokens: Vec::new(),
553 token_cursor: TokenCursor {
554 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
555 delim: token::NoDelim,
560 desugar_doc_comments,
564 let tok = parser.next_tok();
565 parser.token = tok.tok;
566 parser.span = tok.sp;
568 if let Some(directory) = directory {
569 parser.directory = directory;
570 } else if !parser.span.source_equal(&DUMMY_SP) {
571 if let FileName::Real(mut path) = sess.codemap().span_to_unmapped_path(parser.span) {
573 parser.directory.path = Cow::from(path);
577 parser.process_potential_macro_variable();
581 fn next_tok(&mut self) -> TokenAndSpan {
582 let mut next = if self.desugar_doc_comments {
583 self.token_cursor.next_desugared()
585 self.token_cursor.next()
587 if next.sp == syntax_pos::DUMMY_SP {
588 // Tweak the location for better diagnostics, but keep syntactic context intact.
589 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
594 /// Convert the current token to a string using self's reader
595 pub fn this_token_to_string(&self) -> String {
596 pprust::token_to_string(&self.token)
599 fn token_descr(&self) -> Option<&'static str> {
600 Some(match &self.token {
601 t if t.is_special_ident() => "reserved identifier",
602 t if t.is_used_keyword() => "keyword",
603 t if t.is_unused_keyword() => "reserved keyword",
608 fn this_token_descr(&self) -> String {
609 if let Some(prefix) = self.token_descr() {
610 format!("{} `{}`", prefix, self.this_token_to_string())
612 format!("`{}`", self.this_token_to_string())
616 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
617 let token_str = pprust::token_to_string(t);
618 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
621 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
622 match self.expect_one_of(&[], &[]) {
624 Ok(_) => unreachable!(),
628 /// Expect and consume the token t. Signal an error if
629 /// the next token is not t.
630 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
631 if self.expected_tokens.is_empty() {
632 if self.token == *t {
636 let token_str = pprust::token_to_string(t);
637 let this_token_str = self.this_token_to_string();
638 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
642 let sp = if self.token == token::Token::Eof {
643 // EOF, don't want to point at the following char, but rather the last token
646 self.sess.codemap().next_point(self.prev_span)
648 let label_exp = format!("expected `{}`", token_str);
649 let cm = self.sess.codemap();
650 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
651 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
652 // When the spans are in the same line, it means that the only content
653 // between them is whitespace, point only at the found token.
654 err.span_label(self.span, label_exp);
657 err.span_label(sp, label_exp);
658 err.span_label(self.span, "unexpected token");
664 self.expect_one_of(slice::from_ref(t), &[])
668 /// Expect next token to be edible or inedible token. If edible,
669 /// then consume it; if inedible, then return without consuming
670 /// anything. Signal a fatal error if next token is unexpected.
671 fn expect_one_of(&mut self,
672 edible: &[token::Token],
673 inedible: &[token::Token]) -> PResult<'a, ()>{
674 fn tokens_to_string(tokens: &[TokenType]) -> String {
675 let mut i = tokens.iter();
676 // This might be a sign we need a connect method on Iterator.
678 .map_or("".to_string(), |t| t.to_string());
679 i.enumerate().fold(b, |mut b, (i, a)| {
680 if tokens.len() > 2 && i == tokens.len() - 2 {
682 } else if tokens.len() == 2 && i == tokens.len() - 2 {
687 b.push_str(&a.to_string());
691 if edible.contains(&self.token) {
694 } else if inedible.contains(&self.token) {
695 // leave it in the input
698 let mut expected = edible.iter()
699 .map(|x| TokenType::Token(x.clone()))
700 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
701 .chain(self.expected_tokens.iter().cloned())
702 .collect::<Vec<_>>();
703 expected.sort_by_cached_key(|x| x.to_string());
705 let expect = tokens_to_string(&expected[..]);
706 let actual = self.this_token_to_string();
707 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
708 let short_expect = if expected.len() > 6 {
709 format!("{} possible tokens", expected.len())
713 (format!("expected one of {}, found `{}`", expect, actual),
714 (self.sess.codemap().next_point(self.prev_span),
715 format!("expected one of {} here", short_expect)))
716 } else if expected.is_empty() {
717 (format!("unexpected token: `{}`", actual),
718 (self.prev_span, "unexpected token after this".to_string()))
720 (format!("expected {}, found `{}`", expect, actual),
721 (self.sess.codemap().next_point(self.prev_span),
722 format!("expected {} here", expect)))
724 let mut err = self.fatal(&msg_exp);
725 let sp = if self.token == token::Token::Eof {
726 // This is EOF, don't want to point at the following char, but rather the last token
732 let cm = self.sess.codemap();
733 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
734 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
735 // When the spans are in the same line, it means that the only content between
736 // them is whitespace, point at the found token in that case:
738 // X | () => { syntax error };
739 // | ^^^^^ expected one of 8 possible tokens here
741 // instead of having:
743 // X | () => { syntax error };
744 // | -^^^^^ unexpected token
746 // | expected one of 8 possible tokens here
747 err.span_label(self.span, label_exp);
750 err.span_label(sp, label_exp);
751 err.span_label(self.span, "unexpected token");
758 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
759 fn interpolated_or_expr_span(&self,
760 expr: PResult<'a, P<Expr>>)
761 -> PResult<'a, (Span, P<Expr>)> {
763 if self.prev_token_kind == PrevTokenKind::Interpolated {
771 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
772 let mut err = self.struct_span_err(self.span,
773 &format!("expected identifier, found {}",
774 self.this_token_descr()));
775 if let Some(token_descr) = self.token_descr() {
776 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
778 err.span_label(self.span, "expected identifier");
779 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
780 err.span_suggestion(self.span, "remove this comma", "".into());
786 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
787 self.parse_ident_common(true)
790 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
792 token::Ident(ident, _) => {
793 if self.token.is_reserved_ident() {
794 let mut err = self.expected_ident_found();
801 let span = self.span;
803 Ok(Ident::new(ident.name, span))
806 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
807 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
809 self.expected_ident_found()
815 /// Check if the next token is `tok`, and return `true` if so.
817 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
819 fn check(&mut self, tok: &token::Token) -> bool {
820 let is_present = self.token == *tok;
821 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
825 /// Consume token 'tok' if it exists. Returns true if the given
826 /// token was present, false otherwise.
827 pub fn eat(&mut self, tok: &token::Token) -> bool {
828 let is_present = self.check(tok);
829 if is_present { self.bump() }
833 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
834 self.expected_tokens.push(TokenType::Keyword(kw));
835 self.token.is_keyword(kw)
838 /// If the next token is the given keyword, eat it and return
839 /// true. Otherwise, return false.
840 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
841 if self.check_keyword(kw) {
849 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
850 if self.token.is_keyword(kw) {
858 /// If the given word is not a keyword, signal an error.
859 /// If the next token is not the given word, signal an error.
860 /// Otherwise, eat it.
861 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
862 if !self.eat_keyword(kw) {
869 fn check_ident(&mut self) -> bool {
870 if self.token.is_ident() {
873 self.expected_tokens.push(TokenType::Ident);
878 fn check_path(&mut self) -> bool {
879 if self.token.is_path_start() {
882 self.expected_tokens.push(TokenType::Path);
887 fn check_type(&mut self) -> bool {
888 if self.token.can_begin_type() {
891 self.expected_tokens.push(TokenType::Type);
896 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
897 /// and continue. If a `+` is not seen, return false.
899 /// This is using when token splitting += into +.
900 /// See issue 47856 for an example of when this may occur.
901 fn eat_plus(&mut self) -> bool {
902 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
904 token::BinOp(token::Plus) => {
908 token::BinOpEq(token::Plus) => {
909 let span = self.span.with_lo(self.span.lo() + BytePos(1));
910 self.bump_with(token::Eq, span);
918 /// Checks to see if the next token is either `+` or `+=`.
919 /// Otherwise returns false.
920 fn check_plus(&mut self) -> bool {
921 if self.token.is_like_plus() {
925 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
930 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
931 /// `&` and continue. If an `&` is not seen, signal an error.
932 fn expect_and(&mut self) -> PResult<'a, ()> {
933 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
935 token::BinOp(token::And) => {
940 let span = self.span.with_lo(self.span.lo() + BytePos(1));
941 Ok(self.bump_with(token::BinOp(token::And), span))
943 _ => self.unexpected()
947 /// Expect and consume an `|`. If `||` is seen, replace it with a single
948 /// `|` and continue. If an `|` is not seen, signal an error.
949 fn expect_or(&mut self) -> PResult<'a, ()> {
950 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
952 token::BinOp(token::Or) => {
957 let span = self.span.with_lo(self.span.lo() + BytePos(1));
958 Ok(self.bump_with(token::BinOp(token::Or), span))
960 _ => self.unexpected()
964 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
966 None => {/* everything ok */}
968 let text = suf.as_str();
970 self.span_bug(sp, "found empty literal suffix in Some")
972 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
977 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
978 /// `<` and continue. If a `<` is not seen, return false.
980 /// This is meant to be used when parsing generics on a path to get the
982 fn eat_lt(&mut self) -> bool {
983 self.expected_tokens.push(TokenType::Token(token::Lt));
989 token::BinOp(token::Shl) => {
990 let span = self.span.with_lo(self.span.lo() + BytePos(1));
991 self.bump_with(token::Lt, span);
998 fn expect_lt(&mut self) -> PResult<'a, ()> {
1006 /// Expect and consume a GT. if a >> is seen, replace it
1007 /// with a single > and continue. If a GT is not seen,
1008 /// signal an error.
1009 fn expect_gt(&mut self) -> PResult<'a, ()> {
1010 self.expected_tokens.push(TokenType::Token(token::Gt));
1016 token::BinOp(token::Shr) => {
1017 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1018 Ok(self.bump_with(token::Gt, span))
1020 token::BinOpEq(token::Shr) => {
1021 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1022 Ok(self.bump_with(token::Ge, span))
1025 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1026 Ok(self.bump_with(token::Eq, span))
1028 _ => self.unexpected()
1032 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1033 /// passes through any errors encountered. Used for error recovery.
1034 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1035 let handler = self.diagnostic();
1037 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1039 TokenExpectType::Expect,
1040 |p| Ok(p.parse_token_tree())) {
1041 handler.cancel(err);
1045 /// Parse a sequence, including the closing delimiter. The function
1046 /// f must consume tokens until reaching the next separator or
1047 /// closing bracket.
1048 pub fn parse_seq_to_end<T, F>(&mut self,
1052 -> PResult<'a, Vec<T>> where
1053 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1055 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1060 /// Parse a sequence, not including the closing delimiter. The function
1061 /// f must consume tokens until reaching the next separator or
1062 /// closing bracket.
1063 pub fn parse_seq_to_before_end<T, F>(&mut self,
1067 -> PResult<'a, Vec<T>>
1068 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1070 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1073 fn parse_seq_to_before_tokens<T, F>(&mut self,
1074 kets: &[&token::Token],
1076 expect: TokenExpectType,
1078 -> PResult<'a, Vec<T>>
1079 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1081 let mut first: bool = true;
1083 while !kets.iter().any(|k| {
1085 TokenExpectType::Expect => self.check(k),
1086 TokenExpectType::NoExpect => self.token == **k,
1090 token::CloseDelim(..) | token::Eof => break,
1093 if let Some(ref t) = sep.sep {
1097 if let Err(mut e) = self.expect(t) {
1098 // Attempt to keep parsing if it was a similar separator
1099 if let Some(ref tokens) = t.similar_tokens() {
1100 if tokens.contains(&self.token) {
1105 // Attempt to keep parsing if it was an omitted separator
1119 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1121 TokenExpectType::Expect => self.check(k),
1122 TokenExpectType::NoExpect => self.token == **k,
1135 /// Parse a sequence, including the closing delimiter. The function
1136 /// f must consume tokens until reaching the next separator or
1137 /// closing bracket.
1138 fn parse_unspanned_seq<T, F>(&mut self,
1143 -> PResult<'a, Vec<T>> where
1144 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1147 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1148 if self.token == *ket {
1154 /// Advance the parser by one token
1155 pub fn bump(&mut self) {
1156 if self.prev_token_kind == PrevTokenKind::Eof {
1157 // Bumping after EOF is a bad sign, usually an infinite loop.
1158 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1161 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1163 // Record last token kind for possible error recovery.
1164 self.prev_token_kind = match self.token {
1165 token::DocComment(..) => PrevTokenKind::DocComment,
1166 token::Comma => PrevTokenKind::Comma,
1167 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1168 token::Interpolated(..) => PrevTokenKind::Interpolated,
1169 token::Eof => PrevTokenKind::Eof,
1170 token::Ident(..) => PrevTokenKind::Ident,
1171 _ => PrevTokenKind::Other,
1174 let next = self.next_tok();
1175 self.span = next.sp;
1176 self.token = next.tok;
1177 self.expected_tokens.clear();
1178 // check after each token
1179 self.process_potential_macro_variable();
1182 /// Advance the parser using provided token as a next one. Use this when
1183 /// consuming a part of a token. For example a single `<` from `<<`.
1184 fn bump_with(&mut self, next: token::Token, span: Span) {
1185 self.prev_span = self.span.with_hi(span.lo());
1186 // It would be incorrect to record the kind of the current token, but
1187 // fortunately for tokens currently using `bump_with`, the
1188 // prev_token_kind will be of no use anyway.
1189 self.prev_token_kind = PrevTokenKind::Other;
1192 self.expected_tokens.clear();
1195 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1196 F: FnOnce(&token::Token) -> R,
1199 return f(&self.token)
1202 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1203 Some(tree) => match tree {
1204 TokenTree::Token(_, tok) => tok,
1205 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1207 None => token::CloseDelim(self.token_cursor.frame.delim),
1211 fn look_ahead_span(&self, dist: usize) -> Span {
1216 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1217 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1218 None => self.look_ahead_span(dist - 1),
1221 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1222 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1224 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1225 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1227 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1228 err.span_err(sp, self.diagnostic())
1230 fn bug(&self, m: &str) -> ! {
1231 self.sess.span_diagnostic.span_bug(self.span, m)
1233 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1234 self.sess.span_diagnostic.span_err(sp, m)
1236 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1237 self.sess.span_diagnostic.struct_span_err(sp, m)
1239 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1240 self.sess.span_diagnostic.span_bug(sp, m)
1242 crate fn abort_if_errors(&self) {
1243 self.sess.span_diagnostic.abort_if_errors();
1246 fn cancel(&self, err: &mut DiagnosticBuilder) {
1247 self.sess.span_diagnostic.cancel(err)
1250 crate fn diagnostic(&self) -> &'a errors::Handler {
1251 &self.sess.span_diagnostic
1254 /// Is the current token one of the keywords that signals a bare function
1256 fn token_is_bare_fn_keyword(&mut self) -> bool {
1257 self.check_keyword(keywords::Fn) ||
1258 self.check_keyword(keywords::Unsafe) ||
1259 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1262 /// parse a TyKind::BareFn type:
1263 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1266 [unsafe] [extern "ABI"] fn (S) -> T
1276 let unsafety = self.parse_unsafety();
1277 let abi = if self.eat_keyword(keywords::Extern) {
1278 self.parse_opt_abi()?.unwrap_or(Abi::C)
1283 self.expect_keyword(keywords::Fn)?;
1284 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1285 let ret_ty = self.parse_ret_ty(false)?;
1286 let decl = P(FnDecl {
1291 Ok(TyKind::BareFn(P(BareFnTy {
1299 /// Parse asyncness: `async` or nothing
1300 fn parse_asyncness(&mut self) -> IsAsync {
1301 if self.eat_keyword(keywords::Async) {
1302 IsAsync::Async(ast::DUMMY_NODE_ID)
1308 /// Parse unsafety: `unsafe` or nothing.
1309 fn parse_unsafety(&mut self) -> Unsafety {
1310 if self.eat_keyword(keywords::Unsafe) {
1317 /// Parse the items in a trait declaration
1318 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1319 maybe_whole!(self, NtTraitItem, |x| x);
1320 let attrs = self.parse_outer_attributes()?;
1321 let (mut item, tokens) = self.collect_tokens(|this| {
1322 this.parse_trait_item_(at_end, attrs)
1324 // See `parse_item` for why this clause is here.
1325 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1326 item.tokens = Some(tokens);
1331 fn parse_trait_item_(&mut self,
1333 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1336 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1337 self.parse_trait_item_assoc_ty()?
1338 } else if self.is_const_item() {
1339 self.expect_keyword(keywords::Const)?;
1340 let ident = self.parse_ident()?;
1341 self.expect(&token::Colon)?;
1342 let ty = self.parse_ty()?;
1343 let default = if self.check(&token::Eq) {
1345 let expr = self.parse_expr()?;
1346 self.expect(&token::Semi)?;
1349 self.expect(&token::Semi)?;
1352 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1353 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1354 // trait item macro.
1355 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1357 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1359 let ident = self.parse_ident()?;
1360 let mut generics = self.parse_generics()?;
1362 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1363 // This is somewhat dubious; We don't want to allow
1364 // argument names to be left off if there is a
1366 p.parse_arg_general(false)
1368 generics.where_clause = self.parse_where_clause()?;
1370 let sig = ast::MethodSig {
1380 let body = match self.token {
1384 debug!("parse_trait_methods(): parsing required method");
1387 token::OpenDelim(token::Brace) => {
1388 debug!("parse_trait_methods(): parsing provided method");
1390 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1391 attrs.extend(inner_attrs.iter().cloned());
1395 let token_str = self.this_token_to_string();
1396 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1398 err.span_label(self.span, "expected `;` or `{`");
1402 (ident, ast::TraitItemKind::Method(sig, body), generics)
1406 id: ast::DUMMY_NODE_ID,
1411 span: lo.to(self.prev_span),
1416 /// Parse optional return type [ -> TY ] in function decl
1417 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1418 if self.eat(&token::RArrow) {
1419 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1421 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1426 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1427 self.parse_ty_common(true, true)
1430 /// Parse a type in restricted contexts where `+` is not permitted.
1431 /// Example 1: `&'a TYPE`
1432 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1433 /// Example 2: `value1 as TYPE + value2`
1434 /// `+` is prohibited to avoid interactions with expression grammar.
1435 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1436 self.parse_ty_common(false, true)
1439 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1440 -> PResult<'a, P<Ty>> {
1441 maybe_whole!(self, NtTy, |x| x);
1444 let mut impl_dyn_multi = false;
1445 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1446 // `(TYPE)` is a parenthesized type.
1447 // `(TYPE,)` is a tuple with a single field of type TYPE.
1448 let mut ts = vec![];
1449 let mut last_comma = false;
1450 while self.token != token::CloseDelim(token::Paren) {
1451 ts.push(self.parse_ty()?);
1452 if self.eat(&token::Comma) {
1459 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1460 self.expect(&token::CloseDelim(token::Paren))?;
1462 if ts.len() == 1 && !last_comma {
1463 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1464 let maybe_bounds = allow_plus && self.token.is_like_plus();
1466 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1467 TyKind::Path(None, ref path) if maybe_bounds => {
1468 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1470 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1471 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1472 let path = match bounds[0] {
1473 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1474 _ => self.bug("unexpected lifetime bound"),
1476 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1479 _ => TyKind::Paren(P(ty))
1484 } else if self.eat(&token::Not) {
1487 } else if self.eat(&token::BinOp(token::Star)) {
1489 TyKind::Ptr(self.parse_ptr()?)
1490 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1492 let t = self.parse_ty()?;
1493 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1494 let t = match self.maybe_parse_fixed_length_of_vec()? {
1495 None => TyKind::Slice(t),
1496 Some(length) => TyKind::Array(t, AnonConst {
1497 id: ast::DUMMY_NODE_ID,
1501 self.expect(&token::CloseDelim(token::Bracket))?;
1503 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1506 self.parse_borrowed_pointee()?
1507 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1509 // In order to not be ambiguous, the type must be surrounded by parens.
1510 self.expect(&token::OpenDelim(token::Paren))?;
1512 id: ast::DUMMY_NODE_ID,
1513 value: self.parse_expr()?,
1515 self.expect(&token::CloseDelim(token::Paren))?;
1517 } else if self.eat_keyword(keywords::Underscore) {
1518 // A type to be inferred `_`
1520 } else if self.token_is_bare_fn_keyword() {
1521 // Function pointer type
1522 self.parse_ty_bare_fn(Vec::new())?
1523 } else if self.check_keyword(keywords::For) {
1524 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1525 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1526 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1528 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1529 if self.token_is_bare_fn_keyword() {
1530 self.parse_ty_bare_fn(lifetime_defs)?
1532 let path = self.parse_path(PathStyle::Type)?;
1533 let parse_plus = allow_plus && self.check_plus();
1534 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1536 } else if self.eat_keyword(keywords::Impl) {
1537 // Always parse bounds greedily for better error recovery.
1538 let bounds = self.parse_generic_bounds()?;
1539 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1540 TyKind::ImplTrait(bounds)
1541 } else if self.check_keyword(keywords::Dyn) &&
1542 self.look_ahead(1, |t| t.can_begin_bound() &&
1543 !can_continue_type_after_non_fn_ident(t)) {
1544 self.bump(); // `dyn`
1545 // Always parse bounds greedily for better error recovery.
1546 let bounds = self.parse_generic_bounds()?;
1547 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1548 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1549 } else if self.check(&token::Question) ||
1550 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1551 // Bound list (trait object type)
1552 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1553 TraitObjectSyntax::None)
1554 } else if self.eat_lt() {
1556 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1557 TyKind::Path(Some(qself), path)
1558 } else if self.token.is_path_start() {
1560 let path = self.parse_path(PathStyle::Type)?;
1561 if self.eat(&token::Not) {
1562 // Macro invocation in type position
1563 let (delim, tts) = self.expect_delimited_token_tree()?;
1564 let node = Mac_ { path, tts, delim };
1565 TyKind::Mac(respan(lo.to(self.prev_span), node))
1567 // Just a type path or bound list (trait object type) starting with a trait.
1569 // `Trait1 + Trait2 + 'a`
1570 if allow_plus && self.check_plus() {
1571 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1573 TyKind::Path(None, path)
1577 let msg = format!("expected type, found {}", self.this_token_descr());
1578 return Err(self.fatal(&msg));
1581 let span = lo.to(self.prev_span);
1582 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1584 // Try to recover from use of `+` with incorrect priority.
1585 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1586 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1587 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1592 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1593 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1594 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1595 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1597 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1598 bounds.append(&mut self.parse_generic_bounds()?);
1600 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1603 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1604 if !allow_plus && impl_dyn_multi {
1605 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1606 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1607 .span_suggestion_with_applicability(
1609 "use parentheses to disambiguate",
1611 Applicability::MachineApplicable
1616 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1617 // Do not add `+` to expected tokens.
1618 if !allow_plus || !self.token.is_like_plus() {
1623 let bounds = self.parse_generic_bounds()?;
1624 let sum_span = ty.span.to(self.prev_span);
1626 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1627 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1630 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1631 let sum_with_parens = pprust::to_string(|s| {
1632 use print::pprust::PrintState;
1635 s.print_opt_lifetime(lifetime)?;
1636 s.print_mutability(mut_ty.mutbl)?;
1638 s.print_type(&mut_ty.ty)?;
1639 s.print_type_bounds(" +", &bounds)?;
1642 err.span_suggestion_with_applicability(
1644 "try adding parentheses",
1646 Applicability::MachineApplicable
1649 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1650 err.span_label(sum_span, "perhaps you forgot parentheses?");
1653 err.span_label(sum_span, "expected a path");
1660 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1661 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1663 // Do not add `::` to expected tokens.
1664 if !allow_recovery || self.token != token::ModSep {
1667 let ty = match base.to_ty() {
1669 None => return Ok(base),
1672 self.bump(); // `::`
1673 let mut segments = Vec::new();
1674 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1676 let span = ty.span.to(self.prev_span);
1677 let path_span = span.to(span); // use an empty path since `position` == 0
1678 let recovered = base.to_recovered(
1679 Some(QSelf { ty, path_span, position: 0 }),
1680 ast::Path { segments, span },
1684 .struct_span_err(span, "missing angle brackets in associated item path")
1685 .span_suggestion_with_applicability( // this is a best-effort recovery
1686 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1692 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1693 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1694 let mutbl = self.parse_mutability();
1695 let ty = self.parse_ty_no_plus()?;
1696 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1699 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1700 let mutbl = if self.eat_keyword(keywords::Mut) {
1702 } else if self.eat_keyword(keywords::Const) {
1703 Mutability::Immutable
1705 let span = self.prev_span;
1707 "expected mut or const in raw pointer type (use \
1708 `*mut T` or `*const T` as appropriate)");
1709 Mutability::Immutable
1711 let t = self.parse_ty_no_plus()?;
1712 Ok(MutTy { ty: t, mutbl: mutbl })
1715 fn is_named_argument(&mut self) -> bool {
1716 let offset = match self.token {
1717 token::Interpolated(ref nt) => match nt.0 {
1718 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1721 token::BinOp(token::And) | token::AndAnd => 1,
1722 _ if self.token.is_keyword(keywords::Mut) => 1,
1726 self.look_ahead(offset, |t| t.is_ident()) &&
1727 self.look_ahead(offset + 1, |t| t == &token::Colon)
1730 /// This version of parse arg doesn't necessarily require
1731 /// identifier names.
1732 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1733 maybe_whole!(self, NtArg, |x| x);
1735 let (pat, ty) = if require_name || self.is_named_argument() {
1736 debug!("parse_arg_general parse_pat (require_name:{})",
1738 let pat = self.parse_pat()?;
1740 self.expect(&token::Colon)?;
1741 (pat, self.parse_ty()?)
1743 debug!("parse_arg_general ident_to_pat");
1744 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1745 let ty = self.parse_ty()?;
1747 id: ast::DUMMY_NODE_ID,
1748 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
1757 id: ast::DUMMY_NODE_ID,
1761 /// Parse a single function argument
1762 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1763 self.parse_arg_general(true)
1766 /// Parse an argument in a lambda header e.g. |arg, arg|
1767 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1768 let pat = self.parse_pat()?;
1769 let t = if self.eat(&token::Colon) {
1773 id: ast::DUMMY_NODE_ID,
1774 node: TyKind::Infer,
1781 id: ast::DUMMY_NODE_ID
1785 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1786 if self.eat(&token::Semi) {
1787 Ok(Some(self.parse_expr()?))
1793 /// Matches token_lit = LIT_INTEGER | ...
1794 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1795 let out = match self.token {
1796 token::Interpolated(ref nt) => match nt.0 {
1797 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1798 ExprKind::Lit(ref lit) => { lit.node.clone() }
1799 _ => { return self.unexpected_last(&self.token); }
1801 _ => { return self.unexpected_last(&self.token); }
1803 token::Literal(lit, suf) => {
1804 let diag = Some((self.span, &self.sess.span_diagnostic));
1805 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1809 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1814 _ => { return self.unexpected_last(&self.token); }
1821 /// Matches lit = true | false | token_lit
1822 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1824 let lit = if self.eat_keyword(keywords::True) {
1826 } else if self.eat_keyword(keywords::False) {
1827 LitKind::Bool(false)
1829 let lit = self.parse_lit_token()?;
1832 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1835 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1836 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1837 maybe_whole_expr!(self);
1839 let minus_lo = self.span;
1840 let minus_present = self.eat(&token::BinOp(token::Minus));
1842 let literal = P(self.parse_lit()?);
1843 let hi = self.prev_span;
1844 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1847 let minus_hi = self.prev_span;
1848 let unary = self.mk_unary(UnOp::Neg, expr);
1849 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1855 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1857 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1858 let span = self.span;
1860 Ok(Ident::new(ident.name, span))
1862 _ => self.parse_ident(),
1866 /// Parses qualified path.
1867 /// Assumes that the leading `<` has been parsed already.
1869 /// `qualified_path = <type [as trait_ref]>::path`
1874 /// `<T as U>::F::a<S>` (without disambiguator)
1875 /// `<T as U>::F::a::<S>` (with disambiguator)
1876 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1877 let lo = self.prev_span;
1878 let ty = self.parse_ty()?;
1880 // `path` will contain the prefix of the path up to the `>`,
1881 // if any (e.g., `U` in the `<T as U>::*` examples
1882 // above). `path_span` has the span of that path, or an empty
1883 // span in the case of something like `<T>::Bar`.
1884 let (mut path, path_span);
1885 if self.eat_keyword(keywords::As) {
1886 let path_lo = self.span;
1887 path = self.parse_path(PathStyle::Type)?;
1888 path_span = path_lo.to(self.prev_span);
1890 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1891 path_span = self.span.to(self.span);
1894 self.expect(&token::Gt)?;
1895 self.expect(&token::ModSep)?;
1897 let qself = QSelf { ty, path_span, position: path.segments.len() };
1898 self.parse_path_segments(&mut path.segments, style, true)?;
1900 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1903 /// Parses simple paths.
1905 /// `path = [::] segment+`
1906 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1909 /// `a::b::C<D>` (without disambiguator)
1910 /// `a::b::C::<D>` (with disambiguator)
1911 /// `Fn(Args)` (without disambiguator)
1912 /// `Fn::(Args)` (with disambiguator)
1913 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1914 self.parse_path_common(style, true)
1917 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1918 -> PResult<'a, ast::Path> {
1919 maybe_whole!(self, NtPath, |path| {
1920 if style == PathStyle::Mod &&
1921 path.segments.iter().any(|segment| segment.args.is_some()) {
1922 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1927 let lo = self.meta_var_span.unwrap_or(self.span);
1928 let mut segments = Vec::new();
1929 if self.eat(&token::ModSep) {
1930 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1932 self.parse_path_segments(&mut segments, style, enable_warning)?;
1934 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1937 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1938 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1939 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1940 let meta_ident = match self.token {
1941 token::Interpolated(ref nt) => match nt.0 {
1942 token::NtMeta(ref meta) => match meta.node {
1943 ast::MetaItemKind::Word => Some(meta.ident.clone()),
1950 if let Some(path) = meta_ident {
1954 self.parse_path(style)
1957 fn parse_path_segments(&mut self,
1958 segments: &mut Vec<PathSegment>,
1960 enable_warning: bool)
1961 -> PResult<'a, ()> {
1963 segments.push(self.parse_path_segment(style, enable_warning)?);
1965 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1971 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1972 -> PResult<'a, PathSegment> {
1973 let ident = self.parse_path_segment_ident()?;
1975 let is_args_start = |token: &token::Token| match *token {
1976 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1979 let check_args_start = |this: &mut Self| {
1980 this.expected_tokens.extend_from_slice(
1981 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1983 is_args_start(&this.token)
1986 Ok(if style == PathStyle::Type && check_args_start(self) ||
1987 style != PathStyle::Mod && self.check(&token::ModSep)
1988 && self.look_ahead(1, |t| is_args_start(t)) {
1989 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1991 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1992 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1993 .span_label(self.prev_span, "try removing `::`").emit();
1996 let args = if self.eat_lt() {
1998 let (args, bindings) = self.parse_generic_args()?;
2000 let span = lo.to(self.prev_span);
2001 AngleBracketedArgs { args, bindings, span }.into()
2005 let inputs = self.parse_seq_to_before_tokens(
2006 &[&token::CloseDelim(token::Paren)],
2007 SeqSep::trailing_allowed(token::Comma),
2008 TokenExpectType::Expect,
2011 let output = if self.eat(&token::RArrow) {
2012 Some(self.parse_ty_common(false, false)?)
2016 let span = lo.to(self.prev_span);
2017 ParenthesisedArgs { inputs, output, span }.into()
2020 PathSegment { ident, args }
2022 // Generic arguments are not found.
2023 PathSegment::from_ident(ident)
2027 crate fn check_lifetime(&mut self) -> bool {
2028 self.expected_tokens.push(TokenType::Lifetime);
2029 self.token.is_lifetime()
2032 /// Parse single lifetime 'a or panic.
2033 crate fn expect_lifetime(&mut self) -> Lifetime {
2034 if let Some(ident) = self.token.lifetime() {
2035 let span = self.span;
2037 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2039 self.span_bug(self.span, "not a lifetime")
2043 fn eat_label(&mut self) -> Option<Label> {
2044 if let Some(ident) = self.token.lifetime() {
2045 let span = self.span;
2047 Some(Label { ident: Ident::new(ident.name, span) })
2053 /// Parse mutability (`mut` or nothing).
2054 fn parse_mutability(&mut self) -> Mutability {
2055 if self.eat_keyword(keywords::Mut) {
2058 Mutability::Immutable
2062 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2063 if let token::Literal(token::Integer(name), None) = self.token {
2065 Ok(Ident::new(name, self.prev_span))
2067 self.parse_ident_common(false)
2071 /// Parse ident (COLON expr)?
2072 fn parse_field(&mut self) -> PResult<'a, Field> {
2073 let attrs = self.parse_outer_attributes()?;
2076 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2077 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2078 let fieldname = self.parse_field_name()?;
2080 (fieldname, self.parse_expr()?, false)
2082 let fieldname = self.parse_ident_common(false)?;
2084 // Mimic `x: x` for the `x` field shorthand.
2085 let path = ast::Path::from_ident(fieldname);
2086 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2087 (fieldname, expr, true)
2091 span: lo.to(expr.span),
2094 attrs: attrs.into(),
2098 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2099 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2102 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2103 ExprKind::Unary(unop, expr)
2106 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2107 ExprKind::Binary(binop, lhs, rhs)
2110 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2111 ExprKind::Call(f, args)
2114 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2115 ExprKind::Index(expr, idx)
2118 fn mk_range(&mut self,
2119 start: Option<P<Expr>>,
2120 end: Option<P<Expr>>,
2121 limits: RangeLimits)
2122 -> PResult<'a, ast::ExprKind> {
2123 if end.is_none() && limits == RangeLimits::Closed {
2124 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2126 Ok(ExprKind::Range(start, end, limits))
2130 fn mk_assign_op(&mut self, binop: ast::BinOp,
2131 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2132 ExprKind::AssignOp(binop, lhs, rhs)
2135 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2137 id: ast::DUMMY_NODE_ID,
2138 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2144 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2145 let delim = match self.token {
2146 token::OpenDelim(delim) => delim,
2148 let msg = "expected open delimiter";
2149 let mut err = self.fatal(msg);
2150 err.span_label(self.span, msg);
2154 let delimited = match self.parse_token_tree() {
2155 TokenTree::Delimited(_, delimited) => delimited,
2156 _ => unreachable!(),
2158 let delim = match delim {
2159 token::Paren => MacDelimiter::Parenthesis,
2160 token::Bracket => MacDelimiter::Bracket,
2161 token::Brace => MacDelimiter::Brace,
2162 token::NoDelim => self.bug("unexpected no delimiter"),
2164 Ok((delim, delimited.stream().into()))
2167 /// At the bottom (top?) of the precedence hierarchy,
2168 /// parse things like parenthesized exprs,
2169 /// macros, return, etc.
2171 /// NB: This does not parse outer attributes,
2172 /// and is private because it only works
2173 /// correctly if called from parse_dot_or_call_expr().
2174 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2175 maybe_whole_expr!(self);
2177 // Outer attributes are already parsed and will be
2178 // added to the return value after the fact.
2180 // Therefore, prevent sub-parser from parsing
2181 // attributes by giving them a empty "already parsed" list.
2182 let mut attrs = ThinVec::new();
2185 let mut hi = self.span;
2189 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2191 token::OpenDelim(token::Paren) => {
2194 attrs.extend(self.parse_inner_attributes()?);
2196 // (e) is parenthesized e
2197 // (e,) is a tuple with only one field, e
2198 let mut es = vec![];
2199 let mut trailing_comma = false;
2200 while self.token != token::CloseDelim(token::Paren) {
2201 es.push(self.parse_expr()?);
2202 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2203 if self.check(&token::Comma) {
2204 trailing_comma = true;
2208 trailing_comma = false;
2214 hi = self.prev_span;
2215 ex = if es.len() == 1 && !trailing_comma {
2216 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2221 token::OpenDelim(token::Brace) => {
2222 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2224 token::BinOp(token::Or) | token::OrOr => {
2225 return self.parse_lambda_expr(attrs);
2227 token::OpenDelim(token::Bracket) => {
2230 attrs.extend(self.parse_inner_attributes()?);
2232 if self.check(&token::CloseDelim(token::Bracket)) {
2235 ex = ExprKind::Array(Vec::new());
2238 let first_expr = self.parse_expr()?;
2239 if self.check(&token::Semi) {
2240 // Repeating array syntax: [ 0; 512 ]
2242 let count = AnonConst {
2243 id: ast::DUMMY_NODE_ID,
2244 value: self.parse_expr()?,
2246 self.expect(&token::CloseDelim(token::Bracket))?;
2247 ex = ExprKind::Repeat(first_expr, count);
2248 } else if self.check(&token::Comma) {
2249 // Vector with two or more elements.
2251 let remaining_exprs = self.parse_seq_to_end(
2252 &token::CloseDelim(token::Bracket),
2253 SeqSep::trailing_allowed(token::Comma),
2254 |p| Ok(p.parse_expr()?)
2256 let mut exprs = vec![first_expr];
2257 exprs.extend(remaining_exprs);
2258 ex = ExprKind::Array(exprs);
2260 // Vector with one element.
2261 self.expect(&token::CloseDelim(token::Bracket))?;
2262 ex = ExprKind::Array(vec![first_expr]);
2265 hi = self.prev_span;
2269 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2271 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2273 if self.span.edition() >= Edition::Edition2018 &&
2274 self.check_keyword(keywords::Async)
2276 if self.is_async_block() { // check for `async {` and `async move {`
2277 return self.parse_async_block(attrs);
2279 return self.parse_lambda_expr(attrs);
2282 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2283 return self.parse_lambda_expr(attrs);
2285 if self.eat_keyword(keywords::If) {
2286 return self.parse_if_expr(attrs);
2288 if self.eat_keyword(keywords::For) {
2289 let lo = self.prev_span;
2290 return self.parse_for_expr(None, lo, attrs);
2292 if self.eat_keyword(keywords::While) {
2293 let lo = self.prev_span;
2294 return self.parse_while_expr(None, lo, attrs);
2296 if let Some(label) = self.eat_label() {
2297 let lo = label.ident.span;
2298 self.expect(&token::Colon)?;
2299 if self.eat_keyword(keywords::While) {
2300 return self.parse_while_expr(Some(label), lo, attrs)
2302 if self.eat_keyword(keywords::For) {
2303 return self.parse_for_expr(Some(label), lo, attrs)
2305 if self.eat_keyword(keywords::Loop) {
2306 return self.parse_loop_expr(Some(label), lo, attrs)
2308 if self.token == token::OpenDelim(token::Brace) {
2309 return self.parse_block_expr(Some(label),
2311 BlockCheckMode::Default,
2314 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2315 let mut err = self.fatal(msg);
2316 err.span_label(self.span, msg);
2319 if self.eat_keyword(keywords::Loop) {
2320 let lo = self.prev_span;
2321 return self.parse_loop_expr(None, lo, attrs);
2323 if self.eat_keyword(keywords::Continue) {
2324 let label = self.eat_label();
2325 let ex = ExprKind::Continue(label);
2326 let hi = self.prev_span;
2327 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2329 if self.eat_keyword(keywords::Match) {
2330 return self.parse_match_expr(attrs);
2332 if self.eat_keyword(keywords::Unsafe) {
2333 return self.parse_block_expr(
2336 BlockCheckMode::Unsafe(ast::UserProvided),
2339 if self.is_catch_expr() {
2341 assert!(self.eat_keyword(keywords::Do));
2342 assert!(self.eat_keyword(keywords::Catch));
2343 return self.parse_catch_expr(lo, attrs);
2345 if self.eat_keyword(keywords::Return) {
2346 if self.token.can_begin_expr() {
2347 let e = self.parse_expr()?;
2349 ex = ExprKind::Ret(Some(e));
2351 ex = ExprKind::Ret(None);
2353 } else if self.eat_keyword(keywords::Break) {
2354 let label = self.eat_label();
2355 let e = if self.token.can_begin_expr()
2356 && !(self.token == token::OpenDelim(token::Brace)
2357 && self.restrictions.contains(
2358 Restrictions::NO_STRUCT_LITERAL)) {
2359 Some(self.parse_expr()?)
2363 ex = ExprKind::Break(label, e);
2364 hi = self.prev_span;
2365 } else if self.eat_keyword(keywords::Yield) {
2366 if self.token.can_begin_expr() {
2367 let e = self.parse_expr()?;
2369 ex = ExprKind::Yield(Some(e));
2371 ex = ExprKind::Yield(None);
2373 } else if self.token.is_keyword(keywords::Let) {
2374 // Catch this syntax error here, instead of in `parse_ident`, so
2375 // that we can explicitly mention that let is not to be used as an expression
2376 let mut db = self.fatal("expected expression, found statement (`let`)");
2377 db.span_label(self.span, "expected expression");
2378 db.note("variable declaration using `let` is a statement");
2380 } else if self.token.is_path_start() {
2381 let pth = self.parse_path(PathStyle::Expr)?;
2383 // `!`, as an operator, is prefix, so we know this isn't that
2384 if self.eat(&token::Not) {
2385 // MACRO INVOCATION expression
2386 let (delim, tts) = self.expect_delimited_token_tree()?;
2387 let hi = self.prev_span;
2388 let node = Mac_ { path: pth, tts, delim };
2389 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2391 if self.check(&token::OpenDelim(token::Brace)) {
2392 // This is a struct literal, unless we're prohibited
2393 // from parsing struct literals here.
2394 let prohibited = self.restrictions.contains(
2395 Restrictions::NO_STRUCT_LITERAL
2398 return self.parse_struct_expr(lo, pth, attrs);
2403 ex = ExprKind::Path(None, pth);
2405 match self.parse_literal_maybe_minus() {
2408 ex = expr.node.clone();
2411 self.cancel(&mut err);
2412 let msg = format!("expected expression, found {}",
2413 self.this_token_descr());
2414 let mut err = self.fatal(&msg);
2415 err.span_label(self.span, "expected expression");
2423 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2424 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2429 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2430 -> PResult<'a, P<Expr>> {
2431 let struct_sp = lo.to(self.prev_span);
2433 let mut fields = Vec::new();
2434 let mut base = None;
2436 attrs.extend(self.parse_inner_attributes()?);
2438 while self.token != token::CloseDelim(token::Brace) {
2439 if self.eat(&token::DotDot) {
2440 let exp_span = self.prev_span;
2441 match self.parse_expr() {
2447 self.recover_stmt();
2450 if self.token == token::Comma {
2451 let mut err = self.sess.span_diagnostic.mut_span_err(
2452 exp_span.to(self.prev_span),
2453 "cannot use a comma after the base struct",
2455 err.span_suggestion_short_with_applicability(
2457 "remove this comma",
2459 Applicability::MachineApplicable
2461 err.note("the base struct must always be the last field");
2463 self.recover_stmt();
2468 match self.parse_field() {
2469 Ok(f) => fields.push(f),
2471 e.span_label(struct_sp, "while parsing this struct");
2474 // If the next token is a comma, then try to parse
2475 // what comes next as additional fields, rather than
2476 // bailing out until next `}`.
2477 if self.token != token::Comma {
2478 self.recover_stmt();
2484 match self.expect_one_of(&[token::Comma],
2485 &[token::CloseDelim(token::Brace)]) {
2489 self.recover_stmt();
2495 let span = lo.to(self.span);
2496 self.expect(&token::CloseDelim(token::Brace))?;
2497 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2500 fn parse_or_use_outer_attributes(&mut self,
2501 already_parsed_attrs: Option<ThinVec<Attribute>>)
2502 -> PResult<'a, ThinVec<Attribute>> {
2503 if let Some(attrs) = already_parsed_attrs {
2506 self.parse_outer_attributes().map(|a| a.into())
2510 /// Parse a block or unsafe block
2511 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2512 lo: Span, blk_mode: BlockCheckMode,
2513 outer_attrs: ThinVec<Attribute>)
2514 -> PResult<'a, P<Expr>> {
2515 self.expect(&token::OpenDelim(token::Brace))?;
2517 let mut attrs = outer_attrs;
2518 attrs.extend(self.parse_inner_attributes()?);
2520 let blk = self.parse_block_tail(lo, blk_mode)?;
2521 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2524 /// parse a.b or a(13) or a[4] or just a
2525 fn parse_dot_or_call_expr(&mut self,
2526 already_parsed_attrs: Option<ThinVec<Attribute>>)
2527 -> PResult<'a, P<Expr>> {
2528 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2530 let b = self.parse_bottom_expr();
2531 let (span, b) = self.interpolated_or_expr_span(b)?;
2532 self.parse_dot_or_call_expr_with(b, span, attrs)
2535 fn parse_dot_or_call_expr_with(&mut self,
2538 mut attrs: ThinVec<Attribute>)
2539 -> PResult<'a, P<Expr>> {
2540 // Stitch the list of outer attributes onto the return value.
2541 // A little bit ugly, but the best way given the current code
2543 self.parse_dot_or_call_expr_with_(e0, lo)
2545 expr.map(|mut expr| {
2546 attrs.extend::<Vec<_>>(expr.attrs.into());
2549 ExprKind::If(..) | ExprKind::IfLet(..) => {
2550 if !expr.attrs.is_empty() {
2551 // Just point to the first attribute in there...
2552 let span = expr.attrs[0].span;
2555 "attributes are not yet allowed on `if` \
2566 // Assuming we have just parsed `.`, continue parsing into an expression.
2567 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2568 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2569 Ok(match self.token {
2570 token::OpenDelim(token::Paren) => {
2571 // Method call `expr.f()`
2572 let mut args = self.parse_unspanned_seq(
2573 &token::OpenDelim(token::Paren),
2574 &token::CloseDelim(token::Paren),
2575 SeqSep::trailing_allowed(token::Comma),
2576 |p| Ok(p.parse_expr()?)
2578 args.insert(0, self_arg);
2580 let span = lo.to(self.prev_span);
2581 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2584 // Field access `expr.f`
2585 if let Some(args) = segment.args {
2586 self.span_err(args.span(),
2587 "field expressions may not have generic arguments");
2590 let span = lo.to(self.prev_span);
2591 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2596 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2601 while self.eat(&token::Question) {
2602 let hi = self.prev_span;
2603 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2607 if self.eat(&token::Dot) {
2609 token::Ident(..) => {
2610 e = self.parse_dot_suffix(e, lo)?;
2612 token::Literal(token::Integer(name), _) => {
2613 let span = self.span;
2615 let field = ExprKind::Field(e, Ident::new(name, span));
2616 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2618 token::Literal(token::Float(n), _suf) => {
2620 let fstr = n.as_str();
2621 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2622 &format!("unexpected token: `{}`", n));
2623 err.span_label(self.prev_span, "unexpected token");
2624 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2625 let float = match fstr.parse::<f64>().ok() {
2629 let sugg = pprust::to_string(|s| {
2630 use print::pprust::PrintState;
2634 s.print_usize(float.trunc() as usize)?;
2637 s.s.word(fstr.splitn(2, ".").last().unwrap())
2639 err.span_suggestion_with_applicability(
2640 lo.to(self.prev_span),
2641 "try parenthesizing the first index",
2643 Applicability::MachineApplicable
2650 // FIXME Could factor this out into non_fatal_unexpected or something.
2651 let actual = self.this_token_to_string();
2652 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2657 if self.expr_is_complete(&e) { break; }
2660 token::OpenDelim(token::Paren) => {
2661 let es = self.parse_unspanned_seq(
2662 &token::OpenDelim(token::Paren),
2663 &token::CloseDelim(token::Paren),
2664 SeqSep::trailing_allowed(token::Comma),
2665 |p| Ok(p.parse_expr()?)
2667 hi = self.prev_span;
2669 let nd = self.mk_call(e, es);
2670 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2674 // Could be either an index expression or a slicing expression.
2675 token::OpenDelim(token::Bracket) => {
2677 let ix = self.parse_expr()?;
2679 self.expect(&token::CloseDelim(token::Bracket))?;
2680 let index = self.mk_index(e, ix);
2681 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2689 crate fn process_potential_macro_variable(&mut self) {
2690 let (token, span) = match self.token {
2691 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2692 self.look_ahead(1, |t| t.is_ident()) => {
2694 let name = match self.token {
2695 token::Ident(ident, _) => ident,
2698 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2699 err.span_label(self.span, "unknown macro variable");
2703 token::Interpolated(ref nt) => {
2704 self.meta_var_span = Some(self.span);
2705 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2706 // and lifetime tokens, so the former are never encountered during normal parsing.
2708 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2709 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2719 /// parse a single token tree from the input.
2720 crate fn parse_token_tree(&mut self) -> TokenTree {
2722 token::OpenDelim(..) => {
2723 let frame = mem::replace(&mut self.token_cursor.frame,
2724 self.token_cursor.stack.pop().unwrap());
2725 self.span = frame.span;
2727 TokenTree::Delimited(frame.span, Delimited {
2729 tts: frame.tree_cursor.original_stream().into(),
2732 token::CloseDelim(_) | token::Eof => unreachable!(),
2734 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2736 TokenTree::Token(span, token)
2741 // parse a stream of tokens into a list of TokenTree's,
2743 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2744 let mut tts = Vec::new();
2745 while self.token != token::Eof {
2746 tts.push(self.parse_token_tree());
2751 pub fn parse_tokens(&mut self) -> TokenStream {
2752 let mut result = Vec::new();
2755 token::Eof | token::CloseDelim(..) => break,
2756 _ => result.push(self.parse_token_tree().into()),
2759 TokenStream::concat(result)
2762 /// Parse a prefix-unary-operator expr
2763 fn parse_prefix_expr(&mut self,
2764 already_parsed_attrs: Option<ThinVec<Attribute>>)
2765 -> PResult<'a, P<Expr>> {
2766 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2768 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2769 let (hi, ex) = match self.token {
2772 let e = self.parse_prefix_expr(None);
2773 let (span, e) = self.interpolated_or_expr_span(e)?;
2774 (lo.to(span), self.mk_unary(UnOp::Not, e))
2776 // Suggest `!` for bitwise negation when encountering a `~`
2779 let e = self.parse_prefix_expr(None);
2780 let (span, e) = self.interpolated_or_expr_span(e)?;
2781 let span_of_tilde = lo;
2782 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2783 "`~` cannot be used as a unary operator");
2784 err.span_suggestion_short_with_applicability(
2786 "use `!` to perform bitwise negation",
2788 Applicability::MachineApplicable
2791 (lo.to(span), self.mk_unary(UnOp::Not, e))
2793 token::BinOp(token::Minus) => {
2795 let e = self.parse_prefix_expr(None);
2796 let (span, e) = self.interpolated_or_expr_span(e)?;
2797 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2799 token::BinOp(token::Star) => {
2801 let e = self.parse_prefix_expr(None);
2802 let (span, e) = self.interpolated_or_expr_span(e)?;
2803 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2805 token::BinOp(token::And) | token::AndAnd => {
2807 let m = self.parse_mutability();
2808 let e = self.parse_prefix_expr(None);
2809 let (span, e) = self.interpolated_or_expr_span(e)?;
2810 (lo.to(span), ExprKind::AddrOf(m, e))
2812 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2814 let place = self.parse_expr_res(
2815 Restrictions::NO_STRUCT_LITERAL,
2818 let blk = self.parse_block()?;
2819 let span = blk.span;
2820 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2821 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2823 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2825 let e = self.parse_prefix_expr(None);
2826 let (span, e) = self.interpolated_or_expr_span(e)?;
2827 (lo.to(span), ExprKind::Box(e))
2829 token::Ident(..) if self.token.is_ident_named("not") => {
2830 // `not` is just an ordinary identifier in Rust-the-language,
2831 // but as `rustc`-the-compiler, we can issue clever diagnostics
2832 // for confused users who really want to say `!`
2833 let token_cannot_continue_expr = |t: &token::Token| match *t {
2834 // These tokens can start an expression after `!`, but
2835 // can't continue an expression after an ident
2836 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2837 token::Literal(..) | token::Pound => true,
2838 token::Interpolated(ref nt) => match nt.0 {
2839 token::NtIdent(..) | token::NtExpr(..) |
2840 token::NtBlock(..) | token::NtPath(..) => true,
2845 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2846 if cannot_continue_expr {
2848 // Emit the error ...
2849 let mut err = self.diagnostic()
2850 .struct_span_err(self.span,
2851 &format!("unexpected {} after identifier",
2852 self.this_token_descr()));
2853 // span the `not` plus trailing whitespace to avoid
2854 // trailing whitespace after the `!` in our suggestion
2855 let to_replace = self.sess.codemap()
2856 .span_until_non_whitespace(lo.to(self.span));
2857 err.span_suggestion_short_with_applicability(
2859 "use `!` to perform logical negation",
2861 Applicability::MachineApplicable
2864 // —and recover! (just as if we were in the block
2865 // for the `token::Not` arm)
2866 let e = self.parse_prefix_expr(None);
2867 let (span, e) = self.interpolated_or_expr_span(e)?;
2868 (lo.to(span), self.mk_unary(UnOp::Not, e))
2870 return self.parse_dot_or_call_expr(Some(attrs));
2873 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2875 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2878 /// Parse an associative expression
2880 /// This parses an expression accounting for associativity and precedence of the operators in
2882 fn parse_assoc_expr(&mut self,
2883 already_parsed_attrs: Option<ThinVec<Attribute>>)
2884 -> PResult<'a, P<Expr>> {
2885 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2888 /// Parse an associative expression with operators of at least `min_prec` precedence
2889 fn parse_assoc_expr_with(&mut self,
2892 -> PResult<'a, P<Expr>> {
2893 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2896 let attrs = match lhs {
2897 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2900 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2901 return self.parse_prefix_range_expr(attrs);
2903 self.parse_prefix_expr(attrs)?
2907 if self.expr_is_complete(&lhs) {
2908 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2911 self.expected_tokens.push(TokenType::Operator);
2912 while let Some(op) = AssocOp::from_token(&self.token) {
2914 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2915 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2916 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2917 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2918 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2919 (PrevTokenKind::Interpolated, _) => self.prev_span,
2920 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2921 if path.segments.len() == 1 => self.prev_span,
2925 let cur_op_span = self.span;
2926 let restrictions = if op.is_assign_like() {
2927 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2931 if op.precedence() < min_prec {
2934 // Check for deprecated `...` syntax
2935 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2936 self.err_dotdotdot_syntax(self.span);
2940 if op.is_comparison() {
2941 self.check_no_chained_comparison(&lhs, &op);
2944 if op == AssocOp::As {
2945 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2947 } else if op == AssocOp::Colon {
2948 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2951 err.span_label(self.span,
2952 "expecting a type here because of type ascription");
2953 let cm = self.sess.codemap();
2954 let cur_pos = cm.lookup_char_pos(self.span.lo());
2955 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2956 if cur_pos.line != op_pos.line {
2957 err.span_suggestion_with_applicability(
2959 "try using a semicolon",
2961 Applicability::MaybeIncorrect // speculative
2968 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2969 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2970 // generalise it to the Fixity::None code.
2972 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2973 // two variants are handled with `parse_prefix_range_expr` call above.
2974 let rhs = if self.is_at_start_of_range_notation_rhs() {
2975 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2976 LhsExpr::NotYetParsed)?)
2980 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2985 let limits = if op == AssocOp::DotDot {
2986 RangeLimits::HalfOpen
2991 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2992 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2996 let rhs = match op.fixity() {
2997 Fixity::Right => self.with_res(
2998 restrictions - Restrictions::STMT_EXPR,
3000 this.parse_assoc_expr_with(op.precedence(),
3001 LhsExpr::NotYetParsed)
3003 Fixity::Left => self.with_res(
3004 restrictions - Restrictions::STMT_EXPR,
3006 this.parse_assoc_expr_with(op.precedence() + 1,
3007 LhsExpr::NotYetParsed)
3009 // We currently have no non-associative operators that are not handled above by
3010 // the special cases. The code is here only for future convenience.
3011 Fixity::None => self.with_res(
3012 restrictions - Restrictions::STMT_EXPR,
3014 this.parse_assoc_expr_with(op.precedence() + 1,
3015 LhsExpr::NotYetParsed)
3019 let span = lhs_span.to(rhs.span);
3021 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3022 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3023 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3024 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3025 AssocOp::Greater | AssocOp::GreaterEqual => {
3026 let ast_op = op.to_ast_binop().unwrap();
3027 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
3028 self.mk_expr(span, binary, ThinVec::new())
3031 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3032 AssocOp::ObsoleteInPlace =>
3033 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3034 AssocOp::AssignOp(k) => {
3036 token::Plus => BinOpKind::Add,
3037 token::Minus => BinOpKind::Sub,
3038 token::Star => BinOpKind::Mul,
3039 token::Slash => BinOpKind::Div,
3040 token::Percent => BinOpKind::Rem,
3041 token::Caret => BinOpKind::BitXor,
3042 token::And => BinOpKind::BitAnd,
3043 token::Or => BinOpKind::BitOr,
3044 token::Shl => BinOpKind::Shl,
3045 token::Shr => BinOpKind::Shr,
3047 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3048 self.mk_expr(span, aopexpr, ThinVec::new())
3050 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3051 self.bug("AssocOp should have been handled by special case")
3055 if op.fixity() == Fixity::None { break }
3060 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3061 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3062 -> PResult<'a, P<Expr>> {
3063 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3064 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3067 // Save the state of the parser before parsing type normally, in case there is a
3068 // LessThan comparison after this cast.
3069 let parser_snapshot_before_type = self.clone();
3070 match self.parse_ty_no_plus() {
3072 Ok(mk_expr(self, rhs))
3074 Err(mut type_err) => {
3075 // Rewind to before attempting to parse the type with generics, to recover
3076 // from situations like `x as usize < y` in which we first tried to parse
3077 // `usize < y` as a type with generic arguments.
3078 let parser_snapshot_after_type = self.clone();
3079 mem::replace(self, parser_snapshot_before_type);
3081 match self.parse_path(PathStyle::Expr) {
3083 let (op_noun, op_verb) = match self.token {
3084 token::Lt => ("comparison", "comparing"),
3085 token::BinOp(token::Shl) => ("shift", "shifting"),
3087 // We can end up here even without `<` being the next token, for
3088 // example because `parse_ty_no_plus` returns `Err` on keywords,
3089 // but `parse_path` returns `Ok` on them due to error recovery.
3090 // Return original error and parser state.
3091 mem::replace(self, parser_snapshot_after_type);
3092 return Err(type_err);
3096 // Successfully parsed the type path leaving a `<` yet to parse.
3099 // Report non-fatal diagnostics, keep `x as usize` as an expression
3100 // in AST and continue parsing.
3101 let msg = format!("`<` is interpreted as a start of generic \
3102 arguments for `{}`, not a {}", path, op_noun);
3103 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3104 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3105 "interpreted as generic arguments");
3106 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3108 let expr = mk_expr(self, P(Ty {
3110 node: TyKind::Path(None, path),
3111 id: ast::DUMMY_NODE_ID
3114 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3115 .unwrap_or(pprust::expr_to_string(&expr));
3116 err.span_suggestion_with_applicability(
3118 &format!("try {} the cast value", op_verb),
3119 format!("({})", expr_str),
3120 Applicability::MachineApplicable
3126 Err(mut path_err) => {
3127 // Couldn't parse as a path, return original error and parser state.
3129 mem::replace(self, parser_snapshot_after_type);
3137 /// Produce an error if comparison operators are chained (RFC #558).
3138 /// We only need to check lhs, not rhs, because all comparison ops
3139 /// have same precedence and are left-associative
3140 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3141 debug_assert!(outer_op.is_comparison(),
3142 "check_no_chained_comparison: {:?} is not comparison",
3145 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3146 // respan to include both operators
3147 let op_span = op.span.to(self.span);
3148 let mut err = self.diagnostic().struct_span_err(op_span,
3149 "chained comparison operators require parentheses");
3150 if op.node == BinOpKind::Lt &&
3151 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3152 *outer_op == AssocOp::Greater // even in a case like the following:
3153 { // Foo<Bar<Baz<Qux, ()>>>
3155 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3156 err.help("or use `(...)` if you meant to specify fn arguments");
3164 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3165 fn parse_prefix_range_expr(&mut self,
3166 already_parsed_attrs: Option<ThinVec<Attribute>>)
3167 -> PResult<'a, P<Expr>> {
3168 // Check for deprecated `...` syntax
3169 if self.token == token::DotDotDot {
3170 self.err_dotdotdot_syntax(self.span);
3173 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3174 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3176 let tok = self.token.clone();
3177 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3179 let mut hi = self.span;
3181 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3182 // RHS must be parsed with more associativity than the dots.
3183 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3184 Some(self.parse_assoc_expr_with(next_prec,
3185 LhsExpr::NotYetParsed)
3193 let limits = if tok == token::DotDot {
3194 RangeLimits::HalfOpen
3199 let r = try!(self.mk_range(None,
3202 Ok(self.mk_expr(lo.to(hi), r, attrs))
3205 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3206 if self.token.can_begin_expr() {
3207 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3208 if self.token == token::OpenDelim(token::Brace) {
3209 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3217 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3218 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3219 if self.check_keyword(keywords::Let) {
3220 return self.parse_if_let_expr(attrs);
3222 let lo = self.prev_span;
3223 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3225 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3226 // verify that the last statement is either an implicit return (no `;`) or an explicit
3227 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3228 // the dead code lint.
3229 if self.eat_keyword(keywords::Else) || !cond.returns() {
3230 let sp = self.sess.codemap().next_point(lo);
3231 let mut err = self.diagnostic()
3232 .struct_span_err(sp, "missing condition for `if` statemement");
3233 err.span_label(sp, "expected if condition here");
3236 let not_block = self.token != token::OpenDelim(token::Brace);
3237 let thn = self.parse_block().map_err(|mut err| {
3239 err.span_label(lo, "this `if` statement has a condition, but no block");
3243 let mut els: Option<P<Expr>> = None;
3244 let mut hi = thn.span;
3245 if self.eat_keyword(keywords::Else) {
3246 let elexpr = self.parse_else_expr()?;
3250 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3253 /// Parse an 'if let' expression ('if' token already eaten)
3254 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3255 -> PResult<'a, P<Expr>> {
3256 let lo = self.prev_span;
3257 self.expect_keyword(keywords::Let)?;
3258 let pats = self.parse_pats()?;
3259 self.expect(&token::Eq)?;
3260 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3261 let thn = self.parse_block()?;
3262 let (hi, els) = if self.eat_keyword(keywords::Else) {
3263 let expr = self.parse_else_expr()?;
3264 (expr.span, Some(expr))
3268 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3271 // `move |args| expr`
3272 fn parse_lambda_expr(&mut self,
3273 attrs: ThinVec<Attribute>)
3274 -> PResult<'a, P<Expr>>
3277 let movability = if self.eat_keyword(keywords::Static) {
3282 let asyncness = if self.span.edition() >= Edition::Edition2018
3283 && self.eat_keyword(keywords::Async)
3285 IsAsync::Async(ast::DUMMY_NODE_ID)
3289 let capture_clause = if self.eat_keyword(keywords::Move) {
3294 let decl = self.parse_fn_block_decl()?;
3295 let decl_hi = self.prev_span;
3296 let body = match decl.output {
3297 FunctionRetTy::Default(_) => {
3298 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3299 self.parse_expr_res(restrictions, None)?
3302 // If an explicit return type is given, require a
3303 // block to appear (RFC 968).
3304 let body_lo = self.span;
3305 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3311 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3315 // `else` token already eaten
3316 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3317 if self.eat_keyword(keywords::If) {
3318 return self.parse_if_expr(ThinVec::new());
3320 let blk = self.parse_block()?;
3321 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3325 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3326 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3328 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3329 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3331 let pat = self.parse_top_level_pat()?;
3332 if !self.eat_keyword(keywords::In) {
3333 let in_span = self.prev_span.between(self.span);
3334 let mut err = self.sess.span_diagnostic
3335 .struct_span_err(in_span, "missing `in` in `for` loop");
3336 err.span_suggestion_short_with_applicability(
3337 in_span, "try adding `in` here", " in ".into(),
3338 // has been misleading, at least in the past (closed Issue #48492)
3339 Applicability::MaybeIncorrect
3343 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3344 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3345 attrs.extend(iattrs);
3347 let hi = self.prev_span;
3348 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3351 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3352 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3354 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3355 if self.token.is_keyword(keywords::Let) {
3356 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3358 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3359 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3360 attrs.extend(iattrs);
3361 let span = span_lo.to(body.span);
3362 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3365 /// Parse a 'while let' expression ('while' token already eaten)
3366 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3368 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3369 self.expect_keyword(keywords::Let)?;
3370 let pats = self.parse_pats()?;
3371 self.expect(&token::Eq)?;
3372 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3373 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3374 attrs.extend(iattrs);
3375 let span = span_lo.to(body.span);
3376 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3379 // parse `loop {...}`, `loop` token already eaten
3380 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3382 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3383 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3384 attrs.extend(iattrs);
3385 let span = span_lo.to(body.span);
3386 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3389 /// Parse an `async move {...}` expression
3390 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3391 -> PResult<'a, P<Expr>>
3393 let span_lo = self.span;
3394 self.expect_keyword(keywords::Async)?;
3395 let capture_clause = if self.eat_keyword(keywords::Move) {
3400 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3401 attrs.extend(iattrs);
3403 span_lo.to(body.span),
3404 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3407 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3408 fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3409 -> PResult<'a, P<Expr>>
3411 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3412 attrs.extend(iattrs);
3413 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3416 // `match` token already eaten
3417 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3418 let match_span = self.prev_span;
3419 let lo = self.prev_span;
3420 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3422 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3423 if self.token == token::Token::Semi {
3424 e.span_suggestion_short_with_applicability(
3426 "try removing this `match`",
3428 Applicability::MaybeIncorrect // speculative
3433 attrs.extend(self.parse_inner_attributes()?);
3435 let mut arms: Vec<Arm> = Vec::new();
3436 while self.token != token::CloseDelim(token::Brace) {
3437 match self.parse_arm() {
3438 Ok(arm) => arms.push(arm),
3440 // Recover by skipping to the end of the block.
3442 self.recover_stmt();
3443 let span = lo.to(self.span);
3444 if self.token == token::CloseDelim(token::Brace) {
3447 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3453 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3456 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3457 maybe_whole!(self, NtArm, |x| x);
3459 let attrs = self.parse_outer_attributes()?;
3460 // Allow a '|' before the pats (RFC 1925)
3461 self.eat(&token::BinOp(token::Or));
3462 let pats = self.parse_pats()?;
3463 let guard = if self.eat_keyword(keywords::If) {
3464 Some(self.parse_expr()?)
3468 let arrow_span = self.span;
3469 self.expect(&token::FatArrow)?;
3470 let arm_start_span = self.span;
3472 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3473 .map_err(|mut err| {
3474 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3478 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3479 && self.token != token::CloseDelim(token::Brace);
3482 let cm = self.sess.codemap();
3483 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3484 .map_err(|mut err| {
3485 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3486 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3487 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3488 && expr_lines.lines.len() == 2
3489 && self.token == token::FatArrow => {
3490 // We check wether there's any trailing code in the parse span, if there
3491 // isn't, we very likely have the following:
3494 // | -- - missing comma
3500 // | parsed until here as `"y" & X`
3501 err.span_suggestion_short_with_applicability(
3502 cm.next_point(arm_start_span),
3503 "missing a comma here to end this `match` arm",
3505 Applicability::MachineApplicable
3509 err.span_label(arrow_span,
3510 "while parsing the `match` arm starting here");
3516 self.eat(&token::Comma);
3527 /// Parse an expression
3528 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3529 self.parse_expr_res(Restrictions::empty(), None)
3532 /// Evaluate the closure with restrictions in place.
3534 /// After the closure is evaluated, restrictions are reset.
3535 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3536 where F: FnOnce(&mut Self) -> T
3538 let old = self.restrictions;
3539 self.restrictions = r;
3541 self.restrictions = old;
3546 /// Parse an expression, subject to the given restrictions
3547 fn parse_expr_res(&mut self, r: Restrictions,
3548 already_parsed_attrs: Option<ThinVec<Attribute>>)
3549 -> PResult<'a, P<Expr>> {
3550 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3553 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3554 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3555 if self.check(&token::Eq) {
3557 Ok(Some(self.parse_expr()?))
3559 Ok(Some(self.parse_expr()?))
3565 /// Parse patterns, separated by '|' s
3566 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3567 let mut pats = Vec::new();
3569 pats.push(self.parse_top_level_pat()?);
3571 if self.token == token::OrOr {
3572 let mut err = self.struct_span_err(self.span,
3573 "unexpected token `||` after pattern");
3574 err.span_suggestion_with_applicability(
3576 "use a single `|` to specify multiple patterns",
3578 Applicability::MachineApplicable
3582 } else if self.check(&token::BinOp(token::Or)) {
3590 // Parses a parenthesized list of patterns like
3591 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3592 // - a vector of the patterns that were parsed
3593 // - an option indicating the index of the `..` element
3594 // - a boolean indicating whether a trailing comma was present.
3595 // Trailing commas are significant because (p) and (p,) are different patterns.
3596 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3597 self.expect(&token::OpenDelim(token::Paren))?;
3598 let result = self.parse_pat_list()?;
3599 self.expect(&token::CloseDelim(token::Paren))?;
3603 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3604 let mut fields = Vec::new();
3605 let mut ddpos = None;
3606 let mut trailing_comma = false;
3608 if self.eat(&token::DotDot) {
3609 if ddpos.is_none() {
3610 ddpos = Some(fields.len());
3612 // Emit a friendly error, ignore `..` and continue parsing
3613 self.span_err(self.prev_span,
3614 "`..` can only be used once per tuple or tuple struct pattern");
3616 } else if !self.check(&token::CloseDelim(token::Paren)) {
3617 fields.push(self.parse_pat()?);
3622 trailing_comma = self.eat(&token::Comma);
3623 if !trailing_comma {
3628 if ddpos == Some(fields.len()) && trailing_comma {
3629 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3630 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3633 Ok((fields, ddpos, trailing_comma))
3636 fn parse_pat_vec_elements(
3638 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3639 let mut before = Vec::new();
3640 let mut slice = None;
3641 let mut after = Vec::new();
3642 let mut first = true;
3643 let mut before_slice = true;
3645 while self.token != token::CloseDelim(token::Bracket) {
3649 self.expect(&token::Comma)?;
3651 if self.token == token::CloseDelim(token::Bracket)
3652 && (before_slice || !after.is_empty()) {
3658 if self.eat(&token::DotDot) {
3660 if self.check(&token::Comma) ||
3661 self.check(&token::CloseDelim(token::Bracket)) {
3662 slice = Some(P(Pat {
3663 id: ast::DUMMY_NODE_ID,
3664 node: PatKind::Wild,
3665 span: self.prev_span,
3667 before_slice = false;
3673 let subpat = self.parse_pat()?;
3674 if before_slice && self.eat(&token::DotDot) {
3675 slice = Some(subpat);
3676 before_slice = false;
3677 } else if before_slice {
3678 before.push(subpat);
3684 Ok((before, slice, after))
3690 attrs: Vec<Attribute>
3691 ) -> PResult<'a, codemap::Spanned<ast::FieldPat>> {
3692 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3694 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3695 // Parsing a pattern of the form "fieldname: pat"
3696 let fieldname = self.parse_field_name()?;
3698 let pat = self.parse_pat()?;
3700 (pat, fieldname, false)
3702 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3703 let is_box = self.eat_keyword(keywords::Box);
3704 let boxed_span = self.span;
3705 let is_ref = self.eat_keyword(keywords::Ref);
3706 let is_mut = self.eat_keyword(keywords::Mut);
3707 let fieldname = self.parse_ident()?;
3708 hi = self.prev_span;
3710 let bind_type = match (is_ref, is_mut) {
3711 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3712 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3713 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3714 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3716 let fieldpat = P(Pat {
3717 id: ast::DUMMY_NODE_ID,
3718 node: PatKind::Ident(bind_type, fieldname, None),
3719 span: boxed_span.to(hi),
3722 let subpat = if is_box {
3724 id: ast::DUMMY_NODE_ID,
3725 node: PatKind::Box(fieldpat),
3731 (subpat, fieldname, true)
3734 Ok(codemap::Spanned {
3736 node: ast::FieldPat {
3740 attrs: attrs.into(),
3745 /// Parse the fields of a struct-like pattern
3746 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3747 let mut fields = Vec::new();
3748 let mut etc = false;
3749 let mut ate_comma = true;
3750 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3751 let mut etc_span = None;
3753 while self.token != token::CloseDelim(token::Brace) {
3754 let attrs = self.parse_outer_attributes()?;
3757 // check that a comma comes after every field
3759 let err = self.struct_span_err(self.prev_span, "expected `,`");
3764 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3766 let mut etc_sp = self.span;
3768 if self.token == token::DotDotDot { // Issue #46718
3769 // Accept `...` as if it were `..` to avoid further errors
3770 let mut err = self.struct_span_err(self.span,
3771 "expected field pattern, found `...`");
3772 err.span_suggestion_with_applicability(
3774 "to omit remaining fields, use one fewer `.`",
3776 Applicability::MachineApplicable
3780 self.bump(); // `..` || `...`:w
3782 if self.token == token::CloseDelim(token::Brace) {
3783 etc_span = Some(etc_sp);
3786 let token_str = self.this_token_to_string();
3787 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3789 err.span_label(self.span, "expected `}`");
3790 let mut comma_sp = None;
3791 if self.token == token::Comma { // Issue #49257
3792 etc_sp = etc_sp.to(self.sess.codemap().span_until_non_whitespace(self.span));
3793 err.span_label(etc_sp,
3794 "`..` must be at the end and cannot have a trailing comma");
3795 comma_sp = Some(self.span);
3800 etc_span = Some(etc_sp);
3801 if self.token == token::CloseDelim(token::Brace) {
3802 // If the struct looks otherwise well formed, recover and continue.
3803 if let Some(sp) = comma_sp {
3804 err.span_suggestion_short(sp, "remove this comma", "".into());
3808 } else if self.token.is_ident() && ate_comma {
3809 // Accept fields coming after `..,`.
3810 // This way we avoid "pattern missing fields" errors afterwards.
3811 // We delay this error until the end in order to have a span for a
3813 if let Some(mut delayed_err) = delayed_err {
3817 delayed_err = Some(err);
3820 if let Some(mut err) = delayed_err {
3827 fields.push(match self.parse_pat_field(lo, attrs) {
3830 if let Some(mut delayed_err) = delayed_err {
3836 ate_comma = self.eat(&token::Comma);
3839 if let Some(mut err) = delayed_err {
3840 if let Some(etc_span) = etc_span {
3841 err.multipart_suggestion(
3842 "move the `..` to the end of the field list",
3844 (etc_span, "".into()),
3845 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3851 return Ok((fields, etc));
3854 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3855 if self.token.is_path_start() {
3857 let (qself, path) = if self.eat_lt() {
3858 // Parse a qualified path
3859 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3862 // Parse an unqualified path
3863 (None, self.parse_path(PathStyle::Expr)?)
3865 let hi = self.prev_span;
3866 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3868 self.parse_literal_maybe_minus()
3872 // helper function to decide whether to parse as ident binding or to try to do
3873 // something more complex like range patterns
3874 fn parse_as_ident(&mut self) -> bool {
3875 self.look_ahead(1, |t| match *t {
3876 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3877 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3878 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3879 // range pattern branch
3880 token::DotDot => None,
3882 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3883 token::Comma | token::CloseDelim(token::Bracket) => true,
3888 /// A wrapper around `parse_pat` with some special error handling for the
3889 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contast
3890 /// to subpatterns within such).
3891 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3892 let pat = self.parse_pat()?;
3893 if self.token == token::Comma {
3894 // An unexpected comma after a top-level pattern is a clue that the
3895 // user (perhaps more accustomed to some other language) forgot the
3896 // parentheses in what should have been a tuple pattern; return a
3897 // suggestion-enhanced error here rather than choking on the comma
3899 let comma_span = self.span;
3901 if let Err(mut err) = self.parse_pat_list() {
3902 // We didn't expect this to work anyway; we just wanted
3903 // to advance to the end of the comma-sequence so we know
3904 // the span to suggest parenthesizing
3907 let seq_span = pat.span.to(self.prev_span);
3908 let mut err = self.struct_span_err(comma_span,
3909 "unexpected `,` in pattern");
3910 if let Ok(seq_snippet) = self.sess.codemap().span_to_snippet(seq_span) {
3911 err.span_suggestion_with_applicability(
3913 "try adding parentheses",
3914 format!("({})", seq_snippet),
3915 Applicability::MachineApplicable
3923 /// Parse a pattern.
3924 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3925 self.parse_pat_with_range_pat(true)
3928 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3930 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3931 maybe_whole!(self, NtPat, |x| x);
3936 token::BinOp(token::And) | token::AndAnd => {
3937 // Parse &pat / &mut pat
3939 let mutbl = self.parse_mutability();
3940 if let token::Lifetime(ident) = self.token {
3941 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3943 err.span_label(self.span, "unexpected lifetime");
3946 let subpat = self.parse_pat_with_range_pat(false)?;
3947 pat = PatKind::Ref(subpat, mutbl);
3949 token::OpenDelim(token::Paren) => {
3950 // Parse (pat,pat,pat,...) as tuple pattern
3951 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3952 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3953 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3955 PatKind::Tuple(fields, ddpos)
3958 token::OpenDelim(token::Bracket) => {
3959 // Parse [pat,pat,...] as slice pattern
3961 let (before, slice, after) = self.parse_pat_vec_elements()?;
3962 self.expect(&token::CloseDelim(token::Bracket))?;
3963 pat = PatKind::Slice(before, slice, after);
3965 // At this point, token != &, &&, (, [
3966 _ => if self.eat_keyword(keywords::Underscore) {
3968 pat = PatKind::Wild;
3969 } else if self.eat_keyword(keywords::Mut) {
3970 // Parse mut ident @ pat / mut ref ident @ pat
3971 let mutref_span = self.prev_span.to(self.span);
3972 let binding_mode = if self.eat_keyword(keywords::Ref) {
3974 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3975 .span_suggestion_with_applicability(
3977 "try switching the order",
3979 Applicability::MachineApplicable
3981 BindingMode::ByRef(Mutability::Mutable)
3983 BindingMode::ByValue(Mutability::Mutable)
3985 pat = self.parse_pat_ident(binding_mode)?;
3986 } else if self.eat_keyword(keywords::Ref) {
3987 // Parse ref ident @ pat / ref mut ident @ pat
3988 let mutbl = self.parse_mutability();
3989 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3990 } else if self.eat_keyword(keywords::Box) {
3992 let subpat = self.parse_pat_with_range_pat(false)?;
3993 pat = PatKind::Box(subpat);
3994 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3995 self.parse_as_ident() {
3996 // Parse ident @ pat
3997 // This can give false positives and parse nullary enums,
3998 // they are dealt with later in resolve
3999 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4000 pat = self.parse_pat_ident(binding_mode)?;
4001 } else if self.token.is_path_start() {
4002 // Parse pattern starting with a path
4003 let (qself, path) = if self.eat_lt() {
4004 // Parse a qualified path
4005 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4008 // Parse an unqualified path
4009 (None, self.parse_path(PathStyle::Expr)?)
4012 token::Not if qself.is_none() => {
4013 // Parse macro invocation
4015 let (delim, tts) = self.expect_delimited_token_tree()?;
4016 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4017 pat = PatKind::Mac(mac);
4019 token::DotDotDot | token::DotDotEq | token::DotDot => {
4020 let end_kind = match self.token {
4021 token::DotDot => RangeEnd::Excluded,
4022 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4023 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4024 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4027 let op_span = self.span;
4029 let span = lo.to(self.prev_span);
4030 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4032 let end = self.parse_pat_range_end()?;
4033 let op = Spanned { span: op_span, node: end_kind };
4034 pat = PatKind::Range(begin, end, op);
4036 token::OpenDelim(token::Brace) => {
4037 if qself.is_some() {
4038 let msg = "unexpected `{` after qualified path";
4039 let mut err = self.fatal(msg);
4040 err.span_label(self.span, msg);
4043 // Parse struct pattern
4045 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4047 self.recover_stmt();
4051 pat = PatKind::Struct(path, fields, etc);
4053 token::OpenDelim(token::Paren) => {
4054 if qself.is_some() {
4055 let msg = "unexpected `(` after qualified path";
4056 let mut err = self.fatal(msg);
4057 err.span_label(self.span, msg);
4060 // Parse tuple struct or enum pattern
4061 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4062 pat = PatKind::TupleStruct(path, fields, ddpos)
4064 _ => pat = PatKind::Path(qself, path),
4067 // Try to parse everything else as literal with optional minus
4068 match self.parse_literal_maybe_minus() {
4070 let op_span = self.span;
4071 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4072 self.check(&token::DotDotDot) {
4073 let end_kind = if self.eat(&token::DotDotDot) {
4074 RangeEnd::Included(RangeSyntax::DotDotDot)
4075 } else if self.eat(&token::DotDotEq) {
4076 RangeEnd::Included(RangeSyntax::DotDotEq)
4077 } else if self.eat(&token::DotDot) {
4080 panic!("impossible case: we already matched \
4081 on a range-operator token")
4083 let end = self.parse_pat_range_end()?;
4084 let op = Spanned { span: op_span, node: end_kind };
4085 pat = PatKind::Range(begin, end, op);
4087 pat = PatKind::Lit(begin);
4091 self.cancel(&mut err);
4092 let msg = format!("expected pattern, found {}", self.this_token_descr());
4093 let mut err = self.fatal(&msg);
4094 err.span_label(self.span, "expected pattern");
4101 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4102 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4104 if !allow_range_pat {
4107 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4109 PatKind::Range(..) => {
4110 let mut err = self.struct_span_err(
4112 "the range pattern here has ambiguous interpretation",
4114 err.span_suggestion_with_applicability(
4116 "add parentheses to clarify the precedence",
4117 format!("({})", pprust::pat_to_string(&pat)),
4118 // "ambiguous interpretation" implies that we have to be guessing
4119 Applicability::MaybeIncorrect
4130 /// Parse ident or ident @ pat
4131 /// used by the copy foo and ref foo patterns to give a good
4132 /// error message when parsing mistakes like ref foo(a,b)
4133 fn parse_pat_ident(&mut self,
4134 binding_mode: ast::BindingMode)
4135 -> PResult<'a, PatKind> {
4136 let ident = self.parse_ident()?;
4137 let sub = if self.eat(&token::At) {
4138 Some(self.parse_pat()?)
4143 // just to be friendly, if they write something like
4145 // we end up here with ( as the current token. This shortly
4146 // leads to a parse error. Note that if there is no explicit
4147 // binding mode then we do not end up here, because the lookahead
4148 // will direct us over to parse_enum_variant()
4149 if self.token == token::OpenDelim(token::Paren) {
4150 return Err(self.span_fatal(
4152 "expected identifier, found enum pattern"))
4155 Ok(PatKind::Ident(binding_mode, ident, sub))
4158 /// Parse a local variable declaration
4159 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4160 let lo = self.prev_span;
4161 let pat = self.parse_top_level_pat()?;
4163 let (err, ty) = if self.eat(&token::Colon) {
4164 // Save the state of the parser before parsing type normally, in case there is a `:`
4165 // instead of an `=` typo.
4166 let parser_snapshot_before_type = self.clone();
4167 let colon_sp = self.prev_span;
4168 match self.parse_ty() {
4169 Ok(ty) => (None, Some(ty)),
4171 // Rewind to before attempting to parse the type and continue parsing
4172 let parser_snapshot_after_type = self.clone();
4173 mem::replace(self, parser_snapshot_before_type);
4175 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
4176 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4177 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4183 let init = match (self.parse_initializer(err.is_some()), err) {
4184 (Ok(init), None) => { // init parsed, ty parsed
4187 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4188 // Could parse the type as if it were the initializer, it is likely there was a
4189 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4190 err.span_suggestion_short_with_applicability(
4192 "use `=` if you meant to assign",
4194 Applicability::MachineApplicable
4197 // As this was parsed successfully, continue as if the code has been fixed for the
4198 // rest of the file. It will still fail due to the emitted error, but we avoid
4202 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4204 // Couldn't parse the type nor the initializer, only raise the type error and
4205 // return to the parser state before parsing the type as the initializer.
4206 // let x: <parse_error>;
4207 mem::replace(self, snapshot);
4210 (Err(err), None) => { // init error, ty parsed
4211 // Couldn't parse the initializer and we're not attempting to recover a failed
4212 // parse of the type, return the error.
4216 let hi = if self.token == token::Semi {
4225 id: ast::DUMMY_NODE_ID,
4231 /// Parse a structure field
4232 fn parse_name_and_ty(&mut self,
4235 attrs: Vec<Attribute>)
4236 -> PResult<'a, StructField> {
4237 let name = self.parse_ident()?;
4238 self.expect(&token::Colon)?;
4239 let ty = self.parse_ty()?;
4241 span: lo.to(self.prev_span),
4244 id: ast::DUMMY_NODE_ID,
4250 /// Emit an expected item after attributes error.
4251 fn expected_item_err(&self, attrs: &[Attribute]) {
4252 let message = match attrs.last() {
4253 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4254 _ => "expected item after attributes",
4257 self.span_err(self.prev_span, message);
4260 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4261 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4262 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4263 Ok(self.parse_stmt_(true))
4266 // Eat tokens until we can be relatively sure we reached the end of the
4267 // statement. This is something of a best-effort heuristic.
4269 // We terminate when we find an unmatched `}` (without consuming it).
4270 fn recover_stmt(&mut self) {
4271 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4274 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4275 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4276 // approximate - it can mean we break too early due to macros, but that
4277 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4279 // If `break_on_block` is `Break`, then we will stop consuming tokens
4280 // after finding (and consuming) a brace-delimited block.
4281 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4282 let mut brace_depth = 0;
4283 let mut bracket_depth = 0;
4284 let mut in_block = false;
4285 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4286 break_on_semi, break_on_block);
4288 debug!("recover_stmt_ loop {:?}", self.token);
4290 token::OpenDelim(token::DelimToken::Brace) => {
4293 if break_on_block == BlockMode::Break &&
4295 bracket_depth == 0 {
4299 token::OpenDelim(token::DelimToken::Bracket) => {
4303 token::CloseDelim(token::DelimToken::Brace) => {
4304 if brace_depth == 0 {
4305 debug!("recover_stmt_ return - close delim {:?}", self.token);
4310 if in_block && bracket_depth == 0 && brace_depth == 0 {
4311 debug!("recover_stmt_ return - block end {:?}", self.token);
4315 token::CloseDelim(token::DelimToken::Bracket) => {
4317 if bracket_depth < 0 {
4323 debug!("recover_stmt_ return - Eof");
4328 if break_on_semi == SemiColonMode::Break &&
4330 bracket_depth == 0 {
4331 debug!("recover_stmt_ return - Semi");
4342 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4343 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4345 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4350 fn is_async_block(&mut self) -> bool {
4351 self.token.is_keyword(keywords::Async) &&
4354 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4355 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4357 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4362 fn is_catch_expr(&mut self) -> bool {
4363 self.token.is_keyword(keywords::Do) &&
4364 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4365 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4367 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4368 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4371 fn is_union_item(&self) -> bool {
4372 self.token.is_keyword(keywords::Union) &&
4373 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4376 fn is_crate_vis(&self) -> bool {
4377 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4380 fn is_extern_non_path(&self) -> bool {
4381 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4384 fn is_auto_trait_item(&mut self) -> bool {
4386 (self.token.is_keyword(keywords::Auto)
4387 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4388 || // unsafe auto trait
4389 (self.token.is_keyword(keywords::Unsafe) &&
4390 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4391 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4394 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4395 -> PResult<'a, Option<P<Item>>> {
4396 let token_lo = self.span;
4397 let (ident, def) = match self.token {
4398 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4400 let ident = self.parse_ident()?;
4401 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4402 match self.parse_token_tree() {
4403 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4404 _ => unreachable!(),
4406 } else if self.check(&token::OpenDelim(token::Paren)) {
4407 let args = self.parse_token_tree();
4408 let body = if self.check(&token::OpenDelim(token::Brace)) {
4409 self.parse_token_tree()
4414 TokenStream::concat(vec![
4416 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4424 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4426 token::Ident(ident, _) if ident.name == "macro_rules" &&
4427 self.look_ahead(1, |t| *t == token::Not) => {
4428 let prev_span = self.prev_span;
4429 self.complain_if_pub_macro(&vis.node, prev_span);
4433 let ident = self.parse_ident()?;
4434 let (delim, tokens) = self.expect_delimited_token_tree()?;
4435 if delim != MacDelimiter::Brace {
4436 if !self.eat(&token::Semi) {
4437 let msg = "macros that expand to items must either \
4438 be surrounded with braces or followed by a semicolon";
4439 self.span_err(self.prev_span, msg);
4443 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4445 _ => return Ok(None),
4448 let span = lo.to(self.prev_span);
4449 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4452 fn parse_stmt_without_recovery(&mut self,
4453 macro_legacy_warnings: bool)
4454 -> PResult<'a, Option<Stmt>> {
4455 maybe_whole!(self, NtStmt, |x| Some(x));
4457 let attrs = self.parse_outer_attributes()?;
4460 Ok(Some(if self.eat_keyword(keywords::Let) {
4462 id: ast::DUMMY_NODE_ID,
4463 node: StmtKind::Local(self.parse_local(attrs.into())?),
4464 span: lo.to(self.prev_span),
4466 } else if let Some(macro_def) = self.eat_macro_def(
4468 &codemap::respan(lo, VisibilityKind::Inherited),
4472 id: ast::DUMMY_NODE_ID,
4473 node: StmtKind::Item(macro_def),
4474 span: lo.to(self.prev_span),
4476 // Starts like a simple path, being careful to avoid contextual keywords
4477 // such as a union items, item with `crate` visibility or auto trait items.
4478 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4479 // like a path (1 token), but it fact not a path.
4480 // `union::b::c` - path, `union U { ... }` - not a path.
4481 // `crate::b::c` - path, `crate struct S;` - not a path.
4482 // `extern::b::c` - path, `extern crate c;` - not a path.
4483 } else if self.token.is_path_start() &&
4484 !self.token.is_qpath_start() &&
4485 !self.is_union_item() &&
4486 !self.is_crate_vis() &&
4487 !self.is_extern_non_path() &&
4488 !self.is_auto_trait_item() {
4489 let pth = self.parse_path(PathStyle::Expr)?;
4491 if !self.eat(&token::Not) {
4492 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4493 self.parse_struct_expr(lo, pth, ThinVec::new())?
4495 let hi = self.prev_span;
4496 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4499 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4500 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4501 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4504 return Ok(Some(Stmt {
4505 id: ast::DUMMY_NODE_ID,
4506 node: StmtKind::Expr(expr),
4507 span: lo.to(self.prev_span),
4511 // it's a macro invocation
4512 let id = match self.token {
4513 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4514 _ => self.parse_ident()?,
4517 // check that we're pointing at delimiters (need to check
4518 // again after the `if`, because of `parse_ident`
4519 // consuming more tokens).
4521 token::OpenDelim(_) => {}
4523 // we only expect an ident if we didn't parse one
4525 let ident_str = if id.name == keywords::Invalid.name() {
4530 let tok_str = self.this_token_to_string();
4531 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4534 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4539 let (delim, tts) = self.expect_delimited_token_tree()?;
4540 let hi = self.prev_span;
4542 let style = if delim == MacDelimiter::Brace {
4543 MacStmtStyle::Braces
4545 MacStmtStyle::NoBraces
4548 if id.name == keywords::Invalid.name() {
4549 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4550 let node = if delim == MacDelimiter::Brace ||
4551 self.token == token::Semi || self.token == token::Eof {
4552 StmtKind::Mac(P((mac, style, attrs.into())))
4554 // We used to incorrectly stop parsing macro-expanded statements here.
4555 // If the next token will be an error anyway but could have parsed with the
4556 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4557 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4558 // These can continue an expression, so we can't stop parsing and warn.
4559 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4560 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4561 token::BinOp(token::And) | token::BinOp(token::Or) |
4562 token::AndAnd | token::OrOr |
4563 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4566 self.warn_missing_semicolon();
4567 StmtKind::Mac(P((mac, style, attrs.into())))
4569 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4570 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4571 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4575 id: ast::DUMMY_NODE_ID,
4580 // if it has a special ident, it's definitely an item
4582 // Require a semicolon or braces.
4583 if style != MacStmtStyle::Braces {
4584 if !self.eat(&token::Semi) {
4585 self.span_err(self.prev_span,
4586 "macros that expand to items must \
4587 either be surrounded with braces or \
4588 followed by a semicolon");
4591 let span = lo.to(hi);
4593 id: ast::DUMMY_NODE_ID,
4595 node: StmtKind::Item({
4597 span, id /*id is good here*/,
4598 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4599 respan(lo, VisibilityKind::Inherited),
4605 // FIXME: Bad copy of attrs
4606 let old_directory_ownership =
4607 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4608 let item = self.parse_item_(attrs.clone(), false, true)?;
4609 self.directory.ownership = old_directory_ownership;
4613 id: ast::DUMMY_NODE_ID,
4614 span: lo.to(i.span),
4615 node: StmtKind::Item(i),
4618 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4619 if !attrs.is_empty() {
4620 if s.prev_token_kind == PrevTokenKind::DocComment {
4621 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4622 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4623 s.span_err(s.span, "expected statement after outer attribute");
4628 // Do not attempt to parse an expression if we're done here.
4629 if self.token == token::Semi {
4630 unused_attrs(&attrs, self);
4635 if self.token == token::CloseDelim(token::Brace) {
4636 unused_attrs(&attrs, self);
4640 // Remainder are line-expr stmts.
4641 let e = self.parse_expr_res(
4642 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4644 id: ast::DUMMY_NODE_ID,
4645 span: lo.to(e.span),
4646 node: StmtKind::Expr(e),
4653 /// Is this expression a successfully-parsed statement?
4654 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4655 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4656 !classify::expr_requires_semi_to_be_stmt(e)
4659 /// Parse a block. No inner attrs are allowed.
4660 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4661 maybe_whole!(self, NtBlock, |x| x);
4665 if !self.eat(&token::OpenDelim(token::Brace)) {
4667 let tok = self.this_token_to_string();
4668 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4670 // Check to see if the user has written something like
4675 // Which is valid in other languages, but not Rust.
4676 match self.parse_stmt_without_recovery(false) {
4678 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) {
4679 // if the next token is an open brace (e.g., `if a b {`), the place-
4680 // inside-a-block suggestion would be more likely wrong than right
4683 let mut stmt_span = stmt.span;
4684 // expand the span to include the semicolon, if it exists
4685 if self.eat(&token::Semi) {
4686 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4688 let sugg = pprust::to_string(|s| {
4689 use print::pprust::{PrintState, INDENT_UNIT};
4690 s.ibox(INDENT_UNIT)?;
4692 s.print_stmt(&stmt)?;
4693 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4695 e.span_suggestion_with_applicability(
4697 "try placing this code inside a block",
4699 // speculative, has been misleading in the past (closed Issue #46836)
4700 Applicability::MaybeIncorrect
4704 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4705 self.cancel(&mut e);
4712 self.parse_block_tail(lo, BlockCheckMode::Default)
4715 /// Parse a block. Inner attrs are allowed.
4716 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4717 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4720 self.expect(&token::OpenDelim(token::Brace))?;
4721 Ok((self.parse_inner_attributes()?,
4722 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4725 /// Parse the rest of a block expression or function body
4726 /// Precondition: already parsed the '{'.
4727 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4728 let mut stmts = vec![];
4729 let mut recovered = false;
4731 while !self.eat(&token::CloseDelim(token::Brace)) {
4732 let stmt = match self.parse_full_stmt(false) {
4735 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4736 self.eat(&token::CloseDelim(token::Brace));
4742 if let Some(stmt) = stmt {
4744 } else if self.token == token::Eof {
4747 // Found only `;` or `}`.
4753 id: ast::DUMMY_NODE_ID,
4755 span: lo.to(self.prev_span),
4760 /// Parse a statement, including the trailing semicolon.
4761 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4762 // skip looking for a trailing semicolon when we have an interpolated statement
4763 maybe_whole!(self, NtStmt, |x| Some(x));
4765 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4767 None => return Ok(None),
4771 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4772 // expression without semicolon
4773 if classify::expr_requires_semi_to_be_stmt(expr) {
4774 // Just check for errors and recover; do not eat semicolon yet.
4776 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4779 self.recover_stmt();
4783 StmtKind::Local(..) => {
4784 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4785 if macro_legacy_warnings && self.token != token::Semi {
4786 self.warn_missing_semicolon();
4788 self.expect_one_of(&[], &[token::Semi])?;
4794 if self.eat(&token::Semi) {
4795 stmt = stmt.add_trailing_semicolon();
4798 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4802 fn warn_missing_semicolon(&self) {
4803 self.diagnostic().struct_span_warn(self.span, {
4804 &format!("expected `;`, found `{}`", self.this_token_to_string())
4806 "This was erroneously allowed and will become a hard error in a future release"
4810 fn err_dotdotdot_syntax(&self, span: Span) {
4811 self.diagnostic().struct_span_err(span, {
4812 "unexpected token: `...`"
4813 }).span_suggestion_with_applicability(
4814 span, "use `..` for an exclusive range", "..".to_owned(),
4815 Applicability::MaybeIncorrect
4816 ).span_suggestion_with_applicability(
4817 span, "or `..=` for an inclusive range", "..=".to_owned(),
4818 Applicability::MaybeIncorrect
4822 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4823 // BOUND = TY_BOUND | LT_BOUND
4824 // LT_BOUND = LIFETIME (e.g. `'a`)
4825 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4826 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4827 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4828 let mut bounds = Vec::new();
4830 // This needs to be syncronized with `Token::can_begin_bound`.
4831 let is_bound_start = self.check_path() || self.check_lifetime() ||
4832 self.check(&token::Question) ||
4833 self.check_keyword(keywords::For) ||
4834 self.check(&token::OpenDelim(token::Paren));
4837 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4838 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4839 if self.token.is_lifetime() {
4840 if let Some(question_span) = question {
4841 self.span_err(question_span,
4842 "`?` may only modify trait bounds, not lifetime bounds");
4844 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4846 self.expect(&token::CloseDelim(token::Paren))?;
4847 self.span_err(self.prev_span,
4848 "parenthesized lifetime bounds are not supported");
4851 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4852 let path = self.parse_path(PathStyle::Type)?;
4854 self.expect(&token::CloseDelim(token::Paren))?;
4856 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4857 let modifier = if question.is_some() {
4858 TraitBoundModifier::Maybe
4860 TraitBoundModifier::None
4862 bounds.push(GenericBound::Trait(poly_trait, modifier));
4868 if !allow_plus || !self.eat_plus() {
4876 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
4877 self.parse_generic_bounds_common(true)
4880 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4881 // BOUND = LT_BOUND (e.g. `'a`)
4882 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4883 let mut lifetimes = Vec::new();
4884 while self.check_lifetime() {
4885 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4887 if !self.eat_plus() {
4894 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4895 fn parse_ty_param(&mut self,
4896 preceding_attrs: Vec<Attribute>)
4897 -> PResult<'a, GenericParam> {
4898 let ident = self.parse_ident()?;
4900 // Parse optional colon and param bounds.
4901 let bounds = if self.eat(&token::Colon) {
4902 self.parse_generic_bounds()?
4907 let default = if self.eat(&token::Eq) {
4908 Some(self.parse_ty()?)
4915 id: ast::DUMMY_NODE_ID,
4916 attrs: preceding_attrs.into(),
4918 kind: GenericParamKind::Type {
4924 /// Parses the following grammar:
4925 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4926 fn parse_trait_item_assoc_ty(&mut self)
4927 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4928 let ident = self.parse_ident()?;
4929 let mut generics = self.parse_generics()?;
4931 // Parse optional colon and param bounds.
4932 let bounds = if self.eat(&token::Colon) {
4933 self.parse_generic_bounds()?
4937 generics.where_clause = self.parse_where_clause()?;
4939 let default = if self.eat(&token::Eq) {
4940 Some(self.parse_ty()?)
4944 self.expect(&token::Semi)?;
4946 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4949 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4950 /// trailing comma and erroneous trailing attributes.
4951 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4952 let mut params = Vec::new();
4953 let mut seen_ty_param = false;
4955 let attrs = self.parse_outer_attributes()?;
4956 if self.check_lifetime() {
4957 let lifetime = self.expect_lifetime();
4958 // Parse lifetime parameter.
4959 let bounds = if self.eat(&token::Colon) {
4960 self.parse_lt_param_bounds()
4964 params.push(ast::GenericParam {
4965 ident: lifetime.ident,
4967 attrs: attrs.into(),
4969 kind: ast::GenericParamKind::Lifetime,
4972 self.span_err(self.prev_span,
4973 "lifetime parameters must be declared prior to type parameters");
4975 } else if self.check_ident() {
4976 // Parse type parameter.
4977 params.push(self.parse_ty_param(attrs)?);
4978 seen_ty_param = true;
4980 // Check for trailing attributes and stop parsing.
4981 if !attrs.is_empty() {
4982 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4983 self.span_err(attrs[0].span,
4984 &format!("trailing attribute after {} parameters", param_kind));
4989 if !self.eat(&token::Comma) {
4996 /// Parse a set of optional generic type parameter declarations. Where
4997 /// clauses are not parsed here, and must be added later via
4998 /// `parse_where_clause()`.
5000 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5001 /// | ( < lifetimes , typaramseq ( , )? > )
5002 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5003 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5004 maybe_whole!(self, NtGenerics, |x| x);
5006 let span_lo = self.span;
5008 let params = self.parse_generic_params()?;
5012 where_clause: WhereClause {
5013 id: ast::DUMMY_NODE_ID,
5014 predicates: Vec::new(),
5015 span: syntax_pos::DUMMY_SP,
5017 span: span_lo.to(self.prev_span),
5020 Ok(ast::Generics::default())
5024 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5025 /// possibly including trailing comma.
5026 fn parse_generic_args(&mut self)
5027 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5028 let mut args = Vec::new();
5029 let mut bindings = Vec::new();
5030 let mut seen_type = false;
5031 let mut seen_binding = false;
5033 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5034 // Parse lifetime argument.
5035 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5036 if seen_type || seen_binding {
5037 self.span_err(self.prev_span,
5038 "lifetime parameters must be declared prior to type parameters");
5040 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5041 // Parse associated type binding.
5043 let ident = self.parse_ident()?;
5045 let ty = self.parse_ty()?;
5046 bindings.push(TypeBinding {
5047 id: ast::DUMMY_NODE_ID,
5050 span: lo.to(self.prev_span),
5052 seen_binding = true;
5053 } else if self.check_type() {
5054 // Parse type argument.
5055 let ty_param = self.parse_ty()?;
5057 self.span_err(ty_param.span,
5058 "type parameters must be declared prior to associated type bindings");
5060 args.push(GenericArg::Type(ty_param));
5066 if !self.eat(&token::Comma) {
5070 Ok((args, bindings))
5073 /// Parses an optional `where` clause and places it in `generics`.
5075 /// ```ignore (only-for-syntax-highlight)
5076 /// where T : Trait<U, V> + 'b, 'a : 'b
5078 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5079 maybe_whole!(self, NtWhereClause, |x| x);
5081 let mut where_clause = WhereClause {
5082 id: ast::DUMMY_NODE_ID,
5083 predicates: Vec::new(),
5084 span: syntax_pos::DUMMY_SP,
5087 if !self.eat_keyword(keywords::Where) {
5088 return Ok(where_clause);
5090 let lo = self.prev_span;
5092 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5093 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5094 // change we parse those generics now, but report an error.
5095 if self.choose_generics_over_qpath() {
5096 let generics = self.parse_generics()?;
5097 self.span_err(generics.span,
5098 "generic parameters on `where` clauses are reserved for future use");
5103 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5104 let lifetime = self.expect_lifetime();
5105 // Bounds starting with a colon are mandatory, but possibly empty.
5106 self.expect(&token::Colon)?;
5107 let bounds = self.parse_lt_param_bounds();
5108 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5109 ast::WhereRegionPredicate {
5110 span: lo.to(self.prev_span),
5115 } else if self.check_type() {
5116 // Parse optional `for<'a, 'b>`.
5117 // This `for` is parsed greedily and applies to the whole predicate,
5118 // the bounded type can have its own `for` applying only to it.
5119 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5120 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5121 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5122 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5124 // Parse type with mandatory colon and (possibly empty) bounds,
5125 // or with mandatory equality sign and the second type.
5126 let ty = self.parse_ty()?;
5127 if self.eat(&token::Colon) {
5128 let bounds = self.parse_generic_bounds()?;
5129 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5130 ast::WhereBoundPredicate {
5131 span: lo.to(self.prev_span),
5132 bound_generic_params: lifetime_defs,
5137 // FIXME: Decide what should be used here, `=` or `==`.
5138 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5139 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5140 let rhs_ty = self.parse_ty()?;
5141 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5142 ast::WhereEqPredicate {
5143 span: lo.to(self.prev_span),
5146 id: ast::DUMMY_NODE_ID,
5150 return self.unexpected();
5156 if !self.eat(&token::Comma) {
5161 where_clause.span = lo.to(self.prev_span);
5165 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5166 -> PResult<'a, (Vec<Arg> , bool)> {
5168 let mut variadic = false;
5169 let args: Vec<Option<Arg>> =
5170 self.parse_unspanned_seq(
5171 &token::OpenDelim(token::Paren),
5172 &token::CloseDelim(token::Paren),
5173 SeqSep::trailing_allowed(token::Comma),
5175 if p.token == token::DotDotDot {
5179 if p.token != token::CloseDelim(token::Paren) {
5182 "`...` must be last in argument list for variadic function");
5186 let span = p.prev_span;
5187 if p.token == token::CloseDelim(token::Paren) {
5188 // continue parsing to present any further errors
5191 "only foreign functions are allowed to be variadic"
5193 Ok(Some(dummy_arg(span)))
5195 // this function definition looks beyond recovery, stop parsing
5197 "only foreign functions are allowed to be variadic");
5202 match p.parse_arg_general(named_args) {
5203 Ok(arg) => Ok(Some(arg)),
5206 let lo = p.prev_span;
5207 // Skip every token until next possible arg or end.
5208 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5209 // Create a placeholder argument for proper arg count (#34264).
5210 let span = lo.to(p.prev_span);
5211 Ok(Some(dummy_arg(span)))
5218 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5220 if variadic && args.is_empty() {
5222 "variadic function must be declared with at least one named argument");
5225 Ok((args, variadic))
5228 /// Parse the argument list and result type of a function declaration
5229 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5231 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5232 let ret_ty = self.parse_ret_ty(true)?;
5241 /// Returns the parsed optional self argument and whether a self shortcut was used.
5242 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5243 let expect_ident = |this: &mut Self| match this.token {
5244 // Preserve hygienic context.
5245 token::Ident(ident, _) =>
5246 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5249 let isolated_self = |this: &mut Self, n| {
5250 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5251 this.look_ahead(n + 1, |t| t != &token::ModSep)
5254 // Parse optional self parameter of a method.
5255 // Only a limited set of initial token sequences is considered self parameters, anything
5256 // else is parsed as a normal function parameter list, so some lookahead is required.
5257 let eself_lo = self.span;
5258 let (eself, eself_ident, eself_hi) = match self.token {
5259 token::BinOp(token::And) => {
5265 (if isolated_self(self, 1) {
5267 SelfKind::Region(None, Mutability::Immutable)
5268 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5269 isolated_self(self, 2) {
5272 SelfKind::Region(None, Mutability::Mutable)
5273 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5274 isolated_self(self, 2) {
5276 let lt = self.expect_lifetime();
5277 SelfKind::Region(Some(lt), Mutability::Immutable)
5278 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5279 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5280 isolated_self(self, 3) {
5282 let lt = self.expect_lifetime();
5284 SelfKind::Region(Some(lt), Mutability::Mutable)
5287 }, expect_ident(self), self.prev_span)
5289 token::BinOp(token::Star) => {
5294 // Emit special error for `self` cases.
5295 (if isolated_self(self, 1) {
5297 self.span_err(self.span, "cannot pass `self` by raw pointer");
5298 SelfKind::Value(Mutability::Immutable)
5299 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5300 isolated_self(self, 2) {
5303 self.span_err(self.span, "cannot pass `self` by raw pointer");
5304 SelfKind::Value(Mutability::Immutable)
5307 }, expect_ident(self), self.prev_span)
5309 token::Ident(..) => {
5310 if isolated_self(self, 0) {
5313 let eself_ident = expect_ident(self);
5314 let eself_hi = self.prev_span;
5315 (if self.eat(&token::Colon) {
5316 let ty = self.parse_ty()?;
5317 SelfKind::Explicit(ty, Mutability::Immutable)
5319 SelfKind::Value(Mutability::Immutable)
5320 }, eself_ident, eself_hi)
5321 } else if self.token.is_keyword(keywords::Mut) &&
5322 isolated_self(self, 1) {
5326 let eself_ident = expect_ident(self);
5327 let eself_hi = self.prev_span;
5328 (if self.eat(&token::Colon) {
5329 let ty = self.parse_ty()?;
5330 SelfKind::Explicit(ty, Mutability::Mutable)
5332 SelfKind::Value(Mutability::Mutable)
5333 }, eself_ident, eself_hi)
5338 _ => return Ok(None),
5341 let eself = codemap::respan(eself_lo.to(eself_hi), eself);
5342 Ok(Some(Arg::from_self(eself, eself_ident)))
5345 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5346 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5347 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5349 self.expect(&token::OpenDelim(token::Paren))?;
5351 // Parse optional self argument
5352 let self_arg = self.parse_self_arg()?;
5354 // Parse the rest of the function parameter list.
5355 let sep = SeqSep::trailing_allowed(token::Comma);
5356 let fn_inputs = if let Some(self_arg) = self_arg {
5357 if self.check(&token::CloseDelim(token::Paren)) {
5359 } else if self.eat(&token::Comma) {
5360 let mut fn_inputs = vec![self_arg];
5361 fn_inputs.append(&mut self.parse_seq_to_before_end(
5362 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5366 return self.unexpected();
5369 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5372 // Parse closing paren and return type.
5373 self.expect(&token::CloseDelim(token::Paren))?;
5376 output: self.parse_ret_ty(true)?,
5381 // parse the |arg, arg| header on a lambda
5382 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5383 let inputs_captures = {
5384 if self.eat(&token::OrOr) {
5387 self.expect(&token::BinOp(token::Or))?;
5388 let args = self.parse_seq_to_before_tokens(
5389 &[&token::BinOp(token::Or), &token::OrOr],
5390 SeqSep::trailing_allowed(token::Comma),
5391 TokenExpectType::NoExpect,
5392 |p| p.parse_fn_block_arg()
5398 let output = self.parse_ret_ty(true)?;
5401 inputs: inputs_captures,
5407 /// Parse the name and optional generic types of a function header.
5408 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5409 let id = self.parse_ident()?;
5410 let generics = self.parse_generics()?;
5414 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5415 attrs: Vec<Attribute>) -> P<Item> {
5419 id: ast::DUMMY_NODE_ID,
5427 /// Parse an item-position function declaration.
5428 fn parse_item_fn(&mut self,
5431 constness: Spanned<Constness>,
5433 -> PResult<'a, ItemInfo> {
5434 let (ident, mut generics) = self.parse_fn_header()?;
5435 let decl = self.parse_fn_decl(false)?;
5436 generics.where_clause = self.parse_where_clause()?;
5437 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5438 let header = FnHeader { unsafety, asyncness, constness, abi };
5439 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5442 /// true if we are looking at `const ID`, false for things like `const fn` etc
5443 fn is_const_item(&mut self) -> bool {
5444 self.token.is_keyword(keywords::Const) &&
5445 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5446 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5449 /// parses all the "front matter" for a `fn` declaration, up to
5450 /// and including the `fn` keyword:
5454 /// - `const unsafe fn`
5457 fn parse_fn_front_matter(&mut self)
5465 let is_const_fn = self.eat_keyword(keywords::Const);
5466 let const_span = self.prev_span;
5467 let unsafety = self.parse_unsafety();
5468 let asyncness = self.parse_asyncness();
5469 let (constness, unsafety, abi) = if is_const_fn {
5470 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5472 let abi = if self.eat_keyword(keywords::Extern) {
5473 self.parse_opt_abi()?.unwrap_or(Abi::C)
5477 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5479 self.expect_keyword(keywords::Fn)?;
5480 Ok((constness, unsafety, asyncness, abi))
5483 /// Parse an impl item.
5484 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5485 maybe_whole!(self, NtImplItem, |x| x);
5486 let attrs = self.parse_outer_attributes()?;
5487 let (mut item, tokens) = self.collect_tokens(|this| {
5488 this.parse_impl_item_(at_end, attrs)
5491 // See `parse_item` for why this clause is here.
5492 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5493 item.tokens = Some(tokens);
5498 fn parse_impl_item_(&mut self,
5500 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5502 let vis = self.parse_visibility(false)?;
5503 let defaultness = self.parse_defaultness();
5504 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5505 // This parses the grammar:
5506 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5507 let name = self.parse_ident()?;
5508 let mut generics = self.parse_generics()?;
5509 generics.where_clause = self.parse_where_clause()?;
5510 self.expect(&token::Eq)?;
5511 let typ = self.parse_ty()?;
5512 self.expect(&token::Semi)?;
5513 (name, ast::ImplItemKind::Type(typ), generics)
5514 } else if self.is_const_item() {
5515 // This parses the grammar:
5516 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5517 self.expect_keyword(keywords::Const)?;
5518 let name = self.parse_ident()?;
5519 self.expect(&token::Colon)?;
5520 let typ = self.parse_ty()?;
5521 self.expect(&token::Eq)?;
5522 let expr = self.parse_expr()?;
5523 self.expect(&token::Semi)?;
5524 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5526 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5527 attrs.extend(inner_attrs);
5528 (name, node, generics)
5532 id: ast::DUMMY_NODE_ID,
5533 span: lo.to(self.prev_span),
5544 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5545 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5550 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5552 VisibilityKind::Inherited => Ok(()),
5554 let is_macro_rules: bool = match self.token {
5555 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5559 let mut err = self.diagnostic()
5560 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5561 err.span_suggestion_with_applicability(
5563 "try exporting the macro",
5564 "#[macro_export]".to_owned(),
5565 Applicability::MaybeIncorrect // speculative
5569 let mut err = self.diagnostic()
5570 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5571 err.help("try adjusting the macro to put `pub` inside the invocation");
5578 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5579 -> DiagnosticBuilder<'a>
5581 let expected_kinds = if item_type == "extern" {
5582 "missing `fn`, `type`, or `static`"
5584 "missing `fn`, `type`, or `const`"
5587 // Given this code `path(`, it seems like this is not
5588 // setting the visibility of a macro invocation, but rather
5589 // a mistyped method declaration.
5590 // Create a diagnostic pointing out that `fn` is missing.
5592 // x | pub path(&self) {
5593 // | ^ missing `fn`, `type`, or `const`
5595 // ^^ `sp` below will point to this
5596 let sp = prev_span.between(self.prev_span);
5597 let mut err = self.diagnostic().struct_span_err(
5599 &format!("{} for {}-item declaration",
5600 expected_kinds, item_type));
5601 err.span_label(sp, expected_kinds);
5605 /// Parse a method or a macro invocation in a trait impl.
5606 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5607 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5608 ast::ImplItemKind)> {
5609 // code copied from parse_macro_use_or_failure... abstraction!
5610 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5612 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5613 ast::ImplItemKind::Macro(mac)))
5615 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5616 let ident = self.parse_ident()?;
5617 let mut generics = self.parse_generics()?;
5618 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5619 generics.where_clause = self.parse_where_clause()?;
5621 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5622 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5623 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5624 ast::MethodSig { header, decl },
5630 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5631 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5632 let ident = self.parse_ident()?;
5633 let mut tps = self.parse_generics()?;
5635 // Parse optional colon and supertrait bounds.
5636 let bounds = if self.eat(&token::Colon) {
5637 self.parse_generic_bounds()?
5642 if self.eat(&token::Eq) {
5643 // it's a trait alias
5644 let bounds = self.parse_generic_bounds()?;
5645 tps.where_clause = self.parse_where_clause()?;
5646 self.expect(&token::Semi)?;
5647 if unsafety != Unsafety::Normal {
5648 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5650 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5652 // it's a normal trait
5653 tps.where_clause = self.parse_where_clause()?;
5654 self.expect(&token::OpenDelim(token::Brace))?;
5655 let mut trait_items = vec![];
5656 while !self.eat(&token::CloseDelim(token::Brace)) {
5657 let mut at_end = false;
5658 match self.parse_trait_item(&mut at_end) {
5659 Ok(item) => trait_items.push(item),
5663 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5668 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5672 fn choose_generics_over_qpath(&self) -> bool {
5673 // There's an ambiguity between generic parameters and qualified paths in impls.
5674 // If we see `<` it may start both, so we have to inspect some following tokens.
5675 // The following combinations can only start generics,
5676 // but not qualified paths (with one exception):
5677 // `<` `>` - empty generic parameters
5678 // `<` `#` - generic parameters with attributes
5679 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5680 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5681 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5682 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5683 // The only truly ambiguous case is
5684 // `<` IDENT `>` `::` IDENT ...
5685 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5686 // because this is what almost always expected in practice, qualified paths in impls
5687 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5688 self.token == token::Lt &&
5689 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5690 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5691 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5692 t == &token::Colon || t == &token::Eq))
5695 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5696 self.expect(&token::OpenDelim(token::Brace))?;
5697 let attrs = self.parse_inner_attributes()?;
5699 let mut impl_items = Vec::new();
5700 while !self.eat(&token::CloseDelim(token::Brace)) {
5701 let mut at_end = false;
5702 match self.parse_impl_item(&mut at_end) {
5703 Ok(impl_item) => impl_items.push(impl_item),
5707 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5712 Ok((impl_items, attrs))
5715 /// Parses an implementation item, `impl` keyword is already parsed.
5716 /// impl<'a, T> TYPE { /* impl items */ }
5717 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5718 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5719 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5720 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5721 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5722 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5723 -> PResult<'a, ItemInfo> {
5724 // First, parse generic parameters if necessary.
5725 let mut generics = if self.choose_generics_over_qpath() {
5726 self.parse_generics()?
5728 ast::Generics::default()
5731 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5732 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5734 ast::ImplPolarity::Negative
5736 ast::ImplPolarity::Positive
5739 // Parse both types and traits as a type, then reinterpret if necessary.
5740 let ty_first = self.parse_ty()?;
5742 // If `for` is missing we try to recover.
5743 let has_for = self.eat_keyword(keywords::For);
5744 let missing_for_span = self.prev_span.between(self.span);
5746 let ty_second = if self.token == token::DotDot {
5747 // We need to report this error after `cfg` expansion for compatibility reasons
5748 self.bump(); // `..`, do not add it to expected tokens
5749 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5750 } else if has_for || self.token.can_begin_type() {
5751 Some(self.parse_ty()?)
5756 generics.where_clause = self.parse_where_clause()?;
5758 let (impl_items, attrs) = self.parse_impl_body()?;
5760 let item_kind = match ty_second {
5761 Some(ty_second) => {
5762 // impl Trait for Type
5764 self.span_err(missing_for_span, "missing `for` in a trait impl");
5767 let ty_first = ty_first.into_inner();
5768 let path = match ty_first.node {
5769 // This notably includes paths passed through `ty` macro fragments (#46438).
5770 TyKind::Path(None, path) => path,
5772 self.span_err(ty_first.span, "expected a trait, found type");
5773 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5776 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5778 ItemKind::Impl(unsafety, polarity, defaultness,
5779 generics, Some(trait_ref), ty_second, impl_items)
5783 ItemKind::Impl(unsafety, polarity, defaultness,
5784 generics, None, ty_first, impl_items)
5788 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5791 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5792 if self.eat_keyword(keywords::For) {
5794 let params = self.parse_generic_params()?;
5796 // We rely on AST validation to rule out invalid cases: There must not be type
5797 // parameters, and the lifetime parameters must not have bounds.
5804 /// Parse struct Foo { ... }
5805 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5806 let class_name = self.parse_ident()?;
5808 let mut generics = self.parse_generics()?;
5810 // There is a special case worth noting here, as reported in issue #17904.
5811 // If we are parsing a tuple struct it is the case that the where clause
5812 // should follow the field list. Like so:
5814 // struct Foo<T>(T) where T: Copy;
5816 // If we are parsing a normal record-style struct it is the case
5817 // that the where clause comes before the body, and after the generics.
5818 // So if we look ahead and see a brace or a where-clause we begin
5819 // parsing a record style struct.
5821 // Otherwise if we look ahead and see a paren we parse a tuple-style
5824 let vdata = if self.token.is_keyword(keywords::Where) {
5825 generics.where_clause = self.parse_where_clause()?;
5826 if self.eat(&token::Semi) {
5827 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5828 VariantData::Unit(ast::DUMMY_NODE_ID)
5830 // If we see: `struct Foo<T> where T: Copy { ... }`
5831 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5833 // No `where` so: `struct Foo<T>;`
5834 } else if self.eat(&token::Semi) {
5835 VariantData::Unit(ast::DUMMY_NODE_ID)
5836 // Record-style struct definition
5837 } else if self.token == token::OpenDelim(token::Brace) {
5838 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5839 // Tuple-style struct definition with optional where-clause.
5840 } else if self.token == token::OpenDelim(token::Paren) {
5841 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5842 generics.where_clause = self.parse_where_clause()?;
5843 self.expect(&token::Semi)?;
5846 let token_str = self.this_token_to_string();
5847 let mut err = self.fatal(&format!(
5848 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5851 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5855 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5858 /// Parse union Foo { ... }
5859 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5860 let class_name = self.parse_ident()?;
5862 let mut generics = self.parse_generics()?;
5864 let vdata = if self.token.is_keyword(keywords::Where) {
5865 generics.where_clause = self.parse_where_clause()?;
5866 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5867 } else if self.token == token::OpenDelim(token::Brace) {
5868 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5870 let token_str = self.this_token_to_string();
5871 let mut err = self.fatal(&format!(
5872 "expected `where` or `{{` after union name, found `{}`", token_str));
5873 err.span_label(self.span, "expected `where` or `{` after union name");
5877 Ok((class_name, ItemKind::Union(vdata, generics), None))
5880 fn consume_block(&mut self, delim: token::DelimToken) {
5881 let mut brace_depth = 0;
5882 if !self.eat(&token::OpenDelim(delim)) {
5886 if self.eat(&token::OpenDelim(delim)) {
5888 } else if self.eat(&token::CloseDelim(delim)) {
5889 if brace_depth == 0 {
5895 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5903 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5904 let mut fields = Vec::new();
5905 if self.eat(&token::OpenDelim(token::Brace)) {
5906 while self.token != token::CloseDelim(token::Brace) {
5907 let field = self.parse_struct_decl_field().map_err(|e| {
5908 self.recover_stmt();
5912 Ok(field) => fields.push(field),
5918 self.eat(&token::CloseDelim(token::Brace));
5920 let token_str = self.this_token_to_string();
5921 let mut err = self.fatal(&format!(
5922 "expected `where`, or `{{` after struct name, found `{}`", token_str));
5923 err.span_label(self.span, "expected `where`, or `{` after struct name");
5930 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5931 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5932 // Unit like structs are handled in parse_item_struct function
5933 let fields = self.parse_unspanned_seq(
5934 &token::OpenDelim(token::Paren),
5935 &token::CloseDelim(token::Paren),
5936 SeqSep::trailing_allowed(token::Comma),
5938 let attrs = p.parse_outer_attributes()?;
5940 let vis = p.parse_visibility(true)?;
5941 let ty = p.parse_ty()?;
5943 span: lo.to(ty.span),
5946 id: ast::DUMMY_NODE_ID,
5955 /// Parse a structure field declaration
5956 fn parse_single_struct_field(&mut self,
5959 attrs: Vec<Attribute> )
5960 -> PResult<'a, StructField> {
5961 let mut seen_comma: bool = false;
5962 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5963 if self.token == token::Comma {
5970 token::CloseDelim(token::Brace) => {}
5971 token::DocComment(_) => {
5972 let previous_span = self.prev_span;
5973 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5974 self.bump(); // consume the doc comment
5975 let comma_after_doc_seen = self.eat(&token::Comma);
5976 // `seen_comma` is always false, because we are inside doc block
5977 // condition is here to make code more readable
5978 if seen_comma == false && comma_after_doc_seen == true {
5981 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
5984 if seen_comma == false {
5985 let sp = self.sess.codemap().next_point(previous_span);
5986 err.span_suggestion_with_applicability(
5988 "missing comma here",
5990 Applicability::MachineApplicable
5997 let sp = self.sess.codemap().next_point(self.prev_span);
5998 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
5999 self.this_token_to_string()));
6000 if self.token.is_ident() {
6001 // This is likely another field; emit the diagnostic and keep going
6002 err.span_suggestion(sp, "try adding a comma", ",".into());
6012 /// Parse an element of a struct definition
6013 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6014 let attrs = self.parse_outer_attributes()?;
6016 let vis = self.parse_visibility(false)?;
6017 self.parse_single_struct_field(lo, vis, attrs)
6020 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6021 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6022 /// a function definition, it's not a tuple struct field) and the contents within the parens
6023 /// isn't valid, emit a proper diagnostic.
6024 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6025 maybe_whole!(self, NtVis, |x| x);
6027 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6028 if self.is_crate_vis() {
6029 self.bump(); // `crate`
6030 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6033 if !self.eat_keyword(keywords::Pub) {
6034 return Ok(respan(self.prev_span, VisibilityKind::Inherited))
6036 let lo = self.prev_span;
6038 if self.check(&token::OpenDelim(token::Paren)) {
6039 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6040 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6041 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6042 // by the following tokens.
6043 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6046 self.bump(); // `crate`
6047 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6049 lo.to(self.prev_span),
6050 VisibilityKind::Crate(CrateSugar::PubCrate),
6053 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6056 self.bump(); // `in`
6057 let path = self.parse_path(PathStyle::Mod)?; // `path`
6058 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6059 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6061 id: ast::DUMMY_NODE_ID,
6064 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6065 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6066 t.is_keyword(keywords::SelfValue))
6068 // `pub(self)` or `pub(super)`
6070 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6071 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6072 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6074 id: ast::DUMMY_NODE_ID,
6077 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6078 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6080 let msg = "incorrect visibility restriction";
6081 let suggestion = r##"some possible visibility restrictions are:
6082 `pub(crate)`: visible only on the current crate
6083 `pub(super)`: visible only in the current module's parent
6084 `pub(in path::to::module)`: visible only on the specified path"##;
6085 let path = self.parse_path(PathStyle::Mod)?;
6086 let sp = self.prev_span;
6087 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6088 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6089 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6090 err.help(suggestion);
6091 err.span_suggestion_with_applicability(
6092 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6094 err.emit(); // emit diagnostic, but continue with public visibility
6098 Ok(respan(lo, VisibilityKind::Public))
6101 /// Parse defaultness: `default` or nothing.
6102 fn parse_defaultness(&mut self) -> Defaultness {
6103 // `pub` is included for better error messages
6104 if self.check_keyword(keywords::Default) &&
6105 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6106 t.is_keyword(keywords::Const) ||
6107 t.is_keyword(keywords::Fn) ||
6108 t.is_keyword(keywords::Unsafe) ||
6109 t.is_keyword(keywords::Extern) ||
6110 t.is_keyword(keywords::Type) ||
6111 t.is_keyword(keywords::Pub)) {
6112 self.bump(); // `default`
6113 Defaultness::Default
6119 /// Given a termination token, parse all of the items in a module
6120 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6121 let mut items = vec![];
6122 while let Some(item) = self.parse_item()? {
6126 if !self.eat(term) {
6127 let token_str = self.this_token_to_string();
6128 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6129 if token_str == ";" {
6130 let msg = "consider removing this semicolon";
6131 err.span_suggestion_short_with_applicability(
6132 self.span, msg, "".to_string(), Applicability::MachineApplicable
6135 err.span_label(self.span, "expected item");
6140 let hi = if self.span == syntax_pos::DUMMY_SP {
6147 inner: inner_lo.to(hi),
6152 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6153 let id = self.parse_ident()?;
6154 self.expect(&token::Colon)?;
6155 let ty = self.parse_ty()?;
6156 self.expect(&token::Eq)?;
6157 let e = self.parse_expr()?;
6158 self.expect(&token::Semi)?;
6159 let item = match m {
6160 Some(m) => ItemKind::Static(ty, m, e),
6161 None => ItemKind::Const(ty, e),
6163 Ok((id, item, None))
6166 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6167 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6168 let (in_cfg, outer_attrs) = {
6169 let mut strip_unconfigured = ::config::StripUnconfigured {
6171 should_test: false, // irrelevant
6172 features: None, // don't perform gated feature checking
6174 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6175 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6178 let id_span = self.span;
6179 let id = self.parse_ident()?;
6180 if self.check(&token::Semi) {
6182 if in_cfg && self.recurse_into_file_modules {
6183 // This mod is in an external file. Let's go get it!
6184 let ModulePathSuccess { path, directory_ownership, warn } =
6185 self.submod_path(id, &outer_attrs, id_span)?;
6186 let (module, mut attrs) =
6187 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6189 let attr = Attribute {
6190 id: attr::mk_attr_id(),
6191 style: ast::AttrStyle::Outer,
6192 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6193 tokens: TokenStream::empty(),
6194 is_sugared_doc: false,
6195 span: syntax_pos::DUMMY_SP,
6197 attr::mark_known(&attr);
6200 Ok((id, module, Some(attrs)))
6202 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6203 Ok((id, ItemKind::Mod(placeholder), None))
6206 let old_directory = self.directory.clone();
6207 self.push_directory(id, &outer_attrs);
6209 self.expect(&token::OpenDelim(token::Brace))?;
6210 let mod_inner_lo = self.span;
6211 let attrs = self.parse_inner_attributes()?;
6212 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6214 self.directory = old_directory;
6215 Ok((id, ItemKind::Mod(module), Some(attrs)))
6219 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6220 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6221 self.directory.path.to_mut().push(&path.as_str());
6222 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6224 self.directory.path.to_mut().push(&id.as_str());
6228 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6229 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6232 // On windows, the base path might have the form
6233 // `\\?\foo\bar` in which case it does not tolerate
6234 // mixed `/` and `\` separators, so canonicalize
6237 let s = s.replace("/", "\\");
6238 Some(dir_path.join(s))
6244 /// Returns either a path to a module, or .
6245 pub fn default_submod_path(
6247 relative: Option<ast::Ident>,
6249 codemap: &CodeMap) -> ModulePath
6251 // If we're in a foo.rs file instead of a mod.rs file,
6252 // we need to look for submodules in
6253 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6254 // `./<id>.rs` and `./<id>/mod.rs`.
6255 let relative_prefix_string;
6256 let relative_prefix = if let Some(ident) = relative {
6257 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6258 &relative_prefix_string
6263 let mod_name = id.to_string();
6264 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6265 let secondary_path_str = format!("{}{}{}mod.rs",
6266 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6267 let default_path = dir_path.join(&default_path_str);
6268 let secondary_path = dir_path.join(&secondary_path_str);
6269 let default_exists = codemap.file_exists(&default_path);
6270 let secondary_exists = codemap.file_exists(&secondary_path);
6272 let result = match (default_exists, secondary_exists) {
6273 (true, false) => Ok(ModulePathSuccess {
6275 directory_ownership: DirectoryOwnership::Owned {
6280 (false, true) => Ok(ModulePathSuccess {
6281 path: secondary_path,
6282 directory_ownership: DirectoryOwnership::Owned {
6287 (false, false) => Err(Error::FileNotFoundForModule {
6288 mod_name: mod_name.clone(),
6289 default_path: default_path_str,
6290 secondary_path: secondary_path_str,
6291 dir_path: format!("{}", dir_path.display()),
6293 (true, true) => Err(Error::DuplicatePaths {
6294 mod_name: mod_name.clone(),
6295 default_path: default_path_str,
6296 secondary_path: secondary_path_str,
6302 path_exists: default_exists || secondary_exists,
6307 fn submod_path(&mut self,
6309 outer_attrs: &[Attribute],
6311 -> PResult<'a, ModulePathSuccess> {
6312 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6313 return Ok(ModulePathSuccess {
6314 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6315 // All `#[path]` files are treated as though they are a `mod.rs` file.
6316 // This means that `mod foo;` declarations inside `#[path]`-included
6317 // files are siblings,
6319 // Note that this will produce weirdness when a file named `foo.rs` is
6320 // `#[path]` included and contains a `mod foo;` declaration.
6321 // If you encounter this, it's your own darn fault :P
6322 Some(_) => DirectoryOwnership::Owned { relative: None },
6323 _ => DirectoryOwnership::UnownedViaMod(true),
6330 let relative = match self.directory.ownership {
6331 DirectoryOwnership::Owned { relative } => {
6332 // Push the usage onto the list of non-mod.rs mod uses.
6333 // This is used later for feature-gate error reporting.
6334 if let Some(cur_file_ident) = relative {
6336 .non_modrs_mods.borrow_mut()
6337 .push((cur_file_ident, id_sp));
6341 DirectoryOwnership::UnownedViaBlock |
6342 DirectoryOwnership::UnownedViaMod(_) => None,
6344 let paths = Parser::default_submod_path(
6345 id, relative, &self.directory.path, self.sess.codemap());
6347 match self.directory.ownership {
6348 DirectoryOwnership::Owned { .. } => {
6349 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6351 DirectoryOwnership::UnownedViaBlock => {
6353 "Cannot declare a non-inline module inside a block \
6354 unless it has a path attribute";
6355 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6356 if paths.path_exists {
6357 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6359 err.span_note(id_sp, &msg);
6363 DirectoryOwnership::UnownedViaMod(warn) => {
6365 if let Ok(result) = paths.result {
6366 return Ok(ModulePathSuccess { warn: true, ..result });
6369 let mut err = self.diagnostic().struct_span_err(id_sp,
6370 "cannot declare a new module at this location");
6371 if id_sp != syntax_pos::DUMMY_SP {
6372 let src_path = self.sess.codemap().span_to_filename(id_sp);
6373 if let FileName::Real(src_path) = src_path {
6374 if let Some(stem) = src_path.file_stem() {
6375 let mut dest_path = src_path.clone();
6376 dest_path.set_file_name(stem);
6377 dest_path.push("mod.rs");
6378 err.span_note(id_sp,
6379 &format!("maybe move this module `{}` to its own \
6380 directory via `{}`", src_path.display(),
6381 dest_path.display()));
6385 if paths.path_exists {
6386 err.span_note(id_sp,
6387 &format!("... or maybe `use` the module `{}` instead \
6388 of possibly redeclaring it",
6396 /// Read a module from a source file.
6397 fn eval_src_mod(&mut self,
6399 directory_ownership: DirectoryOwnership,
6402 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6403 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6404 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6405 let mut err = String::from("circular modules: ");
6406 let len = included_mod_stack.len();
6407 for p in &included_mod_stack[i.. len] {
6408 err.push_str(&p.to_string_lossy());
6409 err.push_str(" -> ");
6411 err.push_str(&path.to_string_lossy());
6412 return Err(self.span_fatal(id_sp, &err[..]));
6414 included_mod_stack.push(path.clone());
6415 drop(included_mod_stack);
6418 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6419 p0.cfg_mods = self.cfg_mods;
6420 let mod_inner_lo = p0.span;
6421 let mod_attrs = p0.parse_inner_attributes()?;
6422 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6423 self.sess.included_mod_stack.borrow_mut().pop();
6424 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6427 /// Parse a function declaration from a foreign module
6428 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6429 -> PResult<'a, ForeignItem> {
6430 self.expect_keyword(keywords::Fn)?;
6432 let (ident, mut generics) = self.parse_fn_header()?;
6433 let decl = self.parse_fn_decl(true)?;
6434 generics.where_clause = self.parse_where_clause()?;
6436 self.expect(&token::Semi)?;
6437 Ok(ast::ForeignItem {
6440 node: ForeignItemKind::Fn(decl, generics),
6441 id: ast::DUMMY_NODE_ID,
6447 /// Parse a static item from a foreign module.
6448 /// Assumes that the `static` keyword is already parsed.
6449 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6450 -> PResult<'a, ForeignItem> {
6451 let mutbl = self.eat_keyword(keywords::Mut);
6452 let ident = self.parse_ident()?;
6453 self.expect(&token::Colon)?;
6454 let ty = self.parse_ty()?;
6456 self.expect(&token::Semi)?;
6460 node: ForeignItemKind::Static(ty, mutbl),
6461 id: ast::DUMMY_NODE_ID,
6467 /// Parse a type from a foreign module
6468 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6469 -> PResult<'a, ForeignItem> {
6470 self.expect_keyword(keywords::Type)?;
6472 let ident = self.parse_ident()?;
6474 self.expect(&token::Semi)?;
6475 Ok(ast::ForeignItem {
6478 node: ForeignItemKind::Ty,
6479 id: ast::DUMMY_NODE_ID,
6485 /// Parse extern crate links
6489 /// extern crate foo;
6490 /// extern crate bar as foo;
6491 fn parse_item_extern_crate(&mut self,
6493 visibility: Visibility,
6494 attrs: Vec<Attribute>)
6495 -> PResult<'a, P<Item>> {
6496 let orig_name = self.parse_ident()?;
6497 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6498 (rename, Some(orig_name.name))
6502 self.expect(&token::Semi)?;
6504 let span = lo.to(self.prev_span);
6505 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6508 /// Parse `extern` for foreign ABIs
6511 /// `extern` is expected to have been
6512 /// consumed before calling this method
6518 fn parse_item_foreign_mod(&mut self,
6520 opt_abi: Option<Abi>,
6521 visibility: Visibility,
6522 mut attrs: Vec<Attribute>)
6523 -> PResult<'a, P<Item>> {
6524 self.expect(&token::OpenDelim(token::Brace))?;
6526 let abi = opt_abi.unwrap_or(Abi::C);
6528 attrs.extend(self.parse_inner_attributes()?);
6530 let mut foreign_items = vec![];
6531 while let Some(item) = self.parse_foreign_item()? {
6532 foreign_items.push(item);
6534 self.expect(&token::CloseDelim(token::Brace))?;
6536 let prev_span = self.prev_span;
6537 let m = ast::ForeignMod {
6539 items: foreign_items
6541 let invalid = keywords::Invalid.ident();
6542 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6545 /// Parse type Foo = Bar;
6546 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6547 let ident = self.parse_ident()?;
6548 let mut tps = self.parse_generics()?;
6549 tps.where_clause = self.parse_where_clause()?;
6550 self.expect(&token::Eq)?;
6551 let ty = self.parse_ty()?;
6552 self.expect(&token::Semi)?;
6553 Ok((ident, ItemKind::Ty(ty, tps), None))
6556 /// Parse the part of an "enum" decl following the '{'
6557 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6558 let mut variants = Vec::new();
6559 let mut all_nullary = true;
6560 let mut any_disr = None;
6561 while self.token != token::CloseDelim(token::Brace) {
6562 let variant_attrs = self.parse_outer_attributes()?;
6563 let vlo = self.span;
6566 let mut disr_expr = None;
6567 let ident = self.parse_ident()?;
6568 if self.check(&token::OpenDelim(token::Brace)) {
6569 // Parse a struct variant.
6570 all_nullary = false;
6571 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6572 ast::DUMMY_NODE_ID);
6573 } else if self.check(&token::OpenDelim(token::Paren)) {
6574 all_nullary = false;
6575 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6576 ast::DUMMY_NODE_ID);
6577 } else if self.eat(&token::Eq) {
6578 disr_expr = Some(AnonConst {
6579 id: ast::DUMMY_NODE_ID,
6580 value: self.parse_expr()?,
6582 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6583 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6585 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6588 let vr = ast::Variant_ {
6590 attrs: variant_attrs,
6594 variants.push(respan(vlo.to(self.prev_span), vr));
6596 if !self.eat(&token::Comma) { break; }
6598 self.expect(&token::CloseDelim(token::Brace))?;
6600 Some(disr_span) if !all_nullary =>
6601 self.span_err(disr_span,
6602 "discriminator values can only be used with a field-less enum"),
6606 Ok(ast::EnumDef { variants: variants })
6609 /// Parse an "enum" declaration
6610 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6611 let id = self.parse_ident()?;
6612 let mut generics = self.parse_generics()?;
6613 generics.where_clause = self.parse_where_clause()?;
6614 self.expect(&token::OpenDelim(token::Brace))?;
6616 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6617 self.recover_stmt();
6618 self.eat(&token::CloseDelim(token::Brace));
6621 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6624 /// Parses a string as an ABI spec on an extern type or module. Consumes
6625 /// the `extern` keyword, if one is found.
6626 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6628 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6630 self.expect_no_suffix(sp, "ABI spec", suf);
6632 match abi::lookup(&s.as_str()) {
6633 Some(abi) => Ok(Some(abi)),
6635 let prev_span = self.prev_span;
6636 let mut err = struct_span_err!(
6637 self.sess.span_diagnostic,
6640 "invalid ABI: found `{}`",
6642 err.span_label(prev_span, "invalid ABI");
6643 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6654 fn is_static_global(&mut self) -> bool {
6655 if self.check_keyword(keywords::Static) {
6656 // Check if this could be a closure
6657 !self.look_ahead(1, |token| {
6658 if token.is_keyword(keywords::Move) {
6662 token::BinOp(token::Or) | token::OrOr => true,
6671 /// Parse one of the items allowed by the flags.
6672 /// NB: this function no longer parses the items inside an
6674 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6675 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6676 maybe_whole!(self, NtItem, |item| {
6677 let mut item = item.into_inner();
6678 let mut attrs = attrs;
6679 mem::swap(&mut item.attrs, &mut attrs);
6680 item.attrs.extend(attrs);
6686 let visibility = self.parse_visibility(false)?;
6688 if self.eat_keyword(keywords::Use) {
6690 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6691 self.expect(&token::Semi)?;
6693 let span = lo.to(self.prev_span);
6694 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6695 return Ok(Some(item));
6698 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6699 self.bump(); // `extern`
6700 if self.eat_keyword(keywords::Crate) {
6701 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6704 let opt_abi = self.parse_opt_abi()?;
6706 if self.eat_keyword(keywords::Fn) {
6707 // EXTERN FUNCTION ITEM
6708 let fn_span = self.prev_span;
6709 let abi = opt_abi.unwrap_or(Abi::C);
6710 let (ident, item_, extra_attrs) =
6711 self.parse_item_fn(Unsafety::Normal,
6713 respan(fn_span, Constness::NotConst),
6715 let prev_span = self.prev_span;
6716 let item = self.mk_item(lo.to(prev_span),
6720 maybe_append(attrs, extra_attrs));
6721 return Ok(Some(item));
6722 } else if self.check(&token::OpenDelim(token::Brace)) {
6723 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6729 if self.is_static_global() {
6732 let m = if self.eat_keyword(keywords::Mut) {
6735 Mutability::Immutable
6737 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6738 let prev_span = self.prev_span;
6739 let item = self.mk_item(lo.to(prev_span),
6743 maybe_append(attrs, extra_attrs));
6744 return Ok(Some(item));
6746 if self.eat_keyword(keywords::Const) {
6747 let const_span = self.prev_span;
6748 if self.check_keyword(keywords::Fn)
6749 || (self.check_keyword(keywords::Unsafe)
6750 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6751 // CONST FUNCTION ITEM
6752 let unsafety = self.parse_unsafety();
6754 let (ident, item_, extra_attrs) =
6755 self.parse_item_fn(unsafety,
6757 respan(const_span, Constness::Const),
6759 let prev_span = self.prev_span;
6760 let item = self.mk_item(lo.to(prev_span),
6764 maybe_append(attrs, extra_attrs));
6765 return Ok(Some(item));
6769 if self.eat_keyword(keywords::Mut) {
6770 let prev_span = self.prev_span;
6771 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6772 .help("did you mean to declare a static?")
6775 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6776 let prev_span = self.prev_span;
6777 let item = self.mk_item(lo.to(prev_span),
6781 maybe_append(attrs, extra_attrs));
6782 return Ok(Some(item));
6785 // `unsafe async fn` or `async fn`
6787 self.check_keyword(keywords::Unsafe) &&
6788 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
6790 self.check_keyword(keywords::Async) &&
6791 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
6794 // ASYNC FUNCTION ITEM
6795 let unsafety = self.parse_unsafety();
6796 self.expect_keyword(keywords::Async)?;
6797 self.expect_keyword(keywords::Fn)?;
6798 let fn_span = self.prev_span;
6799 let (ident, item_, extra_attrs) =
6800 self.parse_item_fn(unsafety,
6801 IsAsync::Async(ast::DUMMY_NODE_ID),
6802 respan(fn_span, Constness::NotConst),
6804 let prev_span = self.prev_span;
6805 let item = self.mk_item(lo.to(prev_span),
6809 maybe_append(attrs, extra_attrs));
6810 return Ok(Some(item));
6812 if self.check_keyword(keywords::Unsafe) &&
6813 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6814 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6816 // UNSAFE TRAIT ITEM
6817 self.bump(); // `unsafe`
6818 let is_auto = if self.eat_keyword(keywords::Trait) {
6821 self.expect_keyword(keywords::Auto)?;
6822 self.expect_keyword(keywords::Trait)?;
6825 let (ident, item_, extra_attrs) =
6826 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
6827 let prev_span = self.prev_span;
6828 let item = self.mk_item(lo.to(prev_span),
6832 maybe_append(attrs, extra_attrs));
6833 return Ok(Some(item));
6835 if self.check_keyword(keywords::Impl) ||
6836 self.check_keyword(keywords::Unsafe) &&
6837 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6838 self.check_keyword(keywords::Default) &&
6839 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6840 self.check_keyword(keywords::Default) &&
6841 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6843 let defaultness = self.parse_defaultness();
6844 let unsafety = self.parse_unsafety();
6845 self.expect_keyword(keywords::Impl)?;
6846 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6847 let span = lo.to(self.prev_span);
6848 return Ok(Some(self.mk_item(span, ident, item, visibility,
6849 maybe_append(attrs, extra_attrs))));
6851 if self.check_keyword(keywords::Fn) {
6854 let fn_span = self.prev_span;
6855 let (ident, item_, extra_attrs) =
6856 self.parse_item_fn(Unsafety::Normal,
6858 respan(fn_span, Constness::NotConst),
6860 let prev_span = self.prev_span;
6861 let item = self.mk_item(lo.to(prev_span),
6865 maybe_append(attrs, extra_attrs));
6866 return Ok(Some(item));
6868 if self.check_keyword(keywords::Unsafe)
6869 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6870 // UNSAFE FUNCTION ITEM
6871 self.bump(); // `unsafe`
6872 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
6873 self.check(&token::OpenDelim(token::Brace));
6874 let abi = if self.eat_keyword(keywords::Extern) {
6875 self.parse_opt_abi()?.unwrap_or(Abi::C)
6879 self.expect_keyword(keywords::Fn)?;
6880 let fn_span = self.prev_span;
6881 let (ident, item_, extra_attrs) =
6882 self.parse_item_fn(Unsafety::Unsafe,
6884 respan(fn_span, Constness::NotConst),
6886 let prev_span = self.prev_span;
6887 let item = self.mk_item(lo.to(prev_span),
6891 maybe_append(attrs, extra_attrs));
6892 return Ok(Some(item));
6894 if self.eat_keyword(keywords::Mod) {
6896 let (ident, item_, extra_attrs) =
6897 self.parse_item_mod(&attrs[..])?;
6898 let prev_span = self.prev_span;
6899 let item = self.mk_item(lo.to(prev_span),
6903 maybe_append(attrs, extra_attrs));
6904 return Ok(Some(item));
6906 if self.eat_keyword(keywords::Type) {
6908 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6909 let prev_span = self.prev_span;
6910 let item = self.mk_item(lo.to(prev_span),
6914 maybe_append(attrs, extra_attrs));
6915 return Ok(Some(item));
6917 if self.eat_keyword(keywords::Enum) {
6919 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6920 let prev_span = self.prev_span;
6921 let item = self.mk_item(lo.to(prev_span),
6925 maybe_append(attrs, extra_attrs));
6926 return Ok(Some(item));
6928 if self.check_keyword(keywords::Trait)
6929 || (self.check_keyword(keywords::Auto)
6930 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6932 let is_auto = if self.eat_keyword(keywords::Trait) {
6935 self.expect_keyword(keywords::Auto)?;
6936 self.expect_keyword(keywords::Trait)?;
6940 let (ident, item_, extra_attrs) =
6941 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6942 let prev_span = self.prev_span;
6943 let item = self.mk_item(lo.to(prev_span),
6947 maybe_append(attrs, extra_attrs));
6948 return Ok(Some(item));
6950 if self.eat_keyword(keywords::Struct) {
6952 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6953 let prev_span = self.prev_span;
6954 let item = self.mk_item(lo.to(prev_span),
6958 maybe_append(attrs, extra_attrs));
6959 return Ok(Some(item));
6961 if self.is_union_item() {
6964 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6965 let prev_span = self.prev_span;
6966 let item = self.mk_item(lo.to(prev_span),
6970 maybe_append(attrs, extra_attrs));
6971 return Ok(Some(item));
6973 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6974 return Ok(Some(macro_def));
6977 // Verify whether we have encountered a struct or method definition where the user forgot to
6978 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6979 if visibility.node == VisibilityKind::Public &&
6980 self.check_ident() &&
6981 self.look_ahead(1, |t| *t != token::Not)
6983 // Space between `pub` keyword and the identifier
6986 // ^^^ `sp` points here
6987 let sp = self.prev_span.between(self.span);
6988 let full_sp = self.prev_span.to(self.span);
6989 let ident_sp = self.span;
6990 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6991 // possible public struct definition where `struct` was forgotten
6992 let ident = self.parse_ident().unwrap();
6993 let msg = format!("add `struct` here to parse `{}` as a public struct",
6995 let mut err = self.diagnostic()
6996 .struct_span_err(sp, "missing `struct` for struct definition");
6997 err.span_suggestion_short_with_applicability(
6998 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7001 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7002 let ident = self.parse_ident().unwrap();
7003 self.consume_block(token::Paren);
7004 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7005 self.check(&token::OpenDelim(token::Brace))
7007 ("fn", "method", false)
7008 } else if self.check(&token::Colon) {
7012 ("fn` or `struct", "method or struct", true)
7015 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7016 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7018 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7022 err.span_suggestion_short_with_applicability(
7023 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7026 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
7027 err.span_suggestion_with_applicability(
7029 "if you meant to call a macro, try",
7030 format!("{}!", snippet),
7031 // this is the `ambiguous` conditional branch
7032 Applicability::MaybeIncorrect
7035 err.help("if you meant to call a macro, remove the `pub` \
7036 and add a trailing `!` after the identifier");
7042 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7045 /// Parse a foreign item.
7046 crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
7047 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
7049 let attrs = self.parse_outer_attributes()?;
7051 let visibility = self.parse_visibility(false)?;
7053 // FOREIGN STATIC ITEM
7054 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7055 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7056 if self.token.is_keyword(keywords::Const) {
7058 .struct_span_err(self.span, "extern items cannot be `const`")
7059 .span_suggestion_with_applicability(
7061 "try using a static value",
7062 "static".to_owned(),
7063 Applicability::MachineApplicable
7066 self.bump(); // `static` or `const`
7067 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
7069 // FOREIGN FUNCTION ITEM
7070 if self.check_keyword(keywords::Fn) {
7071 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
7073 // FOREIGN TYPE ITEM
7074 if self.check_keyword(keywords::Type) {
7075 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
7078 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7082 ident: keywords::Invalid.ident(),
7083 span: lo.to(self.prev_span),
7084 id: ast::DUMMY_NODE_ID,
7087 node: ForeignItemKind::Macro(mac),
7092 if !attrs.is_empty() {
7093 self.expected_item_err(&attrs);
7101 /// This is the fall-through for parsing items.
7102 fn parse_macro_use_or_failure(
7104 attrs: Vec<Attribute> ,
7105 macros_allowed: bool,
7106 attributes_allowed: bool,
7108 visibility: Visibility
7109 ) -> PResult<'a, Option<P<Item>>> {
7110 if macros_allowed && self.token.is_path_start() {
7111 // MACRO INVOCATION ITEM
7113 let prev_span = self.prev_span;
7114 self.complain_if_pub_macro(&visibility.node, prev_span);
7116 let mac_lo = self.span;
7119 let pth = self.parse_path(PathStyle::Mod)?;
7120 self.expect(&token::Not)?;
7122 // a 'special' identifier (like what `macro_rules!` uses)
7123 // is optional. We should eventually unify invoc syntax
7125 let id = if self.token.is_ident() {
7128 keywords::Invalid.ident() // no special identifier
7130 // eat a matched-delimiter token tree:
7131 let (delim, tts) = self.expect_delimited_token_tree()?;
7132 if delim != MacDelimiter::Brace {
7133 if !self.eat(&token::Semi) {
7134 self.span_err(self.prev_span,
7135 "macros that expand to items must either \
7136 be surrounded with braces or followed by \
7141 let hi = self.prev_span;
7142 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7143 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7144 return Ok(Some(item));
7147 // FAILURE TO PARSE ITEM
7148 match visibility.node {
7149 VisibilityKind::Inherited => {}
7151 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7155 if !attributes_allowed && !attrs.is_empty() {
7156 self.expected_item_err(&attrs);
7161 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7162 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7163 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7165 if self.token.is_path_start() && !self.is_extern_non_path() {
7166 let prev_span = self.prev_span;
7168 let pth = self.parse_path(PathStyle::Mod)?;
7170 if pth.segments.len() == 1 {
7171 if !self.eat(&token::Not) {
7172 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7175 self.expect(&token::Not)?;
7178 if let Some(vis) = vis {
7179 self.complain_if_pub_macro(&vis.node, prev_span);
7184 // eat a matched-delimiter token tree:
7185 let (delim, tts) = self.expect_delimited_token_tree()?;
7186 if delim != MacDelimiter::Brace {
7187 self.expect(&token::Semi)?
7190 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7196 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7197 where F: FnOnce(&mut Self) -> PResult<'a, R>
7199 // Record all tokens we parse when parsing this item.
7200 let mut tokens = Vec::new();
7201 match self.token_cursor.frame.last_token {
7202 LastToken::Collecting(_) => {
7203 panic!("cannot collect tokens recursively yet")
7205 LastToken::Was(ref mut last) => tokens.extend(last.take()),
7207 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7208 let prev = self.token_cursor.stack.len();
7210 let last_token = if self.token_cursor.stack.len() == prev {
7211 &mut self.token_cursor.frame.last_token
7213 &mut self.token_cursor.stack[prev].last_token
7215 let mut tokens = match *last_token {
7216 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7217 LastToken::Was(_) => panic!("our vector went away?"),
7220 // If we're not at EOF our current token wasn't actually consumed by
7221 // `f`, but it'll still be in our list that we pulled out. In that case
7223 if self.token == token::Eof {
7224 *last_token = LastToken::Was(None);
7226 *last_token = LastToken::Was(tokens.pop());
7229 Ok((ret?, tokens.into_iter().collect()))
7232 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7233 let attrs = self.parse_outer_attributes()?;
7235 let (ret, tokens) = self.collect_tokens(|this| {
7236 this.parse_item_(attrs, true, false)
7239 // Once we've parsed an item and recorded the tokens we got while
7240 // parsing we may want to store `tokens` into the item we're about to
7241 // return. Note, though, that we specifically didn't capture tokens
7242 // related to outer attributes. The `tokens` field here may later be
7243 // used with procedural macros to convert this item back into a token
7244 // stream, but during expansion we may be removing attributes as we go
7247 // If we've got inner attributes then the `tokens` we've got above holds
7248 // these inner attributes. If an inner attribute is expanded we won't
7249 // actually remove it from the token stream, so we'll just keep yielding
7250 // it (bad!). To work around this case for now we just avoid recording
7251 // `tokens` if we detect any inner attributes. This should help keep
7252 // expansion correct, but we should fix this bug one day!
7255 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7256 i.tokens = Some(tokens);
7264 fn is_import_coupler(&mut self) -> bool {
7265 self.check(&token::ModSep) &&
7266 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7267 *t == token::BinOp(token::Star))
7272 /// USE_TREE = [`::`] `*` |
7273 /// [`::`] `{` USE_TREE_LIST `}` |
7275 /// PATH `::` `{` USE_TREE_LIST `}` |
7276 /// PATH [`as` IDENT]
7277 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7280 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7281 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7282 self.check(&token::BinOp(token::Star)) ||
7283 self.is_import_coupler() {
7284 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7285 if self.eat(&token::ModSep) {
7286 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7289 if self.eat(&token::BinOp(token::Star)) {
7292 UseTreeKind::Nested(self.parse_use_tree_list()?)
7295 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7296 prefix = self.parse_path(PathStyle::Mod)?;
7298 if self.eat(&token::ModSep) {
7299 if self.eat(&token::BinOp(token::Star)) {
7302 UseTreeKind::Nested(self.parse_use_tree_list()?)
7305 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7309 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7312 /// Parse UseTreeKind::Nested(list)
7314 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7315 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7316 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7317 &token::CloseDelim(token::Brace),
7318 SeqSep::trailing_allowed(token::Comma), |this| {
7319 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7323 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7324 if self.eat_keyword(keywords::As) {
7326 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7328 Ok(Some(ident.gensym()))
7330 _ => self.parse_ident().map(Some),
7337 /// Parses a source module as a crate. This is the main
7338 /// entry point for the parser.
7339 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7342 attrs: self.parse_inner_attributes()?,
7343 module: self.parse_mod_items(&token::Eof, lo)?,
7344 span: lo.to(self.span),
7348 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7349 let ret = match self.token {
7350 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7351 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7358 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7359 match self.parse_optional_str() {
7360 Some((s, style, suf)) => {
7361 let sp = self.prev_span;
7362 self.expect_no_suffix(sp, "string literal", suf);
7366 let msg = "expected string literal";
7367 let mut err = self.fatal(msg);
7368 err.span_label(self.span, msg);