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, 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.is_dummy() {
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.is_dummy() {
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) {
1303 closure_id: ast::DUMMY_NODE_ID,
1304 return_impl_trait_id: ast::DUMMY_NODE_ID,
1311 /// Parse unsafety: `unsafe` or nothing.
1312 fn parse_unsafety(&mut self) -> Unsafety {
1313 if self.eat_keyword(keywords::Unsafe) {
1320 /// Parse the items in a trait declaration
1321 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1322 maybe_whole!(self, NtTraitItem, |x| x);
1323 let attrs = self.parse_outer_attributes()?;
1324 let (mut item, tokens) = self.collect_tokens(|this| {
1325 this.parse_trait_item_(at_end, attrs)
1327 // See `parse_item` for why this clause is here.
1328 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1329 item.tokens = Some(tokens);
1334 fn parse_trait_item_(&mut self,
1336 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1339 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1340 self.parse_trait_item_assoc_ty()?
1341 } else if self.is_const_item() {
1342 self.expect_keyword(keywords::Const)?;
1343 let ident = self.parse_ident()?;
1344 self.expect(&token::Colon)?;
1345 let ty = self.parse_ty()?;
1346 let default = if self.check(&token::Eq) {
1348 let expr = self.parse_expr()?;
1349 self.expect(&token::Semi)?;
1352 self.expect(&token::Semi)?;
1355 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1356 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1357 // trait item macro.
1358 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1360 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1362 let ident = self.parse_ident()?;
1363 let mut generics = self.parse_generics()?;
1365 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1366 // This is somewhat dubious; We don't want to allow
1367 // argument names to be left off if there is a
1369 p.parse_arg_general(false)
1371 generics.where_clause = self.parse_where_clause()?;
1373 let sig = ast::MethodSig {
1383 let body = match self.token {
1387 debug!("parse_trait_methods(): parsing required method");
1390 token::OpenDelim(token::Brace) => {
1391 debug!("parse_trait_methods(): parsing provided method");
1393 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1394 attrs.extend(inner_attrs.iter().cloned());
1398 let token_str = self.this_token_to_string();
1399 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1401 err.span_label(self.span, "expected `;` or `{`");
1405 (ident, ast::TraitItemKind::Method(sig, body), generics)
1409 id: ast::DUMMY_NODE_ID,
1414 span: lo.to(self.prev_span),
1419 /// Parse optional return type [ -> TY ] in function decl
1420 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1421 if self.eat(&token::RArrow) {
1422 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1424 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1429 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1430 self.parse_ty_common(true, true)
1433 /// Parse a type in restricted contexts where `+` is not permitted.
1434 /// Example 1: `&'a TYPE`
1435 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1436 /// Example 2: `value1 as TYPE + value2`
1437 /// `+` is prohibited to avoid interactions with expression grammar.
1438 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1439 self.parse_ty_common(false, true)
1442 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1443 -> PResult<'a, P<Ty>> {
1444 maybe_whole!(self, NtTy, |x| x);
1447 let mut impl_dyn_multi = false;
1448 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1449 // `(TYPE)` is a parenthesized type.
1450 // `(TYPE,)` is a tuple with a single field of type TYPE.
1451 let mut ts = vec![];
1452 let mut last_comma = false;
1453 while self.token != token::CloseDelim(token::Paren) {
1454 ts.push(self.parse_ty()?);
1455 if self.eat(&token::Comma) {
1462 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1463 self.expect(&token::CloseDelim(token::Paren))?;
1465 if ts.len() == 1 && !last_comma {
1466 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1467 let maybe_bounds = allow_plus && self.token.is_like_plus();
1469 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1470 TyKind::Path(None, ref path) if maybe_bounds => {
1471 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1473 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1474 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1475 let path = match bounds[0] {
1476 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1477 _ => self.bug("unexpected lifetime bound"),
1479 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1482 _ => TyKind::Paren(P(ty))
1487 } else if self.eat(&token::Not) {
1490 } else if self.eat(&token::BinOp(token::Star)) {
1492 TyKind::Ptr(self.parse_ptr()?)
1493 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1495 let t = self.parse_ty()?;
1496 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1497 let t = match self.maybe_parse_fixed_length_of_vec()? {
1498 None => TyKind::Slice(t),
1499 Some(length) => TyKind::Array(t, AnonConst {
1500 id: ast::DUMMY_NODE_ID,
1504 self.expect(&token::CloseDelim(token::Bracket))?;
1506 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1509 self.parse_borrowed_pointee()?
1510 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1512 // In order to not be ambiguous, the type must be surrounded by parens.
1513 self.expect(&token::OpenDelim(token::Paren))?;
1515 id: ast::DUMMY_NODE_ID,
1516 value: self.parse_expr()?,
1518 self.expect(&token::CloseDelim(token::Paren))?;
1520 } else if self.eat_keyword(keywords::Underscore) {
1521 // A type to be inferred `_`
1523 } else if self.token_is_bare_fn_keyword() {
1524 // Function pointer type
1525 self.parse_ty_bare_fn(Vec::new())?
1526 } else if self.check_keyword(keywords::For) {
1527 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1528 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1529 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1531 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1532 if self.token_is_bare_fn_keyword() {
1533 self.parse_ty_bare_fn(lifetime_defs)?
1535 let path = self.parse_path(PathStyle::Type)?;
1536 let parse_plus = allow_plus && self.check_plus();
1537 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1539 } else if self.eat_keyword(keywords::Impl) {
1540 // Always parse bounds greedily for better error recovery.
1541 let bounds = self.parse_generic_bounds()?;
1542 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1543 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1544 } else if self.check_keyword(keywords::Dyn) &&
1545 self.look_ahead(1, |t| t.can_begin_bound() &&
1546 !can_continue_type_after_non_fn_ident(t)) {
1547 self.bump(); // `dyn`
1548 // Always parse bounds greedily for better error recovery.
1549 let bounds = self.parse_generic_bounds()?;
1550 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1551 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1552 } else if self.check(&token::Question) ||
1553 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1554 // Bound list (trait object type)
1555 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1556 TraitObjectSyntax::None)
1557 } else if self.eat_lt() {
1559 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1560 TyKind::Path(Some(qself), path)
1561 } else if self.token.is_path_start() {
1563 let path = self.parse_path(PathStyle::Type)?;
1564 if self.eat(&token::Not) {
1565 // Macro invocation in type position
1566 let (delim, tts) = self.expect_delimited_token_tree()?;
1567 let node = Mac_ { path, tts, delim };
1568 TyKind::Mac(respan(lo.to(self.prev_span), node))
1570 // Just a type path or bound list (trait object type) starting with a trait.
1572 // `Trait1 + Trait2 + 'a`
1573 if allow_plus && self.check_plus() {
1574 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1576 TyKind::Path(None, path)
1580 let msg = format!("expected type, found {}", self.this_token_descr());
1581 return Err(self.fatal(&msg));
1584 let span = lo.to(self.prev_span);
1585 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1587 // Try to recover from use of `+` with incorrect priority.
1588 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1589 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1590 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1595 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1596 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1597 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1598 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1600 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1601 bounds.append(&mut self.parse_generic_bounds()?);
1603 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1606 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1607 if !allow_plus && impl_dyn_multi {
1608 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1609 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1610 .span_suggestion_with_applicability(
1612 "use parentheses to disambiguate",
1614 Applicability::MachineApplicable
1619 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1620 // Do not add `+` to expected tokens.
1621 if !allow_plus || !self.token.is_like_plus() {
1626 let bounds = self.parse_generic_bounds()?;
1627 let sum_span = ty.span.to(self.prev_span);
1629 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1630 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1633 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1634 let sum_with_parens = pprust::to_string(|s| {
1635 use print::pprust::PrintState;
1638 s.print_opt_lifetime(lifetime)?;
1639 s.print_mutability(mut_ty.mutbl)?;
1641 s.print_type(&mut_ty.ty)?;
1642 s.print_type_bounds(" +", &bounds)?;
1645 err.span_suggestion_with_applicability(
1647 "try adding parentheses",
1649 Applicability::MachineApplicable
1652 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1653 err.span_label(sum_span, "perhaps you forgot parentheses?");
1656 err.span_label(sum_span, "expected a path");
1663 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1664 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1666 // Do not add `::` to expected tokens.
1667 if !allow_recovery || self.token != token::ModSep {
1670 let ty = match base.to_ty() {
1672 None => return Ok(base),
1675 self.bump(); // `::`
1676 let mut segments = Vec::new();
1677 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1679 let span = ty.span.to(self.prev_span);
1680 let path_span = span.to(span); // use an empty path since `position` == 0
1681 let recovered = base.to_recovered(
1682 Some(QSelf { ty, path_span, position: 0 }),
1683 ast::Path { segments, span },
1687 .struct_span_err(span, "missing angle brackets in associated item path")
1688 .span_suggestion_with_applicability( // this is a best-effort recovery
1689 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1695 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1696 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1697 let mutbl = self.parse_mutability();
1698 let ty = self.parse_ty_no_plus()?;
1699 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1702 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1703 let mutbl = if self.eat_keyword(keywords::Mut) {
1705 } else if self.eat_keyword(keywords::Const) {
1706 Mutability::Immutable
1708 let span = self.prev_span;
1710 "expected mut or const in raw pointer type (use \
1711 `*mut T` or `*const T` as appropriate)");
1712 Mutability::Immutable
1714 let t = self.parse_ty_no_plus()?;
1715 Ok(MutTy { ty: t, mutbl: mutbl })
1718 fn is_named_argument(&mut self) -> bool {
1719 let offset = match self.token {
1720 token::Interpolated(ref nt) => match nt.0 {
1721 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1724 token::BinOp(token::And) | token::AndAnd => 1,
1725 _ if self.token.is_keyword(keywords::Mut) => 1,
1729 self.look_ahead(offset, |t| t.is_ident()) &&
1730 self.look_ahead(offset + 1, |t| t == &token::Colon)
1733 /// This version of parse arg doesn't necessarily require
1734 /// identifier names.
1735 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1736 maybe_whole!(self, NtArg, |x| x);
1738 let (pat, ty) = if require_name || self.is_named_argument() {
1739 debug!("parse_arg_general parse_pat (require_name:{})",
1741 let pat = self.parse_pat()?;
1743 self.expect(&token::Colon)?;
1744 (pat, self.parse_ty()?)
1746 debug!("parse_arg_general ident_to_pat");
1747 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1748 let ty = self.parse_ty()?;
1750 id: ast::DUMMY_NODE_ID,
1751 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
1760 id: ast::DUMMY_NODE_ID,
1764 /// Parse a single function argument
1765 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1766 self.parse_arg_general(true)
1769 /// Parse an argument in a lambda header e.g. |arg, arg|
1770 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1771 let pat = self.parse_pat()?;
1772 let t = if self.eat(&token::Colon) {
1776 id: ast::DUMMY_NODE_ID,
1777 node: TyKind::Infer,
1784 id: ast::DUMMY_NODE_ID
1788 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1789 if self.eat(&token::Semi) {
1790 Ok(Some(self.parse_expr()?))
1796 /// Matches token_lit = LIT_INTEGER | ...
1797 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1798 let out = match self.token {
1799 token::Interpolated(ref nt) => match nt.0 {
1800 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1801 ExprKind::Lit(ref lit) => { lit.node.clone() }
1802 _ => { return self.unexpected_last(&self.token); }
1804 _ => { return self.unexpected_last(&self.token); }
1806 token::Literal(lit, suf) => {
1807 let diag = Some((self.span, &self.sess.span_diagnostic));
1808 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1812 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1817 _ => { return self.unexpected_last(&self.token); }
1824 /// Matches lit = true | false | token_lit
1825 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1827 let lit = if self.eat_keyword(keywords::True) {
1829 } else if self.eat_keyword(keywords::False) {
1830 LitKind::Bool(false)
1832 let lit = self.parse_lit_token()?;
1835 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1838 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1839 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1840 maybe_whole_expr!(self);
1842 let minus_lo = self.span;
1843 let minus_present = self.eat(&token::BinOp(token::Minus));
1845 let literal = P(self.parse_lit()?);
1846 let hi = self.prev_span;
1847 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1850 let minus_hi = self.prev_span;
1851 let unary = self.mk_unary(UnOp::Neg, expr);
1852 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1858 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1860 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1861 let span = self.span;
1863 Ok(Ident::new(ident.name, span))
1865 _ => self.parse_ident(),
1869 /// Parses qualified path.
1870 /// Assumes that the leading `<` has been parsed already.
1872 /// `qualified_path = <type [as trait_ref]>::path`
1877 /// `<T as U>::F::a<S>` (without disambiguator)
1878 /// `<T as U>::F::a::<S>` (with disambiguator)
1879 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1880 let lo = self.prev_span;
1881 let ty = self.parse_ty()?;
1883 // `path` will contain the prefix of the path up to the `>`,
1884 // if any (e.g., `U` in the `<T as U>::*` examples
1885 // above). `path_span` has the span of that path, or an empty
1886 // span in the case of something like `<T>::Bar`.
1887 let (mut path, path_span);
1888 if self.eat_keyword(keywords::As) {
1889 let path_lo = self.span;
1890 path = self.parse_path(PathStyle::Type)?;
1891 path_span = path_lo.to(self.prev_span);
1893 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1894 path_span = self.span.to(self.span);
1897 self.expect(&token::Gt)?;
1898 self.expect(&token::ModSep)?;
1900 let qself = QSelf { ty, path_span, position: path.segments.len() };
1901 self.parse_path_segments(&mut path.segments, style, true)?;
1903 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1906 /// Parses simple paths.
1908 /// `path = [::] segment+`
1909 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1912 /// `a::b::C<D>` (without disambiguator)
1913 /// `a::b::C::<D>` (with disambiguator)
1914 /// `Fn(Args)` (without disambiguator)
1915 /// `Fn::(Args)` (with disambiguator)
1916 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1917 self.parse_path_common(style, true)
1920 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1921 -> PResult<'a, ast::Path> {
1922 maybe_whole!(self, NtPath, |path| {
1923 if style == PathStyle::Mod &&
1924 path.segments.iter().any(|segment| segment.args.is_some()) {
1925 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1930 let lo = self.meta_var_span.unwrap_or(self.span);
1931 let mut segments = Vec::new();
1932 if self.eat(&token::ModSep) {
1933 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1935 self.parse_path_segments(&mut segments, style, enable_warning)?;
1937 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1940 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1941 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1942 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1943 let meta_ident = match self.token {
1944 token::Interpolated(ref nt) => match nt.0 {
1945 token::NtMeta(ref meta) => match meta.node {
1946 ast::MetaItemKind::Word => Some(meta.ident.clone()),
1953 if let Some(path) = meta_ident {
1957 self.parse_path(style)
1960 fn parse_path_segments(&mut self,
1961 segments: &mut Vec<PathSegment>,
1963 enable_warning: bool)
1964 -> PResult<'a, ()> {
1966 segments.push(self.parse_path_segment(style, enable_warning)?);
1968 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1974 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1975 -> PResult<'a, PathSegment> {
1976 let ident = self.parse_path_segment_ident()?;
1978 let is_args_start = |token: &token::Token| match *token {
1979 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1982 let check_args_start = |this: &mut Self| {
1983 this.expected_tokens.extend_from_slice(
1984 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1986 is_args_start(&this.token)
1989 Ok(if style == PathStyle::Type && check_args_start(self) ||
1990 style != PathStyle::Mod && self.check(&token::ModSep)
1991 && self.look_ahead(1, |t| is_args_start(t)) {
1992 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1994 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1995 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1996 .span_label(self.prev_span, "try removing `::`").emit();
1999 let args = if self.eat_lt() {
2001 let (args, bindings) = self.parse_generic_args()?;
2003 let span = lo.to(self.prev_span);
2004 AngleBracketedArgs { args, bindings, span }.into()
2008 let inputs = self.parse_seq_to_before_tokens(
2009 &[&token::CloseDelim(token::Paren)],
2010 SeqSep::trailing_allowed(token::Comma),
2011 TokenExpectType::Expect,
2014 let output = if self.eat(&token::RArrow) {
2015 Some(self.parse_ty_common(false, false)?)
2019 let span = lo.to(self.prev_span);
2020 ParenthesisedArgs { inputs, output, span }.into()
2023 PathSegment { ident, args }
2025 // Generic arguments are not found.
2026 PathSegment::from_ident(ident)
2030 crate fn check_lifetime(&mut self) -> bool {
2031 self.expected_tokens.push(TokenType::Lifetime);
2032 self.token.is_lifetime()
2035 /// Parse single lifetime 'a or panic.
2036 crate fn expect_lifetime(&mut self) -> Lifetime {
2037 if let Some(ident) = self.token.lifetime() {
2038 let span = self.span;
2040 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2042 self.span_bug(self.span, "not a lifetime")
2046 fn eat_label(&mut self) -> Option<Label> {
2047 if let Some(ident) = self.token.lifetime() {
2048 let span = self.span;
2050 Some(Label { ident: Ident::new(ident.name, span) })
2056 /// Parse mutability (`mut` or nothing).
2057 fn parse_mutability(&mut self) -> Mutability {
2058 if self.eat_keyword(keywords::Mut) {
2061 Mutability::Immutable
2065 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2066 if let token::Literal(token::Integer(name), None) = self.token {
2068 Ok(Ident::new(name, self.prev_span))
2070 self.parse_ident_common(false)
2074 /// Parse ident (COLON expr)?
2075 fn parse_field(&mut self) -> PResult<'a, Field> {
2076 let attrs = self.parse_outer_attributes()?;
2079 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2080 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2081 let fieldname = self.parse_field_name()?;
2083 (fieldname, self.parse_expr()?, false)
2085 let fieldname = self.parse_ident_common(false)?;
2087 // Mimic `x: x` for the `x` field shorthand.
2088 let path = ast::Path::from_ident(fieldname);
2089 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2090 (fieldname, expr, true)
2094 span: lo.to(expr.span),
2097 attrs: attrs.into(),
2101 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2102 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2105 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2106 ExprKind::Unary(unop, expr)
2109 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2110 ExprKind::Binary(binop, lhs, rhs)
2113 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2114 ExprKind::Call(f, args)
2117 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2118 ExprKind::Index(expr, idx)
2121 fn mk_range(&mut self,
2122 start: Option<P<Expr>>,
2123 end: Option<P<Expr>>,
2124 limits: RangeLimits)
2125 -> PResult<'a, ast::ExprKind> {
2126 if end.is_none() && limits == RangeLimits::Closed {
2127 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2129 Ok(ExprKind::Range(start, end, limits))
2133 fn mk_assign_op(&mut self, binop: ast::BinOp,
2134 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2135 ExprKind::AssignOp(binop, lhs, rhs)
2138 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2140 id: ast::DUMMY_NODE_ID,
2141 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2147 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2148 let delim = match self.token {
2149 token::OpenDelim(delim) => delim,
2151 let msg = "expected open delimiter";
2152 let mut err = self.fatal(msg);
2153 err.span_label(self.span, msg);
2157 let delimited = match self.parse_token_tree() {
2158 TokenTree::Delimited(_, delimited) => delimited,
2159 _ => unreachable!(),
2161 let delim = match delim {
2162 token::Paren => MacDelimiter::Parenthesis,
2163 token::Bracket => MacDelimiter::Bracket,
2164 token::Brace => MacDelimiter::Brace,
2165 token::NoDelim => self.bug("unexpected no delimiter"),
2167 Ok((delim, delimited.stream().into()))
2170 /// At the bottom (top?) of the precedence hierarchy,
2171 /// parse things like parenthesized exprs,
2172 /// macros, return, etc.
2174 /// NB: This does not parse outer attributes,
2175 /// and is private because it only works
2176 /// correctly if called from parse_dot_or_call_expr().
2177 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2178 maybe_whole_expr!(self);
2180 // Outer attributes are already parsed and will be
2181 // added to the return value after the fact.
2183 // Therefore, prevent sub-parser from parsing
2184 // attributes by giving them a empty "already parsed" list.
2185 let mut attrs = ThinVec::new();
2188 let mut hi = self.span;
2192 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2194 token::OpenDelim(token::Paren) => {
2197 attrs.extend(self.parse_inner_attributes()?);
2199 // (e) is parenthesized e
2200 // (e,) is a tuple with only one field, e
2201 let mut es = vec![];
2202 let mut trailing_comma = false;
2203 while self.token != token::CloseDelim(token::Paren) {
2204 es.push(self.parse_expr()?);
2205 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2206 if self.check(&token::Comma) {
2207 trailing_comma = true;
2211 trailing_comma = false;
2217 hi = self.prev_span;
2218 ex = if es.len() == 1 && !trailing_comma {
2219 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2224 token::OpenDelim(token::Brace) => {
2225 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2227 token::BinOp(token::Or) | token::OrOr => {
2228 return self.parse_lambda_expr(attrs);
2230 token::OpenDelim(token::Bracket) => {
2233 attrs.extend(self.parse_inner_attributes()?);
2235 if self.check(&token::CloseDelim(token::Bracket)) {
2238 ex = ExprKind::Array(Vec::new());
2241 let first_expr = self.parse_expr()?;
2242 if self.check(&token::Semi) {
2243 // Repeating array syntax: [ 0; 512 ]
2245 let count = AnonConst {
2246 id: ast::DUMMY_NODE_ID,
2247 value: self.parse_expr()?,
2249 self.expect(&token::CloseDelim(token::Bracket))?;
2250 ex = ExprKind::Repeat(first_expr, count);
2251 } else if self.check(&token::Comma) {
2252 // Vector with two or more elements.
2254 let remaining_exprs = self.parse_seq_to_end(
2255 &token::CloseDelim(token::Bracket),
2256 SeqSep::trailing_allowed(token::Comma),
2257 |p| Ok(p.parse_expr()?)
2259 let mut exprs = vec![first_expr];
2260 exprs.extend(remaining_exprs);
2261 ex = ExprKind::Array(exprs);
2263 // Vector with one element.
2264 self.expect(&token::CloseDelim(token::Bracket))?;
2265 ex = ExprKind::Array(vec![first_expr]);
2268 hi = self.prev_span;
2272 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2274 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2276 if self.span.edition() >= Edition::Edition2018 &&
2277 self.check_keyword(keywords::Async)
2279 if self.is_async_block() { // check for `async {` and `async move {`
2280 return self.parse_async_block(attrs);
2282 return self.parse_lambda_expr(attrs);
2285 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2286 return self.parse_lambda_expr(attrs);
2288 if self.eat_keyword(keywords::If) {
2289 return self.parse_if_expr(attrs);
2291 if self.eat_keyword(keywords::For) {
2292 let lo = self.prev_span;
2293 return self.parse_for_expr(None, lo, attrs);
2295 if self.eat_keyword(keywords::While) {
2296 let lo = self.prev_span;
2297 return self.parse_while_expr(None, lo, attrs);
2299 if let Some(label) = self.eat_label() {
2300 let lo = label.ident.span;
2301 self.expect(&token::Colon)?;
2302 if self.eat_keyword(keywords::While) {
2303 return self.parse_while_expr(Some(label), lo, attrs)
2305 if self.eat_keyword(keywords::For) {
2306 return self.parse_for_expr(Some(label), lo, attrs)
2308 if self.eat_keyword(keywords::Loop) {
2309 return self.parse_loop_expr(Some(label), lo, attrs)
2311 if self.token == token::OpenDelim(token::Brace) {
2312 return self.parse_block_expr(Some(label),
2314 BlockCheckMode::Default,
2317 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2318 let mut err = self.fatal(msg);
2319 err.span_label(self.span, msg);
2322 if self.eat_keyword(keywords::Loop) {
2323 let lo = self.prev_span;
2324 return self.parse_loop_expr(None, lo, attrs);
2326 if self.eat_keyword(keywords::Continue) {
2327 let label = self.eat_label();
2328 let ex = ExprKind::Continue(label);
2329 let hi = self.prev_span;
2330 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2332 if self.eat_keyword(keywords::Match) {
2333 return self.parse_match_expr(attrs);
2335 if self.eat_keyword(keywords::Unsafe) {
2336 return self.parse_block_expr(
2339 BlockCheckMode::Unsafe(ast::UserProvided),
2342 if self.is_catch_expr() {
2344 assert!(self.eat_keyword(keywords::Do));
2345 assert!(self.eat_keyword(keywords::Catch));
2346 return self.parse_catch_expr(lo, attrs);
2348 if self.eat_keyword(keywords::Return) {
2349 if self.token.can_begin_expr() {
2350 let e = self.parse_expr()?;
2352 ex = ExprKind::Ret(Some(e));
2354 ex = ExprKind::Ret(None);
2356 } else if self.eat_keyword(keywords::Break) {
2357 let label = self.eat_label();
2358 let e = if self.token.can_begin_expr()
2359 && !(self.token == token::OpenDelim(token::Brace)
2360 && self.restrictions.contains(
2361 Restrictions::NO_STRUCT_LITERAL)) {
2362 Some(self.parse_expr()?)
2366 ex = ExprKind::Break(label, e);
2367 hi = self.prev_span;
2368 } else if self.eat_keyword(keywords::Yield) {
2369 if self.token.can_begin_expr() {
2370 let e = self.parse_expr()?;
2372 ex = ExprKind::Yield(Some(e));
2374 ex = ExprKind::Yield(None);
2376 } else if self.token.is_keyword(keywords::Let) {
2377 // Catch this syntax error here, instead of in `parse_ident`, so
2378 // that we can explicitly mention that let is not to be used as an expression
2379 let mut db = self.fatal("expected expression, found statement (`let`)");
2380 db.span_label(self.span, "expected expression");
2381 db.note("variable declaration using `let` is a statement");
2383 } else if self.token.is_path_start() {
2384 let pth = self.parse_path(PathStyle::Expr)?;
2386 // `!`, as an operator, is prefix, so we know this isn't that
2387 if self.eat(&token::Not) {
2388 // MACRO INVOCATION expression
2389 let (delim, tts) = self.expect_delimited_token_tree()?;
2390 let hi = self.prev_span;
2391 let node = Mac_ { path: pth, tts, delim };
2392 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2394 if self.check(&token::OpenDelim(token::Brace)) {
2395 // This is a struct literal, unless we're prohibited
2396 // from parsing struct literals here.
2397 let prohibited = self.restrictions.contains(
2398 Restrictions::NO_STRUCT_LITERAL
2401 return self.parse_struct_expr(lo, pth, attrs);
2406 ex = ExprKind::Path(None, pth);
2408 match self.parse_literal_maybe_minus() {
2411 ex = expr.node.clone();
2414 self.cancel(&mut err);
2415 let msg = format!("expected expression, found {}",
2416 self.this_token_descr());
2417 let mut err = self.fatal(&msg);
2418 err.span_label(self.span, "expected expression");
2426 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2427 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2432 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2433 -> PResult<'a, P<Expr>> {
2434 let struct_sp = lo.to(self.prev_span);
2436 let mut fields = Vec::new();
2437 let mut base = None;
2439 attrs.extend(self.parse_inner_attributes()?);
2441 while self.token != token::CloseDelim(token::Brace) {
2442 if self.eat(&token::DotDot) {
2443 let exp_span = self.prev_span;
2444 match self.parse_expr() {
2450 self.recover_stmt();
2453 if self.token == token::Comma {
2454 let mut err = self.sess.span_diagnostic.mut_span_err(
2455 exp_span.to(self.prev_span),
2456 "cannot use a comma after the base struct",
2458 err.span_suggestion_short_with_applicability(
2460 "remove this comma",
2462 Applicability::MachineApplicable
2464 err.note("the base struct must always be the last field");
2466 self.recover_stmt();
2471 match self.parse_field() {
2472 Ok(f) => fields.push(f),
2474 e.span_label(struct_sp, "while parsing this struct");
2477 // If the next token is a comma, then try to parse
2478 // what comes next as additional fields, rather than
2479 // bailing out until next `}`.
2480 if self.token != token::Comma {
2481 self.recover_stmt();
2487 match self.expect_one_of(&[token::Comma],
2488 &[token::CloseDelim(token::Brace)]) {
2492 self.recover_stmt();
2498 let span = lo.to(self.span);
2499 self.expect(&token::CloseDelim(token::Brace))?;
2500 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2503 fn parse_or_use_outer_attributes(&mut self,
2504 already_parsed_attrs: Option<ThinVec<Attribute>>)
2505 -> PResult<'a, ThinVec<Attribute>> {
2506 if let Some(attrs) = already_parsed_attrs {
2509 self.parse_outer_attributes().map(|a| a.into())
2513 /// Parse a block or unsafe block
2514 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2515 lo: Span, blk_mode: BlockCheckMode,
2516 outer_attrs: ThinVec<Attribute>)
2517 -> PResult<'a, P<Expr>> {
2518 self.expect(&token::OpenDelim(token::Brace))?;
2520 let mut attrs = outer_attrs;
2521 attrs.extend(self.parse_inner_attributes()?);
2523 let blk = self.parse_block_tail(lo, blk_mode)?;
2524 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2527 /// parse a.b or a(13) or a[4] or just a
2528 fn parse_dot_or_call_expr(&mut self,
2529 already_parsed_attrs: Option<ThinVec<Attribute>>)
2530 -> PResult<'a, P<Expr>> {
2531 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2533 let b = self.parse_bottom_expr();
2534 let (span, b) = self.interpolated_or_expr_span(b)?;
2535 self.parse_dot_or_call_expr_with(b, span, attrs)
2538 fn parse_dot_or_call_expr_with(&mut self,
2541 mut attrs: ThinVec<Attribute>)
2542 -> PResult<'a, P<Expr>> {
2543 // Stitch the list of outer attributes onto the return value.
2544 // A little bit ugly, but the best way given the current code
2546 self.parse_dot_or_call_expr_with_(e0, lo)
2548 expr.map(|mut expr| {
2549 attrs.extend::<Vec<_>>(expr.attrs.into());
2552 ExprKind::If(..) | ExprKind::IfLet(..) => {
2553 if !expr.attrs.is_empty() {
2554 // Just point to the first attribute in there...
2555 let span = expr.attrs[0].span;
2558 "attributes are not yet allowed on `if` \
2569 // Assuming we have just parsed `.`, continue parsing into an expression.
2570 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2571 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2572 Ok(match self.token {
2573 token::OpenDelim(token::Paren) => {
2574 // Method call `expr.f()`
2575 let mut args = self.parse_unspanned_seq(
2576 &token::OpenDelim(token::Paren),
2577 &token::CloseDelim(token::Paren),
2578 SeqSep::trailing_allowed(token::Comma),
2579 |p| Ok(p.parse_expr()?)
2581 args.insert(0, self_arg);
2583 let span = lo.to(self.prev_span);
2584 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2587 // Field access `expr.f`
2588 if let Some(args) = segment.args {
2589 self.span_err(args.span(),
2590 "field expressions may not have generic arguments");
2593 let span = lo.to(self.prev_span);
2594 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2599 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2604 while self.eat(&token::Question) {
2605 let hi = self.prev_span;
2606 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2610 if self.eat(&token::Dot) {
2612 token::Ident(..) => {
2613 e = self.parse_dot_suffix(e, lo)?;
2615 token::Literal(token::Integer(name), _) => {
2616 let span = self.span;
2618 let field = ExprKind::Field(e, Ident::new(name, span));
2619 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2621 token::Literal(token::Float(n), _suf) => {
2623 let fstr = n.as_str();
2624 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2625 &format!("unexpected token: `{}`", n));
2626 err.span_label(self.prev_span, "unexpected token");
2627 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2628 let float = match fstr.parse::<f64>().ok() {
2632 let sugg = pprust::to_string(|s| {
2633 use print::pprust::PrintState;
2637 s.print_usize(float.trunc() as usize)?;
2640 s.s.word(fstr.splitn(2, ".").last().unwrap())
2642 err.span_suggestion_with_applicability(
2643 lo.to(self.prev_span),
2644 "try parenthesizing the first index",
2646 Applicability::MachineApplicable
2653 // FIXME Could factor this out into non_fatal_unexpected or something.
2654 let actual = self.this_token_to_string();
2655 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2660 if self.expr_is_complete(&e) { break; }
2663 token::OpenDelim(token::Paren) => {
2664 let es = self.parse_unspanned_seq(
2665 &token::OpenDelim(token::Paren),
2666 &token::CloseDelim(token::Paren),
2667 SeqSep::trailing_allowed(token::Comma),
2668 |p| Ok(p.parse_expr()?)
2670 hi = self.prev_span;
2672 let nd = self.mk_call(e, es);
2673 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2677 // Could be either an index expression or a slicing expression.
2678 token::OpenDelim(token::Bracket) => {
2680 let ix = self.parse_expr()?;
2682 self.expect(&token::CloseDelim(token::Bracket))?;
2683 let index = self.mk_index(e, ix);
2684 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2692 crate fn process_potential_macro_variable(&mut self) {
2693 let (token, span) = match self.token {
2694 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2695 self.look_ahead(1, |t| t.is_ident()) => {
2697 let name = match self.token {
2698 token::Ident(ident, _) => ident,
2701 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2702 err.span_label(self.span, "unknown macro variable");
2706 token::Interpolated(ref nt) => {
2707 self.meta_var_span = Some(self.span);
2708 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2709 // and lifetime tokens, so the former are never encountered during normal parsing.
2711 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2712 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2722 /// parse a single token tree from the input.
2723 crate fn parse_token_tree(&mut self) -> TokenTree {
2725 token::OpenDelim(..) => {
2726 let frame = mem::replace(&mut self.token_cursor.frame,
2727 self.token_cursor.stack.pop().unwrap());
2728 self.span = frame.span;
2730 TokenTree::Delimited(frame.span, Delimited {
2732 tts: frame.tree_cursor.original_stream().into(),
2735 token::CloseDelim(_) | token::Eof => unreachable!(),
2737 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2739 TokenTree::Token(span, token)
2744 // parse a stream of tokens into a list of TokenTree's,
2746 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2747 let mut tts = Vec::new();
2748 while self.token != token::Eof {
2749 tts.push(self.parse_token_tree());
2754 pub fn parse_tokens(&mut self) -> TokenStream {
2755 let mut result = Vec::new();
2758 token::Eof | token::CloseDelim(..) => break,
2759 _ => result.push(self.parse_token_tree().into()),
2762 TokenStream::concat(result)
2765 /// Parse a prefix-unary-operator expr
2766 fn parse_prefix_expr(&mut self,
2767 already_parsed_attrs: Option<ThinVec<Attribute>>)
2768 -> PResult<'a, P<Expr>> {
2769 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2771 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2772 let (hi, ex) = match self.token {
2775 let e = self.parse_prefix_expr(None);
2776 let (span, e) = self.interpolated_or_expr_span(e)?;
2777 (lo.to(span), self.mk_unary(UnOp::Not, e))
2779 // Suggest `!` for bitwise negation when encountering a `~`
2782 let e = self.parse_prefix_expr(None);
2783 let (span, e) = self.interpolated_or_expr_span(e)?;
2784 let span_of_tilde = lo;
2785 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2786 "`~` cannot be used as a unary operator");
2787 err.span_suggestion_short_with_applicability(
2789 "use `!` to perform bitwise negation",
2791 Applicability::MachineApplicable
2794 (lo.to(span), self.mk_unary(UnOp::Not, e))
2796 token::BinOp(token::Minus) => {
2798 let e = self.parse_prefix_expr(None);
2799 let (span, e) = self.interpolated_or_expr_span(e)?;
2800 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2802 token::BinOp(token::Star) => {
2804 let e = self.parse_prefix_expr(None);
2805 let (span, e) = self.interpolated_or_expr_span(e)?;
2806 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2808 token::BinOp(token::And) | token::AndAnd => {
2810 let m = self.parse_mutability();
2811 let e = self.parse_prefix_expr(None);
2812 let (span, e) = self.interpolated_or_expr_span(e)?;
2813 (lo.to(span), ExprKind::AddrOf(m, e))
2815 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2817 let place = self.parse_expr_res(
2818 Restrictions::NO_STRUCT_LITERAL,
2821 let blk = self.parse_block()?;
2822 let span = blk.span;
2823 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2824 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2826 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2828 let e = self.parse_prefix_expr(None);
2829 let (span, e) = self.interpolated_or_expr_span(e)?;
2830 (lo.to(span), ExprKind::Box(e))
2832 token::Ident(..) if self.token.is_ident_named("not") => {
2833 // `not` is just an ordinary identifier in Rust-the-language,
2834 // but as `rustc`-the-compiler, we can issue clever diagnostics
2835 // for confused users who really want to say `!`
2836 let token_cannot_continue_expr = |t: &token::Token| match *t {
2837 // These tokens can start an expression after `!`, but
2838 // can't continue an expression after an ident
2839 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2840 token::Literal(..) | token::Pound => true,
2841 token::Interpolated(ref nt) => match nt.0 {
2842 token::NtIdent(..) | token::NtExpr(..) |
2843 token::NtBlock(..) | token::NtPath(..) => true,
2848 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2849 if cannot_continue_expr {
2851 // Emit the error ...
2852 let mut err = self.diagnostic()
2853 .struct_span_err(self.span,
2854 &format!("unexpected {} after identifier",
2855 self.this_token_descr()));
2856 // span the `not` plus trailing whitespace to avoid
2857 // trailing whitespace after the `!` in our suggestion
2858 let to_replace = self.sess.codemap()
2859 .span_until_non_whitespace(lo.to(self.span));
2860 err.span_suggestion_short_with_applicability(
2862 "use `!` to perform logical negation",
2864 Applicability::MachineApplicable
2867 // —and recover! (just as if we were in the block
2868 // for the `token::Not` arm)
2869 let e = self.parse_prefix_expr(None);
2870 let (span, e) = self.interpolated_or_expr_span(e)?;
2871 (lo.to(span), self.mk_unary(UnOp::Not, e))
2873 return self.parse_dot_or_call_expr(Some(attrs));
2876 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2878 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2881 /// Parse an associative expression
2883 /// This parses an expression accounting for associativity and precedence of the operators in
2885 fn parse_assoc_expr(&mut self,
2886 already_parsed_attrs: Option<ThinVec<Attribute>>)
2887 -> PResult<'a, P<Expr>> {
2888 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2891 /// Parse an associative expression with operators of at least `min_prec` precedence
2892 fn parse_assoc_expr_with(&mut self,
2895 -> PResult<'a, P<Expr>> {
2896 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2899 let attrs = match lhs {
2900 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2903 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2904 return self.parse_prefix_range_expr(attrs);
2906 self.parse_prefix_expr(attrs)?
2910 if self.expr_is_complete(&lhs) {
2911 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2914 self.expected_tokens.push(TokenType::Operator);
2915 while let Some(op) = AssocOp::from_token(&self.token) {
2917 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2918 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2919 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2920 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2921 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2922 (PrevTokenKind::Interpolated, _) => self.prev_span,
2923 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2924 if path.segments.len() == 1 => self.prev_span,
2928 let cur_op_span = self.span;
2929 let restrictions = if op.is_assign_like() {
2930 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2934 if op.precedence() < min_prec {
2937 // Check for deprecated `...` syntax
2938 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2939 self.err_dotdotdot_syntax(self.span);
2943 if op.is_comparison() {
2944 self.check_no_chained_comparison(&lhs, &op);
2947 if op == AssocOp::As {
2948 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2950 } else if op == AssocOp::Colon {
2951 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2954 err.span_label(self.span,
2955 "expecting a type here because of type ascription");
2956 let cm = self.sess.codemap();
2957 let cur_pos = cm.lookup_char_pos(self.span.lo());
2958 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2959 if cur_pos.line != op_pos.line {
2960 err.span_suggestion_with_applicability(
2962 "try using a semicolon",
2964 Applicability::MaybeIncorrect // speculative
2971 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2972 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2973 // generalise it to the Fixity::None code.
2975 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2976 // two variants are handled with `parse_prefix_range_expr` call above.
2977 let rhs = if self.is_at_start_of_range_notation_rhs() {
2978 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2979 LhsExpr::NotYetParsed)?)
2983 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2988 let limits = if op == AssocOp::DotDot {
2989 RangeLimits::HalfOpen
2994 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2995 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2999 let rhs = match op.fixity() {
3000 Fixity::Right => self.with_res(
3001 restrictions - Restrictions::STMT_EXPR,
3003 this.parse_assoc_expr_with(op.precedence(),
3004 LhsExpr::NotYetParsed)
3006 Fixity::Left => self.with_res(
3007 restrictions - Restrictions::STMT_EXPR,
3009 this.parse_assoc_expr_with(op.precedence() + 1,
3010 LhsExpr::NotYetParsed)
3012 // We currently have no non-associative operators that are not handled above by
3013 // the special cases. The code is here only for future convenience.
3014 Fixity::None => self.with_res(
3015 restrictions - Restrictions::STMT_EXPR,
3017 this.parse_assoc_expr_with(op.precedence() + 1,
3018 LhsExpr::NotYetParsed)
3022 let span = lhs_span.to(rhs.span);
3024 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3025 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3026 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3027 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3028 AssocOp::Greater | AssocOp::GreaterEqual => {
3029 let ast_op = op.to_ast_binop().unwrap();
3030 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
3031 self.mk_expr(span, binary, ThinVec::new())
3034 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3035 AssocOp::ObsoleteInPlace =>
3036 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3037 AssocOp::AssignOp(k) => {
3039 token::Plus => BinOpKind::Add,
3040 token::Minus => BinOpKind::Sub,
3041 token::Star => BinOpKind::Mul,
3042 token::Slash => BinOpKind::Div,
3043 token::Percent => BinOpKind::Rem,
3044 token::Caret => BinOpKind::BitXor,
3045 token::And => BinOpKind::BitAnd,
3046 token::Or => BinOpKind::BitOr,
3047 token::Shl => BinOpKind::Shl,
3048 token::Shr => BinOpKind::Shr,
3050 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3051 self.mk_expr(span, aopexpr, ThinVec::new())
3053 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3054 self.bug("AssocOp should have been handled by special case")
3058 if op.fixity() == Fixity::None { break }
3063 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3064 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3065 -> PResult<'a, P<Expr>> {
3066 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3067 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3070 // Save the state of the parser before parsing type normally, in case there is a
3071 // LessThan comparison after this cast.
3072 let parser_snapshot_before_type = self.clone();
3073 match self.parse_ty_no_plus() {
3075 Ok(mk_expr(self, rhs))
3077 Err(mut type_err) => {
3078 // Rewind to before attempting to parse the type with generics, to recover
3079 // from situations like `x as usize < y` in which we first tried to parse
3080 // `usize < y` as a type with generic arguments.
3081 let parser_snapshot_after_type = self.clone();
3082 mem::replace(self, parser_snapshot_before_type);
3084 match self.parse_path(PathStyle::Expr) {
3086 let (op_noun, op_verb) = match self.token {
3087 token::Lt => ("comparison", "comparing"),
3088 token::BinOp(token::Shl) => ("shift", "shifting"),
3090 // We can end up here even without `<` being the next token, for
3091 // example because `parse_ty_no_plus` returns `Err` on keywords,
3092 // but `parse_path` returns `Ok` on them due to error recovery.
3093 // Return original error and parser state.
3094 mem::replace(self, parser_snapshot_after_type);
3095 return Err(type_err);
3099 // Successfully parsed the type path leaving a `<` yet to parse.
3102 // Report non-fatal diagnostics, keep `x as usize` as an expression
3103 // in AST and continue parsing.
3104 let msg = format!("`<` is interpreted as a start of generic \
3105 arguments for `{}`, not a {}", path, op_noun);
3106 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3107 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3108 "interpreted as generic arguments");
3109 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3111 let expr = mk_expr(self, P(Ty {
3113 node: TyKind::Path(None, path),
3114 id: ast::DUMMY_NODE_ID
3117 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3118 .unwrap_or(pprust::expr_to_string(&expr));
3119 err.span_suggestion_with_applicability(
3121 &format!("try {} the cast value", op_verb),
3122 format!("({})", expr_str),
3123 Applicability::MachineApplicable
3129 Err(mut path_err) => {
3130 // Couldn't parse as a path, return original error and parser state.
3132 mem::replace(self, parser_snapshot_after_type);
3140 /// Produce an error if comparison operators are chained (RFC #558).
3141 /// We only need to check lhs, not rhs, because all comparison ops
3142 /// have same precedence and are left-associative
3143 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3144 debug_assert!(outer_op.is_comparison(),
3145 "check_no_chained_comparison: {:?} is not comparison",
3148 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3149 // respan to include both operators
3150 let op_span = op.span.to(self.span);
3151 let mut err = self.diagnostic().struct_span_err(op_span,
3152 "chained comparison operators require parentheses");
3153 if op.node == BinOpKind::Lt &&
3154 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3155 *outer_op == AssocOp::Greater // even in a case like the following:
3156 { // Foo<Bar<Baz<Qux, ()>>>
3158 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3159 err.help("or use `(...)` if you meant to specify fn arguments");
3167 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3168 fn parse_prefix_range_expr(&mut self,
3169 already_parsed_attrs: Option<ThinVec<Attribute>>)
3170 -> PResult<'a, P<Expr>> {
3171 // Check for deprecated `...` syntax
3172 if self.token == token::DotDotDot {
3173 self.err_dotdotdot_syntax(self.span);
3176 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3177 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3179 let tok = self.token.clone();
3180 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3182 let mut hi = self.span;
3184 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3185 // RHS must be parsed with more associativity than the dots.
3186 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3187 Some(self.parse_assoc_expr_with(next_prec,
3188 LhsExpr::NotYetParsed)
3196 let limits = if tok == token::DotDot {
3197 RangeLimits::HalfOpen
3202 let r = try!(self.mk_range(None,
3205 Ok(self.mk_expr(lo.to(hi), r, attrs))
3208 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3209 if self.token.can_begin_expr() {
3210 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3211 if self.token == token::OpenDelim(token::Brace) {
3212 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3220 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3221 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3222 if self.check_keyword(keywords::Let) {
3223 return self.parse_if_let_expr(attrs);
3225 let lo = self.prev_span;
3226 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3228 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3229 // verify that the last statement is either an implicit return (no `;`) or an explicit
3230 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3231 // the dead code lint.
3232 if self.eat_keyword(keywords::Else) || !cond.returns() {
3233 let sp = self.sess.codemap().next_point(lo);
3234 let mut err = self.diagnostic()
3235 .struct_span_err(sp, "missing condition for `if` statemement");
3236 err.span_label(sp, "expected if condition here");
3239 let not_block = self.token != token::OpenDelim(token::Brace);
3240 let thn = self.parse_block().map_err(|mut err| {
3242 err.span_label(lo, "this `if` statement has a condition, but no block");
3246 let mut els: Option<P<Expr>> = None;
3247 let mut hi = thn.span;
3248 if self.eat_keyword(keywords::Else) {
3249 let elexpr = self.parse_else_expr()?;
3253 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3256 /// Parse an 'if let' expression ('if' token already eaten)
3257 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3258 -> PResult<'a, P<Expr>> {
3259 let lo = self.prev_span;
3260 self.expect_keyword(keywords::Let)?;
3261 let pats = self.parse_pats()?;
3262 self.expect(&token::Eq)?;
3263 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3264 let thn = self.parse_block()?;
3265 let (hi, els) = if self.eat_keyword(keywords::Else) {
3266 let expr = self.parse_else_expr()?;
3267 (expr.span, Some(expr))
3271 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3274 // `move |args| expr`
3275 fn parse_lambda_expr(&mut self,
3276 attrs: ThinVec<Attribute>)
3277 -> PResult<'a, P<Expr>>
3280 let movability = if self.eat_keyword(keywords::Static) {
3285 let asyncness = if self.span.edition() >= Edition::Edition2018 {
3286 self.parse_asyncness()
3290 let capture_clause = if self.eat_keyword(keywords::Move) {
3295 let decl = self.parse_fn_block_decl()?;
3296 let decl_hi = self.prev_span;
3297 let body = match decl.output {
3298 FunctionRetTy::Default(_) => {
3299 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3300 self.parse_expr_res(restrictions, None)?
3303 // If an explicit return type is given, require a
3304 // block to appear (RFC 968).
3305 let body_lo = self.span;
3306 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3312 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3316 // `else` token already eaten
3317 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3318 if self.eat_keyword(keywords::If) {
3319 return self.parse_if_expr(ThinVec::new());
3321 let blk = self.parse_block()?;
3322 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3326 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3327 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3329 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3330 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3332 let pat = self.parse_top_level_pat()?;
3333 if !self.eat_keyword(keywords::In) {
3334 let in_span = self.prev_span.between(self.span);
3335 let mut err = self.sess.span_diagnostic
3336 .struct_span_err(in_span, "missing `in` in `for` loop");
3337 err.span_suggestion_short_with_applicability(
3338 in_span, "try adding `in` here", " in ".into(),
3339 // has been misleading, at least in the past (closed Issue #48492)
3340 Applicability::MaybeIncorrect
3344 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3345 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3346 attrs.extend(iattrs);
3348 let hi = self.prev_span;
3349 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3352 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3353 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3355 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3356 if self.token.is_keyword(keywords::Let) {
3357 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3359 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3360 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3361 attrs.extend(iattrs);
3362 let span = span_lo.to(body.span);
3363 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3366 /// Parse a 'while let' expression ('while' token already eaten)
3367 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3369 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3370 self.expect_keyword(keywords::Let)?;
3371 let pats = self.parse_pats()?;
3372 self.expect(&token::Eq)?;
3373 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3374 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3375 attrs.extend(iattrs);
3376 let span = span_lo.to(body.span);
3377 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3380 // parse `loop {...}`, `loop` token already eaten
3381 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3383 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3384 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3385 attrs.extend(iattrs);
3386 let span = span_lo.to(body.span);
3387 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3390 /// Parse an `async move {...}` expression
3391 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3392 -> PResult<'a, P<Expr>>
3394 let span_lo = self.span;
3395 self.expect_keyword(keywords::Async)?;
3396 let capture_clause = if self.eat_keyword(keywords::Move) {
3401 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3402 attrs.extend(iattrs);
3404 span_lo.to(body.span),
3405 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3408 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3409 fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3410 -> PResult<'a, P<Expr>>
3412 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3413 attrs.extend(iattrs);
3414 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3417 // `match` token already eaten
3418 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3419 let match_span = self.prev_span;
3420 let lo = self.prev_span;
3421 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3423 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3424 if self.token == token::Token::Semi {
3425 e.span_suggestion_short_with_applicability(
3427 "try removing this `match`",
3429 Applicability::MaybeIncorrect // speculative
3434 attrs.extend(self.parse_inner_attributes()?);
3436 let mut arms: Vec<Arm> = Vec::new();
3437 while self.token != token::CloseDelim(token::Brace) {
3438 match self.parse_arm() {
3439 Ok(arm) => arms.push(arm),
3441 // Recover by skipping to the end of the block.
3443 self.recover_stmt();
3444 let span = lo.to(self.span);
3445 if self.token == token::CloseDelim(token::Brace) {
3448 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3454 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3457 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3458 maybe_whole!(self, NtArm, |x| x);
3460 let attrs = self.parse_outer_attributes()?;
3461 // Allow a '|' before the pats (RFC 1925)
3462 self.eat(&token::BinOp(token::Or));
3463 let pats = self.parse_pats()?;
3464 let guard = if self.eat_keyword(keywords::If) {
3465 Some(self.parse_expr()?)
3469 let arrow_span = self.span;
3470 self.expect(&token::FatArrow)?;
3471 let arm_start_span = self.span;
3473 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3474 .map_err(|mut err| {
3475 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3479 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3480 && self.token != token::CloseDelim(token::Brace);
3483 let cm = self.sess.codemap();
3484 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3485 .map_err(|mut err| {
3486 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3487 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3488 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3489 && expr_lines.lines.len() == 2
3490 && self.token == token::FatArrow => {
3491 // We check wether there's any trailing code in the parse span, if there
3492 // isn't, we very likely have the following:
3495 // | -- - missing comma
3501 // | parsed until here as `"y" & X`
3502 err.span_suggestion_short_with_applicability(
3503 cm.next_point(arm_start_span),
3504 "missing a comma here to end this `match` arm",
3506 Applicability::MachineApplicable
3510 err.span_label(arrow_span,
3511 "while parsing the `match` arm starting here");
3517 self.eat(&token::Comma);
3528 /// Parse an expression
3529 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3530 self.parse_expr_res(Restrictions::empty(), None)
3533 /// Evaluate the closure with restrictions in place.
3535 /// After the closure is evaluated, restrictions are reset.
3536 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3537 where F: FnOnce(&mut Self) -> T
3539 let old = self.restrictions;
3540 self.restrictions = r;
3542 self.restrictions = old;
3547 /// Parse an expression, subject to the given restrictions
3548 fn parse_expr_res(&mut self, r: Restrictions,
3549 already_parsed_attrs: Option<ThinVec<Attribute>>)
3550 -> PResult<'a, P<Expr>> {
3551 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3554 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3555 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3556 if self.check(&token::Eq) {
3558 Ok(Some(self.parse_expr()?))
3560 Ok(Some(self.parse_expr()?))
3566 /// Parse patterns, separated by '|' s
3567 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3568 let mut pats = Vec::new();
3570 pats.push(self.parse_top_level_pat()?);
3572 if self.token == token::OrOr {
3573 let mut err = self.struct_span_err(self.span,
3574 "unexpected token `||` after pattern");
3575 err.span_suggestion_with_applicability(
3577 "use a single `|` to specify multiple patterns",
3579 Applicability::MachineApplicable
3583 } else if self.check(&token::BinOp(token::Or)) {
3591 // Parses a parenthesized list of patterns like
3592 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3593 // - a vector of the patterns that were parsed
3594 // - an option indicating the index of the `..` element
3595 // - a boolean indicating whether a trailing comma was present.
3596 // Trailing commas are significant because (p) and (p,) are different patterns.
3597 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3598 self.expect(&token::OpenDelim(token::Paren))?;
3599 let result = self.parse_pat_list()?;
3600 self.expect(&token::CloseDelim(token::Paren))?;
3604 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3605 let mut fields = Vec::new();
3606 let mut ddpos = None;
3607 let mut trailing_comma = false;
3609 if self.eat(&token::DotDot) {
3610 if ddpos.is_none() {
3611 ddpos = Some(fields.len());
3613 // Emit a friendly error, ignore `..` and continue parsing
3614 self.span_err(self.prev_span,
3615 "`..` can only be used once per tuple or tuple struct pattern");
3617 } else if !self.check(&token::CloseDelim(token::Paren)) {
3618 fields.push(self.parse_pat()?);
3623 trailing_comma = self.eat(&token::Comma);
3624 if !trailing_comma {
3629 if ddpos == Some(fields.len()) && trailing_comma {
3630 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3631 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3634 Ok((fields, ddpos, trailing_comma))
3637 fn parse_pat_vec_elements(
3639 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3640 let mut before = Vec::new();
3641 let mut slice = None;
3642 let mut after = Vec::new();
3643 let mut first = true;
3644 let mut before_slice = true;
3646 while self.token != token::CloseDelim(token::Bracket) {
3650 self.expect(&token::Comma)?;
3652 if self.token == token::CloseDelim(token::Bracket)
3653 && (before_slice || !after.is_empty()) {
3659 if self.eat(&token::DotDot) {
3661 if self.check(&token::Comma) ||
3662 self.check(&token::CloseDelim(token::Bracket)) {
3663 slice = Some(P(Pat {
3664 id: ast::DUMMY_NODE_ID,
3665 node: PatKind::Wild,
3666 span: self.prev_span,
3668 before_slice = false;
3674 let subpat = self.parse_pat()?;
3675 if before_slice && self.eat(&token::DotDot) {
3676 slice = Some(subpat);
3677 before_slice = false;
3678 } else if before_slice {
3679 before.push(subpat);
3685 Ok((before, slice, after))
3691 attrs: Vec<Attribute>
3692 ) -> PResult<'a, codemap::Spanned<ast::FieldPat>> {
3693 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3695 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3696 // Parsing a pattern of the form "fieldname: pat"
3697 let fieldname = self.parse_field_name()?;
3699 let pat = self.parse_pat()?;
3701 (pat, fieldname, false)
3703 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3704 let is_box = self.eat_keyword(keywords::Box);
3705 let boxed_span = self.span;
3706 let is_ref = self.eat_keyword(keywords::Ref);
3707 let is_mut = self.eat_keyword(keywords::Mut);
3708 let fieldname = self.parse_ident()?;
3709 hi = self.prev_span;
3711 let bind_type = match (is_ref, is_mut) {
3712 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3713 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3714 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3715 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3717 let fieldpat = P(Pat {
3718 id: ast::DUMMY_NODE_ID,
3719 node: PatKind::Ident(bind_type, fieldname, None),
3720 span: boxed_span.to(hi),
3723 let subpat = if is_box {
3725 id: ast::DUMMY_NODE_ID,
3726 node: PatKind::Box(fieldpat),
3732 (subpat, fieldname, true)
3735 Ok(codemap::Spanned {
3737 node: ast::FieldPat {
3741 attrs: attrs.into(),
3746 /// Parse the fields of a struct-like pattern
3747 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3748 let mut fields = Vec::new();
3749 let mut etc = false;
3750 let mut ate_comma = true;
3751 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3752 let mut etc_span = None;
3754 while self.token != token::CloseDelim(token::Brace) {
3755 let attrs = self.parse_outer_attributes()?;
3758 // check that a comma comes after every field
3760 let err = self.struct_span_err(self.prev_span, "expected `,`");
3765 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3767 let mut etc_sp = self.span;
3769 if self.token == token::DotDotDot { // Issue #46718
3770 // Accept `...` as if it were `..` to avoid further errors
3771 let mut err = self.struct_span_err(self.span,
3772 "expected field pattern, found `...`");
3773 err.span_suggestion_with_applicability(
3775 "to omit remaining fields, use one fewer `.`",
3777 Applicability::MachineApplicable
3781 self.bump(); // `..` || `...`:w
3783 if self.token == token::CloseDelim(token::Brace) {
3784 etc_span = Some(etc_sp);
3787 let token_str = self.this_token_to_string();
3788 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3790 err.span_label(self.span, "expected `}`");
3791 let mut comma_sp = None;
3792 if self.token == token::Comma { // Issue #49257
3793 etc_sp = etc_sp.to(self.sess.codemap().span_until_non_whitespace(self.span));
3794 err.span_label(etc_sp,
3795 "`..` must be at the end and cannot have a trailing comma");
3796 comma_sp = Some(self.span);
3801 etc_span = Some(etc_sp);
3802 if self.token == token::CloseDelim(token::Brace) {
3803 // If the struct looks otherwise well formed, recover and continue.
3804 if let Some(sp) = comma_sp {
3805 err.span_suggestion_short(sp, "remove this comma", "".into());
3809 } else if self.token.is_ident() && ate_comma {
3810 // Accept fields coming after `..,`.
3811 // This way we avoid "pattern missing fields" errors afterwards.
3812 // We delay this error until the end in order to have a span for a
3814 if let Some(mut delayed_err) = delayed_err {
3818 delayed_err = Some(err);
3821 if let Some(mut err) = delayed_err {
3828 fields.push(match self.parse_pat_field(lo, attrs) {
3831 if let Some(mut delayed_err) = delayed_err {
3837 ate_comma = self.eat(&token::Comma);
3840 if let Some(mut err) = delayed_err {
3841 if let Some(etc_span) = etc_span {
3842 err.multipart_suggestion(
3843 "move the `..` to the end of the field list",
3845 (etc_span, "".into()),
3846 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3852 return Ok((fields, etc));
3855 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3856 if self.token.is_path_start() {
3858 let (qself, path) = if self.eat_lt() {
3859 // Parse a qualified path
3860 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3863 // Parse an unqualified path
3864 (None, self.parse_path(PathStyle::Expr)?)
3866 let hi = self.prev_span;
3867 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3869 self.parse_literal_maybe_minus()
3873 // helper function to decide whether to parse as ident binding or to try to do
3874 // something more complex like range patterns
3875 fn parse_as_ident(&mut self) -> bool {
3876 self.look_ahead(1, |t| match *t {
3877 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3878 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3879 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3880 // range pattern branch
3881 token::DotDot => None,
3883 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3884 token::Comma | token::CloseDelim(token::Bracket) => true,
3889 /// A wrapper around `parse_pat` with some special error handling for the
3890 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contast
3891 /// to subpatterns within such).
3892 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3893 let pat = self.parse_pat()?;
3894 if self.token == token::Comma {
3895 // An unexpected comma after a top-level pattern is a clue that the
3896 // user (perhaps more accustomed to some other language) forgot the
3897 // parentheses in what should have been a tuple pattern; return a
3898 // suggestion-enhanced error here rather than choking on the comma
3900 let comma_span = self.span;
3902 if let Err(mut err) = self.parse_pat_list() {
3903 // We didn't expect this to work anyway; we just wanted
3904 // to advance to the end of the comma-sequence so we know
3905 // the span to suggest parenthesizing
3908 let seq_span = pat.span.to(self.prev_span);
3909 let mut err = self.struct_span_err(comma_span,
3910 "unexpected `,` in pattern");
3911 if let Ok(seq_snippet) = self.sess.codemap().span_to_snippet(seq_span) {
3912 err.span_suggestion_with_applicability(
3914 "try adding parentheses",
3915 format!("({})", seq_snippet),
3916 Applicability::MachineApplicable
3924 /// Parse a pattern.
3925 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3926 self.parse_pat_with_range_pat(true)
3929 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3931 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3932 maybe_whole!(self, NtPat, |x| x);
3937 token::BinOp(token::And) | token::AndAnd => {
3938 // Parse &pat / &mut pat
3940 let mutbl = self.parse_mutability();
3941 if let token::Lifetime(ident) = self.token {
3942 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3944 err.span_label(self.span, "unexpected lifetime");
3947 let subpat = self.parse_pat_with_range_pat(false)?;
3948 pat = PatKind::Ref(subpat, mutbl);
3950 token::OpenDelim(token::Paren) => {
3951 // Parse (pat,pat,pat,...) as tuple pattern
3952 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3953 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3954 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3956 PatKind::Tuple(fields, ddpos)
3959 token::OpenDelim(token::Bracket) => {
3960 // Parse [pat,pat,...] as slice pattern
3962 let (before, slice, after) = self.parse_pat_vec_elements()?;
3963 self.expect(&token::CloseDelim(token::Bracket))?;
3964 pat = PatKind::Slice(before, slice, after);
3966 // At this point, token != &, &&, (, [
3967 _ => if self.eat_keyword(keywords::Underscore) {
3969 pat = PatKind::Wild;
3970 } else if self.eat_keyword(keywords::Mut) {
3971 // Parse mut ident @ pat / mut ref ident @ pat
3972 let mutref_span = self.prev_span.to(self.span);
3973 let binding_mode = if self.eat_keyword(keywords::Ref) {
3975 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3976 .span_suggestion_with_applicability(
3978 "try switching the order",
3980 Applicability::MachineApplicable
3982 BindingMode::ByRef(Mutability::Mutable)
3984 BindingMode::ByValue(Mutability::Mutable)
3986 pat = self.parse_pat_ident(binding_mode)?;
3987 } else if self.eat_keyword(keywords::Ref) {
3988 // Parse ref ident @ pat / ref mut ident @ pat
3989 let mutbl = self.parse_mutability();
3990 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3991 } else if self.eat_keyword(keywords::Box) {
3993 let subpat = self.parse_pat_with_range_pat(false)?;
3994 pat = PatKind::Box(subpat);
3995 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3996 self.parse_as_ident() {
3997 // Parse ident @ pat
3998 // This can give false positives and parse nullary enums,
3999 // they are dealt with later in resolve
4000 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4001 pat = self.parse_pat_ident(binding_mode)?;
4002 } else if self.token.is_path_start() {
4003 // Parse pattern starting with a path
4004 let (qself, path) = if self.eat_lt() {
4005 // Parse a qualified path
4006 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4009 // Parse an unqualified path
4010 (None, self.parse_path(PathStyle::Expr)?)
4013 token::Not if qself.is_none() => {
4014 // Parse macro invocation
4016 let (delim, tts) = self.expect_delimited_token_tree()?;
4017 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4018 pat = PatKind::Mac(mac);
4020 token::DotDotDot | token::DotDotEq | token::DotDot => {
4021 let end_kind = match self.token {
4022 token::DotDot => RangeEnd::Excluded,
4023 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4024 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4025 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4028 let op_span = self.span;
4030 let span = lo.to(self.prev_span);
4031 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4033 let end = self.parse_pat_range_end()?;
4034 let op = Spanned { span: op_span, node: end_kind };
4035 pat = PatKind::Range(begin, end, op);
4037 token::OpenDelim(token::Brace) => {
4038 if qself.is_some() {
4039 let msg = "unexpected `{` after qualified path";
4040 let mut err = self.fatal(msg);
4041 err.span_label(self.span, msg);
4044 // Parse struct pattern
4046 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4048 self.recover_stmt();
4052 pat = PatKind::Struct(path, fields, etc);
4054 token::OpenDelim(token::Paren) => {
4055 if qself.is_some() {
4056 let msg = "unexpected `(` after qualified path";
4057 let mut err = self.fatal(msg);
4058 err.span_label(self.span, msg);
4061 // Parse tuple struct or enum pattern
4062 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4063 pat = PatKind::TupleStruct(path, fields, ddpos)
4065 _ => pat = PatKind::Path(qself, path),
4068 // Try to parse everything else as literal with optional minus
4069 match self.parse_literal_maybe_minus() {
4071 let op_span = self.span;
4072 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4073 self.check(&token::DotDotDot) {
4074 let end_kind = if self.eat(&token::DotDotDot) {
4075 RangeEnd::Included(RangeSyntax::DotDotDot)
4076 } else if self.eat(&token::DotDotEq) {
4077 RangeEnd::Included(RangeSyntax::DotDotEq)
4078 } else if self.eat(&token::DotDot) {
4081 panic!("impossible case: we already matched \
4082 on a range-operator token")
4084 let end = self.parse_pat_range_end()?;
4085 let op = Spanned { span: op_span, node: end_kind };
4086 pat = PatKind::Range(begin, end, op);
4088 pat = PatKind::Lit(begin);
4092 self.cancel(&mut err);
4093 let msg = format!("expected pattern, found {}", self.this_token_descr());
4094 let mut err = self.fatal(&msg);
4095 err.span_label(self.span, "expected pattern");
4102 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4103 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4105 if !allow_range_pat {
4108 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4110 PatKind::Range(..) => {
4111 let mut err = self.struct_span_err(
4113 "the range pattern here has ambiguous interpretation",
4115 err.span_suggestion_with_applicability(
4117 "add parentheses to clarify the precedence",
4118 format!("({})", pprust::pat_to_string(&pat)),
4119 // "ambiguous interpretation" implies that we have to be guessing
4120 Applicability::MaybeIncorrect
4131 /// Parse ident or ident @ pat
4132 /// used by the copy foo and ref foo patterns to give a good
4133 /// error message when parsing mistakes like ref foo(a,b)
4134 fn parse_pat_ident(&mut self,
4135 binding_mode: ast::BindingMode)
4136 -> PResult<'a, PatKind> {
4137 let ident = self.parse_ident()?;
4138 let sub = if self.eat(&token::At) {
4139 Some(self.parse_pat()?)
4144 // just to be friendly, if they write something like
4146 // we end up here with ( as the current token. This shortly
4147 // leads to a parse error. Note that if there is no explicit
4148 // binding mode then we do not end up here, because the lookahead
4149 // will direct us over to parse_enum_variant()
4150 if self.token == token::OpenDelim(token::Paren) {
4151 return Err(self.span_fatal(
4153 "expected identifier, found enum pattern"))
4156 Ok(PatKind::Ident(binding_mode, ident, sub))
4159 /// Parse a local variable declaration
4160 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4161 let lo = self.prev_span;
4162 let pat = self.parse_top_level_pat()?;
4164 let (err, ty) = if self.eat(&token::Colon) {
4165 // Save the state of the parser before parsing type normally, in case there is a `:`
4166 // instead of an `=` typo.
4167 let parser_snapshot_before_type = self.clone();
4168 let colon_sp = self.prev_span;
4169 match self.parse_ty() {
4170 Ok(ty) => (None, Some(ty)),
4172 // Rewind to before attempting to parse the type and continue parsing
4173 let parser_snapshot_after_type = self.clone();
4174 mem::replace(self, parser_snapshot_before_type);
4176 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
4177 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4178 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4184 let init = match (self.parse_initializer(err.is_some()), err) {
4185 (Ok(init), None) => { // init parsed, ty parsed
4188 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4189 // Could parse the type as if it were the initializer, it is likely there was a
4190 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4191 err.span_suggestion_short_with_applicability(
4193 "use `=` if you meant to assign",
4195 Applicability::MachineApplicable
4198 // As this was parsed successfully, continue as if the code has been fixed for the
4199 // rest of the file. It will still fail due to the emitted error, but we avoid
4203 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4205 // Couldn't parse the type nor the initializer, only raise the type error and
4206 // return to the parser state before parsing the type as the initializer.
4207 // let x: <parse_error>;
4208 mem::replace(self, snapshot);
4211 (Err(err), None) => { // init error, ty parsed
4212 // Couldn't parse the initializer and we're not attempting to recover a failed
4213 // parse of the type, return the error.
4217 let hi = if self.token == token::Semi {
4226 id: ast::DUMMY_NODE_ID,
4232 /// Parse a structure field
4233 fn parse_name_and_ty(&mut self,
4236 attrs: Vec<Attribute>)
4237 -> PResult<'a, StructField> {
4238 let name = self.parse_ident()?;
4239 self.expect(&token::Colon)?;
4240 let ty = self.parse_ty()?;
4242 span: lo.to(self.prev_span),
4245 id: ast::DUMMY_NODE_ID,
4251 /// Emit an expected item after attributes error.
4252 fn expected_item_err(&self, attrs: &[Attribute]) {
4253 let message = match attrs.last() {
4254 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4255 _ => "expected item after attributes",
4258 self.span_err(self.prev_span, message);
4261 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4262 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4263 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4264 Ok(self.parse_stmt_(true))
4267 // Eat tokens until we can be relatively sure we reached the end of the
4268 // statement. This is something of a best-effort heuristic.
4270 // We terminate when we find an unmatched `}` (without consuming it).
4271 fn recover_stmt(&mut self) {
4272 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4275 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4276 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4277 // approximate - it can mean we break too early due to macros, but that
4278 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4280 // If `break_on_block` is `Break`, then we will stop consuming tokens
4281 // after finding (and consuming) a brace-delimited block.
4282 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4283 let mut brace_depth = 0;
4284 let mut bracket_depth = 0;
4285 let mut in_block = false;
4286 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4287 break_on_semi, break_on_block);
4289 debug!("recover_stmt_ loop {:?}", self.token);
4291 token::OpenDelim(token::DelimToken::Brace) => {
4294 if break_on_block == BlockMode::Break &&
4296 bracket_depth == 0 {
4300 token::OpenDelim(token::DelimToken::Bracket) => {
4304 token::CloseDelim(token::DelimToken::Brace) => {
4305 if brace_depth == 0 {
4306 debug!("recover_stmt_ return - close delim {:?}", self.token);
4311 if in_block && bracket_depth == 0 && brace_depth == 0 {
4312 debug!("recover_stmt_ return - block end {:?}", self.token);
4316 token::CloseDelim(token::DelimToken::Bracket) => {
4318 if bracket_depth < 0 {
4324 debug!("recover_stmt_ return - Eof");
4329 if break_on_semi == SemiColonMode::Break &&
4331 bracket_depth == 0 {
4332 debug!("recover_stmt_ return - Semi");
4343 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4344 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4346 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4351 fn is_async_block(&mut self) -> bool {
4352 self.token.is_keyword(keywords::Async) &&
4355 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4356 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4358 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4363 fn is_catch_expr(&mut self) -> bool {
4364 self.token.is_keyword(keywords::Do) &&
4365 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4366 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4368 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4369 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4372 fn is_union_item(&self) -> bool {
4373 self.token.is_keyword(keywords::Union) &&
4374 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4377 fn is_crate_vis(&self) -> bool {
4378 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4381 fn is_extern_non_path(&self) -> bool {
4382 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4385 fn is_auto_trait_item(&mut self) -> bool {
4387 (self.token.is_keyword(keywords::Auto)
4388 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4389 || // unsafe auto trait
4390 (self.token.is_keyword(keywords::Unsafe) &&
4391 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4392 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4395 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4396 -> PResult<'a, Option<P<Item>>> {
4397 let token_lo = self.span;
4398 let (ident, def) = match self.token {
4399 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4401 let ident = self.parse_ident()?;
4402 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4403 match self.parse_token_tree() {
4404 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4405 _ => unreachable!(),
4407 } else if self.check(&token::OpenDelim(token::Paren)) {
4408 let args = self.parse_token_tree();
4409 let body = if self.check(&token::OpenDelim(token::Brace)) {
4410 self.parse_token_tree()
4415 TokenStream::concat(vec![
4417 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4425 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4427 token::Ident(ident, _) if ident.name == "macro_rules" &&
4428 self.look_ahead(1, |t| *t == token::Not) => {
4429 let prev_span = self.prev_span;
4430 self.complain_if_pub_macro(&vis.node, prev_span);
4434 let ident = self.parse_ident()?;
4435 let (delim, tokens) = self.expect_delimited_token_tree()?;
4436 if delim != MacDelimiter::Brace {
4437 if !self.eat(&token::Semi) {
4438 let msg = "macros that expand to items must either \
4439 be surrounded with braces or followed by a semicolon";
4440 self.span_err(self.prev_span, msg);
4444 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4446 _ => return Ok(None),
4449 let span = lo.to(self.prev_span);
4450 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4453 fn parse_stmt_without_recovery(&mut self,
4454 macro_legacy_warnings: bool)
4455 -> PResult<'a, Option<Stmt>> {
4456 maybe_whole!(self, NtStmt, |x| Some(x));
4458 let attrs = self.parse_outer_attributes()?;
4461 Ok(Some(if self.eat_keyword(keywords::Let) {
4463 id: ast::DUMMY_NODE_ID,
4464 node: StmtKind::Local(self.parse_local(attrs.into())?),
4465 span: lo.to(self.prev_span),
4467 } else if let Some(macro_def) = self.eat_macro_def(
4469 &codemap::respan(lo, VisibilityKind::Inherited),
4473 id: ast::DUMMY_NODE_ID,
4474 node: StmtKind::Item(macro_def),
4475 span: lo.to(self.prev_span),
4477 // Starts like a simple path, being careful to avoid contextual keywords
4478 // such as a union items, item with `crate` visibility or auto trait items.
4479 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4480 // like a path (1 token), but it fact not a path.
4481 // `union::b::c` - path, `union U { ... }` - not a path.
4482 // `crate::b::c` - path, `crate struct S;` - not a path.
4483 // `extern::b::c` - path, `extern crate c;` - not a path.
4484 } else if self.token.is_path_start() &&
4485 !self.token.is_qpath_start() &&
4486 !self.is_union_item() &&
4487 !self.is_crate_vis() &&
4488 !self.is_extern_non_path() &&
4489 !self.is_auto_trait_item() {
4490 let pth = self.parse_path(PathStyle::Expr)?;
4492 if !self.eat(&token::Not) {
4493 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4494 self.parse_struct_expr(lo, pth, ThinVec::new())?
4496 let hi = self.prev_span;
4497 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4500 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4501 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4502 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4505 return Ok(Some(Stmt {
4506 id: ast::DUMMY_NODE_ID,
4507 node: StmtKind::Expr(expr),
4508 span: lo.to(self.prev_span),
4512 // it's a macro invocation
4513 let id = match self.token {
4514 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4515 _ => self.parse_ident()?,
4518 // check that we're pointing at delimiters (need to check
4519 // again after the `if`, because of `parse_ident`
4520 // consuming more tokens).
4522 token::OpenDelim(_) => {}
4524 // we only expect an ident if we didn't parse one
4526 let ident_str = if id.name == keywords::Invalid.name() {
4531 let tok_str = self.this_token_to_string();
4532 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4535 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4540 let (delim, tts) = self.expect_delimited_token_tree()?;
4541 let hi = self.prev_span;
4543 let style = if delim == MacDelimiter::Brace {
4544 MacStmtStyle::Braces
4546 MacStmtStyle::NoBraces
4549 if id.name == keywords::Invalid.name() {
4550 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4551 let node = if delim == MacDelimiter::Brace ||
4552 self.token == token::Semi || self.token == token::Eof {
4553 StmtKind::Mac(P((mac, style, attrs.into())))
4555 // We used to incorrectly stop parsing macro-expanded statements here.
4556 // If the next token will be an error anyway but could have parsed with the
4557 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4558 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4559 // These can continue an expression, so we can't stop parsing and warn.
4560 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4561 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4562 token::BinOp(token::And) | token::BinOp(token::Or) |
4563 token::AndAnd | token::OrOr |
4564 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4567 self.warn_missing_semicolon();
4568 StmtKind::Mac(P((mac, style, attrs.into())))
4570 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4571 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4572 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4576 id: ast::DUMMY_NODE_ID,
4581 // if it has a special ident, it's definitely an item
4583 // Require a semicolon or braces.
4584 if style != MacStmtStyle::Braces {
4585 if !self.eat(&token::Semi) {
4586 self.span_err(self.prev_span,
4587 "macros that expand to items must \
4588 either be surrounded with braces or \
4589 followed by a semicolon");
4592 let span = lo.to(hi);
4594 id: ast::DUMMY_NODE_ID,
4596 node: StmtKind::Item({
4598 span, id /*id is good here*/,
4599 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4600 respan(lo, VisibilityKind::Inherited),
4606 // FIXME: Bad copy of attrs
4607 let old_directory_ownership =
4608 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4609 let item = self.parse_item_(attrs.clone(), false, true)?;
4610 self.directory.ownership = old_directory_ownership;
4614 id: ast::DUMMY_NODE_ID,
4615 span: lo.to(i.span),
4616 node: StmtKind::Item(i),
4619 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4620 if !attrs.is_empty() {
4621 if s.prev_token_kind == PrevTokenKind::DocComment {
4622 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4623 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4624 s.span_err(s.span, "expected statement after outer attribute");
4629 // Do not attempt to parse an expression if we're done here.
4630 if self.token == token::Semi {
4631 unused_attrs(&attrs, self);
4636 if self.token == token::CloseDelim(token::Brace) {
4637 unused_attrs(&attrs, self);
4641 // Remainder are line-expr stmts.
4642 let e = self.parse_expr_res(
4643 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4645 id: ast::DUMMY_NODE_ID,
4646 span: lo.to(e.span),
4647 node: StmtKind::Expr(e),
4654 /// Is this expression a successfully-parsed statement?
4655 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4656 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4657 !classify::expr_requires_semi_to_be_stmt(e)
4660 /// Parse a block. No inner attrs are allowed.
4661 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4662 maybe_whole!(self, NtBlock, |x| x);
4666 if !self.eat(&token::OpenDelim(token::Brace)) {
4668 let tok = self.this_token_to_string();
4669 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4671 // Check to see if the user has written something like
4676 // Which is valid in other languages, but not Rust.
4677 match self.parse_stmt_without_recovery(false) {
4679 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) {
4680 // if the next token is an open brace (e.g., `if a b {`), the place-
4681 // inside-a-block suggestion would be more likely wrong than right
4684 let mut stmt_span = stmt.span;
4685 // expand the span to include the semicolon, if it exists
4686 if self.eat(&token::Semi) {
4687 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4689 let sugg = pprust::to_string(|s| {
4690 use print::pprust::{PrintState, INDENT_UNIT};
4691 s.ibox(INDENT_UNIT)?;
4693 s.print_stmt(&stmt)?;
4694 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4696 e.span_suggestion_with_applicability(
4698 "try placing this code inside a block",
4700 // speculative, has been misleading in the past (closed Issue #46836)
4701 Applicability::MaybeIncorrect
4705 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4706 self.cancel(&mut e);
4713 self.parse_block_tail(lo, BlockCheckMode::Default)
4716 /// Parse a block. Inner attrs are allowed.
4717 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4718 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4721 self.expect(&token::OpenDelim(token::Brace))?;
4722 Ok((self.parse_inner_attributes()?,
4723 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4726 /// Parse the rest of a block expression or function body
4727 /// Precondition: already parsed the '{'.
4728 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4729 let mut stmts = vec![];
4730 let mut recovered = false;
4732 while !self.eat(&token::CloseDelim(token::Brace)) {
4733 let stmt = match self.parse_full_stmt(false) {
4736 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4737 self.eat(&token::CloseDelim(token::Brace));
4743 if let Some(stmt) = stmt {
4745 } else if self.token == token::Eof {
4748 // Found only `;` or `}`.
4754 id: ast::DUMMY_NODE_ID,
4756 span: lo.to(self.prev_span),
4761 /// Parse a statement, including the trailing semicolon.
4762 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4763 // skip looking for a trailing semicolon when we have an interpolated statement
4764 maybe_whole!(self, NtStmt, |x| Some(x));
4766 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4768 None => return Ok(None),
4772 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4773 // expression without semicolon
4774 if classify::expr_requires_semi_to_be_stmt(expr) {
4775 // Just check for errors and recover; do not eat semicolon yet.
4777 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4780 self.recover_stmt();
4784 StmtKind::Local(..) => {
4785 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4786 if macro_legacy_warnings && self.token != token::Semi {
4787 self.warn_missing_semicolon();
4789 self.expect_one_of(&[], &[token::Semi])?;
4795 if self.eat(&token::Semi) {
4796 stmt = stmt.add_trailing_semicolon();
4799 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4803 fn warn_missing_semicolon(&self) {
4804 self.diagnostic().struct_span_warn(self.span, {
4805 &format!("expected `;`, found `{}`", self.this_token_to_string())
4807 "This was erroneously allowed and will become a hard error in a future release"
4811 fn err_dotdotdot_syntax(&self, span: Span) {
4812 self.diagnostic().struct_span_err(span, {
4813 "unexpected token: `...`"
4814 }).span_suggestion_with_applicability(
4815 span, "use `..` for an exclusive range", "..".to_owned(),
4816 Applicability::MaybeIncorrect
4817 ).span_suggestion_with_applicability(
4818 span, "or `..=` for an inclusive range", "..=".to_owned(),
4819 Applicability::MaybeIncorrect
4823 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4824 // BOUND = TY_BOUND | LT_BOUND
4825 // LT_BOUND = LIFETIME (e.g. `'a`)
4826 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4827 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4828 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4829 let mut bounds = Vec::new();
4831 // This needs to be syncronized with `Token::can_begin_bound`.
4832 let is_bound_start = self.check_path() || self.check_lifetime() ||
4833 self.check(&token::Question) ||
4834 self.check_keyword(keywords::For) ||
4835 self.check(&token::OpenDelim(token::Paren));
4838 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4839 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4840 if self.token.is_lifetime() {
4841 if let Some(question_span) = question {
4842 self.span_err(question_span,
4843 "`?` may only modify trait bounds, not lifetime bounds");
4845 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4847 self.expect(&token::CloseDelim(token::Paren))?;
4848 self.span_err(self.prev_span,
4849 "parenthesized lifetime bounds are not supported");
4852 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4853 let path = self.parse_path(PathStyle::Type)?;
4855 self.expect(&token::CloseDelim(token::Paren))?;
4857 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4858 let modifier = if question.is_some() {
4859 TraitBoundModifier::Maybe
4861 TraitBoundModifier::None
4863 bounds.push(GenericBound::Trait(poly_trait, modifier));
4869 if !allow_plus || !self.eat_plus() {
4877 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
4878 self.parse_generic_bounds_common(true)
4881 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4882 // BOUND = LT_BOUND (e.g. `'a`)
4883 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4884 let mut lifetimes = Vec::new();
4885 while self.check_lifetime() {
4886 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4888 if !self.eat_plus() {
4895 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4896 fn parse_ty_param(&mut self,
4897 preceding_attrs: Vec<Attribute>)
4898 -> PResult<'a, GenericParam> {
4899 let ident = self.parse_ident()?;
4901 // Parse optional colon and param bounds.
4902 let bounds = if self.eat(&token::Colon) {
4903 self.parse_generic_bounds()?
4908 let default = if self.eat(&token::Eq) {
4909 Some(self.parse_ty()?)
4916 id: ast::DUMMY_NODE_ID,
4917 attrs: preceding_attrs.into(),
4919 kind: GenericParamKind::Type {
4925 /// Parses the following grammar:
4926 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4927 fn parse_trait_item_assoc_ty(&mut self)
4928 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4929 let ident = self.parse_ident()?;
4930 let mut generics = self.parse_generics()?;
4932 // Parse optional colon and param bounds.
4933 let bounds = if self.eat(&token::Colon) {
4934 self.parse_generic_bounds()?
4938 generics.where_clause = self.parse_where_clause()?;
4940 let default = if self.eat(&token::Eq) {
4941 Some(self.parse_ty()?)
4945 self.expect(&token::Semi)?;
4947 Ok((ident, TraitItemKind::Type(bounds, default), generics))
4950 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4951 /// trailing comma and erroneous trailing attributes.
4952 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4953 let mut params = Vec::new();
4954 let mut seen_ty_param = false;
4956 let attrs = self.parse_outer_attributes()?;
4957 if self.check_lifetime() {
4958 let lifetime = self.expect_lifetime();
4959 // Parse lifetime parameter.
4960 let bounds = if self.eat(&token::Colon) {
4961 self.parse_lt_param_bounds()
4965 params.push(ast::GenericParam {
4966 ident: lifetime.ident,
4968 attrs: attrs.into(),
4970 kind: ast::GenericParamKind::Lifetime,
4973 self.span_err(self.prev_span,
4974 "lifetime parameters must be declared prior to type parameters");
4976 } else if self.check_ident() {
4977 // Parse type parameter.
4978 params.push(self.parse_ty_param(attrs)?);
4979 seen_ty_param = true;
4981 // Check for trailing attributes and stop parsing.
4982 if !attrs.is_empty() {
4983 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4984 self.span_err(attrs[0].span,
4985 &format!("trailing attribute after {} parameters", param_kind));
4990 if !self.eat(&token::Comma) {
4997 /// Parse a set of optional generic type parameter declarations. Where
4998 /// clauses are not parsed here, and must be added later via
4999 /// `parse_where_clause()`.
5001 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5002 /// | ( < lifetimes , typaramseq ( , )? > )
5003 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5004 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5005 maybe_whole!(self, NtGenerics, |x| x);
5007 let span_lo = self.span;
5009 let params = self.parse_generic_params()?;
5013 where_clause: WhereClause {
5014 id: ast::DUMMY_NODE_ID,
5015 predicates: Vec::new(),
5016 span: syntax_pos::DUMMY_SP,
5018 span: span_lo.to(self.prev_span),
5021 Ok(ast::Generics::default())
5025 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5026 /// possibly including trailing comma.
5027 fn parse_generic_args(&mut self)
5028 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5029 let mut args = Vec::new();
5030 let mut bindings = Vec::new();
5031 let mut seen_type = false;
5032 let mut seen_binding = false;
5034 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5035 // Parse lifetime argument.
5036 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5037 if seen_type || seen_binding {
5038 self.span_err(self.prev_span,
5039 "lifetime parameters must be declared prior to type parameters");
5041 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5042 // Parse associated type binding.
5044 let ident = self.parse_ident()?;
5046 let ty = self.parse_ty()?;
5047 bindings.push(TypeBinding {
5048 id: ast::DUMMY_NODE_ID,
5051 span: lo.to(self.prev_span),
5053 seen_binding = true;
5054 } else if self.check_type() {
5055 // Parse type argument.
5056 let ty_param = self.parse_ty()?;
5058 self.span_err(ty_param.span,
5059 "type parameters must be declared prior to associated type bindings");
5061 args.push(GenericArg::Type(ty_param));
5067 if !self.eat(&token::Comma) {
5071 Ok((args, bindings))
5074 /// Parses an optional `where` clause and places it in `generics`.
5076 /// ```ignore (only-for-syntax-highlight)
5077 /// where T : Trait<U, V> + 'b, 'a : 'b
5079 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5080 maybe_whole!(self, NtWhereClause, |x| x);
5082 let mut where_clause = WhereClause {
5083 id: ast::DUMMY_NODE_ID,
5084 predicates: Vec::new(),
5085 span: syntax_pos::DUMMY_SP,
5088 if !self.eat_keyword(keywords::Where) {
5089 return Ok(where_clause);
5091 let lo = self.prev_span;
5093 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5094 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5095 // change we parse those generics now, but report an error.
5096 if self.choose_generics_over_qpath() {
5097 let generics = self.parse_generics()?;
5098 self.span_err(generics.span,
5099 "generic parameters on `where` clauses are reserved for future use");
5104 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5105 let lifetime = self.expect_lifetime();
5106 // Bounds starting with a colon are mandatory, but possibly empty.
5107 self.expect(&token::Colon)?;
5108 let bounds = self.parse_lt_param_bounds();
5109 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5110 ast::WhereRegionPredicate {
5111 span: lo.to(self.prev_span),
5116 } else if self.check_type() {
5117 // Parse optional `for<'a, 'b>`.
5118 // This `for` is parsed greedily and applies to the whole predicate,
5119 // the bounded type can have its own `for` applying only to it.
5120 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5121 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5122 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5123 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5125 // Parse type with mandatory colon and (possibly empty) bounds,
5126 // or with mandatory equality sign and the second type.
5127 let ty = self.parse_ty()?;
5128 if self.eat(&token::Colon) {
5129 let bounds = self.parse_generic_bounds()?;
5130 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5131 ast::WhereBoundPredicate {
5132 span: lo.to(self.prev_span),
5133 bound_generic_params: lifetime_defs,
5138 // FIXME: Decide what should be used here, `=` or `==`.
5139 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5140 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5141 let rhs_ty = self.parse_ty()?;
5142 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5143 ast::WhereEqPredicate {
5144 span: lo.to(self.prev_span),
5147 id: ast::DUMMY_NODE_ID,
5151 return self.unexpected();
5157 if !self.eat(&token::Comma) {
5162 where_clause.span = lo.to(self.prev_span);
5166 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5167 -> PResult<'a, (Vec<Arg> , bool)> {
5169 let mut variadic = false;
5170 let args: Vec<Option<Arg>> =
5171 self.parse_unspanned_seq(
5172 &token::OpenDelim(token::Paren),
5173 &token::CloseDelim(token::Paren),
5174 SeqSep::trailing_allowed(token::Comma),
5176 if p.token == token::DotDotDot {
5180 if p.token != token::CloseDelim(token::Paren) {
5183 "`...` must be last in argument list for variadic function");
5187 let span = p.prev_span;
5188 if p.token == token::CloseDelim(token::Paren) {
5189 // continue parsing to present any further errors
5192 "only foreign functions are allowed to be variadic"
5194 Ok(Some(dummy_arg(span)))
5196 // this function definition looks beyond recovery, stop parsing
5198 "only foreign functions are allowed to be variadic");
5203 match p.parse_arg_general(named_args) {
5204 Ok(arg) => Ok(Some(arg)),
5207 let lo = p.prev_span;
5208 // Skip every token until next possible arg or end.
5209 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5210 // Create a placeholder argument for proper arg count (#34264).
5211 let span = lo.to(p.prev_span);
5212 Ok(Some(dummy_arg(span)))
5219 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5221 if variadic && args.is_empty() {
5223 "variadic function must be declared with at least one named argument");
5226 Ok((args, variadic))
5229 /// Parse the argument list and result type of a function declaration
5230 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5232 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5233 let ret_ty = self.parse_ret_ty(true)?;
5242 /// Returns the parsed optional self argument and whether a self shortcut was used.
5243 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5244 let expect_ident = |this: &mut Self| match this.token {
5245 // Preserve hygienic context.
5246 token::Ident(ident, _) =>
5247 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5250 let isolated_self = |this: &mut Self, n| {
5251 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5252 this.look_ahead(n + 1, |t| t != &token::ModSep)
5255 // Parse optional self parameter of a method.
5256 // Only a limited set of initial token sequences is considered self parameters, anything
5257 // else is parsed as a normal function parameter list, so some lookahead is required.
5258 let eself_lo = self.span;
5259 let (eself, eself_ident, eself_hi) = match self.token {
5260 token::BinOp(token::And) => {
5266 (if isolated_self(self, 1) {
5268 SelfKind::Region(None, Mutability::Immutable)
5269 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5270 isolated_self(self, 2) {
5273 SelfKind::Region(None, Mutability::Mutable)
5274 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5275 isolated_self(self, 2) {
5277 let lt = self.expect_lifetime();
5278 SelfKind::Region(Some(lt), Mutability::Immutable)
5279 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5280 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5281 isolated_self(self, 3) {
5283 let lt = self.expect_lifetime();
5285 SelfKind::Region(Some(lt), Mutability::Mutable)
5288 }, expect_ident(self), self.prev_span)
5290 token::BinOp(token::Star) => {
5295 // Emit special error for `self` cases.
5296 (if isolated_self(self, 1) {
5298 self.span_err(self.span, "cannot pass `self` by raw pointer");
5299 SelfKind::Value(Mutability::Immutable)
5300 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5301 isolated_self(self, 2) {
5304 self.span_err(self.span, "cannot pass `self` by raw pointer");
5305 SelfKind::Value(Mutability::Immutable)
5308 }, expect_ident(self), self.prev_span)
5310 token::Ident(..) => {
5311 if isolated_self(self, 0) {
5314 let eself_ident = expect_ident(self);
5315 let eself_hi = self.prev_span;
5316 (if self.eat(&token::Colon) {
5317 let ty = self.parse_ty()?;
5318 SelfKind::Explicit(ty, Mutability::Immutable)
5320 SelfKind::Value(Mutability::Immutable)
5321 }, eself_ident, eself_hi)
5322 } else if self.token.is_keyword(keywords::Mut) &&
5323 isolated_self(self, 1) {
5327 let eself_ident = expect_ident(self);
5328 let eself_hi = self.prev_span;
5329 (if self.eat(&token::Colon) {
5330 let ty = self.parse_ty()?;
5331 SelfKind::Explicit(ty, Mutability::Mutable)
5333 SelfKind::Value(Mutability::Mutable)
5334 }, eself_ident, eself_hi)
5339 _ => return Ok(None),
5342 let eself = codemap::respan(eself_lo.to(eself_hi), eself);
5343 Ok(Some(Arg::from_self(eself, eself_ident)))
5346 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5347 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5348 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5350 self.expect(&token::OpenDelim(token::Paren))?;
5352 // Parse optional self argument
5353 let self_arg = self.parse_self_arg()?;
5355 // Parse the rest of the function parameter list.
5356 let sep = SeqSep::trailing_allowed(token::Comma);
5357 let fn_inputs = if let Some(self_arg) = self_arg {
5358 if self.check(&token::CloseDelim(token::Paren)) {
5360 } else if self.eat(&token::Comma) {
5361 let mut fn_inputs = vec![self_arg];
5362 fn_inputs.append(&mut self.parse_seq_to_before_end(
5363 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5367 return self.unexpected();
5370 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5373 // Parse closing paren and return type.
5374 self.expect(&token::CloseDelim(token::Paren))?;
5377 output: self.parse_ret_ty(true)?,
5382 // parse the |arg, arg| header on a lambda
5383 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5384 let inputs_captures = {
5385 if self.eat(&token::OrOr) {
5388 self.expect(&token::BinOp(token::Or))?;
5389 let args = self.parse_seq_to_before_tokens(
5390 &[&token::BinOp(token::Or), &token::OrOr],
5391 SeqSep::trailing_allowed(token::Comma),
5392 TokenExpectType::NoExpect,
5393 |p| p.parse_fn_block_arg()
5399 let output = self.parse_ret_ty(true)?;
5402 inputs: inputs_captures,
5408 /// Parse the name and optional generic types of a function header.
5409 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5410 let id = self.parse_ident()?;
5411 let generics = self.parse_generics()?;
5415 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5416 attrs: Vec<Attribute>) -> P<Item> {
5420 id: ast::DUMMY_NODE_ID,
5428 /// Parse an item-position function declaration.
5429 fn parse_item_fn(&mut self,
5432 constness: Spanned<Constness>,
5434 -> PResult<'a, ItemInfo> {
5435 let (ident, mut generics) = self.parse_fn_header()?;
5436 let decl = self.parse_fn_decl(false)?;
5437 generics.where_clause = self.parse_where_clause()?;
5438 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5439 let header = FnHeader { unsafety, asyncness, constness, abi };
5440 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5443 /// true if we are looking at `const ID`, false for things like `const fn` etc
5444 fn is_const_item(&mut self) -> bool {
5445 self.token.is_keyword(keywords::Const) &&
5446 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5447 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5450 /// parses all the "front matter" for a `fn` declaration, up to
5451 /// and including the `fn` keyword:
5455 /// - `const unsafe fn`
5458 fn parse_fn_front_matter(&mut self)
5466 let is_const_fn = self.eat_keyword(keywords::Const);
5467 let const_span = self.prev_span;
5468 let unsafety = self.parse_unsafety();
5469 let asyncness = self.parse_asyncness();
5470 let (constness, unsafety, abi) = if is_const_fn {
5471 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5473 let abi = if self.eat_keyword(keywords::Extern) {
5474 self.parse_opt_abi()?.unwrap_or(Abi::C)
5478 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5480 self.expect_keyword(keywords::Fn)?;
5481 Ok((constness, unsafety, asyncness, abi))
5484 /// Parse an impl item.
5485 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5486 maybe_whole!(self, NtImplItem, |x| x);
5487 let attrs = self.parse_outer_attributes()?;
5488 let (mut item, tokens) = self.collect_tokens(|this| {
5489 this.parse_impl_item_(at_end, attrs)
5492 // See `parse_item` for why this clause is here.
5493 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5494 item.tokens = Some(tokens);
5499 fn parse_impl_item_(&mut self,
5501 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5503 let vis = self.parse_visibility(false)?;
5504 let defaultness = self.parse_defaultness();
5505 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5506 // This parses the grammar:
5507 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5508 let name = self.parse_ident()?;
5509 let mut generics = self.parse_generics()?;
5510 generics.where_clause = self.parse_where_clause()?;
5511 self.expect(&token::Eq)?;
5512 let typ = self.parse_ty()?;
5513 self.expect(&token::Semi)?;
5514 (name, ast::ImplItemKind::Type(typ), generics)
5515 } else if self.is_const_item() {
5516 // This parses the grammar:
5517 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5518 self.expect_keyword(keywords::Const)?;
5519 let name = self.parse_ident()?;
5520 self.expect(&token::Colon)?;
5521 let typ = self.parse_ty()?;
5522 self.expect(&token::Eq)?;
5523 let expr = self.parse_expr()?;
5524 self.expect(&token::Semi)?;
5525 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5527 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5528 attrs.extend(inner_attrs);
5529 (name, node, generics)
5533 id: ast::DUMMY_NODE_ID,
5534 span: lo.to(self.prev_span),
5545 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5546 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5551 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5553 VisibilityKind::Inherited => Ok(()),
5555 let is_macro_rules: bool = match self.token {
5556 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5560 let mut err = self.diagnostic()
5561 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5562 err.span_suggestion_with_applicability(
5564 "try exporting the macro",
5565 "#[macro_export]".to_owned(),
5566 Applicability::MaybeIncorrect // speculative
5570 let mut err = self.diagnostic()
5571 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5572 err.help("try adjusting the macro to put `pub` inside the invocation");
5579 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5580 -> DiagnosticBuilder<'a>
5582 let expected_kinds = if item_type == "extern" {
5583 "missing `fn`, `type`, or `static`"
5585 "missing `fn`, `type`, or `const`"
5588 // Given this code `path(`, it seems like this is not
5589 // setting the visibility of a macro invocation, but rather
5590 // a mistyped method declaration.
5591 // Create a diagnostic pointing out that `fn` is missing.
5593 // x | pub path(&self) {
5594 // | ^ missing `fn`, `type`, or `const`
5596 // ^^ `sp` below will point to this
5597 let sp = prev_span.between(self.prev_span);
5598 let mut err = self.diagnostic().struct_span_err(
5600 &format!("{} for {}-item declaration",
5601 expected_kinds, item_type));
5602 err.span_label(sp, expected_kinds);
5606 /// Parse a method or a macro invocation in a trait impl.
5607 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5608 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5609 ast::ImplItemKind)> {
5610 // code copied from parse_macro_use_or_failure... abstraction!
5611 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5613 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5614 ast::ImplItemKind::Macro(mac)))
5616 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5617 let ident = self.parse_ident()?;
5618 let mut generics = self.parse_generics()?;
5619 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5620 generics.where_clause = self.parse_where_clause()?;
5622 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5623 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5624 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5625 ast::MethodSig { header, decl },
5631 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5632 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5633 let ident = self.parse_ident()?;
5634 let mut tps = self.parse_generics()?;
5636 // Parse optional colon and supertrait bounds.
5637 let bounds = if self.eat(&token::Colon) {
5638 self.parse_generic_bounds()?
5643 if self.eat(&token::Eq) {
5644 // it's a trait alias
5645 let bounds = self.parse_generic_bounds()?;
5646 tps.where_clause = self.parse_where_clause()?;
5647 self.expect(&token::Semi)?;
5648 if unsafety != Unsafety::Normal {
5649 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5651 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5653 // it's a normal trait
5654 tps.where_clause = self.parse_where_clause()?;
5655 self.expect(&token::OpenDelim(token::Brace))?;
5656 let mut trait_items = vec![];
5657 while !self.eat(&token::CloseDelim(token::Brace)) {
5658 let mut at_end = false;
5659 match self.parse_trait_item(&mut at_end) {
5660 Ok(item) => trait_items.push(item),
5664 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5669 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5673 fn choose_generics_over_qpath(&self) -> bool {
5674 // There's an ambiguity between generic parameters and qualified paths in impls.
5675 // If we see `<` it may start both, so we have to inspect some following tokens.
5676 // The following combinations can only start generics,
5677 // but not qualified paths (with one exception):
5678 // `<` `>` - empty generic parameters
5679 // `<` `#` - generic parameters with attributes
5680 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5681 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5682 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5683 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5684 // The only truly ambiguous case is
5685 // `<` IDENT `>` `::` IDENT ...
5686 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5687 // because this is what almost always expected in practice, qualified paths in impls
5688 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5689 self.token == token::Lt &&
5690 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5691 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5692 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5693 t == &token::Colon || t == &token::Eq))
5696 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5697 self.expect(&token::OpenDelim(token::Brace))?;
5698 let attrs = self.parse_inner_attributes()?;
5700 let mut impl_items = Vec::new();
5701 while !self.eat(&token::CloseDelim(token::Brace)) {
5702 let mut at_end = false;
5703 match self.parse_impl_item(&mut at_end) {
5704 Ok(impl_item) => impl_items.push(impl_item),
5708 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5713 Ok((impl_items, attrs))
5716 /// Parses an implementation item, `impl` keyword is already parsed.
5717 /// impl<'a, T> TYPE { /* impl items */ }
5718 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5719 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5720 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5721 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5722 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5723 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5724 -> PResult<'a, ItemInfo> {
5725 // First, parse generic parameters if necessary.
5726 let mut generics = if self.choose_generics_over_qpath() {
5727 self.parse_generics()?
5729 ast::Generics::default()
5732 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5733 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5735 ast::ImplPolarity::Negative
5737 ast::ImplPolarity::Positive
5740 // Parse both types and traits as a type, then reinterpret if necessary.
5741 let ty_first = self.parse_ty()?;
5743 // If `for` is missing we try to recover.
5744 let has_for = self.eat_keyword(keywords::For);
5745 let missing_for_span = self.prev_span.between(self.span);
5747 let ty_second = if self.token == token::DotDot {
5748 // We need to report this error after `cfg` expansion for compatibility reasons
5749 self.bump(); // `..`, do not add it to expected tokens
5750 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5751 } else if has_for || self.token.can_begin_type() {
5752 Some(self.parse_ty()?)
5757 generics.where_clause = self.parse_where_clause()?;
5759 let (impl_items, attrs) = self.parse_impl_body()?;
5761 let item_kind = match ty_second {
5762 Some(ty_second) => {
5763 // impl Trait for Type
5765 self.span_err(missing_for_span, "missing `for` in a trait impl");
5768 let ty_first = ty_first.into_inner();
5769 let path = match ty_first.node {
5770 // This notably includes paths passed through `ty` macro fragments (#46438).
5771 TyKind::Path(None, path) => path,
5773 self.span_err(ty_first.span, "expected a trait, found type");
5774 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5777 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5779 ItemKind::Impl(unsafety, polarity, defaultness,
5780 generics, Some(trait_ref), ty_second, impl_items)
5784 ItemKind::Impl(unsafety, polarity, defaultness,
5785 generics, None, ty_first, impl_items)
5789 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5792 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5793 if self.eat_keyword(keywords::For) {
5795 let params = self.parse_generic_params()?;
5797 // We rely on AST validation to rule out invalid cases: There must not be type
5798 // parameters, and the lifetime parameters must not have bounds.
5805 /// Parse struct Foo { ... }
5806 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5807 let class_name = self.parse_ident()?;
5809 let mut generics = self.parse_generics()?;
5811 // There is a special case worth noting here, as reported in issue #17904.
5812 // If we are parsing a tuple struct it is the case that the where clause
5813 // should follow the field list. Like so:
5815 // struct Foo<T>(T) where T: Copy;
5817 // If we are parsing a normal record-style struct it is the case
5818 // that the where clause comes before the body, and after the generics.
5819 // So if we look ahead and see a brace or a where-clause we begin
5820 // parsing a record style struct.
5822 // Otherwise if we look ahead and see a paren we parse a tuple-style
5825 let vdata = if self.token.is_keyword(keywords::Where) {
5826 generics.where_clause = self.parse_where_clause()?;
5827 if self.eat(&token::Semi) {
5828 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5829 VariantData::Unit(ast::DUMMY_NODE_ID)
5831 // If we see: `struct Foo<T> where T: Copy { ... }`
5832 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5834 // No `where` so: `struct Foo<T>;`
5835 } else if self.eat(&token::Semi) {
5836 VariantData::Unit(ast::DUMMY_NODE_ID)
5837 // Record-style struct definition
5838 } else if self.token == token::OpenDelim(token::Brace) {
5839 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5840 // Tuple-style struct definition with optional where-clause.
5841 } else if self.token == token::OpenDelim(token::Paren) {
5842 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5843 generics.where_clause = self.parse_where_clause()?;
5844 self.expect(&token::Semi)?;
5847 let token_str = self.this_token_to_string();
5848 let mut err = self.fatal(&format!(
5849 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5852 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5856 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5859 /// Parse union Foo { ... }
5860 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5861 let class_name = self.parse_ident()?;
5863 let mut generics = self.parse_generics()?;
5865 let vdata = if self.token.is_keyword(keywords::Where) {
5866 generics.where_clause = self.parse_where_clause()?;
5867 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5868 } else if self.token == token::OpenDelim(token::Brace) {
5869 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5871 let token_str = self.this_token_to_string();
5872 let mut err = self.fatal(&format!(
5873 "expected `where` or `{{` after union name, found `{}`", token_str));
5874 err.span_label(self.span, "expected `where` or `{` after union name");
5878 Ok((class_name, ItemKind::Union(vdata, generics), None))
5881 fn consume_block(&mut self, delim: token::DelimToken) {
5882 let mut brace_depth = 0;
5883 if !self.eat(&token::OpenDelim(delim)) {
5887 if self.eat(&token::OpenDelim(delim)) {
5889 } else if self.eat(&token::CloseDelim(delim)) {
5890 if brace_depth == 0 {
5896 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5904 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5905 let mut fields = Vec::new();
5906 if self.eat(&token::OpenDelim(token::Brace)) {
5907 while self.token != token::CloseDelim(token::Brace) {
5908 let field = self.parse_struct_decl_field().map_err(|e| {
5909 self.recover_stmt();
5913 Ok(field) => fields.push(field),
5919 self.eat(&token::CloseDelim(token::Brace));
5921 let token_str = self.this_token_to_string();
5922 let mut err = self.fatal(&format!(
5923 "expected `where`, or `{{` after struct name, found `{}`", token_str));
5924 err.span_label(self.span, "expected `where`, or `{` after struct name");
5931 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5932 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5933 // Unit like structs are handled in parse_item_struct function
5934 let fields = self.parse_unspanned_seq(
5935 &token::OpenDelim(token::Paren),
5936 &token::CloseDelim(token::Paren),
5937 SeqSep::trailing_allowed(token::Comma),
5939 let attrs = p.parse_outer_attributes()?;
5941 let vis = p.parse_visibility(true)?;
5942 let ty = p.parse_ty()?;
5944 span: lo.to(ty.span),
5947 id: ast::DUMMY_NODE_ID,
5956 /// Parse a structure field declaration
5957 fn parse_single_struct_field(&mut self,
5960 attrs: Vec<Attribute> )
5961 -> PResult<'a, StructField> {
5962 let mut seen_comma: bool = false;
5963 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5964 if self.token == token::Comma {
5971 token::CloseDelim(token::Brace) => {}
5972 token::DocComment(_) => {
5973 let previous_span = self.prev_span;
5974 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5975 self.bump(); // consume the doc comment
5976 let comma_after_doc_seen = self.eat(&token::Comma);
5977 // `seen_comma` is always false, because we are inside doc block
5978 // condition is here to make code more readable
5979 if seen_comma == false && comma_after_doc_seen == true {
5982 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
5985 if seen_comma == false {
5986 let sp = self.sess.codemap().next_point(previous_span);
5987 err.span_suggestion_with_applicability(
5989 "missing comma here",
5991 Applicability::MachineApplicable
5998 let sp = self.sess.codemap().next_point(self.prev_span);
5999 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
6000 self.this_token_to_string()));
6001 if self.token.is_ident() {
6002 // This is likely another field; emit the diagnostic and keep going
6003 err.span_suggestion(sp, "try adding a comma", ",".into());
6013 /// Parse an element of a struct definition
6014 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6015 let attrs = self.parse_outer_attributes()?;
6017 let vis = self.parse_visibility(false)?;
6018 self.parse_single_struct_field(lo, vis, attrs)
6021 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6022 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6023 /// a function definition, it's not a tuple struct field) and the contents within the parens
6024 /// isn't valid, emit a proper diagnostic.
6025 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6026 maybe_whole!(self, NtVis, |x| x);
6028 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6029 if self.is_crate_vis() {
6030 self.bump(); // `crate`
6031 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6034 if !self.eat_keyword(keywords::Pub) {
6035 return Ok(respan(self.prev_span, VisibilityKind::Inherited))
6037 let lo = self.prev_span;
6039 if self.check(&token::OpenDelim(token::Paren)) {
6040 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6041 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6042 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6043 // by the following tokens.
6044 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6047 self.bump(); // `crate`
6048 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6050 lo.to(self.prev_span),
6051 VisibilityKind::Crate(CrateSugar::PubCrate),
6054 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6057 self.bump(); // `in`
6058 let path = self.parse_path(PathStyle::Mod)?; // `path`
6059 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6060 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6062 id: ast::DUMMY_NODE_ID,
6065 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6066 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6067 t.is_keyword(keywords::SelfValue))
6069 // `pub(self)` or `pub(super)`
6071 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6072 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6073 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6075 id: ast::DUMMY_NODE_ID,
6078 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6079 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6081 let msg = "incorrect visibility restriction";
6082 let suggestion = r##"some possible visibility restrictions are:
6083 `pub(crate)`: visible only on the current crate
6084 `pub(super)`: visible only in the current module's parent
6085 `pub(in path::to::module)`: visible only on the specified path"##;
6086 let path = self.parse_path(PathStyle::Mod)?;
6087 let sp = self.prev_span;
6088 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6089 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6090 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6091 err.help(suggestion);
6092 err.span_suggestion_with_applicability(
6093 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6095 err.emit(); // emit diagnostic, but continue with public visibility
6099 Ok(respan(lo, VisibilityKind::Public))
6102 /// Parse defaultness: `default` or nothing.
6103 fn parse_defaultness(&mut self) -> Defaultness {
6104 // `pub` is included for better error messages
6105 if self.check_keyword(keywords::Default) &&
6106 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6107 t.is_keyword(keywords::Const) ||
6108 t.is_keyword(keywords::Fn) ||
6109 t.is_keyword(keywords::Unsafe) ||
6110 t.is_keyword(keywords::Extern) ||
6111 t.is_keyword(keywords::Type) ||
6112 t.is_keyword(keywords::Pub)) {
6113 self.bump(); // `default`
6114 Defaultness::Default
6120 /// Given a termination token, parse all of the items in a module
6121 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6122 let mut items = vec![];
6123 while let Some(item) = self.parse_item()? {
6127 if !self.eat(term) {
6128 let token_str = self.this_token_to_string();
6129 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6130 if token_str == ";" {
6131 let msg = "consider removing this semicolon";
6132 err.span_suggestion_short_with_applicability(
6133 self.span, msg, "".to_string(), Applicability::MachineApplicable
6135 if !items.is_empty() { // Issue #51603
6136 let previous_item = &items[items.len()-1];
6137 let previous_item_kind_name = match previous_item.node {
6138 // say "braced struct" because tuple-structs and
6139 // braceless-empty-struct declarations do take a semicolon
6140 ItemKind::Struct(..) => Some("braced struct"),
6141 ItemKind::Enum(..) => Some("enum"),
6142 ItemKind::Trait(..) => Some("trait"),
6143 ItemKind::Union(..) => Some("union"),
6146 if let Some(name) = previous_item_kind_name {
6147 err.help(&format!("{} declarations are not followed by a semicolon",
6152 err.span_label(self.span, "expected item");
6157 let hi = if self.span.is_dummy() {
6164 inner: inner_lo.to(hi),
6169 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6170 let id = self.parse_ident()?;
6171 self.expect(&token::Colon)?;
6172 let ty = self.parse_ty()?;
6173 self.expect(&token::Eq)?;
6174 let e = self.parse_expr()?;
6175 self.expect(&token::Semi)?;
6176 let item = match m {
6177 Some(m) => ItemKind::Static(ty, m, e),
6178 None => ItemKind::Const(ty, e),
6180 Ok((id, item, None))
6183 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6184 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6185 let (in_cfg, outer_attrs) = {
6186 let mut strip_unconfigured = ::config::StripUnconfigured {
6188 should_test: false, // irrelevant
6189 features: None, // don't perform gated feature checking
6191 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6192 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6195 let id_span = self.span;
6196 let id = self.parse_ident()?;
6197 if self.check(&token::Semi) {
6199 if in_cfg && self.recurse_into_file_modules {
6200 // This mod is in an external file. Let's go get it!
6201 let ModulePathSuccess { path, directory_ownership, warn } =
6202 self.submod_path(id, &outer_attrs, id_span)?;
6203 let (module, mut attrs) =
6204 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6206 let attr = Attribute {
6207 id: attr::mk_attr_id(),
6208 style: ast::AttrStyle::Outer,
6209 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6210 tokens: TokenStream::empty(),
6211 is_sugared_doc: false,
6212 span: syntax_pos::DUMMY_SP,
6214 attr::mark_known(&attr);
6217 Ok((id, module, Some(attrs)))
6219 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6220 Ok((id, ItemKind::Mod(placeholder), None))
6223 let old_directory = self.directory.clone();
6224 self.push_directory(id, &outer_attrs);
6226 self.expect(&token::OpenDelim(token::Brace))?;
6227 let mod_inner_lo = self.span;
6228 let attrs = self.parse_inner_attributes()?;
6229 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6231 self.directory = old_directory;
6232 Ok((id, ItemKind::Mod(module), Some(attrs)))
6236 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6237 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6238 self.directory.path.to_mut().push(&path.as_str());
6239 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6241 self.directory.path.to_mut().push(&id.as_str());
6245 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6246 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6249 // On windows, the base path might have the form
6250 // `\\?\foo\bar` in which case it does not tolerate
6251 // mixed `/` and `\` separators, so canonicalize
6254 let s = s.replace("/", "\\");
6255 Some(dir_path.join(s))
6261 /// Returns either a path to a module, or .
6262 pub fn default_submod_path(
6264 relative: Option<ast::Ident>,
6266 codemap: &CodeMap) -> ModulePath
6268 // If we're in a foo.rs file instead of a mod.rs file,
6269 // we need to look for submodules in
6270 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6271 // `./<id>.rs` and `./<id>/mod.rs`.
6272 let relative_prefix_string;
6273 let relative_prefix = if let Some(ident) = relative {
6274 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6275 &relative_prefix_string
6280 let mod_name = id.to_string();
6281 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6282 let secondary_path_str = format!("{}{}{}mod.rs",
6283 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6284 let default_path = dir_path.join(&default_path_str);
6285 let secondary_path = dir_path.join(&secondary_path_str);
6286 let default_exists = codemap.file_exists(&default_path);
6287 let secondary_exists = codemap.file_exists(&secondary_path);
6289 let result = match (default_exists, secondary_exists) {
6290 (true, false) => Ok(ModulePathSuccess {
6292 directory_ownership: DirectoryOwnership::Owned {
6297 (false, true) => Ok(ModulePathSuccess {
6298 path: secondary_path,
6299 directory_ownership: DirectoryOwnership::Owned {
6304 (false, false) => Err(Error::FileNotFoundForModule {
6305 mod_name: mod_name.clone(),
6306 default_path: default_path_str,
6307 secondary_path: secondary_path_str,
6308 dir_path: format!("{}", dir_path.display()),
6310 (true, true) => Err(Error::DuplicatePaths {
6311 mod_name: mod_name.clone(),
6312 default_path: default_path_str,
6313 secondary_path: secondary_path_str,
6319 path_exists: default_exists || secondary_exists,
6324 fn submod_path(&mut self,
6326 outer_attrs: &[Attribute],
6328 -> PResult<'a, ModulePathSuccess> {
6329 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6330 return Ok(ModulePathSuccess {
6331 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6332 // All `#[path]` files are treated as though they are a `mod.rs` file.
6333 // This means that `mod foo;` declarations inside `#[path]`-included
6334 // files are siblings,
6336 // Note that this will produce weirdness when a file named `foo.rs` is
6337 // `#[path]` included and contains a `mod foo;` declaration.
6338 // If you encounter this, it's your own darn fault :P
6339 Some(_) => DirectoryOwnership::Owned { relative: None },
6340 _ => DirectoryOwnership::UnownedViaMod(true),
6347 let relative = match self.directory.ownership {
6348 DirectoryOwnership::Owned { relative } => {
6349 // Push the usage onto the list of non-mod.rs mod uses.
6350 // This is used later for feature-gate error reporting.
6351 if let Some(cur_file_ident) = relative {
6353 .non_modrs_mods.borrow_mut()
6354 .push((cur_file_ident, id_sp));
6358 DirectoryOwnership::UnownedViaBlock |
6359 DirectoryOwnership::UnownedViaMod(_) => None,
6361 let paths = Parser::default_submod_path(
6362 id, relative, &self.directory.path, self.sess.codemap());
6364 match self.directory.ownership {
6365 DirectoryOwnership::Owned { .. } => {
6366 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6368 DirectoryOwnership::UnownedViaBlock => {
6370 "Cannot declare a non-inline module inside a block \
6371 unless it has a path attribute";
6372 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6373 if paths.path_exists {
6374 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6376 err.span_note(id_sp, &msg);
6380 DirectoryOwnership::UnownedViaMod(warn) => {
6382 if let Ok(result) = paths.result {
6383 return Ok(ModulePathSuccess { warn: true, ..result });
6386 let mut err = self.diagnostic().struct_span_err(id_sp,
6387 "cannot declare a new module at this location");
6388 if !id_sp.is_dummy() {
6389 let src_path = self.sess.codemap().span_to_filename(id_sp);
6390 if let FileName::Real(src_path) = src_path {
6391 if let Some(stem) = src_path.file_stem() {
6392 let mut dest_path = src_path.clone();
6393 dest_path.set_file_name(stem);
6394 dest_path.push("mod.rs");
6395 err.span_note(id_sp,
6396 &format!("maybe move this module `{}` to its own \
6397 directory via `{}`", src_path.display(),
6398 dest_path.display()));
6402 if paths.path_exists {
6403 err.span_note(id_sp,
6404 &format!("... or maybe `use` the module `{}` instead \
6405 of possibly redeclaring it",
6413 /// Read a module from a source file.
6414 fn eval_src_mod(&mut self,
6416 directory_ownership: DirectoryOwnership,
6419 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6420 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6421 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6422 let mut err = String::from("circular modules: ");
6423 let len = included_mod_stack.len();
6424 for p in &included_mod_stack[i.. len] {
6425 err.push_str(&p.to_string_lossy());
6426 err.push_str(" -> ");
6428 err.push_str(&path.to_string_lossy());
6429 return Err(self.span_fatal(id_sp, &err[..]));
6431 included_mod_stack.push(path.clone());
6432 drop(included_mod_stack);
6435 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6436 p0.cfg_mods = self.cfg_mods;
6437 let mod_inner_lo = p0.span;
6438 let mod_attrs = p0.parse_inner_attributes()?;
6439 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6440 self.sess.included_mod_stack.borrow_mut().pop();
6441 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6444 /// Parse a function declaration from a foreign module
6445 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6446 -> PResult<'a, ForeignItem> {
6447 self.expect_keyword(keywords::Fn)?;
6449 let (ident, mut generics) = self.parse_fn_header()?;
6450 let decl = self.parse_fn_decl(true)?;
6451 generics.where_clause = self.parse_where_clause()?;
6453 self.expect(&token::Semi)?;
6454 Ok(ast::ForeignItem {
6457 node: ForeignItemKind::Fn(decl, generics),
6458 id: ast::DUMMY_NODE_ID,
6464 /// Parse a static item from a foreign module.
6465 /// Assumes that the `static` keyword is already parsed.
6466 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6467 -> PResult<'a, ForeignItem> {
6468 let mutbl = self.eat_keyword(keywords::Mut);
6469 let ident = self.parse_ident()?;
6470 self.expect(&token::Colon)?;
6471 let ty = self.parse_ty()?;
6473 self.expect(&token::Semi)?;
6477 node: ForeignItemKind::Static(ty, mutbl),
6478 id: ast::DUMMY_NODE_ID,
6484 /// Parse a type from a foreign module
6485 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6486 -> PResult<'a, ForeignItem> {
6487 self.expect_keyword(keywords::Type)?;
6489 let ident = self.parse_ident()?;
6491 self.expect(&token::Semi)?;
6492 Ok(ast::ForeignItem {
6495 node: ForeignItemKind::Ty,
6496 id: ast::DUMMY_NODE_ID,
6502 /// Parse extern crate links
6506 /// extern crate foo;
6507 /// extern crate bar as foo;
6508 fn parse_item_extern_crate(&mut self,
6510 visibility: Visibility,
6511 attrs: Vec<Attribute>)
6512 -> PResult<'a, P<Item>> {
6513 let orig_name = self.parse_ident()?;
6514 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6515 (rename, Some(orig_name.name))
6519 self.expect(&token::Semi)?;
6521 let span = lo.to(self.prev_span);
6522 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6525 /// Parse `extern` for foreign ABIs
6528 /// `extern` is expected to have been
6529 /// consumed before calling this method
6535 fn parse_item_foreign_mod(&mut self,
6537 opt_abi: Option<Abi>,
6538 visibility: Visibility,
6539 mut attrs: Vec<Attribute>)
6540 -> PResult<'a, P<Item>> {
6541 self.expect(&token::OpenDelim(token::Brace))?;
6543 let abi = opt_abi.unwrap_or(Abi::C);
6545 attrs.extend(self.parse_inner_attributes()?);
6547 let mut foreign_items = vec![];
6548 while let Some(item) = self.parse_foreign_item()? {
6549 foreign_items.push(item);
6551 self.expect(&token::CloseDelim(token::Brace))?;
6553 let prev_span = self.prev_span;
6554 let m = ast::ForeignMod {
6556 items: foreign_items
6558 let invalid = keywords::Invalid.ident();
6559 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6562 /// Parse type Foo = Bar;
6563 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6564 let ident = self.parse_ident()?;
6565 let mut tps = self.parse_generics()?;
6566 tps.where_clause = self.parse_where_clause()?;
6567 self.expect(&token::Eq)?;
6568 let ty = self.parse_ty()?;
6569 self.expect(&token::Semi)?;
6570 Ok((ident, ItemKind::Ty(ty, tps), None))
6573 /// Parse the part of an "enum" decl following the '{'
6574 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6575 let mut variants = Vec::new();
6576 let mut all_nullary = true;
6577 let mut any_disr = None;
6578 while self.token != token::CloseDelim(token::Brace) {
6579 let variant_attrs = self.parse_outer_attributes()?;
6580 let vlo = self.span;
6583 let mut disr_expr = None;
6584 let ident = self.parse_ident()?;
6585 if self.check(&token::OpenDelim(token::Brace)) {
6586 // Parse a struct variant.
6587 all_nullary = false;
6588 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6589 ast::DUMMY_NODE_ID);
6590 } else if self.check(&token::OpenDelim(token::Paren)) {
6591 all_nullary = false;
6592 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6593 ast::DUMMY_NODE_ID);
6594 } else if self.eat(&token::Eq) {
6595 disr_expr = Some(AnonConst {
6596 id: ast::DUMMY_NODE_ID,
6597 value: self.parse_expr()?,
6599 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6600 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6602 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6605 let vr = ast::Variant_ {
6607 attrs: variant_attrs,
6611 variants.push(respan(vlo.to(self.prev_span), vr));
6613 if !self.eat(&token::Comma) { break; }
6615 self.expect(&token::CloseDelim(token::Brace))?;
6617 Some(disr_span) if !all_nullary =>
6618 self.span_err(disr_span,
6619 "discriminator values can only be used with a field-less enum"),
6623 Ok(ast::EnumDef { variants: variants })
6626 /// Parse an "enum" declaration
6627 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6628 let id = self.parse_ident()?;
6629 let mut generics = self.parse_generics()?;
6630 generics.where_clause = self.parse_where_clause()?;
6631 self.expect(&token::OpenDelim(token::Brace))?;
6633 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6634 self.recover_stmt();
6635 self.eat(&token::CloseDelim(token::Brace));
6638 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6641 /// Parses a string as an ABI spec on an extern type or module. Consumes
6642 /// the `extern` keyword, if one is found.
6643 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6645 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6647 self.expect_no_suffix(sp, "ABI spec", suf);
6649 match abi::lookup(&s.as_str()) {
6650 Some(abi) => Ok(Some(abi)),
6652 let prev_span = self.prev_span;
6653 let mut err = struct_span_err!(
6654 self.sess.span_diagnostic,
6657 "invalid ABI: found `{}`",
6659 err.span_label(prev_span, "invalid ABI");
6660 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6671 fn is_static_global(&mut self) -> bool {
6672 if self.check_keyword(keywords::Static) {
6673 // Check if this could be a closure
6674 !self.look_ahead(1, |token| {
6675 if token.is_keyword(keywords::Move) {
6679 token::BinOp(token::Or) | token::OrOr => true,
6688 /// Parse one of the items allowed by the flags.
6689 /// NB: this function no longer parses the items inside an
6691 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6692 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6693 maybe_whole!(self, NtItem, |item| {
6694 let mut item = item.into_inner();
6695 let mut attrs = attrs;
6696 mem::swap(&mut item.attrs, &mut attrs);
6697 item.attrs.extend(attrs);
6703 let visibility = self.parse_visibility(false)?;
6705 if self.eat_keyword(keywords::Use) {
6707 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6708 self.expect(&token::Semi)?;
6710 let span = lo.to(self.prev_span);
6711 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6712 return Ok(Some(item));
6715 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6716 self.bump(); // `extern`
6717 if self.eat_keyword(keywords::Crate) {
6718 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6721 let opt_abi = self.parse_opt_abi()?;
6723 if self.eat_keyword(keywords::Fn) {
6724 // EXTERN FUNCTION ITEM
6725 let fn_span = self.prev_span;
6726 let abi = opt_abi.unwrap_or(Abi::C);
6727 let (ident, item_, extra_attrs) =
6728 self.parse_item_fn(Unsafety::Normal,
6730 respan(fn_span, Constness::NotConst),
6732 let prev_span = self.prev_span;
6733 let item = self.mk_item(lo.to(prev_span),
6737 maybe_append(attrs, extra_attrs));
6738 return Ok(Some(item));
6739 } else if self.check(&token::OpenDelim(token::Brace)) {
6740 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6746 if self.is_static_global() {
6749 let m = if self.eat_keyword(keywords::Mut) {
6752 Mutability::Immutable
6754 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6755 let prev_span = self.prev_span;
6756 let item = self.mk_item(lo.to(prev_span),
6760 maybe_append(attrs, extra_attrs));
6761 return Ok(Some(item));
6763 if self.eat_keyword(keywords::Const) {
6764 let const_span = self.prev_span;
6765 if self.check_keyword(keywords::Fn)
6766 || (self.check_keyword(keywords::Unsafe)
6767 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6768 // CONST FUNCTION ITEM
6769 let unsafety = self.parse_unsafety();
6771 let (ident, item_, extra_attrs) =
6772 self.parse_item_fn(unsafety,
6774 respan(const_span, Constness::Const),
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));
6786 if self.eat_keyword(keywords::Mut) {
6787 let prev_span = self.prev_span;
6788 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6789 .help("did you mean to declare a static?")
6792 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6793 let prev_span = self.prev_span;
6794 let item = self.mk_item(lo.to(prev_span),
6798 maybe_append(attrs, extra_attrs));
6799 return Ok(Some(item));
6802 // `unsafe async fn` or `async fn`
6804 self.check_keyword(keywords::Unsafe) &&
6805 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
6807 self.check_keyword(keywords::Async) &&
6808 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
6811 // ASYNC FUNCTION ITEM
6812 let unsafety = self.parse_unsafety();
6813 self.expect_keyword(keywords::Async)?;
6814 self.expect_keyword(keywords::Fn)?;
6815 let fn_span = self.prev_span;
6816 let (ident, item_, extra_attrs) =
6817 self.parse_item_fn(unsafety,
6819 closure_id: ast::DUMMY_NODE_ID,
6820 return_impl_trait_id: ast::DUMMY_NODE_ID,
6822 respan(fn_span, Constness::NotConst),
6824 let prev_span = self.prev_span;
6825 let item = self.mk_item(lo.to(prev_span),
6829 maybe_append(attrs, extra_attrs));
6830 return Ok(Some(item));
6832 if self.check_keyword(keywords::Unsafe) &&
6833 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6834 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6836 // UNSAFE TRAIT ITEM
6837 self.bump(); // `unsafe`
6838 let is_auto = if self.eat_keyword(keywords::Trait) {
6841 self.expect_keyword(keywords::Auto)?;
6842 self.expect_keyword(keywords::Trait)?;
6845 let (ident, item_, extra_attrs) =
6846 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
6847 let prev_span = self.prev_span;
6848 let item = self.mk_item(lo.to(prev_span),
6852 maybe_append(attrs, extra_attrs));
6853 return Ok(Some(item));
6855 if self.check_keyword(keywords::Impl) ||
6856 self.check_keyword(keywords::Unsafe) &&
6857 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6858 self.check_keyword(keywords::Default) &&
6859 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6860 self.check_keyword(keywords::Default) &&
6861 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6863 let defaultness = self.parse_defaultness();
6864 let unsafety = self.parse_unsafety();
6865 self.expect_keyword(keywords::Impl)?;
6866 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6867 let span = lo.to(self.prev_span);
6868 return Ok(Some(self.mk_item(span, ident, item, visibility,
6869 maybe_append(attrs, extra_attrs))));
6871 if self.check_keyword(keywords::Fn) {
6874 let fn_span = self.prev_span;
6875 let (ident, item_, extra_attrs) =
6876 self.parse_item_fn(Unsafety::Normal,
6878 respan(fn_span, Constness::NotConst),
6880 let prev_span = self.prev_span;
6881 let item = self.mk_item(lo.to(prev_span),
6885 maybe_append(attrs, extra_attrs));
6886 return Ok(Some(item));
6888 if self.check_keyword(keywords::Unsafe)
6889 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6890 // UNSAFE FUNCTION ITEM
6891 self.bump(); // `unsafe`
6892 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
6893 self.check(&token::OpenDelim(token::Brace));
6894 let abi = if self.eat_keyword(keywords::Extern) {
6895 self.parse_opt_abi()?.unwrap_or(Abi::C)
6899 self.expect_keyword(keywords::Fn)?;
6900 let fn_span = self.prev_span;
6901 let (ident, item_, extra_attrs) =
6902 self.parse_item_fn(Unsafety::Unsafe,
6904 respan(fn_span, Constness::NotConst),
6906 let prev_span = self.prev_span;
6907 let item = self.mk_item(lo.to(prev_span),
6911 maybe_append(attrs, extra_attrs));
6912 return Ok(Some(item));
6914 if self.eat_keyword(keywords::Mod) {
6916 let (ident, item_, extra_attrs) =
6917 self.parse_item_mod(&attrs[..])?;
6918 let prev_span = self.prev_span;
6919 let item = self.mk_item(lo.to(prev_span),
6923 maybe_append(attrs, extra_attrs));
6924 return Ok(Some(item));
6926 if self.eat_keyword(keywords::Type) {
6928 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6929 let prev_span = self.prev_span;
6930 let item = self.mk_item(lo.to(prev_span),
6934 maybe_append(attrs, extra_attrs));
6935 return Ok(Some(item));
6937 if self.eat_keyword(keywords::Enum) {
6939 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6940 let prev_span = self.prev_span;
6941 let item = self.mk_item(lo.to(prev_span),
6945 maybe_append(attrs, extra_attrs));
6946 return Ok(Some(item));
6948 if self.check_keyword(keywords::Trait)
6949 || (self.check_keyword(keywords::Auto)
6950 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6952 let is_auto = if self.eat_keyword(keywords::Trait) {
6955 self.expect_keyword(keywords::Auto)?;
6956 self.expect_keyword(keywords::Trait)?;
6960 let (ident, item_, extra_attrs) =
6961 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6962 let prev_span = self.prev_span;
6963 let item = self.mk_item(lo.to(prev_span),
6967 maybe_append(attrs, extra_attrs));
6968 return Ok(Some(item));
6970 if self.eat_keyword(keywords::Struct) {
6972 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6973 let prev_span = self.prev_span;
6974 let item = self.mk_item(lo.to(prev_span),
6978 maybe_append(attrs, extra_attrs));
6979 return Ok(Some(item));
6981 if self.is_union_item() {
6984 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6985 let prev_span = self.prev_span;
6986 let item = self.mk_item(lo.to(prev_span),
6990 maybe_append(attrs, extra_attrs));
6991 return Ok(Some(item));
6993 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6994 return Ok(Some(macro_def));
6997 // Verify whether we have encountered a struct or method definition where the user forgot to
6998 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6999 if visibility.node == VisibilityKind::Public &&
7000 self.check_ident() &&
7001 self.look_ahead(1, |t| *t != token::Not)
7003 // Space between `pub` keyword and the identifier
7006 // ^^^ `sp` points here
7007 let sp = self.prev_span.between(self.span);
7008 let full_sp = self.prev_span.to(self.span);
7009 let ident_sp = self.span;
7010 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7011 // possible public struct definition where `struct` was forgotten
7012 let ident = self.parse_ident().unwrap();
7013 let msg = format!("add `struct` here to parse `{}` as a public struct",
7015 let mut err = self.diagnostic()
7016 .struct_span_err(sp, "missing `struct` for struct definition");
7017 err.span_suggestion_short_with_applicability(
7018 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7021 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7022 let ident = self.parse_ident().unwrap();
7023 self.consume_block(token::Paren);
7024 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7025 self.check(&token::OpenDelim(token::Brace))
7027 ("fn", "method", false)
7028 } else if self.check(&token::Colon) {
7032 ("fn` or `struct", "method or struct", true)
7035 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7036 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7038 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7042 err.span_suggestion_short_with_applicability(
7043 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7046 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
7047 err.span_suggestion_with_applicability(
7049 "if you meant to call a macro, try",
7050 format!("{}!", snippet),
7051 // this is the `ambiguous` conditional branch
7052 Applicability::MaybeIncorrect
7055 err.help("if you meant to call a macro, remove the `pub` \
7056 and add a trailing `!` after the identifier");
7062 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7065 /// Parse a foreign item.
7066 crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
7067 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
7069 let attrs = self.parse_outer_attributes()?;
7071 let visibility = self.parse_visibility(false)?;
7073 // FOREIGN STATIC ITEM
7074 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7075 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7076 if self.token.is_keyword(keywords::Const) {
7078 .struct_span_err(self.span, "extern items cannot be `const`")
7079 .span_suggestion_with_applicability(
7081 "try using a static value",
7082 "static".to_owned(),
7083 Applicability::MachineApplicable
7086 self.bump(); // `static` or `const`
7087 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
7089 // FOREIGN FUNCTION ITEM
7090 if self.check_keyword(keywords::Fn) {
7091 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
7093 // FOREIGN TYPE ITEM
7094 if self.check_keyword(keywords::Type) {
7095 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
7098 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7102 ident: keywords::Invalid.ident(),
7103 span: lo.to(self.prev_span),
7104 id: ast::DUMMY_NODE_ID,
7107 node: ForeignItemKind::Macro(mac),
7112 if !attrs.is_empty() {
7113 self.expected_item_err(&attrs);
7121 /// This is the fall-through for parsing items.
7122 fn parse_macro_use_or_failure(
7124 attrs: Vec<Attribute> ,
7125 macros_allowed: bool,
7126 attributes_allowed: bool,
7128 visibility: Visibility
7129 ) -> PResult<'a, Option<P<Item>>> {
7130 if macros_allowed && self.token.is_path_start() {
7131 // MACRO INVOCATION ITEM
7133 let prev_span = self.prev_span;
7134 self.complain_if_pub_macro(&visibility.node, prev_span);
7136 let mac_lo = self.span;
7139 let pth = self.parse_path(PathStyle::Mod)?;
7140 self.expect(&token::Not)?;
7142 // a 'special' identifier (like what `macro_rules!` uses)
7143 // is optional. We should eventually unify invoc syntax
7145 let id = if self.token.is_ident() {
7148 keywords::Invalid.ident() // no special identifier
7150 // eat a matched-delimiter token tree:
7151 let (delim, tts) = self.expect_delimited_token_tree()?;
7152 if delim != MacDelimiter::Brace {
7153 if !self.eat(&token::Semi) {
7154 self.span_err(self.prev_span,
7155 "macros that expand to items must either \
7156 be surrounded with braces or followed by \
7161 let hi = self.prev_span;
7162 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7163 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7164 return Ok(Some(item));
7167 // FAILURE TO PARSE ITEM
7168 match visibility.node {
7169 VisibilityKind::Inherited => {}
7171 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7175 if !attributes_allowed && !attrs.is_empty() {
7176 self.expected_item_err(&attrs);
7181 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7182 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7183 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7185 if self.token.is_path_start() && !self.is_extern_non_path() {
7186 let prev_span = self.prev_span;
7188 let pth = self.parse_path(PathStyle::Mod)?;
7190 if pth.segments.len() == 1 {
7191 if !self.eat(&token::Not) {
7192 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7195 self.expect(&token::Not)?;
7198 if let Some(vis) = vis {
7199 self.complain_if_pub_macro(&vis.node, prev_span);
7204 // eat a matched-delimiter token tree:
7205 let (delim, tts) = self.expect_delimited_token_tree()?;
7206 if delim != MacDelimiter::Brace {
7207 self.expect(&token::Semi)?
7210 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7216 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7217 where F: FnOnce(&mut Self) -> PResult<'a, R>
7219 // Record all tokens we parse when parsing this item.
7220 let mut tokens = Vec::new();
7221 match self.token_cursor.frame.last_token {
7222 LastToken::Collecting(_) => {
7223 panic!("cannot collect tokens recursively yet")
7225 LastToken::Was(ref mut last) => tokens.extend(last.take()),
7227 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7228 let prev = self.token_cursor.stack.len();
7230 let last_token = if self.token_cursor.stack.len() == prev {
7231 &mut self.token_cursor.frame.last_token
7233 &mut self.token_cursor.stack[prev].last_token
7235 let mut tokens = match *last_token {
7236 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7237 LastToken::Was(_) => panic!("our vector went away?"),
7240 // If we're not at EOF our current token wasn't actually consumed by
7241 // `f`, but it'll still be in our list that we pulled out. In that case
7243 if self.token == token::Eof {
7244 *last_token = LastToken::Was(None);
7246 *last_token = LastToken::Was(tokens.pop());
7249 Ok((ret?, tokens.into_iter().collect()))
7252 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7253 let attrs = self.parse_outer_attributes()?;
7255 let (ret, tokens) = self.collect_tokens(|this| {
7256 this.parse_item_(attrs, true, false)
7259 // Once we've parsed an item and recorded the tokens we got while
7260 // parsing we may want to store `tokens` into the item we're about to
7261 // return. Note, though, that we specifically didn't capture tokens
7262 // related to outer attributes. The `tokens` field here may later be
7263 // used with procedural macros to convert this item back into a token
7264 // stream, but during expansion we may be removing attributes as we go
7267 // If we've got inner attributes then the `tokens` we've got above holds
7268 // these inner attributes. If an inner attribute is expanded we won't
7269 // actually remove it from the token stream, so we'll just keep yielding
7270 // it (bad!). To work around this case for now we just avoid recording
7271 // `tokens` if we detect any inner attributes. This should help keep
7272 // expansion correct, but we should fix this bug one day!
7275 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7276 i.tokens = Some(tokens);
7284 fn is_import_coupler(&mut self) -> bool {
7285 self.check(&token::ModSep) &&
7286 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7287 *t == token::BinOp(token::Star))
7292 /// USE_TREE = [`::`] `*` |
7293 /// [`::`] `{` USE_TREE_LIST `}` |
7295 /// PATH `::` `{` USE_TREE_LIST `}` |
7296 /// PATH [`as` IDENT]
7297 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7300 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7301 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7302 self.check(&token::BinOp(token::Star)) ||
7303 self.is_import_coupler() {
7304 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7305 if self.eat(&token::ModSep) {
7306 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7309 if self.eat(&token::BinOp(token::Star)) {
7312 UseTreeKind::Nested(self.parse_use_tree_list()?)
7315 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7316 prefix = self.parse_path(PathStyle::Mod)?;
7318 if self.eat(&token::ModSep) {
7319 if self.eat(&token::BinOp(token::Star)) {
7322 UseTreeKind::Nested(self.parse_use_tree_list()?)
7325 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7329 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7332 /// Parse UseTreeKind::Nested(list)
7334 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7335 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7336 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7337 &token::CloseDelim(token::Brace),
7338 SeqSep::trailing_allowed(token::Comma), |this| {
7339 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7343 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7344 if self.eat_keyword(keywords::As) {
7346 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7348 Ok(Some(ident.gensym()))
7350 _ => self.parse_ident().map(Some),
7357 /// Parses a source module as a crate. This is the main
7358 /// entry point for the parser.
7359 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7362 attrs: self.parse_inner_attributes()?,
7363 module: self.parse_mod_items(&token::Eof, lo)?,
7364 span: lo.to(self.span),
7368 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7369 let ret = match self.token {
7370 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7371 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7378 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7379 match self.parse_optional_str() {
7380 Some((s, style, suf)) => {
7381 let sp = self.prev_span;
7382 self.expect_no_suffix(sp, "string literal", suf);
7386 let msg = "expected string literal";
7387 let mut err = self.fatal(msg);
7388 err.span_label(self.span, msg);