1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc_target::spec::abi::{self, Abi};
12 use ast::{AngleBracketedArgs, ParenthesisedArgs, AttrStyle, BareFnTy};
13 use ast::{GenericBound, TraitBoundModifier};
15 use ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy, Movability};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl, FnHeader};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::{GenericParam, GenericParamKind};
26 use ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
27 use ast::{Label, Lifetime, Lit, LitKind};
29 use ast::MacStmtStyle;
30 use ast::{Mac, Mac_, MacDelimiter};
31 use ast::{MutTy, Mutability};
32 use ast::{Pat, PatKind, PathSegment};
33 use ast::{PolyTraitRef, QSelf};
34 use ast::{Stmt, StmtKind};
35 use ast::{VariantData, StructField};
38 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
39 use ast::{Ty, TyKind, TypeBinding, GenericBounds};
40 use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
41 use ast::{UseTree, UseTreeKind};
42 use ast::{BinOpKind, UnOp};
43 use ast::{RangeEnd, RangeSyntax};
45 use source_map::{self, SourceMap, Spanned, respan};
46 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName, edition::Edition};
47 use errors::{self, Applicability, DiagnosticBuilder, DiagnosticId};
48 use parse::{self, SeqSep, classify, token};
49 use parse::lexer::TokenAndSpan;
50 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
57 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
58 use symbol::{Symbol, keywords};
63 use std::path::{self, Path, PathBuf};
67 /// Whether the type alias or associated type is a concrete type or an existential type
69 /// Just a new name for the same type
71 /// Only trait impls of the type will be usable, not the actual type itself
72 Existential(GenericBounds),
76 struct Restrictions: u8 {
77 const STMT_EXPR = 1 << 0;
78 const NO_STRUCT_LITERAL = 1 << 1;
82 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
84 /// How to parse a path.
85 #[derive(Copy, Clone, PartialEq)]
87 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
88 /// with something else. For example, in expressions `segment < ....` can be interpreted
89 /// as a comparison and `segment ( ....` can be interpreted as a function call.
90 /// In all such contexts the non-path interpretation is preferred by default for practical
91 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
92 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
94 /// In other contexts, notably in types, no ambiguity exists and paths can be written
95 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
96 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
98 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
99 /// visibilities or attributes.
100 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
101 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
102 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
103 /// tokens when something goes wrong.
107 #[derive(Clone, Copy, PartialEq, Debug)]
113 #[derive(Clone, Copy, PartialEq, Debug)]
119 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
120 /// dropped into the token stream, which happens while parsing the result of
121 /// macro expansion). Placement of these is not as complex as I feared it would
122 /// be. The important thing is to make sure that lookahead doesn't balk at
123 /// `token::Interpolated` tokens.
124 macro_rules! maybe_whole_expr {
126 if let token::Interpolated(nt) = $p.token.clone() {
128 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
130 return Ok((*e).clone());
132 token::NtPath(ref path) => {
135 let kind = ExprKind::Path(None, (*path).clone());
136 return Ok($p.mk_expr(span, kind, ThinVec::new()));
138 token::NtBlock(ref block) => {
141 let kind = ExprKind::Block((*block).clone(), None);
142 return Ok($p.mk_expr(span, kind, ThinVec::new()));
150 /// As maybe_whole_expr, but for things other than expressions
151 macro_rules! maybe_whole {
152 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
153 if let token::Interpolated(nt) = $p.token.clone() {
154 if let token::$constructor($x) = nt.0.clone() {
162 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
163 if let Some(ref mut rhs) = rhs {
169 #[derive(Debug, Clone, Copy, PartialEq)]
180 trait RecoverQPath: Sized {
181 const PATH_STYLE: PathStyle = PathStyle::Expr;
182 fn to_ty(&self) -> Option<P<Ty>>;
183 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
184 fn to_string(&self) -> String;
187 impl RecoverQPath for Ty {
188 const PATH_STYLE: PathStyle = PathStyle::Type;
189 fn to_ty(&self) -> Option<P<Ty>> {
190 Some(P(self.clone()))
192 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
193 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
195 fn to_string(&self) -> String {
196 pprust::ty_to_string(self)
200 impl RecoverQPath for Pat {
201 fn to_ty(&self) -> Option<P<Ty>> {
204 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
205 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
207 fn to_string(&self) -> String {
208 pprust::pat_to_string(self)
212 impl RecoverQPath for Expr {
213 fn to_ty(&self) -> Option<P<Ty>> {
216 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
217 Self { span: path.span, node: ExprKind::Path(qself, path),
218 id: self.id, attrs: self.attrs.clone() }
220 fn to_string(&self) -> String {
221 pprust::expr_to_string(self)
225 /* ident is handled by common.rs */
228 pub struct Parser<'a> {
229 pub sess: &'a ParseSess,
230 /// the current token:
231 pub token: token::Token,
232 /// the span of the current token:
234 /// the span of the previous token:
235 meta_var_span: Option<Span>,
237 /// the previous token kind
238 prev_token_kind: PrevTokenKind,
239 restrictions: Restrictions,
240 /// Used to determine the path to externally loaded source files
241 crate directory: Directory<'a>,
242 /// Whether to parse sub-modules in other files.
243 pub recurse_into_file_modules: bool,
244 /// Name of the root module this parser originated from. If `None`, then the
245 /// name is not known. This does not change while the parser is descending
246 /// into modules, and sub-parsers have new values for this name.
247 pub root_module_name: Option<String>,
248 crate expected_tokens: Vec<TokenType>,
249 token_cursor: TokenCursor,
250 desugar_doc_comments: bool,
251 /// Whether we should configure out of line modules as we parse.
258 frame: TokenCursorFrame,
259 stack: Vec<TokenCursorFrame>,
263 struct TokenCursorFrame {
264 delim: token::DelimToken,
267 tree_cursor: tokenstream::Cursor,
269 last_token: LastToken,
272 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
273 /// by the parser, and then that's transitively used to record the tokens that
274 /// each parse AST item is created with.
276 /// Right now this has two states, either collecting tokens or not collecting
277 /// tokens. If we're collecting tokens we just save everything off into a local
278 /// `Vec`. This should eventually though likely save tokens from the original
279 /// token stream and just use slicing of token streams to avoid creation of a
280 /// whole new vector.
282 /// The second state is where we're passively not recording tokens, but the last
283 /// token is still tracked for when we want to start recording tokens. This
284 /// "last token" means that when we start recording tokens we'll want to ensure
285 /// that this, the first token, is included in the output.
287 /// You can find some more example usage of this in the `collect_tokens` method
291 Collecting(Vec<TokenStream>),
292 Was(Option<TokenStream>),
295 impl TokenCursorFrame {
296 fn new(sp: Span, delimited: &Delimited) -> Self {
298 delim: delimited.delim,
300 open_delim: delimited.delim == token::NoDelim,
301 tree_cursor: delimited.stream().into_trees(),
302 close_delim: delimited.delim == token::NoDelim,
303 last_token: LastToken::Was(None),
309 fn next(&mut self) -> TokenAndSpan {
311 let tree = if !self.frame.open_delim {
312 self.frame.open_delim = true;
313 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
314 .open_tt(self.frame.span)
315 } else if let Some(tree) = self.frame.tree_cursor.next() {
317 } else if !self.frame.close_delim {
318 self.frame.close_delim = true;
319 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
320 .close_tt(self.frame.span)
321 } else if let Some(frame) = self.stack.pop() {
325 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
328 match self.frame.last_token {
329 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
330 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
334 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
335 TokenTree::Delimited(sp, ref delimited) => {
336 let frame = TokenCursorFrame::new(sp, delimited);
337 self.stack.push(mem::replace(&mut self.frame, frame));
343 fn next_desugared(&mut self) -> TokenAndSpan {
344 let (sp, name) = match self.next() {
345 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
349 let stripped = strip_doc_comment_decoration(&name.as_str());
351 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
352 // required to wrap the text.
353 let mut num_of_hashes = 0;
355 for ch in stripped.chars() {
358 '#' if count > 0 => count + 1,
361 num_of_hashes = cmp::max(num_of_hashes, count);
364 let body = TokenTree::Delimited(sp, Delimited {
365 delim: token::Bracket,
366 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
367 TokenTree::Token(sp, token::Eq),
368 TokenTree::Token(sp, token::Literal(
369 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
370 .iter().cloned().collect::<TokenStream>().into(),
373 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
374 delim: token::NoDelim,
375 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
376 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
377 .iter().cloned().collect::<TokenStream>().into()
379 [TokenTree::Token(sp, token::Pound), body]
380 .iter().cloned().collect::<TokenStream>().into()
388 #[derive(Clone, PartialEq)]
389 crate enum TokenType {
391 Keyword(keywords::Keyword),
400 fn to_string(&self) -> String {
402 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
403 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
404 TokenType::Operator => "an operator".to_string(),
405 TokenType::Lifetime => "lifetime".to_string(),
406 TokenType::Ident => "identifier".to_string(),
407 TokenType::Path => "path".to_string(),
408 TokenType::Type => "type".to_string(),
413 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
414 /// `IDENT<<u8 as Trait>::AssocTy>`.
416 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
417 /// that IDENT is not the ident of a fn trait
418 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
419 t == &token::ModSep || t == &token::Lt ||
420 t == &token::BinOp(token::Shl)
423 /// Information about the path to a module.
424 pub struct ModulePath {
427 pub result: Result<ModulePathSuccess, Error>,
430 pub struct ModulePathSuccess {
432 pub directory_ownership: DirectoryOwnership,
437 FileNotFoundForModule {
439 default_path: String,
440 secondary_path: String,
445 default_path: String,
446 secondary_path: String,
449 InclusiveRangeWithNoEnd,
453 fn span_err<S: Into<MultiSpan>>(self,
455 handler: &errors::Handler) -> DiagnosticBuilder {
457 Error::FileNotFoundForModule { ref mod_name,
461 let mut err = struct_span_err!(handler, sp, E0583,
462 "file not found for module `{}`", mod_name);
463 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
469 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
470 let mut err = struct_span_err!(handler, sp, E0584,
471 "file for module `{}` found at both {} and {}",
475 err.help("delete or rename one of them to remove the ambiguity");
478 Error::UselessDocComment => {
479 let mut err = struct_span_err!(handler, sp, E0585,
480 "found a documentation comment that doesn't document anything");
481 err.help("doc comments must come before what they document, maybe a comment was \
482 intended with `//`?");
485 Error::InclusiveRangeWithNoEnd => {
486 let mut err = struct_span_err!(handler, sp, E0586,
487 "inclusive range with no end");
488 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
498 AttributesParsed(ThinVec<Attribute>),
499 AlreadyParsed(P<Expr>),
502 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
503 fn from(o: Option<ThinVec<Attribute>>) -> Self {
504 if let Some(attrs) = o {
505 LhsExpr::AttributesParsed(attrs)
507 LhsExpr::NotYetParsed
512 impl From<P<Expr>> for LhsExpr {
513 fn from(expr: P<Expr>) -> Self {
514 LhsExpr::AlreadyParsed(expr)
518 /// Create a placeholder argument.
519 fn dummy_arg(span: Span) -> Arg {
520 let ident = Ident::new(keywords::Invalid.name(), span);
522 id: ast::DUMMY_NODE_ID,
523 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
529 id: ast::DUMMY_NODE_ID
531 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
534 #[derive(Copy, Clone, Debug)]
535 enum TokenExpectType {
540 impl<'a> Parser<'a> {
541 pub fn new(sess: &'a ParseSess,
543 directory: Option<Directory<'a>>,
544 recurse_into_file_modules: bool,
545 desugar_doc_comments: bool)
547 let mut parser = Parser {
549 token: token::Whitespace,
550 span: syntax_pos::DUMMY_SP,
551 prev_span: syntax_pos::DUMMY_SP,
553 prev_token_kind: PrevTokenKind::Other,
554 restrictions: Restrictions::empty(),
555 recurse_into_file_modules,
556 directory: Directory {
557 path: Cow::from(PathBuf::new()),
558 ownership: DirectoryOwnership::Owned { relative: None }
560 root_module_name: None,
561 expected_tokens: Vec::new(),
562 token_cursor: TokenCursor {
563 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
564 delim: token::NoDelim,
569 desugar_doc_comments,
573 let tok = parser.next_tok();
574 parser.token = tok.tok;
575 parser.span = tok.sp;
577 if let Some(directory) = directory {
578 parser.directory = directory;
579 } else if !parser.span.is_dummy() {
580 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
582 parser.directory.path = Cow::from(path);
586 parser.process_potential_macro_variable();
590 fn next_tok(&mut self) -> TokenAndSpan {
591 let mut next = if self.desugar_doc_comments {
592 self.token_cursor.next_desugared()
594 self.token_cursor.next()
596 if next.sp.is_dummy() {
597 // Tweak the location for better diagnostics, but keep syntactic context intact.
598 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
603 /// Convert the current token to a string using self's reader
604 pub fn this_token_to_string(&self) -> String {
605 pprust::token_to_string(&self.token)
608 fn token_descr(&self) -> Option<&'static str> {
609 Some(match &self.token {
610 t if t.is_special_ident() => "reserved identifier",
611 t if t.is_used_keyword() => "keyword",
612 t if t.is_unused_keyword() => "reserved keyword",
617 fn this_token_descr(&self) -> String {
618 if let Some(prefix) = self.token_descr() {
619 format!("{} `{}`", prefix, self.this_token_to_string())
621 format!("`{}`", self.this_token_to_string())
625 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
626 let token_str = pprust::token_to_string(t);
627 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
630 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
631 match self.expect_one_of(&[], &[]) {
633 Ok(_) => unreachable!(),
637 /// Expect and consume the token t. Signal an error if
638 /// the next token is not t.
639 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
640 if self.expected_tokens.is_empty() {
641 if self.token == *t {
645 let token_str = pprust::token_to_string(t);
646 let this_token_str = self.this_token_to_string();
647 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
651 let sp = if self.token == token::Token::Eof {
652 // EOF, don't want to point at the following char, but rather the last token
655 self.sess.source_map().next_point(self.prev_span)
657 let label_exp = format!("expected `{}`", token_str);
658 let cm = self.sess.source_map();
659 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
660 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
661 // When the spans are in the same line, it means that the only content
662 // between them is whitespace, point only at the found token.
663 err.span_label(self.span, label_exp);
666 err.span_label(sp, label_exp);
667 err.span_label(self.span, "unexpected token");
673 self.expect_one_of(slice::from_ref(t), &[])
677 /// Expect next token to be edible or inedible token. If edible,
678 /// then consume it; if inedible, then return without consuming
679 /// anything. Signal a fatal error if next token is unexpected.
680 fn expect_one_of(&mut self,
681 edible: &[token::Token],
682 inedible: &[token::Token]) -> PResult<'a, ()>{
683 fn tokens_to_string(tokens: &[TokenType]) -> String {
684 let mut i = tokens.iter();
685 // This might be a sign we need a connect method on Iterator.
687 .map_or("".to_string(), |t| t.to_string());
688 i.enumerate().fold(b, |mut b, (i, a)| {
689 if tokens.len() > 2 && i == tokens.len() - 2 {
691 } else if tokens.len() == 2 && i == tokens.len() - 2 {
696 b.push_str(&a.to_string());
700 if edible.contains(&self.token) {
703 } else if inedible.contains(&self.token) {
704 // leave it in the input
707 let mut expected = edible.iter()
708 .map(|x| TokenType::Token(x.clone()))
709 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
710 .chain(self.expected_tokens.iter().cloned())
711 .collect::<Vec<_>>();
712 expected.sort_by_cached_key(|x| x.to_string());
714 let expect = tokens_to_string(&expected[..]);
715 let actual = self.this_token_to_string();
716 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
717 let short_expect = if expected.len() > 6 {
718 format!("{} possible tokens", expected.len())
722 (format!("expected one of {}, found `{}`", expect, actual),
723 (self.sess.source_map().next_point(self.prev_span),
724 format!("expected one of {} here", short_expect)))
725 } else if expected.is_empty() {
726 (format!("unexpected token: `{}`", actual),
727 (self.prev_span, "unexpected token after this".to_string()))
729 (format!("expected {}, found `{}`", expect, actual),
730 (self.sess.source_map().next_point(self.prev_span),
731 format!("expected {} here", expect)))
733 let mut err = self.fatal(&msg_exp);
734 let sp = if self.token == token::Token::Eof {
735 // This is EOF, don't want to point at the following char, but rather the last token
741 let cm = self.sess.source_map();
742 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
743 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
744 // When the spans are in the same line, it means that the only content between
745 // them is whitespace, point at the found token in that case:
747 // X | () => { syntax error };
748 // | ^^^^^ expected one of 8 possible tokens here
750 // instead of having:
752 // X | () => { syntax error };
753 // | -^^^^^ unexpected token
755 // | expected one of 8 possible tokens here
756 err.span_label(self.span, label_exp);
759 err.span_label(sp, label_exp);
760 err.span_label(self.span, "unexpected token");
767 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
768 fn interpolated_or_expr_span(&self,
769 expr: PResult<'a, P<Expr>>)
770 -> PResult<'a, (Span, P<Expr>)> {
772 if self.prev_token_kind == PrevTokenKind::Interpolated {
780 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
781 let mut err = self.struct_span_err(self.span,
782 &format!("expected identifier, found {}",
783 self.this_token_descr()));
784 if let Some(token_descr) = self.token_descr() {
785 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
787 err.span_label(self.span, "expected identifier");
788 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
789 err.span_suggestion(self.span, "remove this comma", "".into());
795 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
796 self.parse_ident_common(true)
799 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
801 token::Ident(ident, _) => {
802 if self.token.is_reserved_ident() {
803 let mut err = self.expected_ident_found();
810 let span = self.span;
812 Ok(Ident::new(ident.name, span))
815 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
816 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
818 self.expected_ident_found()
824 /// Check if the next token is `tok`, and return `true` if so.
826 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
828 crate fn check(&mut self, tok: &token::Token) -> bool {
829 let is_present = self.token == *tok;
830 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
834 /// Consume token 'tok' if it exists. Returns true if the given
835 /// token was present, false otherwise.
836 pub fn eat(&mut self, tok: &token::Token) -> bool {
837 let is_present = self.check(tok);
838 if is_present { self.bump() }
842 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
843 self.expected_tokens.push(TokenType::Keyword(kw));
844 self.token.is_keyword(kw)
847 /// If the next token is the given keyword, eat it and return
848 /// true. Otherwise, return false.
849 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
850 if self.check_keyword(kw) {
858 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
859 if self.token.is_keyword(kw) {
867 /// If the given word is not a keyword, signal an error.
868 /// If the next token is not the given word, signal an error.
869 /// Otherwise, eat it.
870 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
871 if !self.eat_keyword(kw) {
878 fn check_ident(&mut self) -> bool {
879 if self.token.is_ident() {
882 self.expected_tokens.push(TokenType::Ident);
887 fn check_path(&mut self) -> bool {
888 if self.token.is_path_start() {
891 self.expected_tokens.push(TokenType::Path);
896 fn check_type(&mut self) -> bool {
897 if self.token.can_begin_type() {
900 self.expected_tokens.push(TokenType::Type);
905 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
906 /// and continue. If a `+` is not seen, return false.
908 /// This is using when token splitting += into +.
909 /// See issue 47856 for an example of when this may occur.
910 fn eat_plus(&mut self) -> bool {
911 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
913 token::BinOp(token::Plus) => {
917 token::BinOpEq(token::Plus) => {
918 let span = self.span.with_lo(self.span.lo() + BytePos(1));
919 self.bump_with(token::Eq, span);
927 /// Checks to see if the next token is either `+` or `+=`.
928 /// Otherwise returns false.
929 fn check_plus(&mut self) -> bool {
930 if self.token.is_like_plus() {
934 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
939 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
940 /// `&` and continue. If an `&` is not seen, signal an error.
941 fn expect_and(&mut self) -> PResult<'a, ()> {
942 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
944 token::BinOp(token::And) => {
949 let span = self.span.with_lo(self.span.lo() + BytePos(1));
950 Ok(self.bump_with(token::BinOp(token::And), span))
952 _ => self.unexpected()
956 /// Expect and consume an `|`. If `||` is seen, replace it with a single
957 /// `|` and continue. If an `|` is not seen, signal an error.
958 fn expect_or(&mut self) -> PResult<'a, ()> {
959 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
961 token::BinOp(token::Or) => {
966 let span = self.span.with_lo(self.span.lo() + BytePos(1));
967 Ok(self.bump_with(token::BinOp(token::Or), span))
969 _ => self.unexpected()
973 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
975 None => {/* everything ok */}
977 let text = suf.as_str();
979 self.span_bug(sp, "found empty literal suffix in Some")
981 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
986 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
987 /// `<` and continue. If a `<` is not seen, return false.
989 /// This is meant to be used when parsing generics on a path to get the
991 fn eat_lt(&mut self) -> bool {
992 self.expected_tokens.push(TokenType::Token(token::Lt));
998 token::BinOp(token::Shl) => {
999 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1000 self.bump_with(token::Lt, span);
1007 fn expect_lt(&mut self) -> PResult<'a, ()> {
1015 /// Expect and consume a GT. if a >> is seen, replace it
1016 /// with a single > and continue. If a GT is not seen,
1017 /// signal an error.
1018 fn expect_gt(&mut self) -> PResult<'a, ()> {
1019 self.expected_tokens.push(TokenType::Token(token::Gt));
1025 token::BinOp(token::Shr) => {
1026 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1027 Ok(self.bump_with(token::Gt, span))
1029 token::BinOpEq(token::Shr) => {
1030 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1031 Ok(self.bump_with(token::Ge, span))
1034 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1035 Ok(self.bump_with(token::Eq, span))
1037 _ => self.unexpected()
1041 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1042 /// passes through any errors encountered. Used for error recovery.
1043 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1044 let handler = self.diagnostic();
1046 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1048 TokenExpectType::Expect,
1049 |p| Ok(p.parse_token_tree())) {
1050 handler.cancel(err);
1054 /// Parse a sequence, including the closing delimiter. The function
1055 /// f must consume tokens until reaching the next separator or
1056 /// closing bracket.
1057 pub fn parse_seq_to_end<T, F>(&mut self,
1061 -> PResult<'a, Vec<T>> where
1062 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1064 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1069 /// Parse a sequence, not including the closing delimiter. The function
1070 /// f must consume tokens until reaching the next separator or
1071 /// closing bracket.
1072 pub fn parse_seq_to_before_end<T, F>(&mut self,
1076 -> PResult<'a, Vec<T>>
1077 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1079 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1082 fn parse_seq_to_before_tokens<T, F>(
1084 kets: &[&token::Token],
1086 expect: TokenExpectType,
1088 ) -> PResult<'a, Vec<T>>
1089 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1091 let mut first: bool = true;
1093 while !kets.iter().any(|k| {
1095 TokenExpectType::Expect => self.check(k),
1096 TokenExpectType::NoExpect => self.token == **k,
1100 token::CloseDelim(..) | token::Eof => break,
1103 if let Some(ref t) = sep.sep {
1107 if let Err(mut e) = self.expect(t) {
1108 // Attempt to keep parsing if it was a similar separator
1109 if let Some(ref tokens) = t.similar_tokens() {
1110 if tokens.contains(&self.token) {
1115 // Attempt to keep parsing if it was an omitted separator
1129 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1131 TokenExpectType::Expect => self.check(k),
1132 TokenExpectType::NoExpect => self.token == **k,
1145 /// Parse a sequence, including the closing delimiter. The function
1146 /// f must consume tokens until reaching the next separator or
1147 /// closing bracket.
1148 fn parse_unspanned_seq<T, F>(&mut self,
1153 -> PResult<'a, Vec<T>> where
1154 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1157 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1158 if self.token == *ket {
1164 /// Advance the parser by one token
1165 pub fn bump(&mut self) {
1166 if self.prev_token_kind == PrevTokenKind::Eof {
1167 // Bumping after EOF is a bad sign, usually an infinite loop.
1168 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1171 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1173 // Record last token kind for possible error recovery.
1174 self.prev_token_kind = match self.token {
1175 token::DocComment(..) => PrevTokenKind::DocComment,
1176 token::Comma => PrevTokenKind::Comma,
1177 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1178 token::Interpolated(..) => PrevTokenKind::Interpolated,
1179 token::Eof => PrevTokenKind::Eof,
1180 token::Ident(..) => PrevTokenKind::Ident,
1181 _ => PrevTokenKind::Other,
1184 let next = self.next_tok();
1185 self.span = next.sp;
1186 self.token = next.tok;
1187 self.expected_tokens.clear();
1188 // check after each token
1189 self.process_potential_macro_variable();
1192 /// Advance the parser using provided token as a next one. Use this when
1193 /// consuming a part of a token. For example a single `<` from `<<`.
1194 fn bump_with(&mut self, next: token::Token, span: Span) {
1195 self.prev_span = self.span.with_hi(span.lo());
1196 // It would be incorrect to record the kind of the current token, but
1197 // fortunately for tokens currently using `bump_with`, the
1198 // prev_token_kind will be of no use anyway.
1199 self.prev_token_kind = PrevTokenKind::Other;
1202 self.expected_tokens.clear();
1205 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1206 F: FnOnce(&token::Token) -> R,
1209 return f(&self.token)
1212 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1213 Some(tree) => match tree {
1214 TokenTree::Token(_, tok) => tok,
1215 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1217 None => token::CloseDelim(self.token_cursor.frame.delim),
1221 fn look_ahead_span(&self, dist: usize) -> Span {
1226 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1227 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1228 None => self.look_ahead_span(dist - 1),
1231 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1232 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1234 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1235 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1237 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1238 err.span_err(sp, self.diagnostic())
1240 fn bug(&self, m: &str) -> ! {
1241 self.sess.span_diagnostic.span_bug(self.span, m)
1243 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1244 self.sess.span_diagnostic.span_err(sp, m)
1246 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1247 self.sess.span_diagnostic.struct_span_err(sp, m)
1249 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1250 self.sess.span_diagnostic.span_bug(sp, m)
1252 crate fn abort_if_errors(&self) {
1253 self.sess.span_diagnostic.abort_if_errors();
1256 fn cancel(&self, err: &mut DiagnosticBuilder) {
1257 self.sess.span_diagnostic.cancel(err)
1260 crate fn diagnostic(&self) -> &'a errors::Handler {
1261 &self.sess.span_diagnostic
1264 /// Is the current token one of the keywords that signals a bare function
1266 fn token_is_bare_fn_keyword(&mut self) -> bool {
1267 self.check_keyword(keywords::Fn) ||
1268 self.check_keyword(keywords::Unsafe) ||
1269 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1272 /// parse a TyKind::BareFn type:
1273 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1276 [unsafe] [extern "ABI"] fn (S) -> T
1286 let unsafety = self.parse_unsafety();
1287 let abi = if self.eat_keyword(keywords::Extern) {
1288 self.parse_opt_abi()?.unwrap_or(Abi::C)
1293 self.expect_keyword(keywords::Fn)?;
1294 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1295 let ret_ty = self.parse_ret_ty(false)?;
1296 let decl = P(FnDecl {
1301 Ok(TyKind::BareFn(P(BareFnTy {
1309 /// Parse asyncness: `async` or nothing
1310 fn parse_asyncness(&mut self) -> IsAsync {
1311 if self.eat_keyword(keywords::Async) {
1313 closure_id: ast::DUMMY_NODE_ID,
1314 return_impl_trait_id: ast::DUMMY_NODE_ID,
1321 /// Parse unsafety: `unsafe` or nothing.
1322 fn parse_unsafety(&mut self) -> Unsafety {
1323 if self.eat_keyword(keywords::Unsafe) {
1330 /// Parse the items in a trait declaration
1331 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1332 maybe_whole!(self, NtTraitItem, |x| x);
1333 let attrs = self.parse_outer_attributes()?;
1334 let (mut item, tokens) = self.collect_tokens(|this| {
1335 this.parse_trait_item_(at_end, attrs)
1337 // See `parse_item` for why this clause is here.
1338 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1339 item.tokens = Some(tokens);
1344 fn parse_trait_item_(&mut self,
1346 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1349 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1350 self.parse_trait_item_assoc_ty()?
1351 } else if self.is_const_item() {
1352 self.expect_keyword(keywords::Const)?;
1353 let ident = self.parse_ident()?;
1354 self.expect(&token::Colon)?;
1355 let ty = self.parse_ty()?;
1356 let default = if self.check(&token::Eq) {
1358 let expr = self.parse_expr()?;
1359 self.expect(&token::Semi)?;
1362 self.expect(&token::Semi)?;
1365 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1366 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1367 // trait item macro.
1368 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1370 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1372 let ident = self.parse_ident()?;
1373 let mut generics = self.parse_generics()?;
1375 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1376 // This is somewhat dubious; We don't want to allow
1377 // argument names to be left off if there is a
1379 p.parse_arg_general(false)
1381 generics.where_clause = self.parse_where_clause()?;
1383 let sig = ast::MethodSig {
1393 let body = match self.token {
1397 debug!("parse_trait_methods(): parsing required method");
1400 token::OpenDelim(token::Brace) => {
1401 debug!("parse_trait_methods(): parsing provided method");
1403 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1404 attrs.extend(inner_attrs.iter().cloned());
1408 let token_str = self.this_token_to_string();
1409 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1411 err.span_label(self.span, "expected `;` or `{`");
1415 (ident, ast::TraitItemKind::Method(sig, body), generics)
1419 id: ast::DUMMY_NODE_ID,
1424 span: lo.to(self.prev_span),
1429 /// Parse optional return type [ -> TY ] in function decl
1430 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1431 if self.eat(&token::RArrow) {
1432 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1434 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1439 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1440 self.parse_ty_common(true, true)
1443 /// Parse a type in restricted contexts where `+` is not permitted.
1444 /// Example 1: `&'a TYPE`
1445 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1446 /// Example 2: `value1 as TYPE + value2`
1447 /// `+` is prohibited to avoid interactions with expression grammar.
1448 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1449 self.parse_ty_common(false, true)
1452 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1453 -> PResult<'a, P<Ty>> {
1454 maybe_whole!(self, NtTy, |x| x);
1457 let mut impl_dyn_multi = false;
1458 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1459 // `(TYPE)` is a parenthesized type.
1460 // `(TYPE,)` is a tuple with a single field of type TYPE.
1461 let mut ts = vec![];
1462 let mut last_comma = false;
1463 while self.token != token::CloseDelim(token::Paren) {
1464 ts.push(self.parse_ty()?);
1465 if self.eat(&token::Comma) {
1472 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1473 self.expect(&token::CloseDelim(token::Paren))?;
1475 if ts.len() == 1 && !last_comma {
1476 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1477 let maybe_bounds = allow_plus && self.token.is_like_plus();
1479 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1480 TyKind::Path(None, ref path) if maybe_bounds => {
1481 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1483 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1484 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1485 let path = match bounds[0] {
1486 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1487 _ => self.bug("unexpected lifetime bound"),
1489 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1492 _ => TyKind::Paren(P(ty))
1497 } else if self.eat(&token::Not) {
1500 } else if self.eat(&token::BinOp(token::Star)) {
1502 TyKind::Ptr(self.parse_ptr()?)
1503 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1505 let t = self.parse_ty()?;
1506 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1507 let t = match self.maybe_parse_fixed_length_of_vec()? {
1508 None => TyKind::Slice(t),
1509 Some(length) => TyKind::Array(t, AnonConst {
1510 id: ast::DUMMY_NODE_ID,
1514 self.expect(&token::CloseDelim(token::Bracket))?;
1516 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1519 self.parse_borrowed_pointee()?
1520 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1522 // In order to not be ambiguous, the type must be surrounded by parens.
1523 self.expect(&token::OpenDelim(token::Paren))?;
1525 id: ast::DUMMY_NODE_ID,
1526 value: self.parse_expr()?,
1528 self.expect(&token::CloseDelim(token::Paren))?;
1530 } else if self.eat_keyword(keywords::Underscore) {
1531 // A type to be inferred `_`
1533 } else if self.token_is_bare_fn_keyword() {
1534 // Function pointer type
1535 self.parse_ty_bare_fn(Vec::new())?
1536 } else if self.check_keyword(keywords::For) {
1537 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1538 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1539 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1541 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1542 if self.token_is_bare_fn_keyword() {
1543 self.parse_ty_bare_fn(lifetime_defs)?
1545 let path = self.parse_path(PathStyle::Type)?;
1546 let parse_plus = allow_plus && self.check_plus();
1547 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1549 } else if self.eat_keyword(keywords::Impl) {
1550 // Always parse bounds greedily for better error recovery.
1551 let bounds = self.parse_generic_bounds()?;
1552 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1553 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1554 } else if self.check_keyword(keywords::Dyn) &&
1555 self.look_ahead(1, |t| t.can_begin_bound() &&
1556 !can_continue_type_after_non_fn_ident(t)) {
1557 self.bump(); // `dyn`
1558 // Always parse bounds greedily for better error recovery.
1559 let bounds = self.parse_generic_bounds()?;
1560 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1561 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1562 } else if self.check(&token::Question) ||
1563 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1564 // Bound list (trait object type)
1565 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1566 TraitObjectSyntax::None)
1567 } else if self.eat_lt() {
1569 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1570 TyKind::Path(Some(qself), path)
1571 } else if self.token.is_path_start() {
1573 let path = self.parse_path(PathStyle::Type)?;
1574 if self.eat(&token::Not) {
1575 // Macro invocation in type position
1576 let (delim, tts) = self.expect_delimited_token_tree()?;
1577 let node = Mac_ { path, tts, delim };
1578 TyKind::Mac(respan(lo.to(self.prev_span), node))
1580 // Just a type path or bound list (trait object type) starting with a trait.
1582 // `Trait1 + Trait2 + 'a`
1583 if allow_plus && self.check_plus() {
1584 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1586 TyKind::Path(None, path)
1590 let msg = format!("expected type, found {}", self.this_token_descr());
1591 return Err(self.fatal(&msg));
1594 let span = lo.to(self.prev_span);
1595 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1597 // Try to recover from use of `+` with incorrect priority.
1598 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1599 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1600 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1605 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1606 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1607 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1608 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1610 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1611 bounds.append(&mut self.parse_generic_bounds()?);
1613 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1616 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1617 if !allow_plus && impl_dyn_multi {
1618 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1619 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1620 .span_suggestion_with_applicability(
1622 "use parentheses to disambiguate",
1624 Applicability::MachineApplicable
1629 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1630 // Do not add `+` to expected tokens.
1631 if !allow_plus || !self.token.is_like_plus() {
1636 let bounds = self.parse_generic_bounds()?;
1637 let sum_span = ty.span.to(self.prev_span);
1639 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1640 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1643 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1644 let sum_with_parens = pprust::to_string(|s| {
1645 use print::pprust::PrintState;
1648 s.print_opt_lifetime(lifetime)?;
1649 s.print_mutability(mut_ty.mutbl)?;
1651 s.print_type(&mut_ty.ty)?;
1652 s.print_type_bounds(" +", &bounds)?;
1655 err.span_suggestion_with_applicability(
1657 "try adding parentheses",
1659 Applicability::MachineApplicable
1662 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1663 err.span_label(sum_span, "perhaps you forgot parentheses?");
1666 err.span_label(sum_span, "expected a path");
1673 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1674 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1676 // Do not add `::` to expected tokens.
1677 if !allow_recovery || self.token != token::ModSep {
1680 let ty = match base.to_ty() {
1682 None => return Ok(base),
1685 self.bump(); // `::`
1686 let mut segments = Vec::new();
1687 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1689 let span = ty.span.to(self.prev_span);
1690 let path_span = span.to(span); // use an empty path since `position` == 0
1691 let recovered = base.to_recovered(
1692 Some(QSelf { ty, path_span, position: 0 }),
1693 ast::Path { segments, span },
1697 .struct_span_err(span, "missing angle brackets in associated item path")
1698 .span_suggestion_with_applicability( // this is a best-effort recovery
1699 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1705 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1706 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1707 let mutbl = self.parse_mutability();
1708 let ty = self.parse_ty_no_plus()?;
1709 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1712 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1713 let mutbl = if self.eat_keyword(keywords::Mut) {
1715 } else if self.eat_keyword(keywords::Const) {
1716 Mutability::Immutable
1718 let span = self.prev_span;
1720 "expected mut or const in raw pointer type (use \
1721 `*mut T` or `*const T` as appropriate)");
1722 Mutability::Immutable
1724 let t = self.parse_ty_no_plus()?;
1725 Ok(MutTy { ty: t, mutbl: mutbl })
1728 fn is_named_argument(&mut self) -> bool {
1729 let offset = match self.token {
1730 token::Interpolated(ref nt) => match nt.0 {
1731 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1734 token::BinOp(token::And) | token::AndAnd => 1,
1735 _ if self.token.is_keyword(keywords::Mut) => 1,
1739 self.look_ahead(offset, |t| t.is_ident()) &&
1740 self.look_ahead(offset + 1, |t| t == &token::Colon)
1743 /// This version of parse arg doesn't necessarily require
1744 /// identifier names.
1745 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1746 maybe_whole!(self, NtArg, |x| x);
1748 let (pat, ty) = if require_name || self.is_named_argument() {
1749 debug!("parse_arg_general parse_pat (require_name:{})",
1751 let pat = self.parse_pat()?;
1753 self.expect(&token::Colon)?;
1754 (pat, self.parse_ty()?)
1756 debug!("parse_arg_general ident_to_pat");
1758 let parser_snapshot_before_pat = self.clone();
1760 // We're going to try parsing the argument as a pattern (even though it's not
1761 // allowed). This way we can provide better errors to the user.
1762 let pat_arg: PResult<'a, _> = do catch {
1763 let pat = self.parse_pat()?;
1764 self.expect(&token::Colon)?;
1765 (pat, self.parse_ty()?)
1770 let mut err = self.diagnostic().struct_span_err_with_code(
1772 "patterns aren't allowed in methods without bodies",
1773 DiagnosticId::Error("E0642".into()),
1775 err.span_suggestion_short_with_applicability(
1777 "give this argument a name or use an underscore to ignore it",
1779 Applicability::MachineApplicable,
1782 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1784 node: PatKind::Wild,
1786 id: ast::DUMMY_NODE_ID
1792 // Recover from attempting to parse the argument as a pattern. This means
1793 // the type is alone, with no name, e.g. `fn foo(u32)`.
1794 mem::replace(self, parser_snapshot_before_pat);
1795 debug!("parse_arg_general ident_to_pat");
1796 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1797 let ty = self.parse_ty()?;
1799 id: ast::DUMMY_NODE_ID,
1800 node: PatKind::Ident(
1801 BindingMode::ByValue(Mutability::Immutable), ident, None),
1809 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1812 /// Parse a single function argument
1813 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1814 self.parse_arg_general(true)
1817 /// Parse an argument in a lambda header e.g. |arg, arg|
1818 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1819 let pat = self.parse_pat()?;
1820 let t = if self.eat(&token::Colon) {
1824 id: ast::DUMMY_NODE_ID,
1825 node: TyKind::Infer,
1832 id: ast::DUMMY_NODE_ID
1836 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1837 if self.eat(&token::Semi) {
1838 Ok(Some(self.parse_expr()?))
1844 /// Matches token_lit = LIT_INTEGER | ...
1845 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1846 let out = match self.token {
1847 token::Interpolated(ref nt) => match nt.0 {
1848 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1849 ExprKind::Lit(ref lit) => { lit.node.clone() }
1850 _ => { return self.unexpected_last(&self.token); }
1852 _ => { return self.unexpected_last(&self.token); }
1854 token::Literal(lit, suf) => {
1855 let diag = Some((self.span, &self.sess.span_diagnostic));
1856 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1860 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1865 _ => { return self.unexpected_last(&self.token); }
1872 /// Matches lit = true | false | token_lit
1873 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1875 let lit = if self.eat_keyword(keywords::True) {
1877 } else if self.eat_keyword(keywords::False) {
1878 LitKind::Bool(false)
1880 let lit = self.parse_lit_token()?;
1883 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
1886 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1887 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1888 maybe_whole_expr!(self);
1890 let minus_lo = self.span;
1891 let minus_present = self.eat(&token::BinOp(token::Minus));
1893 let literal = P(self.parse_lit()?);
1894 let hi = self.prev_span;
1895 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1898 let minus_hi = self.prev_span;
1899 let unary = self.mk_unary(UnOp::Neg, expr);
1900 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1906 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1908 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1909 let span = self.span;
1911 Ok(Ident::new(ident.name, span))
1913 _ => self.parse_ident(),
1917 /// Parses qualified path.
1918 /// Assumes that the leading `<` has been parsed already.
1920 /// `qualified_path = <type [as trait_ref]>::path`
1925 /// `<T as U>::F::a<S>` (without disambiguator)
1926 /// `<T as U>::F::a::<S>` (with disambiguator)
1927 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1928 let lo = self.prev_span;
1929 let ty = self.parse_ty()?;
1931 // `path` will contain the prefix of the path up to the `>`,
1932 // if any (e.g., `U` in the `<T as U>::*` examples
1933 // above). `path_span` has the span of that path, or an empty
1934 // span in the case of something like `<T>::Bar`.
1935 let (mut path, path_span);
1936 if self.eat_keyword(keywords::As) {
1937 let path_lo = self.span;
1938 path = self.parse_path(PathStyle::Type)?;
1939 path_span = path_lo.to(self.prev_span);
1941 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1942 path_span = self.span.to(self.span);
1945 self.expect(&token::Gt)?;
1946 self.expect(&token::ModSep)?;
1948 let qself = QSelf { ty, path_span, position: path.segments.len() };
1949 self.parse_path_segments(&mut path.segments, style, true)?;
1951 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1954 /// Parses simple paths.
1956 /// `path = [::] segment+`
1957 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1960 /// `a::b::C<D>` (without disambiguator)
1961 /// `a::b::C::<D>` (with disambiguator)
1962 /// `Fn(Args)` (without disambiguator)
1963 /// `Fn::(Args)` (with disambiguator)
1964 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1965 self.parse_path_common(style, true)
1968 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1969 -> PResult<'a, ast::Path> {
1970 maybe_whole!(self, NtPath, |path| {
1971 if style == PathStyle::Mod &&
1972 path.segments.iter().any(|segment| segment.args.is_some()) {
1973 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1978 let lo = self.meta_var_span.unwrap_or(self.span);
1979 let mut segments = Vec::new();
1980 if self.eat(&token::ModSep) {
1981 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1983 self.parse_path_segments(&mut segments, style, enable_warning)?;
1985 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1988 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1989 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1990 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1991 let meta_ident = match self.token {
1992 token::Interpolated(ref nt) => match nt.0 {
1993 token::NtMeta(ref meta) => match meta.node {
1994 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2001 if let Some(path) = meta_ident {
2005 self.parse_path(style)
2008 fn parse_path_segments(&mut self,
2009 segments: &mut Vec<PathSegment>,
2011 enable_warning: bool)
2012 -> PResult<'a, ()> {
2014 segments.push(self.parse_path_segment(style, enable_warning)?);
2016 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2022 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2023 -> PResult<'a, PathSegment> {
2024 let ident = self.parse_path_segment_ident()?;
2026 let is_args_start = |token: &token::Token| match *token {
2027 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2030 let check_args_start = |this: &mut Self| {
2031 this.expected_tokens.extend_from_slice(
2032 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2034 is_args_start(&this.token)
2037 Ok(if style == PathStyle::Type && check_args_start(self) ||
2038 style != PathStyle::Mod && self.check(&token::ModSep)
2039 && self.look_ahead(1, |t| is_args_start(t)) {
2040 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2042 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2043 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2044 .span_label(self.prev_span, "try removing `::`").emit();
2047 let args = if self.eat_lt() {
2049 let (args, bindings) = self.parse_generic_args()?;
2051 let span = lo.to(self.prev_span);
2052 AngleBracketedArgs { args, bindings, span }.into()
2056 let inputs = self.parse_seq_to_before_tokens(
2057 &[&token::CloseDelim(token::Paren)],
2058 SeqSep::trailing_allowed(token::Comma),
2059 TokenExpectType::Expect,
2062 let span = lo.to(self.prev_span);
2063 let output = if self.eat(&token::RArrow) {
2064 Some(self.parse_ty_common(false, false)?)
2068 ParenthesisedArgs { inputs, output, span }.into()
2071 PathSegment { ident, args }
2073 // Generic arguments are not found.
2074 PathSegment::from_ident(ident)
2078 crate fn check_lifetime(&mut self) -> bool {
2079 self.expected_tokens.push(TokenType::Lifetime);
2080 self.token.is_lifetime()
2083 /// Parse single lifetime 'a or panic.
2084 crate fn expect_lifetime(&mut self) -> Lifetime {
2085 if let Some(ident) = self.token.lifetime() {
2086 let span = self.span;
2088 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2090 self.span_bug(self.span, "not a lifetime")
2094 fn eat_label(&mut self) -> Option<Label> {
2095 if let Some(ident) = self.token.lifetime() {
2096 let span = self.span;
2098 Some(Label { ident: Ident::new(ident.name, span) })
2104 /// Parse mutability (`mut` or nothing).
2105 fn parse_mutability(&mut self) -> Mutability {
2106 if self.eat_keyword(keywords::Mut) {
2109 Mutability::Immutable
2113 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2114 if let token::Literal(token::Integer(name), None) = self.token {
2116 Ok(Ident::new(name, self.prev_span))
2118 self.parse_ident_common(false)
2122 /// Parse ident (COLON expr)?
2123 fn parse_field(&mut self) -> PResult<'a, Field> {
2124 let attrs = self.parse_outer_attributes()?;
2127 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2128 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2129 let fieldname = self.parse_field_name()?;
2131 (fieldname, self.parse_expr()?, false)
2133 let fieldname = self.parse_ident_common(false)?;
2135 // Mimic `x: x` for the `x` field shorthand.
2136 let path = ast::Path::from_ident(fieldname);
2137 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2138 (fieldname, expr, true)
2142 span: lo.to(expr.span),
2145 attrs: attrs.into(),
2149 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2150 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2153 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2154 ExprKind::Unary(unop, expr)
2157 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2158 ExprKind::Binary(binop, lhs, rhs)
2161 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2162 ExprKind::Call(f, args)
2165 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2166 ExprKind::Index(expr, idx)
2169 fn mk_range(&mut self,
2170 start: Option<P<Expr>>,
2171 end: Option<P<Expr>>,
2172 limits: RangeLimits)
2173 -> PResult<'a, ast::ExprKind> {
2174 if end.is_none() && limits == RangeLimits::Closed {
2175 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2177 Ok(ExprKind::Range(start, end, limits))
2181 fn mk_assign_op(&mut self, binop: ast::BinOp,
2182 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2183 ExprKind::AssignOp(binop, lhs, rhs)
2186 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2188 id: ast::DUMMY_NODE_ID,
2189 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2195 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2196 let delim = match self.token {
2197 token::OpenDelim(delim) => delim,
2199 let msg = "expected open delimiter";
2200 let mut err = self.fatal(msg);
2201 err.span_label(self.span, msg);
2205 let delimited = match self.parse_token_tree() {
2206 TokenTree::Delimited(_, delimited) => delimited,
2207 _ => unreachable!(),
2209 let delim = match delim {
2210 token::Paren => MacDelimiter::Parenthesis,
2211 token::Bracket => MacDelimiter::Bracket,
2212 token::Brace => MacDelimiter::Brace,
2213 token::NoDelim => self.bug("unexpected no delimiter"),
2215 Ok((delim, delimited.stream().into()))
2218 /// At the bottom (top?) of the precedence hierarchy,
2219 /// parse things like parenthesized exprs,
2220 /// macros, return, etc.
2222 /// NB: This does not parse outer attributes,
2223 /// and is private because it only works
2224 /// correctly if called from parse_dot_or_call_expr().
2225 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2226 maybe_whole_expr!(self);
2228 // Outer attributes are already parsed and will be
2229 // added to the return value after the fact.
2231 // Therefore, prevent sub-parser from parsing
2232 // attributes by giving them a empty "already parsed" list.
2233 let mut attrs = ThinVec::new();
2236 let mut hi = self.span;
2240 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2242 token::OpenDelim(token::Paren) => {
2245 attrs.extend(self.parse_inner_attributes()?);
2247 // (e) is parenthesized e
2248 // (e,) is a tuple with only one field, e
2249 let mut es = vec![];
2250 let mut trailing_comma = false;
2251 while self.token != token::CloseDelim(token::Paren) {
2252 es.push(self.parse_expr()?);
2253 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2254 if self.check(&token::Comma) {
2255 trailing_comma = true;
2259 trailing_comma = false;
2265 hi = self.prev_span;
2266 ex = if es.len() == 1 && !trailing_comma {
2267 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2272 token::OpenDelim(token::Brace) => {
2273 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2275 token::BinOp(token::Or) | token::OrOr => {
2276 return self.parse_lambda_expr(attrs);
2278 token::OpenDelim(token::Bracket) => {
2281 attrs.extend(self.parse_inner_attributes()?);
2283 if self.check(&token::CloseDelim(token::Bracket)) {
2286 ex = ExprKind::Array(Vec::new());
2289 let first_expr = self.parse_expr()?;
2290 if self.check(&token::Semi) {
2291 // Repeating array syntax: [ 0; 512 ]
2293 let count = AnonConst {
2294 id: ast::DUMMY_NODE_ID,
2295 value: self.parse_expr()?,
2297 self.expect(&token::CloseDelim(token::Bracket))?;
2298 ex = ExprKind::Repeat(first_expr, count);
2299 } else if self.check(&token::Comma) {
2300 // Vector with two or more elements.
2302 let remaining_exprs = self.parse_seq_to_end(
2303 &token::CloseDelim(token::Bracket),
2304 SeqSep::trailing_allowed(token::Comma),
2305 |p| Ok(p.parse_expr()?)
2307 let mut exprs = vec![first_expr];
2308 exprs.extend(remaining_exprs);
2309 ex = ExprKind::Array(exprs);
2311 // Vector with one element.
2312 self.expect(&token::CloseDelim(token::Bracket))?;
2313 ex = ExprKind::Array(vec![first_expr]);
2316 hi = self.prev_span;
2320 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2322 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2324 if self.span.edition() >= Edition::Edition2018 &&
2325 self.check_keyword(keywords::Async)
2327 if self.is_async_block() { // check for `async {` and `async move {`
2328 return self.parse_async_block(attrs);
2330 return self.parse_lambda_expr(attrs);
2333 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2334 return self.parse_lambda_expr(attrs);
2336 if self.eat_keyword(keywords::If) {
2337 return self.parse_if_expr(attrs);
2339 if self.eat_keyword(keywords::For) {
2340 let lo = self.prev_span;
2341 return self.parse_for_expr(None, lo, attrs);
2343 if self.eat_keyword(keywords::While) {
2344 let lo = self.prev_span;
2345 return self.parse_while_expr(None, lo, attrs);
2347 if let Some(label) = self.eat_label() {
2348 let lo = label.ident.span;
2349 self.expect(&token::Colon)?;
2350 if self.eat_keyword(keywords::While) {
2351 return self.parse_while_expr(Some(label), lo, attrs)
2353 if self.eat_keyword(keywords::For) {
2354 return self.parse_for_expr(Some(label), lo, attrs)
2356 if self.eat_keyword(keywords::Loop) {
2357 return self.parse_loop_expr(Some(label), lo, attrs)
2359 if self.token == token::OpenDelim(token::Brace) {
2360 return self.parse_block_expr(Some(label),
2362 BlockCheckMode::Default,
2365 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2366 let mut err = self.fatal(msg);
2367 err.span_label(self.span, msg);
2370 if self.eat_keyword(keywords::Loop) {
2371 let lo = self.prev_span;
2372 return self.parse_loop_expr(None, lo, attrs);
2374 if self.eat_keyword(keywords::Continue) {
2375 let label = self.eat_label();
2376 let ex = ExprKind::Continue(label);
2377 let hi = self.prev_span;
2378 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2380 if self.eat_keyword(keywords::Match) {
2381 return self.parse_match_expr(attrs);
2383 if self.eat_keyword(keywords::Unsafe) {
2384 return self.parse_block_expr(
2387 BlockCheckMode::Unsafe(ast::UserProvided),
2390 if self.is_catch_expr() {
2392 assert!(self.eat_keyword(keywords::Do));
2393 assert!(self.eat_keyword(keywords::Catch));
2394 return self.parse_catch_expr(lo, attrs);
2396 if self.eat_keyword(keywords::Return) {
2397 if self.token.can_begin_expr() {
2398 let e = self.parse_expr()?;
2400 ex = ExprKind::Ret(Some(e));
2402 ex = ExprKind::Ret(None);
2404 } else if self.eat_keyword(keywords::Break) {
2405 let label = self.eat_label();
2406 let e = if self.token.can_begin_expr()
2407 && !(self.token == token::OpenDelim(token::Brace)
2408 && self.restrictions.contains(
2409 Restrictions::NO_STRUCT_LITERAL)) {
2410 Some(self.parse_expr()?)
2414 ex = ExprKind::Break(label, e);
2415 hi = self.prev_span;
2416 } else if self.eat_keyword(keywords::Yield) {
2417 if self.token.can_begin_expr() {
2418 let e = self.parse_expr()?;
2420 ex = ExprKind::Yield(Some(e));
2422 ex = ExprKind::Yield(None);
2424 } else if self.token.is_keyword(keywords::Let) {
2425 // Catch this syntax error here, instead of in `parse_ident`, so
2426 // that we can explicitly mention that let is not to be used as an expression
2427 let mut db = self.fatal("expected expression, found statement (`let`)");
2428 db.span_label(self.span, "expected expression");
2429 db.note("variable declaration using `let` is a statement");
2431 } else if self.token.is_path_start() {
2432 let pth = self.parse_path(PathStyle::Expr)?;
2434 // `!`, as an operator, is prefix, so we know this isn't that
2435 if self.eat(&token::Not) {
2436 // MACRO INVOCATION expression
2437 let (delim, tts) = self.expect_delimited_token_tree()?;
2438 let hi = self.prev_span;
2439 let node = Mac_ { path: pth, tts, delim };
2440 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2442 if self.check(&token::OpenDelim(token::Brace)) {
2443 // This is a struct literal, unless we're prohibited
2444 // from parsing struct literals here.
2445 let prohibited = self.restrictions.contains(
2446 Restrictions::NO_STRUCT_LITERAL
2449 return self.parse_struct_expr(lo, pth, attrs);
2454 ex = ExprKind::Path(None, pth);
2456 match self.parse_literal_maybe_minus() {
2459 ex = expr.node.clone();
2462 self.cancel(&mut err);
2463 let msg = format!("expected expression, found {}",
2464 self.this_token_descr());
2465 let mut err = self.fatal(&msg);
2466 err.span_label(self.span, "expected expression");
2474 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2475 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2480 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2481 -> PResult<'a, P<Expr>> {
2482 let struct_sp = lo.to(self.prev_span);
2484 let mut fields = Vec::new();
2485 let mut base = None;
2487 attrs.extend(self.parse_inner_attributes()?);
2489 while self.token != token::CloseDelim(token::Brace) {
2490 if self.eat(&token::DotDot) {
2491 let exp_span = self.prev_span;
2492 match self.parse_expr() {
2498 self.recover_stmt();
2501 if self.token == token::Comma {
2502 let mut err = self.sess.span_diagnostic.mut_span_err(
2503 exp_span.to(self.prev_span),
2504 "cannot use a comma after the base struct",
2506 err.span_suggestion_short_with_applicability(
2508 "remove this comma",
2510 Applicability::MachineApplicable
2512 err.note("the base struct must always be the last field");
2514 self.recover_stmt();
2519 match self.parse_field() {
2520 Ok(f) => fields.push(f),
2522 e.span_label(struct_sp, "while parsing this struct");
2525 // If the next token is a comma, then try to parse
2526 // what comes next as additional fields, rather than
2527 // bailing out until next `}`.
2528 if self.token != token::Comma {
2529 self.recover_stmt();
2535 match self.expect_one_of(&[token::Comma],
2536 &[token::CloseDelim(token::Brace)]) {
2540 self.recover_stmt();
2546 let span = lo.to(self.span);
2547 self.expect(&token::CloseDelim(token::Brace))?;
2548 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2551 fn parse_or_use_outer_attributes(&mut self,
2552 already_parsed_attrs: Option<ThinVec<Attribute>>)
2553 -> PResult<'a, ThinVec<Attribute>> {
2554 if let Some(attrs) = already_parsed_attrs {
2557 self.parse_outer_attributes().map(|a| a.into())
2561 /// Parse a block or unsafe block
2562 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2563 lo: Span, blk_mode: BlockCheckMode,
2564 outer_attrs: ThinVec<Attribute>)
2565 -> PResult<'a, P<Expr>> {
2566 self.expect(&token::OpenDelim(token::Brace))?;
2568 let mut attrs = outer_attrs;
2569 attrs.extend(self.parse_inner_attributes()?);
2571 let blk = self.parse_block_tail(lo, blk_mode)?;
2572 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2575 /// parse a.b or a(13) or a[4] or just a
2576 fn parse_dot_or_call_expr(&mut self,
2577 already_parsed_attrs: Option<ThinVec<Attribute>>)
2578 -> PResult<'a, P<Expr>> {
2579 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2581 let b = self.parse_bottom_expr();
2582 let (span, b) = self.interpolated_or_expr_span(b)?;
2583 self.parse_dot_or_call_expr_with(b, span, attrs)
2586 fn parse_dot_or_call_expr_with(&mut self,
2589 mut attrs: ThinVec<Attribute>)
2590 -> PResult<'a, P<Expr>> {
2591 // Stitch the list of outer attributes onto the return value.
2592 // A little bit ugly, but the best way given the current code
2594 self.parse_dot_or_call_expr_with_(e0, lo)
2596 expr.map(|mut expr| {
2597 attrs.extend::<Vec<_>>(expr.attrs.into());
2600 ExprKind::If(..) | ExprKind::IfLet(..) => {
2601 if !expr.attrs.is_empty() {
2602 // Just point to the first attribute in there...
2603 let span = expr.attrs[0].span;
2606 "attributes are not yet allowed on `if` \
2617 // Assuming we have just parsed `.`, continue parsing into an expression.
2618 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2619 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2620 Ok(match self.token {
2621 token::OpenDelim(token::Paren) => {
2622 // Method call `expr.f()`
2623 let mut args = self.parse_unspanned_seq(
2624 &token::OpenDelim(token::Paren),
2625 &token::CloseDelim(token::Paren),
2626 SeqSep::trailing_allowed(token::Comma),
2627 |p| Ok(p.parse_expr()?)
2629 args.insert(0, self_arg);
2631 let span = lo.to(self.prev_span);
2632 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2635 // Field access `expr.f`
2636 if let Some(args) = segment.args {
2637 self.span_err(args.span(),
2638 "field expressions may not have generic arguments");
2641 let span = lo.to(self.prev_span);
2642 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2647 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2652 while self.eat(&token::Question) {
2653 let hi = self.prev_span;
2654 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2658 if self.eat(&token::Dot) {
2660 token::Ident(..) => {
2661 e = self.parse_dot_suffix(e, lo)?;
2663 token::Literal(token::Integer(name), _) => {
2664 let span = self.span;
2666 let field = ExprKind::Field(e, Ident::new(name, span));
2667 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2669 token::Literal(token::Float(n), _suf) => {
2671 let fstr = n.as_str();
2672 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2673 &format!("unexpected token: `{}`", n));
2674 err.span_label(self.prev_span, "unexpected token");
2675 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2676 let float = match fstr.parse::<f64>().ok() {
2680 let sugg = pprust::to_string(|s| {
2681 use print::pprust::PrintState;
2685 s.print_usize(float.trunc() as usize)?;
2688 s.s.word(fstr.splitn(2, ".").last().unwrap())
2690 err.span_suggestion_with_applicability(
2691 lo.to(self.prev_span),
2692 "try parenthesizing the first index",
2694 Applicability::MachineApplicable
2701 // FIXME Could factor this out into non_fatal_unexpected or something.
2702 let actual = self.this_token_to_string();
2703 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2708 if self.expr_is_complete(&e) { break; }
2711 token::OpenDelim(token::Paren) => {
2712 let es = self.parse_unspanned_seq(
2713 &token::OpenDelim(token::Paren),
2714 &token::CloseDelim(token::Paren),
2715 SeqSep::trailing_allowed(token::Comma),
2716 |p| Ok(p.parse_expr()?)
2718 hi = self.prev_span;
2720 let nd = self.mk_call(e, es);
2721 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2725 // Could be either an index expression or a slicing expression.
2726 token::OpenDelim(token::Bracket) => {
2728 let ix = self.parse_expr()?;
2730 self.expect(&token::CloseDelim(token::Bracket))?;
2731 let index = self.mk_index(e, ix);
2732 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2740 crate fn process_potential_macro_variable(&mut self) {
2741 let (token, span) = match self.token {
2742 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2743 self.look_ahead(1, |t| t.is_ident()) => {
2745 let name = match self.token {
2746 token::Ident(ident, _) => ident,
2749 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2750 err.span_label(self.span, "unknown macro variable");
2754 token::Interpolated(ref nt) => {
2755 self.meta_var_span = Some(self.span);
2756 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2757 // and lifetime tokens, so the former are never encountered during normal parsing.
2759 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2760 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2770 /// parse a single token tree from the input.
2771 crate fn parse_token_tree(&mut self) -> TokenTree {
2773 token::OpenDelim(..) => {
2774 let frame = mem::replace(&mut self.token_cursor.frame,
2775 self.token_cursor.stack.pop().unwrap());
2776 self.span = frame.span;
2778 TokenTree::Delimited(frame.span, Delimited {
2780 tts: frame.tree_cursor.original_stream().into(),
2783 token::CloseDelim(_) | token::Eof => unreachable!(),
2785 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2787 TokenTree::Token(span, token)
2792 // parse a stream of tokens into a list of TokenTree's,
2794 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2795 let mut tts = Vec::new();
2796 while self.token != token::Eof {
2797 tts.push(self.parse_token_tree());
2802 pub fn parse_tokens(&mut self) -> TokenStream {
2803 let mut result = Vec::new();
2806 token::Eof | token::CloseDelim(..) => break,
2807 _ => result.push(self.parse_token_tree().into()),
2810 TokenStream::concat(result)
2813 /// Parse a prefix-unary-operator expr
2814 fn parse_prefix_expr(&mut self,
2815 already_parsed_attrs: Option<ThinVec<Attribute>>)
2816 -> PResult<'a, P<Expr>> {
2817 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2819 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2820 let (hi, ex) = match self.token {
2823 let e = self.parse_prefix_expr(None);
2824 let (span, e) = self.interpolated_or_expr_span(e)?;
2825 (lo.to(span), self.mk_unary(UnOp::Not, e))
2827 // Suggest `!` for bitwise negation when encountering a `~`
2830 let e = self.parse_prefix_expr(None);
2831 let (span, e) = self.interpolated_or_expr_span(e)?;
2832 let span_of_tilde = lo;
2833 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2834 "`~` cannot be used as a unary operator");
2835 err.span_suggestion_short_with_applicability(
2837 "use `!` to perform bitwise negation",
2839 Applicability::MachineApplicable
2842 (lo.to(span), self.mk_unary(UnOp::Not, e))
2844 token::BinOp(token::Minus) => {
2846 let e = self.parse_prefix_expr(None);
2847 let (span, e) = self.interpolated_or_expr_span(e)?;
2848 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2850 token::BinOp(token::Star) => {
2852 let e = self.parse_prefix_expr(None);
2853 let (span, e) = self.interpolated_or_expr_span(e)?;
2854 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2856 token::BinOp(token::And) | token::AndAnd => {
2858 let m = self.parse_mutability();
2859 let e = self.parse_prefix_expr(None);
2860 let (span, e) = self.interpolated_or_expr_span(e)?;
2861 (lo.to(span), ExprKind::AddrOf(m, e))
2863 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2865 let place = self.parse_expr_res(
2866 Restrictions::NO_STRUCT_LITERAL,
2869 let blk = self.parse_block()?;
2870 let span = blk.span;
2871 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2872 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2874 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2876 let e = self.parse_prefix_expr(None);
2877 let (span, e) = self.interpolated_or_expr_span(e)?;
2878 (lo.to(span), ExprKind::Box(e))
2880 token::Ident(..) if self.token.is_ident_named("not") => {
2881 // `not` is just an ordinary identifier in Rust-the-language,
2882 // but as `rustc`-the-compiler, we can issue clever diagnostics
2883 // for confused users who really want to say `!`
2884 let token_cannot_continue_expr = |t: &token::Token| match *t {
2885 // These tokens can start an expression after `!`, but
2886 // can't continue an expression after an ident
2887 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2888 token::Literal(..) | token::Pound => true,
2889 token::Interpolated(ref nt) => match nt.0 {
2890 token::NtIdent(..) | token::NtExpr(..) |
2891 token::NtBlock(..) | token::NtPath(..) => true,
2896 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2897 if cannot_continue_expr {
2899 // Emit the error ...
2900 let mut err = self.diagnostic()
2901 .struct_span_err(self.span,
2902 &format!("unexpected {} after identifier",
2903 self.this_token_descr()));
2904 // span the `not` plus trailing whitespace to avoid
2905 // trailing whitespace after the `!` in our suggestion
2906 let to_replace = self.sess.source_map()
2907 .span_until_non_whitespace(lo.to(self.span));
2908 err.span_suggestion_short_with_applicability(
2910 "use `!` to perform logical negation",
2912 Applicability::MachineApplicable
2915 // —and recover! (just as if we were in the block
2916 // for the `token::Not` arm)
2917 let e = self.parse_prefix_expr(None);
2918 let (span, e) = self.interpolated_or_expr_span(e)?;
2919 (lo.to(span), self.mk_unary(UnOp::Not, e))
2921 return self.parse_dot_or_call_expr(Some(attrs));
2924 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2926 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2929 /// Parse an associative expression
2931 /// This parses an expression accounting for associativity and precedence of the operators in
2933 fn parse_assoc_expr(&mut self,
2934 already_parsed_attrs: Option<ThinVec<Attribute>>)
2935 -> PResult<'a, P<Expr>> {
2936 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2939 /// Parse an associative expression with operators of at least `min_prec` precedence
2940 fn parse_assoc_expr_with(&mut self,
2943 -> PResult<'a, P<Expr>> {
2944 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2947 let attrs = match lhs {
2948 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2951 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2952 return self.parse_prefix_range_expr(attrs);
2954 self.parse_prefix_expr(attrs)?
2958 if self.expr_is_complete(&lhs) {
2959 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2962 self.expected_tokens.push(TokenType::Operator);
2963 while let Some(op) = AssocOp::from_token(&self.token) {
2965 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2966 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2967 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2968 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2969 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2970 (PrevTokenKind::Interpolated, _) => self.prev_span,
2971 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2972 if path.segments.len() == 1 => self.prev_span,
2976 let cur_op_span = self.span;
2977 let restrictions = if op.is_assign_like() {
2978 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2982 if op.precedence() < min_prec {
2985 // Check for deprecated `...` syntax
2986 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2987 self.err_dotdotdot_syntax(self.span);
2991 if op.is_comparison() {
2992 self.check_no_chained_comparison(&lhs, &op);
2995 if op == AssocOp::As {
2996 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2998 } else if op == AssocOp::Colon {
2999 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3002 err.span_label(self.span,
3003 "expecting a type here because of type ascription");
3004 let cm = self.sess.source_map();
3005 let cur_pos = cm.lookup_char_pos(self.span.lo());
3006 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3007 if cur_pos.line != op_pos.line {
3008 err.span_suggestion_with_applicability(
3010 "try using a semicolon",
3012 Applicability::MaybeIncorrect // speculative
3019 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3020 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3021 // generalise it to the Fixity::None code.
3023 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3024 // two variants are handled with `parse_prefix_range_expr` call above.
3025 let rhs = if self.is_at_start_of_range_notation_rhs() {
3026 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3027 LhsExpr::NotYetParsed)?)
3031 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3036 let limits = if op == AssocOp::DotDot {
3037 RangeLimits::HalfOpen
3042 let r = try!(self.mk_range(Some(lhs), rhs, limits));
3043 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3047 let rhs = match op.fixity() {
3048 Fixity::Right => self.with_res(
3049 restrictions - Restrictions::STMT_EXPR,
3051 this.parse_assoc_expr_with(op.precedence(),
3052 LhsExpr::NotYetParsed)
3054 Fixity::Left => self.with_res(
3055 restrictions - Restrictions::STMT_EXPR,
3057 this.parse_assoc_expr_with(op.precedence() + 1,
3058 LhsExpr::NotYetParsed)
3060 // We currently have no non-associative operators that are not handled above by
3061 // the special cases. The code is here only for future convenience.
3062 Fixity::None => self.with_res(
3063 restrictions - Restrictions::STMT_EXPR,
3065 this.parse_assoc_expr_with(op.precedence() + 1,
3066 LhsExpr::NotYetParsed)
3070 let span = lhs_span.to(rhs.span);
3072 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3073 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3074 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3075 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3076 AssocOp::Greater | AssocOp::GreaterEqual => {
3077 let ast_op = op.to_ast_binop().unwrap();
3078 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3079 self.mk_expr(span, binary, ThinVec::new())
3082 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3083 AssocOp::ObsoleteInPlace =>
3084 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3085 AssocOp::AssignOp(k) => {
3087 token::Plus => BinOpKind::Add,
3088 token::Minus => BinOpKind::Sub,
3089 token::Star => BinOpKind::Mul,
3090 token::Slash => BinOpKind::Div,
3091 token::Percent => BinOpKind::Rem,
3092 token::Caret => BinOpKind::BitXor,
3093 token::And => BinOpKind::BitAnd,
3094 token::Or => BinOpKind::BitOr,
3095 token::Shl => BinOpKind::Shl,
3096 token::Shr => BinOpKind::Shr,
3098 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3099 self.mk_expr(span, aopexpr, ThinVec::new())
3101 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3102 self.bug("AssocOp should have been handled by special case")
3106 if op.fixity() == Fixity::None { break }
3111 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3112 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3113 -> PResult<'a, P<Expr>> {
3114 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3115 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3118 // Save the state of the parser before parsing type normally, in case there is a
3119 // LessThan comparison after this cast.
3120 let parser_snapshot_before_type = self.clone();
3121 match self.parse_ty_no_plus() {
3123 Ok(mk_expr(self, rhs))
3125 Err(mut type_err) => {
3126 // Rewind to before attempting to parse the type with generics, to recover
3127 // from situations like `x as usize < y` in which we first tried to parse
3128 // `usize < y` as a type with generic arguments.
3129 let parser_snapshot_after_type = self.clone();
3130 mem::replace(self, parser_snapshot_before_type);
3132 match self.parse_path(PathStyle::Expr) {
3134 let (op_noun, op_verb) = match self.token {
3135 token::Lt => ("comparison", "comparing"),
3136 token::BinOp(token::Shl) => ("shift", "shifting"),
3138 // We can end up here even without `<` being the next token, for
3139 // example because `parse_ty_no_plus` returns `Err` on keywords,
3140 // but `parse_path` returns `Ok` on them due to error recovery.
3141 // Return original error and parser state.
3142 mem::replace(self, parser_snapshot_after_type);
3143 return Err(type_err);
3147 // Successfully parsed the type path leaving a `<` yet to parse.
3150 // Report non-fatal diagnostics, keep `x as usize` as an expression
3151 // in AST and continue parsing.
3152 let msg = format!("`<` is interpreted as a start of generic \
3153 arguments for `{}`, not a {}", path, op_noun);
3154 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3155 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3156 "interpreted as generic arguments");
3157 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3159 let expr = mk_expr(self, P(Ty {
3161 node: TyKind::Path(None, path),
3162 id: ast::DUMMY_NODE_ID
3165 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3166 .unwrap_or(pprust::expr_to_string(&expr));
3167 err.span_suggestion_with_applicability(
3169 &format!("try {} the cast value", op_verb),
3170 format!("({})", expr_str),
3171 Applicability::MachineApplicable
3177 Err(mut path_err) => {
3178 // Couldn't parse as a path, return original error and parser state.
3180 mem::replace(self, parser_snapshot_after_type);
3188 /// Produce an error if comparison operators are chained (RFC #558).
3189 /// We only need to check lhs, not rhs, because all comparison ops
3190 /// have same precedence and are left-associative
3191 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3192 debug_assert!(outer_op.is_comparison(),
3193 "check_no_chained_comparison: {:?} is not comparison",
3196 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3197 // respan to include both operators
3198 let op_span = op.span.to(self.span);
3199 let mut err = self.diagnostic().struct_span_err(op_span,
3200 "chained comparison operators require parentheses");
3201 if op.node == BinOpKind::Lt &&
3202 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3203 *outer_op == AssocOp::Greater // even in a case like the following:
3204 { // Foo<Bar<Baz<Qux, ()>>>
3206 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3207 err.help("or use `(...)` if you meant to specify fn arguments");
3215 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3216 fn parse_prefix_range_expr(&mut self,
3217 already_parsed_attrs: Option<ThinVec<Attribute>>)
3218 -> PResult<'a, P<Expr>> {
3219 // Check for deprecated `...` syntax
3220 if self.token == token::DotDotDot {
3221 self.err_dotdotdot_syntax(self.span);
3224 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3225 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3227 let tok = self.token.clone();
3228 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3230 let mut hi = self.span;
3232 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3233 // RHS must be parsed with more associativity than the dots.
3234 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3235 Some(self.parse_assoc_expr_with(next_prec,
3236 LhsExpr::NotYetParsed)
3244 let limits = if tok == token::DotDot {
3245 RangeLimits::HalfOpen
3250 let r = try!(self.mk_range(None,
3253 Ok(self.mk_expr(lo.to(hi), r, attrs))
3256 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3257 if self.token.can_begin_expr() {
3258 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3259 if self.token == token::OpenDelim(token::Brace) {
3260 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3268 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3269 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3270 if self.check_keyword(keywords::Let) {
3271 return self.parse_if_let_expr(attrs);
3273 let lo = self.prev_span;
3274 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3276 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3277 // verify that the last statement is either an implicit return (no `;`) or an explicit
3278 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3279 // the dead code lint.
3280 if self.eat_keyword(keywords::Else) || !cond.returns() {
3281 let sp = self.sess.source_map().next_point(lo);
3282 let mut err = self.diagnostic()
3283 .struct_span_err(sp, "missing condition for `if` statemement");
3284 err.span_label(sp, "expected if condition here");
3287 let not_block = self.token != token::OpenDelim(token::Brace);
3288 let thn = self.parse_block().map_err(|mut err| {
3290 err.span_label(lo, "this `if` statement has a condition, but no block");
3294 let mut els: Option<P<Expr>> = None;
3295 let mut hi = thn.span;
3296 if self.eat_keyword(keywords::Else) {
3297 let elexpr = self.parse_else_expr()?;
3301 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3304 /// Parse an 'if let' expression ('if' token already eaten)
3305 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3306 -> PResult<'a, P<Expr>> {
3307 let lo = self.prev_span;
3308 self.expect_keyword(keywords::Let)?;
3309 let pats = self.parse_pats()?;
3310 self.expect(&token::Eq)?;
3311 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3312 let thn = self.parse_block()?;
3313 let (hi, els) = if self.eat_keyword(keywords::Else) {
3314 let expr = self.parse_else_expr()?;
3315 (expr.span, Some(expr))
3319 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3322 // `move |args| expr`
3323 fn parse_lambda_expr(&mut self,
3324 attrs: ThinVec<Attribute>)
3325 -> PResult<'a, P<Expr>>
3328 let movability = if self.eat_keyword(keywords::Static) {
3333 let asyncness = if self.span.edition() >= Edition::Edition2018 {
3334 self.parse_asyncness()
3338 let capture_clause = if self.eat_keyword(keywords::Move) {
3343 let decl = self.parse_fn_block_decl()?;
3344 let decl_hi = self.prev_span;
3345 let body = match decl.output {
3346 FunctionRetTy::Default(_) => {
3347 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3348 self.parse_expr_res(restrictions, None)?
3351 // If an explicit return type is given, require a
3352 // block to appear (RFC 968).
3353 let body_lo = self.span;
3354 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3360 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3364 // `else` token already eaten
3365 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3366 if self.eat_keyword(keywords::If) {
3367 return self.parse_if_expr(ThinVec::new());
3369 let blk = self.parse_block()?;
3370 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3374 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3375 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3377 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3378 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3380 let pat = self.parse_top_level_pat()?;
3381 if !self.eat_keyword(keywords::In) {
3382 let in_span = self.prev_span.between(self.span);
3383 let mut err = self.sess.span_diagnostic
3384 .struct_span_err(in_span, "missing `in` in `for` loop");
3385 err.span_suggestion_short_with_applicability(
3386 in_span, "try adding `in` here", " in ".into(),
3387 // has been misleading, at least in the past (closed Issue #48492)
3388 Applicability::MaybeIncorrect
3392 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3393 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3394 attrs.extend(iattrs);
3396 let hi = self.prev_span;
3397 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3400 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3401 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3403 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3404 if self.token.is_keyword(keywords::Let) {
3405 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3407 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3408 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3409 attrs.extend(iattrs);
3410 let span = span_lo.to(body.span);
3411 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3414 /// Parse a 'while let' expression ('while' token already eaten)
3415 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3417 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3418 self.expect_keyword(keywords::Let)?;
3419 let pats = self.parse_pats()?;
3420 self.expect(&token::Eq)?;
3421 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3422 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3423 attrs.extend(iattrs);
3424 let span = span_lo.to(body.span);
3425 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3428 // parse `loop {...}`, `loop` token already eaten
3429 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3431 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3432 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3433 attrs.extend(iattrs);
3434 let span = span_lo.to(body.span);
3435 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3438 /// Parse an `async move {...}` expression
3439 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3440 -> PResult<'a, P<Expr>>
3442 let span_lo = self.span;
3443 self.expect_keyword(keywords::Async)?;
3444 let capture_clause = if self.eat_keyword(keywords::Move) {
3449 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3450 attrs.extend(iattrs);
3452 span_lo.to(body.span),
3453 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3456 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3457 fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3458 -> PResult<'a, P<Expr>>
3460 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3461 attrs.extend(iattrs);
3462 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3465 // `match` token already eaten
3466 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3467 let match_span = self.prev_span;
3468 let lo = self.prev_span;
3469 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3471 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3472 if self.token == token::Token::Semi {
3473 e.span_suggestion_short_with_applicability(
3475 "try removing this `match`",
3477 Applicability::MaybeIncorrect // speculative
3482 attrs.extend(self.parse_inner_attributes()?);
3484 let mut arms: Vec<Arm> = Vec::new();
3485 while self.token != token::CloseDelim(token::Brace) {
3486 match self.parse_arm() {
3487 Ok(arm) => arms.push(arm),
3489 // Recover by skipping to the end of the block.
3491 self.recover_stmt();
3492 let span = lo.to(self.span);
3493 if self.token == token::CloseDelim(token::Brace) {
3496 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3502 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3505 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3506 maybe_whole!(self, NtArm, |x| x);
3508 let attrs = self.parse_outer_attributes()?;
3509 // Allow a '|' before the pats (RFC 1925)
3510 self.eat(&token::BinOp(token::Or));
3511 let pats = self.parse_pats()?;
3512 let guard = if self.eat_keyword(keywords::If) {
3513 Some(self.parse_expr()?)
3517 let arrow_span = self.span;
3518 self.expect(&token::FatArrow)?;
3519 let arm_start_span = self.span;
3521 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3522 .map_err(|mut err| {
3523 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3527 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3528 && self.token != token::CloseDelim(token::Brace);
3531 let cm = self.sess.source_map();
3532 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3533 .map_err(|mut err| {
3534 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3535 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3536 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3537 && expr_lines.lines.len() == 2
3538 && self.token == token::FatArrow => {
3539 // We check whether there's any trailing code in the parse span,
3540 // if there isn't, we very likely have the following:
3543 // | -- - missing comma
3549 // | parsed until here as `"y" & X`
3550 err.span_suggestion_short_with_applicability(
3551 cm.next_point(arm_start_span),
3552 "missing a comma here to end this `match` arm",
3554 Applicability::MachineApplicable
3558 err.span_label(arrow_span,
3559 "while parsing the `match` arm starting here");
3565 self.eat(&token::Comma);
3576 /// Parse an expression
3577 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3578 self.parse_expr_res(Restrictions::empty(), None)
3581 /// Evaluate the closure with restrictions in place.
3583 /// After the closure is evaluated, restrictions are reset.
3584 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3585 where F: FnOnce(&mut Self) -> T
3587 let old = self.restrictions;
3588 self.restrictions = r;
3590 self.restrictions = old;
3595 /// Parse an expression, subject to the given restrictions
3596 fn parse_expr_res(&mut self, r: Restrictions,
3597 already_parsed_attrs: Option<ThinVec<Attribute>>)
3598 -> PResult<'a, P<Expr>> {
3599 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3602 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3603 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3604 if self.check(&token::Eq) {
3606 Ok(Some(self.parse_expr()?))
3608 Ok(Some(self.parse_expr()?))
3614 /// Parse patterns, separated by '|' s
3615 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3616 let mut pats = Vec::new();
3618 pats.push(self.parse_top_level_pat()?);
3620 if self.token == token::OrOr {
3621 let mut err = self.struct_span_err(self.span,
3622 "unexpected token `||` after pattern");
3623 err.span_suggestion_with_applicability(
3625 "use a single `|` to specify multiple patterns",
3627 Applicability::MachineApplicable
3631 } else if self.check(&token::BinOp(token::Or)) {
3639 // Parses a parenthesized list of patterns like
3640 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3641 // - a vector of the patterns that were parsed
3642 // - an option indicating the index of the `..` element
3643 // - a boolean indicating whether a trailing comma was present.
3644 // Trailing commas are significant because (p) and (p,) are different patterns.
3645 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3646 self.expect(&token::OpenDelim(token::Paren))?;
3647 let result = self.parse_pat_list()?;
3648 self.expect(&token::CloseDelim(token::Paren))?;
3652 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3653 let mut fields = Vec::new();
3654 let mut ddpos = None;
3655 let mut trailing_comma = false;
3657 if self.eat(&token::DotDot) {
3658 if ddpos.is_none() {
3659 ddpos = Some(fields.len());
3661 // Emit a friendly error, ignore `..` and continue parsing
3662 self.span_err(self.prev_span,
3663 "`..` can only be used once per tuple or tuple struct pattern");
3665 } else if !self.check(&token::CloseDelim(token::Paren)) {
3666 fields.push(self.parse_pat()?);
3671 trailing_comma = self.eat(&token::Comma);
3672 if !trailing_comma {
3677 if ddpos == Some(fields.len()) && trailing_comma {
3678 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3679 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3682 Ok((fields, ddpos, trailing_comma))
3685 fn parse_pat_vec_elements(
3687 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3688 let mut before = Vec::new();
3689 let mut slice = None;
3690 let mut after = Vec::new();
3691 let mut first = true;
3692 let mut before_slice = true;
3694 while self.token != token::CloseDelim(token::Bracket) {
3698 self.expect(&token::Comma)?;
3700 if self.token == token::CloseDelim(token::Bracket)
3701 && (before_slice || !after.is_empty()) {
3707 if self.eat(&token::DotDot) {
3709 if self.check(&token::Comma) ||
3710 self.check(&token::CloseDelim(token::Bracket)) {
3711 slice = Some(P(Pat {
3712 id: ast::DUMMY_NODE_ID,
3713 node: PatKind::Wild,
3714 span: self.prev_span,
3716 before_slice = false;
3722 let subpat = self.parse_pat()?;
3723 if before_slice && self.eat(&token::DotDot) {
3724 slice = Some(subpat);
3725 before_slice = false;
3726 } else if before_slice {
3727 before.push(subpat);
3733 Ok((before, slice, after))
3739 attrs: Vec<Attribute>
3740 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3741 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3743 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3744 // Parsing a pattern of the form "fieldname: pat"
3745 let fieldname = self.parse_field_name()?;
3747 let pat = self.parse_pat()?;
3749 (pat, fieldname, false)
3751 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3752 let is_box = self.eat_keyword(keywords::Box);
3753 let boxed_span = self.span;
3754 let is_ref = self.eat_keyword(keywords::Ref);
3755 let is_mut = self.eat_keyword(keywords::Mut);
3756 let fieldname = self.parse_ident()?;
3757 hi = self.prev_span;
3759 let bind_type = match (is_ref, is_mut) {
3760 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3761 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3762 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3763 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3765 let fieldpat = P(Pat {
3766 id: ast::DUMMY_NODE_ID,
3767 node: PatKind::Ident(bind_type, fieldname, None),
3768 span: boxed_span.to(hi),
3771 let subpat = if is_box {
3773 id: ast::DUMMY_NODE_ID,
3774 node: PatKind::Box(fieldpat),
3780 (subpat, fieldname, true)
3783 Ok(source_map::Spanned {
3785 node: ast::FieldPat {
3789 attrs: attrs.into(),
3794 /// Parse the fields of a struct-like pattern
3795 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3796 let mut fields = Vec::new();
3797 let mut etc = false;
3798 let mut ate_comma = true;
3799 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3800 let mut etc_span = None;
3802 while self.token != token::CloseDelim(token::Brace) {
3803 let attrs = self.parse_outer_attributes()?;
3806 // check that a comma comes after every field
3808 let err = self.struct_span_err(self.prev_span, "expected `,`");
3813 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3815 let mut etc_sp = self.span;
3817 if self.token == token::DotDotDot { // Issue #46718
3818 // Accept `...` as if it were `..` to avoid further errors
3819 let mut err = self.struct_span_err(self.span,
3820 "expected field pattern, found `...`");
3821 err.span_suggestion_with_applicability(
3823 "to omit remaining fields, use one fewer `.`",
3825 Applicability::MachineApplicable
3829 self.bump(); // `..` || `...`:w
3831 if self.token == token::CloseDelim(token::Brace) {
3832 etc_span = Some(etc_sp);
3835 let token_str = self.this_token_to_string();
3836 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3838 err.span_label(self.span, "expected `}`");
3839 let mut comma_sp = None;
3840 if self.token == token::Comma { // Issue #49257
3841 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3842 err.span_label(etc_sp,
3843 "`..` must be at the end and cannot have a trailing comma");
3844 comma_sp = Some(self.span);
3849 etc_span = Some(etc_sp);
3850 if self.token == token::CloseDelim(token::Brace) {
3851 // If the struct looks otherwise well formed, recover and continue.
3852 if let Some(sp) = comma_sp {
3853 err.span_suggestion_short(sp, "remove this comma", "".into());
3857 } else if self.token.is_ident() && ate_comma {
3858 // Accept fields coming after `..,`.
3859 // This way we avoid "pattern missing fields" errors afterwards.
3860 // We delay this error until the end in order to have a span for a
3862 if let Some(mut delayed_err) = delayed_err {
3866 delayed_err = Some(err);
3869 if let Some(mut err) = delayed_err {
3876 fields.push(match self.parse_pat_field(lo, attrs) {
3879 if let Some(mut delayed_err) = delayed_err {
3885 ate_comma = self.eat(&token::Comma);
3888 if let Some(mut err) = delayed_err {
3889 if let Some(etc_span) = etc_span {
3890 err.multipart_suggestion(
3891 "move the `..` to the end of the field list",
3893 (etc_span, "".into()),
3894 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3900 return Ok((fields, etc));
3903 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3904 if self.token.is_path_start() {
3906 let (qself, path) = if self.eat_lt() {
3907 // Parse a qualified path
3908 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3911 // Parse an unqualified path
3912 (None, self.parse_path(PathStyle::Expr)?)
3914 let hi = self.prev_span;
3915 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3917 self.parse_literal_maybe_minus()
3921 // helper function to decide whether to parse as ident binding or to try to do
3922 // something more complex like range patterns
3923 fn parse_as_ident(&mut self) -> bool {
3924 self.look_ahead(1, |t| match *t {
3925 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3926 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3927 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3928 // range pattern branch
3929 token::DotDot => None,
3931 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3932 token::Comma | token::CloseDelim(token::Bracket) => true,
3937 /// A wrapper around `parse_pat` with some special error handling for the
3938 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3939 /// to subpatterns within such).
3940 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3941 let pat = self.parse_pat()?;
3942 if self.token == token::Comma {
3943 // An unexpected comma after a top-level pattern is a clue that the
3944 // user (perhaps more accustomed to some other language) forgot the
3945 // parentheses in what should have been a tuple pattern; return a
3946 // suggestion-enhanced error here rather than choking on the comma
3948 let comma_span = self.span;
3950 if let Err(mut err) = self.parse_pat_list() {
3951 // We didn't expect this to work anyway; we just wanted
3952 // to advance to the end of the comma-sequence so we know
3953 // the span to suggest parenthesizing
3956 let seq_span = pat.span.to(self.prev_span);
3957 let mut err = self.struct_span_err(comma_span,
3958 "unexpected `,` in pattern");
3959 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3960 err.span_suggestion_with_applicability(
3962 "try adding parentheses",
3963 format!("({})", seq_snippet),
3964 Applicability::MachineApplicable
3972 /// Parse a pattern.
3973 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3974 self.parse_pat_with_range_pat(true)
3977 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3979 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3980 maybe_whole!(self, NtPat, |x| x);
3985 token::BinOp(token::And) | token::AndAnd => {
3986 // Parse &pat / &mut pat
3988 let mutbl = self.parse_mutability();
3989 if let token::Lifetime(ident) = self.token {
3990 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3992 err.span_label(self.span, "unexpected lifetime");
3995 let subpat = self.parse_pat_with_range_pat(false)?;
3996 pat = PatKind::Ref(subpat, mutbl);
3998 token::OpenDelim(token::Paren) => {
3999 // Parse (pat,pat,pat,...) as tuple pattern
4000 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4001 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4002 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4004 PatKind::Tuple(fields, ddpos)
4007 token::OpenDelim(token::Bracket) => {
4008 // Parse [pat,pat,...] as slice pattern
4010 let (before, slice, after) = self.parse_pat_vec_elements()?;
4011 self.expect(&token::CloseDelim(token::Bracket))?;
4012 pat = PatKind::Slice(before, slice, after);
4014 // At this point, token != &, &&, (, [
4015 _ => if self.eat_keyword(keywords::Underscore) {
4017 pat = PatKind::Wild;
4018 } else if self.eat_keyword(keywords::Mut) {
4019 // Parse mut ident @ pat / mut ref ident @ pat
4020 let mutref_span = self.prev_span.to(self.span);
4021 let binding_mode = if self.eat_keyword(keywords::Ref) {
4023 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4024 .span_suggestion_with_applicability(
4026 "try switching the order",
4028 Applicability::MachineApplicable
4030 BindingMode::ByRef(Mutability::Mutable)
4032 BindingMode::ByValue(Mutability::Mutable)
4034 pat = self.parse_pat_ident(binding_mode)?;
4035 } else if self.eat_keyword(keywords::Ref) {
4036 // Parse ref ident @ pat / ref mut ident @ pat
4037 let mutbl = self.parse_mutability();
4038 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4039 } else if self.eat_keyword(keywords::Box) {
4041 let subpat = self.parse_pat_with_range_pat(false)?;
4042 pat = PatKind::Box(subpat);
4043 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4044 self.parse_as_ident() {
4045 // Parse ident @ pat
4046 // This can give false positives and parse nullary enums,
4047 // they are dealt with later in resolve
4048 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4049 pat = self.parse_pat_ident(binding_mode)?;
4050 } else if self.token.is_path_start() {
4051 // Parse pattern starting with a path
4052 let (qself, path) = if self.eat_lt() {
4053 // Parse a qualified path
4054 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4057 // Parse an unqualified path
4058 (None, self.parse_path(PathStyle::Expr)?)
4061 token::Not if qself.is_none() => {
4062 // Parse macro invocation
4064 let (delim, tts) = self.expect_delimited_token_tree()?;
4065 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4066 pat = PatKind::Mac(mac);
4068 token::DotDotDot | token::DotDotEq | token::DotDot => {
4069 let end_kind = match self.token {
4070 token::DotDot => RangeEnd::Excluded,
4071 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4072 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4073 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4076 let op_span = self.span;
4078 let span = lo.to(self.prev_span);
4079 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4081 let end = self.parse_pat_range_end()?;
4082 let op = Spanned { span: op_span, node: end_kind };
4083 pat = PatKind::Range(begin, end, op);
4085 token::OpenDelim(token::Brace) => {
4086 if qself.is_some() {
4087 let msg = "unexpected `{` after qualified path";
4088 let mut err = self.fatal(msg);
4089 err.span_label(self.span, msg);
4092 // Parse struct pattern
4094 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4096 self.recover_stmt();
4100 pat = PatKind::Struct(path, fields, etc);
4102 token::OpenDelim(token::Paren) => {
4103 if qself.is_some() {
4104 let msg = "unexpected `(` after qualified path";
4105 let mut err = self.fatal(msg);
4106 err.span_label(self.span, msg);
4109 // Parse tuple struct or enum pattern
4110 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4111 pat = PatKind::TupleStruct(path, fields, ddpos)
4113 _ => pat = PatKind::Path(qself, path),
4116 // Try to parse everything else as literal with optional minus
4117 match self.parse_literal_maybe_minus() {
4119 let op_span = self.span;
4120 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4121 self.check(&token::DotDotDot) {
4122 let end_kind = if self.eat(&token::DotDotDot) {
4123 RangeEnd::Included(RangeSyntax::DotDotDot)
4124 } else if self.eat(&token::DotDotEq) {
4125 RangeEnd::Included(RangeSyntax::DotDotEq)
4126 } else if self.eat(&token::DotDot) {
4129 panic!("impossible case: we already matched \
4130 on a range-operator token")
4132 let end = self.parse_pat_range_end()?;
4133 let op = Spanned { span: op_span, node: end_kind };
4134 pat = PatKind::Range(begin, end, op);
4136 pat = PatKind::Lit(begin);
4140 self.cancel(&mut err);
4141 let msg = format!("expected pattern, found {}", self.this_token_descr());
4142 let mut err = self.fatal(&msg);
4143 err.span_label(self.span, "expected pattern");
4150 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4151 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4153 if !allow_range_pat {
4156 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4158 PatKind::Range(..) => {
4159 let mut err = self.struct_span_err(
4161 "the range pattern here has ambiguous interpretation",
4163 err.span_suggestion_with_applicability(
4165 "add parentheses to clarify the precedence",
4166 format!("({})", pprust::pat_to_string(&pat)),
4167 // "ambiguous interpretation" implies that we have to be guessing
4168 Applicability::MaybeIncorrect
4179 /// Parse ident or ident @ pat
4180 /// used by the copy foo and ref foo patterns to give a good
4181 /// error message when parsing mistakes like ref foo(a,b)
4182 fn parse_pat_ident(&mut self,
4183 binding_mode: ast::BindingMode)
4184 -> PResult<'a, PatKind> {
4185 let ident = self.parse_ident()?;
4186 let sub = if self.eat(&token::At) {
4187 Some(self.parse_pat()?)
4192 // just to be friendly, if they write something like
4194 // we end up here with ( as the current token. This shortly
4195 // leads to a parse error. Note that if there is no explicit
4196 // binding mode then we do not end up here, because the lookahead
4197 // will direct us over to parse_enum_variant()
4198 if self.token == token::OpenDelim(token::Paren) {
4199 return Err(self.span_fatal(
4201 "expected identifier, found enum pattern"))
4204 Ok(PatKind::Ident(binding_mode, ident, sub))
4207 /// Parse a local variable declaration
4208 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4209 let lo = self.prev_span;
4210 let pat = self.parse_top_level_pat()?;
4212 let (err, ty) = if self.eat(&token::Colon) {
4213 // Save the state of the parser before parsing type normally, in case there is a `:`
4214 // instead of an `=` typo.
4215 let parser_snapshot_before_type = self.clone();
4216 let colon_sp = self.prev_span;
4217 match self.parse_ty() {
4218 Ok(ty) => (None, Some(ty)),
4220 // Rewind to before attempting to parse the type and continue parsing
4221 let parser_snapshot_after_type = self.clone();
4222 mem::replace(self, parser_snapshot_before_type);
4224 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4225 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4226 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4232 let init = match (self.parse_initializer(err.is_some()), err) {
4233 (Ok(init), None) => { // init parsed, ty parsed
4236 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4237 // Could parse the type as if it were the initializer, it is likely there was a
4238 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4239 err.span_suggestion_short_with_applicability(
4241 "use `=` if you meant to assign",
4243 Applicability::MachineApplicable
4246 // As this was parsed successfully, continue as if the code has been fixed for the
4247 // rest of the file. It will still fail due to the emitted error, but we avoid
4251 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4253 // Couldn't parse the type nor the initializer, only raise the type error and
4254 // return to the parser state before parsing the type as the initializer.
4255 // let x: <parse_error>;
4256 mem::replace(self, snapshot);
4259 (Err(err), None) => { // init error, ty parsed
4260 // Couldn't parse the initializer and we're not attempting to recover a failed
4261 // parse of the type, return the error.
4265 let hi = if self.token == token::Semi {
4274 id: ast::DUMMY_NODE_ID,
4280 /// Parse a structure field
4281 fn parse_name_and_ty(&mut self,
4284 attrs: Vec<Attribute>)
4285 -> PResult<'a, StructField> {
4286 let name = self.parse_ident()?;
4287 self.expect(&token::Colon)?;
4288 let ty = self.parse_ty()?;
4290 span: lo.to(self.prev_span),
4293 id: ast::DUMMY_NODE_ID,
4299 /// Emit an expected item after attributes error.
4300 fn expected_item_err(&self, attrs: &[Attribute]) {
4301 let message = match attrs.last() {
4302 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4303 _ => "expected item after attributes",
4306 self.span_err(self.prev_span, message);
4309 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4310 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4311 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4312 Ok(self.parse_stmt_(true))
4315 // Eat tokens until we can be relatively sure we reached the end of the
4316 // statement. This is something of a best-effort heuristic.
4318 // We terminate when we find an unmatched `}` (without consuming it).
4319 fn recover_stmt(&mut self) {
4320 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4323 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4324 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4325 // approximate - it can mean we break too early due to macros, but that
4326 // should only lead to sub-optimal recovery, not inaccurate parsing).
4328 // If `break_on_block` is `Break`, then we will stop consuming tokens
4329 // after finding (and consuming) a brace-delimited block.
4330 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4331 let mut brace_depth = 0;
4332 let mut bracket_depth = 0;
4333 let mut in_block = false;
4334 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4335 break_on_semi, break_on_block);
4337 debug!("recover_stmt_ loop {:?}", self.token);
4339 token::OpenDelim(token::DelimToken::Brace) => {
4342 if break_on_block == BlockMode::Break &&
4344 bracket_depth == 0 {
4348 token::OpenDelim(token::DelimToken::Bracket) => {
4352 token::CloseDelim(token::DelimToken::Brace) => {
4353 if brace_depth == 0 {
4354 debug!("recover_stmt_ return - close delim {:?}", self.token);
4359 if in_block && bracket_depth == 0 && brace_depth == 0 {
4360 debug!("recover_stmt_ return - block end {:?}", self.token);
4364 token::CloseDelim(token::DelimToken::Bracket) => {
4366 if bracket_depth < 0 {
4372 debug!("recover_stmt_ return - Eof");
4377 if break_on_semi == SemiColonMode::Break &&
4379 bracket_depth == 0 {
4380 debug!("recover_stmt_ return - Semi");
4391 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4392 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4394 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4399 fn is_async_block(&mut self) -> bool {
4400 self.token.is_keyword(keywords::Async) &&
4403 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4404 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4406 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4411 fn is_catch_expr(&mut self) -> bool {
4412 self.token.is_keyword(keywords::Do) &&
4413 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4414 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4416 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4417 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4420 fn is_union_item(&self) -> bool {
4421 self.token.is_keyword(keywords::Union) &&
4422 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4425 fn is_crate_vis(&self) -> bool {
4426 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4429 fn is_extern_non_path(&self) -> bool {
4430 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4433 fn is_existential_type_decl(&self) -> bool {
4434 self.token.is_keyword(keywords::Existential) &&
4435 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4438 fn is_auto_trait_item(&mut self) -> bool {
4440 (self.token.is_keyword(keywords::Auto)
4441 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4442 || // unsafe auto trait
4443 (self.token.is_keyword(keywords::Unsafe) &&
4444 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4445 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4448 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4449 -> PResult<'a, Option<P<Item>>> {
4450 let token_lo = self.span;
4451 let (ident, def) = match self.token {
4452 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4454 let ident = self.parse_ident()?;
4455 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4456 match self.parse_token_tree() {
4457 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4458 _ => unreachable!(),
4460 } else if self.check(&token::OpenDelim(token::Paren)) {
4461 let args = self.parse_token_tree();
4462 let body = if self.check(&token::OpenDelim(token::Brace)) {
4463 self.parse_token_tree()
4468 TokenStream::concat(vec![
4470 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4478 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4480 token::Ident(ident, _) if ident.name == "macro_rules" &&
4481 self.look_ahead(1, |t| *t == token::Not) => {
4482 let prev_span = self.prev_span;
4483 self.complain_if_pub_macro(&vis.node, prev_span);
4487 let ident = self.parse_ident()?;
4488 let (delim, tokens) = self.expect_delimited_token_tree()?;
4489 if delim != MacDelimiter::Brace {
4490 if !self.eat(&token::Semi) {
4491 let msg = "macros that expand to items must either \
4492 be surrounded with braces or followed by a semicolon";
4493 self.span_err(self.prev_span, msg);
4497 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4499 _ => return Ok(None),
4502 let span = lo.to(self.prev_span);
4503 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4506 fn parse_stmt_without_recovery(&mut self,
4507 macro_legacy_warnings: bool)
4508 -> PResult<'a, Option<Stmt>> {
4509 maybe_whole!(self, NtStmt, |x| Some(x));
4511 let attrs = self.parse_outer_attributes()?;
4514 Ok(Some(if self.eat_keyword(keywords::Let) {
4516 id: ast::DUMMY_NODE_ID,
4517 node: StmtKind::Local(self.parse_local(attrs.into())?),
4518 span: lo.to(self.prev_span),
4520 } else if let Some(macro_def) = self.eat_macro_def(
4522 &source_map::respan(lo, VisibilityKind::Inherited),
4526 id: ast::DUMMY_NODE_ID,
4527 node: StmtKind::Item(macro_def),
4528 span: lo.to(self.prev_span),
4530 // Starts like a simple path, being careful to avoid contextual keywords
4531 // such as a union items, item with `crate` visibility or auto trait items.
4532 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4533 // like a path (1 token), but it fact not a path.
4534 // `union::b::c` - path, `union U { ... }` - not a path.
4535 // `crate::b::c` - path, `crate struct S;` - not a path.
4536 // `extern::b::c` - path, `extern crate c;` - not a path.
4537 } else if self.token.is_path_start() &&
4538 !self.token.is_qpath_start() &&
4539 !self.is_union_item() &&
4540 !self.is_crate_vis() &&
4541 !self.is_extern_non_path() &&
4542 !self.is_existential_type_decl() &&
4543 !self.is_auto_trait_item() {
4544 let pth = self.parse_path(PathStyle::Expr)?;
4546 if !self.eat(&token::Not) {
4547 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4548 self.parse_struct_expr(lo, pth, ThinVec::new())?
4550 let hi = self.prev_span;
4551 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4554 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4555 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4556 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4559 return Ok(Some(Stmt {
4560 id: ast::DUMMY_NODE_ID,
4561 node: StmtKind::Expr(expr),
4562 span: lo.to(self.prev_span),
4566 // it's a macro invocation
4567 let id = match self.token {
4568 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4569 _ => self.parse_ident()?,
4572 // check that we're pointing at delimiters (need to check
4573 // again after the `if`, because of `parse_ident`
4574 // consuming more tokens).
4576 token::OpenDelim(_) => {}
4578 // we only expect an ident if we didn't parse one
4580 let ident_str = if id.name == keywords::Invalid.name() {
4585 let tok_str = self.this_token_to_string();
4586 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4589 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4594 let (delim, tts) = self.expect_delimited_token_tree()?;
4595 let hi = self.prev_span;
4597 let style = if delim == MacDelimiter::Brace {
4598 MacStmtStyle::Braces
4600 MacStmtStyle::NoBraces
4603 if id.name == keywords::Invalid.name() {
4604 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4605 let node = if delim == MacDelimiter::Brace ||
4606 self.token == token::Semi || self.token == token::Eof {
4607 StmtKind::Mac(P((mac, style, attrs.into())))
4609 // We used to incorrectly stop parsing macro-expanded statements here.
4610 // If the next token will be an error anyway but could have parsed with the
4611 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4612 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4613 // These can continue an expression, so we can't stop parsing and warn.
4614 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4615 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4616 token::BinOp(token::And) | token::BinOp(token::Or) |
4617 token::AndAnd | token::OrOr |
4618 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4621 self.warn_missing_semicolon();
4622 StmtKind::Mac(P((mac, style, attrs.into())))
4624 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4625 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4626 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4630 id: ast::DUMMY_NODE_ID,
4635 // if it has a special ident, it's definitely an item
4637 // Require a semicolon or braces.
4638 if style != MacStmtStyle::Braces {
4639 if !self.eat(&token::Semi) {
4640 self.span_err(self.prev_span,
4641 "macros that expand to items must \
4642 either be surrounded with braces or \
4643 followed by a semicolon");
4646 let span = lo.to(hi);
4648 id: ast::DUMMY_NODE_ID,
4650 node: StmtKind::Item({
4652 span, id /*id is good here*/,
4653 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4654 respan(lo, VisibilityKind::Inherited),
4660 // FIXME: Bad copy of attrs
4661 let old_directory_ownership =
4662 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4663 let item = self.parse_item_(attrs.clone(), false, true)?;
4664 self.directory.ownership = old_directory_ownership;
4668 id: ast::DUMMY_NODE_ID,
4669 span: lo.to(i.span),
4670 node: StmtKind::Item(i),
4673 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4674 if !attrs.is_empty() {
4675 if s.prev_token_kind == PrevTokenKind::DocComment {
4676 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4677 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4678 s.span_err(s.span, "expected statement after outer attribute");
4683 // Do not attempt to parse an expression if we're done here.
4684 if self.token == token::Semi {
4685 unused_attrs(&attrs, self);
4690 if self.token == token::CloseDelim(token::Brace) {
4691 unused_attrs(&attrs, self);
4695 // Remainder are line-expr stmts.
4696 let e = self.parse_expr_res(
4697 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4699 id: ast::DUMMY_NODE_ID,
4700 span: lo.to(e.span),
4701 node: StmtKind::Expr(e),
4708 /// Is this expression a successfully-parsed statement?
4709 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4710 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4711 !classify::expr_requires_semi_to_be_stmt(e)
4714 /// Parse a block. No inner attrs are allowed.
4715 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4716 maybe_whole!(self, NtBlock, |x| x);
4720 if !self.eat(&token::OpenDelim(token::Brace)) {
4722 let tok = self.this_token_to_string();
4723 let mut do_not_suggest_help = false;
4724 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4725 if self.token.is_keyword(keywords::In) || self.token == token::Colon {
4726 do_not_suggest_help = true;
4727 e.span_label(sp, "expected `{`");
4730 // Check to see if the user has written something like
4735 // Which is valid in other languages, but not Rust.
4736 match self.parse_stmt_without_recovery(false) {
4738 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4739 || do_not_suggest_help {
4740 // if the next token is an open brace (e.g., `if a b {`), the place-
4741 // inside-a-block suggestion would be more likely wrong than right
4744 let mut stmt_span = stmt.span;
4745 // expand the span to include the semicolon, if it exists
4746 if self.eat(&token::Semi) {
4747 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4749 let sugg = pprust::to_string(|s| {
4750 use print::pprust::{PrintState, INDENT_UNIT};
4751 s.ibox(INDENT_UNIT)?;
4753 s.print_stmt(&stmt)?;
4754 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4756 e.span_suggestion_with_applicability(
4758 "try placing this code inside a block",
4760 // speculative, has been misleading in the past (closed Issue #46836)
4761 Applicability::MaybeIncorrect
4765 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4766 self.cancel(&mut e);
4773 self.parse_block_tail(lo, BlockCheckMode::Default)
4776 /// Parse a block. Inner attrs are allowed.
4777 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4778 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4781 self.expect(&token::OpenDelim(token::Brace))?;
4782 Ok((self.parse_inner_attributes()?,
4783 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4786 /// Parse the rest of a block expression or function body
4787 /// Precondition: already parsed the '{'.
4788 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4789 let mut stmts = vec![];
4790 let mut recovered = false;
4792 while !self.eat(&token::CloseDelim(token::Brace)) {
4793 let stmt = match self.parse_full_stmt(false) {
4796 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4797 self.eat(&token::CloseDelim(token::Brace));
4803 if let Some(stmt) = stmt {
4805 } else if self.token == token::Eof {
4808 // Found only `;` or `}`.
4814 id: ast::DUMMY_NODE_ID,
4816 span: lo.to(self.prev_span),
4821 /// Parse a statement, including the trailing semicolon.
4822 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4823 // skip looking for a trailing semicolon when we have an interpolated statement
4824 maybe_whole!(self, NtStmt, |x| Some(x));
4826 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4828 None => return Ok(None),
4832 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4833 // expression without semicolon
4834 if classify::expr_requires_semi_to_be_stmt(expr) {
4835 // Just check for errors and recover; do not eat semicolon yet.
4837 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4840 self.recover_stmt();
4844 StmtKind::Local(..) => {
4845 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4846 if macro_legacy_warnings && self.token != token::Semi {
4847 self.warn_missing_semicolon();
4849 self.expect_one_of(&[], &[token::Semi])?;
4855 if self.eat(&token::Semi) {
4856 stmt = stmt.add_trailing_semicolon();
4859 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4863 fn warn_missing_semicolon(&self) {
4864 self.diagnostic().struct_span_warn(self.span, {
4865 &format!("expected `;`, found `{}`", self.this_token_to_string())
4867 "This was erroneously allowed and will become a hard error in a future release"
4871 fn err_dotdotdot_syntax(&self, span: Span) {
4872 self.diagnostic().struct_span_err(span, {
4873 "unexpected token: `...`"
4874 }).span_suggestion_with_applicability(
4875 span, "use `..` for an exclusive range", "..".to_owned(),
4876 Applicability::MaybeIncorrect
4877 ).span_suggestion_with_applicability(
4878 span, "or `..=` for an inclusive range", "..=".to_owned(),
4879 Applicability::MaybeIncorrect
4883 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4884 // BOUND = TY_BOUND | LT_BOUND
4885 // LT_BOUND = LIFETIME (e.g. `'a`)
4886 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4887 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4888 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4889 let mut bounds = Vec::new();
4891 // This needs to be synchronized with `Token::can_begin_bound`.
4892 let is_bound_start = self.check_path() || self.check_lifetime() ||
4893 self.check(&token::Question) ||
4894 self.check_keyword(keywords::For) ||
4895 self.check(&token::OpenDelim(token::Paren));
4898 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4899 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4900 if self.token.is_lifetime() {
4901 if let Some(question_span) = question {
4902 self.span_err(question_span,
4903 "`?` may only modify trait bounds, not lifetime bounds");
4905 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4907 self.expect(&token::CloseDelim(token::Paren))?;
4908 self.span_err(self.prev_span,
4909 "parenthesized lifetime bounds are not supported");
4912 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4913 let path = self.parse_path(PathStyle::Type)?;
4915 self.expect(&token::CloseDelim(token::Paren))?;
4917 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4918 let modifier = if question.is_some() {
4919 TraitBoundModifier::Maybe
4921 TraitBoundModifier::None
4923 bounds.push(GenericBound::Trait(poly_trait, modifier));
4929 if !allow_plus || !self.eat_plus() {
4937 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
4938 self.parse_generic_bounds_common(true)
4941 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4942 // BOUND = LT_BOUND (e.g. `'a`)
4943 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4944 let mut lifetimes = Vec::new();
4945 while self.check_lifetime() {
4946 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4948 if !self.eat_plus() {
4955 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4956 fn parse_ty_param(&mut self,
4957 preceding_attrs: Vec<Attribute>)
4958 -> PResult<'a, GenericParam> {
4959 let ident = self.parse_ident()?;
4961 // Parse optional colon and param bounds.
4962 let bounds = if self.eat(&token::Colon) {
4963 self.parse_generic_bounds()?
4968 let default = if self.eat(&token::Eq) {
4969 Some(self.parse_ty()?)
4976 id: ast::DUMMY_NODE_ID,
4977 attrs: preceding_attrs.into(),
4979 kind: GenericParamKind::Type {
4985 /// Parses the following grammar:
4986 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4987 fn parse_trait_item_assoc_ty(&mut self)
4988 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4989 let ident = self.parse_ident()?;
4990 let mut generics = self.parse_generics()?;
4992 // Parse optional colon and param bounds.
4993 let bounds = if self.eat(&token::Colon) {
4994 self.parse_generic_bounds()?
4998 generics.where_clause = self.parse_where_clause()?;
5000 let default = if self.eat(&token::Eq) {
5001 Some(self.parse_ty()?)
5005 self.expect(&token::Semi)?;
5007 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5010 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5011 /// trailing comma and erroneous trailing attributes.
5012 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5013 let mut params = Vec::new();
5014 let mut seen_ty_param = false;
5016 let attrs = self.parse_outer_attributes()?;
5017 if self.check_lifetime() {
5018 let lifetime = self.expect_lifetime();
5019 // Parse lifetime parameter.
5020 let bounds = if self.eat(&token::Colon) {
5021 self.parse_lt_param_bounds()
5025 params.push(ast::GenericParam {
5026 ident: lifetime.ident,
5028 attrs: attrs.into(),
5030 kind: ast::GenericParamKind::Lifetime,
5033 self.span_err(self.prev_span,
5034 "lifetime parameters must be declared prior to type parameters");
5036 } else if self.check_ident() {
5037 // Parse type parameter.
5038 params.push(self.parse_ty_param(attrs)?);
5039 seen_ty_param = true;
5041 // Check for trailing attributes and stop parsing.
5042 if !attrs.is_empty() {
5043 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
5044 self.span_err(attrs[0].span,
5045 &format!("trailing attribute after {} parameters", param_kind));
5050 if !self.eat(&token::Comma) {
5057 /// Parse a set of optional generic type parameter declarations. Where
5058 /// clauses are not parsed here, and must be added later via
5059 /// `parse_where_clause()`.
5061 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5062 /// | ( < lifetimes , typaramseq ( , )? > )
5063 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5064 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5065 maybe_whole!(self, NtGenerics, |x| x);
5067 let span_lo = self.span;
5069 let params = self.parse_generic_params()?;
5073 where_clause: WhereClause {
5074 id: ast::DUMMY_NODE_ID,
5075 predicates: Vec::new(),
5076 span: syntax_pos::DUMMY_SP,
5078 span: span_lo.to(self.prev_span),
5081 Ok(ast::Generics::default())
5085 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5086 /// possibly including trailing comma.
5087 fn parse_generic_args(&mut self)
5088 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5089 let mut args = Vec::new();
5090 let mut bindings = Vec::new();
5091 let mut seen_type = false;
5092 let mut seen_binding = false;
5094 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5095 // Parse lifetime argument.
5096 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5097 if seen_type || seen_binding {
5098 self.span_err(self.prev_span,
5099 "lifetime parameters must be declared prior to type parameters");
5101 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5102 // Parse associated type binding.
5104 let ident = self.parse_ident()?;
5106 let ty = self.parse_ty()?;
5107 bindings.push(TypeBinding {
5108 id: ast::DUMMY_NODE_ID,
5111 span: lo.to(self.prev_span),
5113 seen_binding = true;
5114 } else if self.check_type() {
5115 // Parse type argument.
5116 let ty_param = self.parse_ty()?;
5118 self.span_err(ty_param.span,
5119 "type parameters must be declared prior to associated type bindings");
5121 args.push(GenericArg::Type(ty_param));
5127 if !self.eat(&token::Comma) {
5131 Ok((args, bindings))
5134 /// Parses an optional `where` clause and places it in `generics`.
5136 /// ```ignore (only-for-syntax-highlight)
5137 /// where T : Trait<U, V> + 'b, 'a : 'b
5139 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5140 maybe_whole!(self, NtWhereClause, |x| x);
5142 let mut where_clause = WhereClause {
5143 id: ast::DUMMY_NODE_ID,
5144 predicates: Vec::new(),
5145 span: syntax_pos::DUMMY_SP,
5148 if !self.eat_keyword(keywords::Where) {
5149 return Ok(where_clause);
5151 let lo = self.prev_span;
5153 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5154 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5155 // change we parse those generics now, but report an error.
5156 if self.choose_generics_over_qpath() {
5157 let generics = self.parse_generics()?;
5158 self.span_err(generics.span,
5159 "generic parameters on `where` clauses are reserved for future use");
5164 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5165 let lifetime = self.expect_lifetime();
5166 // Bounds starting with a colon are mandatory, but possibly empty.
5167 self.expect(&token::Colon)?;
5168 let bounds = self.parse_lt_param_bounds();
5169 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5170 ast::WhereRegionPredicate {
5171 span: lo.to(self.prev_span),
5176 } else if self.check_type() {
5177 // Parse optional `for<'a, 'b>`.
5178 // This `for` is parsed greedily and applies to the whole predicate,
5179 // the bounded type can have its own `for` applying only to it.
5180 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5181 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5182 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5183 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5185 // Parse type with mandatory colon and (possibly empty) bounds,
5186 // or with mandatory equality sign and the second type.
5187 let ty = self.parse_ty()?;
5188 if self.eat(&token::Colon) {
5189 let bounds = self.parse_generic_bounds()?;
5190 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5191 ast::WhereBoundPredicate {
5192 span: lo.to(self.prev_span),
5193 bound_generic_params: lifetime_defs,
5198 // FIXME: Decide what should be used here, `=` or `==`.
5199 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5200 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5201 let rhs_ty = self.parse_ty()?;
5202 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5203 ast::WhereEqPredicate {
5204 span: lo.to(self.prev_span),
5207 id: ast::DUMMY_NODE_ID,
5211 return self.unexpected();
5217 if !self.eat(&token::Comma) {
5222 where_clause.span = lo.to(self.prev_span);
5226 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5227 -> PResult<'a, (Vec<Arg> , bool)> {
5229 let mut variadic = false;
5230 let args: Vec<Option<Arg>> =
5231 self.parse_unspanned_seq(
5232 &token::OpenDelim(token::Paren),
5233 &token::CloseDelim(token::Paren),
5234 SeqSep::trailing_allowed(token::Comma),
5236 if p.token == token::DotDotDot {
5240 if p.token != token::CloseDelim(token::Paren) {
5243 "`...` must be last in argument list for variadic function");
5247 let span = p.prev_span;
5248 if p.token == token::CloseDelim(token::Paren) {
5249 // continue parsing to present any further errors
5252 "only foreign functions are allowed to be variadic"
5254 Ok(Some(dummy_arg(span)))
5256 // this function definition looks beyond recovery, stop parsing
5258 "only foreign functions are allowed to be variadic");
5263 match p.parse_arg_general(named_args) {
5264 Ok(arg) => Ok(Some(arg)),
5267 let lo = p.prev_span;
5268 // Skip every token until next possible arg or end.
5269 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5270 // Create a placeholder argument for proper arg count (#34264).
5271 let span = lo.to(p.prev_span);
5272 Ok(Some(dummy_arg(span)))
5279 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5281 if variadic && args.is_empty() {
5283 "variadic function must be declared with at least one named argument");
5286 Ok((args, variadic))
5289 /// Parse the argument list and result type of a function declaration
5290 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5292 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5293 let ret_ty = self.parse_ret_ty(true)?;
5302 /// Returns the parsed optional self argument and whether a self shortcut was used.
5303 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5304 let expect_ident = |this: &mut Self| match this.token {
5305 // Preserve hygienic context.
5306 token::Ident(ident, _) =>
5307 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5310 let isolated_self = |this: &mut Self, n| {
5311 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5312 this.look_ahead(n + 1, |t| t != &token::ModSep)
5315 // Parse optional self parameter of a method.
5316 // Only a limited set of initial token sequences is considered self parameters, anything
5317 // else is parsed as a normal function parameter list, so some lookahead is required.
5318 let eself_lo = self.span;
5319 let (eself, eself_ident, eself_hi) = match self.token {
5320 token::BinOp(token::And) => {
5326 (if isolated_self(self, 1) {
5328 SelfKind::Region(None, Mutability::Immutable)
5329 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5330 isolated_self(self, 2) {
5333 SelfKind::Region(None, Mutability::Mutable)
5334 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5335 isolated_self(self, 2) {
5337 let lt = self.expect_lifetime();
5338 SelfKind::Region(Some(lt), Mutability::Immutable)
5339 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5340 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5341 isolated_self(self, 3) {
5343 let lt = self.expect_lifetime();
5345 SelfKind::Region(Some(lt), Mutability::Mutable)
5348 }, expect_ident(self), self.prev_span)
5350 token::BinOp(token::Star) => {
5355 // Emit special error for `self` cases.
5356 (if isolated_self(self, 1) {
5358 self.span_err(self.span, "cannot pass `self` by raw pointer");
5359 SelfKind::Value(Mutability::Immutable)
5360 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5361 isolated_self(self, 2) {
5364 self.span_err(self.span, "cannot pass `self` by raw pointer");
5365 SelfKind::Value(Mutability::Immutable)
5368 }, expect_ident(self), self.prev_span)
5370 token::Ident(..) => {
5371 if isolated_self(self, 0) {
5374 let eself_ident = expect_ident(self);
5375 let eself_hi = self.prev_span;
5376 (if self.eat(&token::Colon) {
5377 let ty = self.parse_ty()?;
5378 SelfKind::Explicit(ty, Mutability::Immutable)
5380 SelfKind::Value(Mutability::Immutable)
5381 }, eself_ident, eself_hi)
5382 } else if self.token.is_keyword(keywords::Mut) &&
5383 isolated_self(self, 1) {
5387 let eself_ident = expect_ident(self);
5388 let eself_hi = self.prev_span;
5389 (if self.eat(&token::Colon) {
5390 let ty = self.parse_ty()?;
5391 SelfKind::Explicit(ty, Mutability::Mutable)
5393 SelfKind::Value(Mutability::Mutable)
5394 }, eself_ident, eself_hi)
5399 _ => return Ok(None),
5402 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5403 Ok(Some(Arg::from_self(eself, eself_ident)))
5406 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5407 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5408 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5410 self.expect(&token::OpenDelim(token::Paren))?;
5412 // Parse optional self argument
5413 let self_arg = self.parse_self_arg()?;
5415 // Parse the rest of the function parameter list.
5416 let sep = SeqSep::trailing_allowed(token::Comma);
5417 let fn_inputs = if let Some(self_arg) = self_arg {
5418 if self.check(&token::CloseDelim(token::Paren)) {
5420 } else if self.eat(&token::Comma) {
5421 let mut fn_inputs = vec![self_arg];
5422 fn_inputs.append(&mut self.parse_seq_to_before_end(
5423 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5427 return self.unexpected();
5430 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5433 // Parse closing paren and return type.
5434 self.expect(&token::CloseDelim(token::Paren))?;
5437 output: self.parse_ret_ty(true)?,
5442 // parse the |arg, arg| header on a lambda
5443 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5444 let inputs_captures = {
5445 if self.eat(&token::OrOr) {
5448 self.expect(&token::BinOp(token::Or))?;
5449 let args = self.parse_seq_to_before_tokens(
5450 &[&token::BinOp(token::Or), &token::OrOr],
5451 SeqSep::trailing_allowed(token::Comma),
5452 TokenExpectType::NoExpect,
5453 |p| p.parse_fn_block_arg()
5459 let output = self.parse_ret_ty(true)?;
5462 inputs: inputs_captures,
5468 /// Parse the name and optional generic types of a function header.
5469 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5470 let id = self.parse_ident()?;
5471 let generics = self.parse_generics()?;
5475 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5476 attrs: Vec<Attribute>) -> P<Item> {
5480 id: ast::DUMMY_NODE_ID,
5488 /// Parse an item-position function declaration.
5489 fn parse_item_fn(&mut self,
5492 constness: Spanned<Constness>,
5494 -> PResult<'a, ItemInfo> {
5495 let (ident, mut generics) = self.parse_fn_header()?;
5496 let decl = self.parse_fn_decl(false)?;
5497 generics.where_clause = self.parse_where_clause()?;
5498 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5499 let header = FnHeader { unsafety, asyncness, constness, abi };
5500 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5503 /// true if we are looking at `const ID`, false for things like `const fn` etc
5504 fn is_const_item(&mut self) -> bool {
5505 self.token.is_keyword(keywords::Const) &&
5506 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5507 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5510 /// parses all the "front matter" for a `fn` declaration, up to
5511 /// and including the `fn` keyword:
5515 /// - `const unsafe fn`
5518 fn parse_fn_front_matter(&mut self)
5526 let is_const_fn = self.eat_keyword(keywords::Const);
5527 let const_span = self.prev_span;
5528 let unsafety = self.parse_unsafety();
5529 let asyncness = self.parse_asyncness();
5530 let (constness, unsafety, abi) = if is_const_fn {
5531 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5533 let abi = if self.eat_keyword(keywords::Extern) {
5534 self.parse_opt_abi()?.unwrap_or(Abi::C)
5538 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5540 self.expect_keyword(keywords::Fn)?;
5541 Ok((constness, unsafety, asyncness, abi))
5544 /// Parse an impl item.
5545 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5546 maybe_whole!(self, NtImplItem, |x| x);
5547 let attrs = self.parse_outer_attributes()?;
5548 let (mut item, tokens) = self.collect_tokens(|this| {
5549 this.parse_impl_item_(at_end, attrs)
5552 // See `parse_item` for why this clause is here.
5553 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5554 item.tokens = Some(tokens);
5559 fn parse_impl_item_(&mut self,
5561 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5563 let vis = self.parse_visibility(false)?;
5564 let defaultness = self.parse_defaultness();
5565 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5566 let (name, alias, generics) = type_?;
5567 let kind = match alias {
5568 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5569 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5571 (name, kind, generics)
5572 } else if self.is_const_item() {
5573 // This parses the grammar:
5574 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5575 self.expect_keyword(keywords::Const)?;
5576 let name = self.parse_ident()?;
5577 self.expect(&token::Colon)?;
5578 let typ = self.parse_ty()?;
5579 self.expect(&token::Eq)?;
5580 let expr = self.parse_expr()?;
5581 self.expect(&token::Semi)?;
5582 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5584 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5585 attrs.extend(inner_attrs);
5586 (name, node, generics)
5590 id: ast::DUMMY_NODE_ID,
5591 span: lo.to(self.prev_span),
5602 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5603 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5608 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5610 VisibilityKind::Inherited => Ok(()),
5612 let is_macro_rules: bool = match self.token {
5613 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5617 let mut err = self.diagnostic()
5618 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5619 err.span_suggestion_with_applicability(
5621 "try exporting the macro",
5622 "#[macro_export]".to_owned(),
5623 Applicability::MaybeIncorrect // speculative
5627 let mut err = self.diagnostic()
5628 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5629 err.help("try adjusting the macro to put `pub` inside the invocation");
5636 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5637 -> DiagnosticBuilder<'a>
5639 let expected_kinds = if item_type == "extern" {
5640 "missing `fn`, `type`, or `static`"
5642 "missing `fn`, `type`, or `const`"
5645 // Given this code `path(`, it seems like this is not
5646 // setting the visibility of a macro invocation, but rather
5647 // a mistyped method declaration.
5648 // Create a diagnostic pointing out that `fn` is missing.
5650 // x | pub path(&self) {
5651 // | ^ missing `fn`, `type`, or `const`
5653 // ^^ `sp` below will point to this
5654 let sp = prev_span.between(self.prev_span);
5655 let mut err = self.diagnostic().struct_span_err(
5657 &format!("{} for {}-item declaration",
5658 expected_kinds, item_type));
5659 err.span_label(sp, expected_kinds);
5663 /// Parse a method or a macro invocation in a trait impl.
5664 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5665 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5666 ast::ImplItemKind)> {
5667 // code copied from parse_macro_use_or_failure... abstraction!
5668 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5670 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5671 ast::ImplItemKind::Macro(mac)))
5673 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5674 let ident = self.parse_ident()?;
5675 let mut generics = self.parse_generics()?;
5676 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5677 generics.where_clause = self.parse_where_clause()?;
5679 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5680 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5681 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5682 ast::MethodSig { header, decl },
5688 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5689 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5690 let ident = self.parse_ident()?;
5691 let mut tps = self.parse_generics()?;
5693 // Parse optional colon and supertrait bounds.
5694 let bounds = if self.eat(&token::Colon) {
5695 self.parse_generic_bounds()?
5700 if self.eat(&token::Eq) {
5701 // it's a trait alias
5702 let bounds = self.parse_generic_bounds()?;
5703 tps.where_clause = self.parse_where_clause()?;
5704 self.expect(&token::Semi)?;
5705 if unsafety != Unsafety::Normal {
5706 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5708 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5710 // it's a normal trait
5711 tps.where_clause = self.parse_where_clause()?;
5712 self.expect(&token::OpenDelim(token::Brace))?;
5713 let mut trait_items = vec![];
5714 while !self.eat(&token::CloseDelim(token::Brace)) {
5715 let mut at_end = false;
5716 match self.parse_trait_item(&mut at_end) {
5717 Ok(item) => trait_items.push(item),
5721 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5726 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5730 fn choose_generics_over_qpath(&self) -> bool {
5731 // There's an ambiguity between generic parameters and qualified paths in impls.
5732 // If we see `<` it may start both, so we have to inspect some following tokens.
5733 // The following combinations can only start generics,
5734 // but not qualified paths (with one exception):
5735 // `<` `>` - empty generic parameters
5736 // `<` `#` - generic parameters with attributes
5737 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5738 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5739 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5740 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5741 // The only truly ambiguous case is
5742 // `<` IDENT `>` `::` IDENT ...
5743 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5744 // because this is what almost always expected in practice, qualified paths in impls
5745 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5746 self.token == token::Lt &&
5747 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5748 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5749 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5750 t == &token::Colon || t == &token::Eq))
5753 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5754 self.expect(&token::OpenDelim(token::Brace))?;
5755 let attrs = self.parse_inner_attributes()?;
5757 let mut impl_items = Vec::new();
5758 while !self.eat(&token::CloseDelim(token::Brace)) {
5759 let mut at_end = false;
5760 match self.parse_impl_item(&mut at_end) {
5761 Ok(impl_item) => impl_items.push(impl_item),
5765 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5770 Ok((impl_items, attrs))
5773 /// Parses an implementation item, `impl` keyword is already parsed.
5774 /// impl<'a, T> TYPE { /* impl items */ }
5775 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5776 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5777 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5778 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5779 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5780 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5781 -> PResult<'a, ItemInfo> {
5782 // First, parse generic parameters if necessary.
5783 let mut generics = if self.choose_generics_over_qpath() {
5784 self.parse_generics()?
5786 ast::Generics::default()
5789 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5790 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5792 ast::ImplPolarity::Negative
5794 ast::ImplPolarity::Positive
5797 // Parse both types and traits as a type, then reinterpret if necessary.
5798 let ty_first = self.parse_ty()?;
5800 // If `for` is missing we try to recover.
5801 let has_for = self.eat_keyword(keywords::For);
5802 let missing_for_span = self.prev_span.between(self.span);
5804 let ty_second = if self.token == token::DotDot {
5805 // We need to report this error after `cfg` expansion for compatibility reasons
5806 self.bump(); // `..`, do not add it to expected tokens
5807 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5808 } else if has_for || self.token.can_begin_type() {
5809 Some(self.parse_ty()?)
5814 generics.where_clause = self.parse_where_clause()?;
5816 let (impl_items, attrs) = self.parse_impl_body()?;
5818 let item_kind = match ty_second {
5819 Some(ty_second) => {
5820 // impl Trait for Type
5822 self.span_err(missing_for_span, "missing `for` in a trait impl");
5825 let ty_first = ty_first.into_inner();
5826 let path = match ty_first.node {
5827 // This notably includes paths passed through `ty` macro fragments (#46438).
5828 TyKind::Path(None, path) => path,
5830 self.span_err(ty_first.span, "expected a trait, found type");
5831 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5834 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5836 ItemKind::Impl(unsafety, polarity, defaultness,
5837 generics, Some(trait_ref), ty_second, impl_items)
5841 ItemKind::Impl(unsafety, polarity, defaultness,
5842 generics, None, ty_first, impl_items)
5846 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5849 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5850 if self.eat_keyword(keywords::For) {
5852 let params = self.parse_generic_params()?;
5854 // We rely on AST validation to rule out invalid cases: There must not be type
5855 // parameters, and the lifetime parameters must not have bounds.
5862 /// Parse struct Foo { ... }
5863 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5864 let class_name = self.parse_ident()?;
5866 let mut generics = self.parse_generics()?;
5868 // There is a special case worth noting here, as reported in issue #17904.
5869 // If we are parsing a tuple struct it is the case that the where clause
5870 // should follow the field list. Like so:
5872 // struct Foo<T>(T) where T: Copy;
5874 // If we are parsing a normal record-style struct it is the case
5875 // that the where clause comes before the body, and after the generics.
5876 // So if we look ahead and see a brace or a where-clause we begin
5877 // parsing a record style struct.
5879 // Otherwise if we look ahead and see a paren we parse a tuple-style
5882 let vdata = if self.token.is_keyword(keywords::Where) {
5883 generics.where_clause = self.parse_where_clause()?;
5884 if self.eat(&token::Semi) {
5885 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5886 VariantData::Unit(ast::DUMMY_NODE_ID)
5888 // If we see: `struct Foo<T> where T: Copy { ... }`
5889 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5891 // No `where` so: `struct Foo<T>;`
5892 } else if self.eat(&token::Semi) {
5893 VariantData::Unit(ast::DUMMY_NODE_ID)
5894 // Record-style struct definition
5895 } else if self.token == token::OpenDelim(token::Brace) {
5896 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5897 // Tuple-style struct definition with optional where-clause.
5898 } else if self.token == token::OpenDelim(token::Paren) {
5899 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5900 generics.where_clause = self.parse_where_clause()?;
5901 self.expect(&token::Semi)?;
5904 let token_str = self.this_token_to_string();
5905 let mut err = self.fatal(&format!(
5906 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5909 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5913 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5916 /// Parse union Foo { ... }
5917 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5918 let class_name = self.parse_ident()?;
5920 let mut generics = self.parse_generics()?;
5922 let vdata = if self.token.is_keyword(keywords::Where) {
5923 generics.where_clause = self.parse_where_clause()?;
5924 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5925 } else if self.token == token::OpenDelim(token::Brace) {
5926 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5928 let token_str = self.this_token_to_string();
5929 let mut err = self.fatal(&format!(
5930 "expected `where` or `{{` after union name, found `{}`", token_str));
5931 err.span_label(self.span, "expected `where` or `{` after union name");
5935 Ok((class_name, ItemKind::Union(vdata, generics), None))
5938 fn consume_block(&mut self, delim: token::DelimToken) {
5939 let mut brace_depth = 0;
5940 if !self.eat(&token::OpenDelim(delim)) {
5944 if self.eat(&token::OpenDelim(delim)) {
5946 } else if self.eat(&token::CloseDelim(delim)) {
5947 if brace_depth == 0 {
5953 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5961 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5962 let mut fields = Vec::new();
5963 if self.eat(&token::OpenDelim(token::Brace)) {
5964 while self.token != token::CloseDelim(token::Brace) {
5965 let field = self.parse_struct_decl_field().map_err(|e| {
5966 self.recover_stmt();
5970 Ok(field) => fields.push(field),
5976 self.eat(&token::CloseDelim(token::Brace));
5978 let token_str = self.this_token_to_string();
5979 let mut err = self.fatal(&format!(
5980 "expected `where`, or `{{` after struct name, found `{}`", token_str));
5981 err.span_label(self.span, "expected `where`, or `{` after struct name");
5988 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5989 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5990 // Unit like structs are handled in parse_item_struct function
5991 let fields = self.parse_unspanned_seq(
5992 &token::OpenDelim(token::Paren),
5993 &token::CloseDelim(token::Paren),
5994 SeqSep::trailing_allowed(token::Comma),
5996 let attrs = p.parse_outer_attributes()?;
5998 let vis = p.parse_visibility(true)?;
5999 let ty = p.parse_ty()?;
6001 span: lo.to(ty.span),
6004 id: ast::DUMMY_NODE_ID,
6013 /// Parse a structure field declaration
6014 fn parse_single_struct_field(&mut self,
6017 attrs: Vec<Attribute> )
6018 -> PResult<'a, StructField> {
6019 let mut seen_comma: bool = false;
6020 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6021 if self.token == token::Comma {
6028 token::CloseDelim(token::Brace) => {}
6029 token::DocComment(_) => {
6030 let previous_span = self.prev_span;
6031 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6032 self.bump(); // consume the doc comment
6033 let comma_after_doc_seen = self.eat(&token::Comma);
6034 // `seen_comma` is always false, because we are inside doc block
6035 // condition is here to make code more readable
6036 if seen_comma == false && comma_after_doc_seen == true {
6039 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6042 if seen_comma == false {
6043 let sp = self.sess.source_map().next_point(previous_span);
6044 err.span_suggestion_with_applicability(
6046 "missing comma here",
6048 Applicability::MachineApplicable
6055 let sp = self.sess.source_map().next_point(self.prev_span);
6056 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
6057 self.this_token_to_string()));
6058 if self.token.is_ident() {
6059 // This is likely another field; emit the diagnostic and keep going
6060 err.span_suggestion(sp, "try adding a comma", ",".into());
6070 /// Parse an element of a struct definition
6071 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6072 let attrs = self.parse_outer_attributes()?;
6074 let vis = self.parse_visibility(false)?;
6075 self.parse_single_struct_field(lo, vis, attrs)
6078 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6079 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6080 /// a function definition, it's not a tuple struct field) and the contents within the parens
6081 /// isn't valid, emit a proper diagnostic.
6082 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6083 maybe_whole!(self, NtVis, |x| x);
6085 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6086 if self.is_crate_vis() {
6087 self.bump(); // `crate`
6088 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6091 if !self.eat_keyword(keywords::Pub) {
6092 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6093 // keyword to grab a span from for inherited visibility; an empty span at the
6094 // beginning of the current token would seem to be the "Schelling span".
6095 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6097 let lo = self.prev_span;
6099 if self.check(&token::OpenDelim(token::Paren)) {
6100 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6101 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6102 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6103 // by the following tokens.
6104 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6107 self.bump(); // `crate`
6108 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6110 lo.to(self.prev_span),
6111 VisibilityKind::Crate(CrateSugar::PubCrate),
6114 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6117 self.bump(); // `in`
6118 let path = self.parse_path(PathStyle::Mod)?; // `path`
6119 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6120 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6122 id: ast::DUMMY_NODE_ID,
6125 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6126 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6127 t.is_keyword(keywords::SelfValue))
6129 // `pub(self)` or `pub(super)`
6131 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6132 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6133 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6135 id: ast::DUMMY_NODE_ID,
6138 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6139 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6141 let msg = "incorrect visibility restriction";
6142 let suggestion = r##"some possible visibility restrictions are:
6143 `pub(crate)`: visible only on the current crate
6144 `pub(super)`: visible only in the current module's parent
6145 `pub(in path::to::module)`: visible only on the specified path"##;
6146 let path = self.parse_path(PathStyle::Mod)?;
6147 let sp = self.prev_span;
6148 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6149 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6150 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6151 err.help(suggestion);
6152 err.span_suggestion_with_applicability(
6153 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6155 err.emit(); // emit diagnostic, but continue with public visibility
6159 Ok(respan(lo, VisibilityKind::Public))
6162 /// Parse defaultness: `default` or nothing.
6163 fn parse_defaultness(&mut self) -> Defaultness {
6164 // `pub` is included for better error messages
6165 if self.check_keyword(keywords::Default) &&
6166 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6167 t.is_keyword(keywords::Const) ||
6168 t.is_keyword(keywords::Fn) ||
6169 t.is_keyword(keywords::Unsafe) ||
6170 t.is_keyword(keywords::Extern) ||
6171 t.is_keyword(keywords::Type) ||
6172 t.is_keyword(keywords::Pub)) {
6173 self.bump(); // `default`
6174 Defaultness::Default
6180 /// Given a termination token, parse all of the items in a module
6181 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6182 let mut items = vec![];
6183 while let Some(item) = self.parse_item()? {
6187 if !self.eat(term) {
6188 let token_str = self.this_token_to_string();
6189 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6190 if token_str == ";" {
6191 let msg = "consider removing this semicolon";
6192 err.span_suggestion_short_with_applicability(
6193 self.span, msg, "".to_string(), Applicability::MachineApplicable
6195 if !items.is_empty() { // Issue #51603
6196 let previous_item = &items[items.len()-1];
6197 let previous_item_kind_name = match previous_item.node {
6198 // say "braced struct" because tuple-structs and
6199 // braceless-empty-struct declarations do take a semicolon
6200 ItemKind::Struct(..) => Some("braced struct"),
6201 ItemKind::Enum(..) => Some("enum"),
6202 ItemKind::Trait(..) => Some("trait"),
6203 ItemKind::Union(..) => Some("union"),
6206 if let Some(name) = previous_item_kind_name {
6207 err.help(&format!("{} declarations are not followed by a semicolon",
6212 err.span_label(self.span, "expected item");
6217 let hi = if self.span.is_dummy() {
6224 inner: inner_lo.to(hi),
6229 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6230 let id = self.parse_ident()?;
6231 self.expect(&token::Colon)?;
6232 let ty = self.parse_ty()?;
6233 self.expect(&token::Eq)?;
6234 let e = self.parse_expr()?;
6235 self.expect(&token::Semi)?;
6236 let item = match m {
6237 Some(m) => ItemKind::Static(ty, m, e),
6238 None => ItemKind::Const(ty, e),
6240 Ok((id, item, None))
6243 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6244 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6245 let (in_cfg, outer_attrs) = {
6246 let mut strip_unconfigured = ::config::StripUnconfigured {
6248 should_test: false, // irrelevant
6249 features: None, // don't perform gated feature checking
6251 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6252 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6255 let id_span = self.span;
6256 let id = self.parse_ident()?;
6257 if self.check(&token::Semi) {
6259 if in_cfg && self.recurse_into_file_modules {
6260 // This mod is in an external file. Let's go get it!
6261 let ModulePathSuccess { path, directory_ownership, warn } =
6262 self.submod_path(id, &outer_attrs, id_span)?;
6263 let (module, mut attrs) =
6264 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6266 let attr = Attribute {
6267 id: attr::mk_attr_id(),
6268 style: ast::AttrStyle::Outer,
6269 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6270 tokens: TokenStream::empty(),
6271 is_sugared_doc: false,
6272 span: syntax_pos::DUMMY_SP,
6274 attr::mark_known(&attr);
6277 Ok((id, module, Some(attrs)))
6279 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6280 Ok((id, ItemKind::Mod(placeholder), None))
6283 let old_directory = self.directory.clone();
6284 self.push_directory(id, &outer_attrs);
6286 self.expect(&token::OpenDelim(token::Brace))?;
6287 let mod_inner_lo = self.span;
6288 let attrs = self.parse_inner_attributes()?;
6289 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6291 self.directory = old_directory;
6292 Ok((id, ItemKind::Mod(module), Some(attrs)))
6296 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6297 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6298 self.directory.path.to_mut().push(&path.as_str());
6299 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6301 self.directory.path.to_mut().push(&id.as_str());
6305 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6306 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6309 // On windows, the base path might have the form
6310 // `\\?\foo\bar` in which case it does not tolerate
6311 // mixed `/` and `\` separators, so canonicalize
6314 let s = s.replace("/", "\\");
6315 Some(dir_path.join(s))
6321 /// Returns either a path to a module, or .
6322 pub fn default_submod_path(
6324 relative: Option<ast::Ident>,
6326 source_map: &SourceMap) -> ModulePath
6328 // If we're in a foo.rs file instead of a mod.rs file,
6329 // we need to look for submodules in
6330 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6331 // `./<id>.rs` and `./<id>/mod.rs`.
6332 let relative_prefix_string;
6333 let relative_prefix = if let Some(ident) = relative {
6334 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6335 &relative_prefix_string
6340 let mod_name = id.to_string();
6341 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6342 let secondary_path_str = format!("{}{}{}mod.rs",
6343 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6344 let default_path = dir_path.join(&default_path_str);
6345 let secondary_path = dir_path.join(&secondary_path_str);
6346 let default_exists = source_map.file_exists(&default_path);
6347 let secondary_exists = source_map.file_exists(&secondary_path);
6349 let result = match (default_exists, secondary_exists) {
6350 (true, false) => Ok(ModulePathSuccess {
6352 directory_ownership: DirectoryOwnership::Owned {
6357 (false, true) => Ok(ModulePathSuccess {
6358 path: secondary_path,
6359 directory_ownership: DirectoryOwnership::Owned {
6364 (false, false) => Err(Error::FileNotFoundForModule {
6365 mod_name: mod_name.clone(),
6366 default_path: default_path_str,
6367 secondary_path: secondary_path_str,
6368 dir_path: dir_path.display().to_string(),
6370 (true, true) => Err(Error::DuplicatePaths {
6371 mod_name: mod_name.clone(),
6372 default_path: default_path_str,
6373 secondary_path: secondary_path_str,
6379 path_exists: default_exists || secondary_exists,
6384 fn submod_path(&mut self,
6386 outer_attrs: &[Attribute],
6388 -> PResult<'a, ModulePathSuccess> {
6389 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6390 return Ok(ModulePathSuccess {
6391 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6392 // All `#[path]` files are treated as though they are a `mod.rs` file.
6393 // This means that `mod foo;` declarations inside `#[path]`-included
6394 // files are siblings,
6396 // Note that this will produce weirdness when a file named `foo.rs` is
6397 // `#[path]` included and contains a `mod foo;` declaration.
6398 // If you encounter this, it's your own darn fault :P
6399 Some(_) => DirectoryOwnership::Owned { relative: None },
6400 _ => DirectoryOwnership::UnownedViaMod(true),
6407 let relative = match self.directory.ownership {
6408 DirectoryOwnership::Owned { relative } => {
6409 // Push the usage onto the list of non-mod.rs mod uses.
6410 // This is used later for feature-gate error reporting.
6411 if let Some(cur_file_ident) = relative {
6413 .non_modrs_mods.borrow_mut()
6414 .push((cur_file_ident, id_sp));
6418 DirectoryOwnership::UnownedViaBlock |
6419 DirectoryOwnership::UnownedViaMod(_) => None,
6421 let paths = Parser::default_submod_path(
6422 id, relative, &self.directory.path, self.sess.source_map());
6424 match self.directory.ownership {
6425 DirectoryOwnership::Owned { .. } => {
6426 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6428 DirectoryOwnership::UnownedViaBlock => {
6430 "Cannot declare a non-inline module inside a block \
6431 unless it has a path attribute";
6432 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6433 if paths.path_exists {
6434 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6436 err.span_note(id_sp, &msg);
6440 DirectoryOwnership::UnownedViaMod(warn) => {
6442 if let Ok(result) = paths.result {
6443 return Ok(ModulePathSuccess { warn: true, ..result });
6446 let mut err = self.diagnostic().struct_span_err(id_sp,
6447 "cannot declare a new module at this location");
6448 if !id_sp.is_dummy() {
6449 let src_path = self.sess.source_map().span_to_filename(id_sp);
6450 if let FileName::Real(src_path) = src_path {
6451 if let Some(stem) = src_path.file_stem() {
6452 let mut dest_path = src_path.clone();
6453 dest_path.set_file_name(stem);
6454 dest_path.push("mod.rs");
6455 err.span_note(id_sp,
6456 &format!("maybe move this module `{}` to its own \
6457 directory via `{}`", src_path.display(),
6458 dest_path.display()));
6462 if paths.path_exists {
6463 err.span_note(id_sp,
6464 &format!("... or maybe `use` the module `{}` instead \
6465 of possibly redeclaring it",
6473 /// Read a module from a source file.
6474 fn eval_src_mod(&mut self,
6476 directory_ownership: DirectoryOwnership,
6479 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6480 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6481 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6482 let mut err = String::from("circular modules: ");
6483 let len = included_mod_stack.len();
6484 for p in &included_mod_stack[i.. len] {
6485 err.push_str(&p.to_string_lossy());
6486 err.push_str(" -> ");
6488 err.push_str(&path.to_string_lossy());
6489 return Err(self.span_fatal(id_sp, &err[..]));
6491 included_mod_stack.push(path.clone());
6492 drop(included_mod_stack);
6495 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6496 p0.cfg_mods = self.cfg_mods;
6497 let mod_inner_lo = p0.span;
6498 let mod_attrs = p0.parse_inner_attributes()?;
6499 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6500 self.sess.included_mod_stack.borrow_mut().pop();
6501 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6504 /// Parse a function declaration from a foreign module
6505 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6506 -> PResult<'a, ForeignItem> {
6507 self.expect_keyword(keywords::Fn)?;
6509 let (ident, mut generics) = self.parse_fn_header()?;
6510 let decl = self.parse_fn_decl(true)?;
6511 generics.where_clause = self.parse_where_clause()?;
6513 self.expect(&token::Semi)?;
6514 Ok(ast::ForeignItem {
6517 node: ForeignItemKind::Fn(decl, generics),
6518 id: ast::DUMMY_NODE_ID,
6524 /// Parse a static item from a foreign module.
6525 /// Assumes that the `static` keyword is already parsed.
6526 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6527 -> PResult<'a, ForeignItem> {
6528 let mutbl = self.eat_keyword(keywords::Mut);
6529 let ident = self.parse_ident()?;
6530 self.expect(&token::Colon)?;
6531 let ty = self.parse_ty()?;
6533 self.expect(&token::Semi)?;
6537 node: ForeignItemKind::Static(ty, mutbl),
6538 id: ast::DUMMY_NODE_ID,
6544 /// Parse a type from a foreign module
6545 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6546 -> PResult<'a, ForeignItem> {
6547 self.expect_keyword(keywords::Type)?;
6549 let ident = self.parse_ident()?;
6551 self.expect(&token::Semi)?;
6552 Ok(ast::ForeignItem {
6555 node: ForeignItemKind::Ty,
6556 id: ast::DUMMY_NODE_ID,
6562 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6563 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6564 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6566 let mut ident = self.parse_ident()?;
6567 let mut idents = vec![];
6568 let mut replacement = vec![];
6569 let mut fixed_crate_name = false;
6570 // Accept `extern crate name-like-this` for better diagnostics
6571 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6572 if self.token == dash { // Do not include `-` as part of the expected tokens list
6573 while self.eat(&dash) {
6574 fixed_crate_name = true;
6575 replacement.push((self.prev_span, "_".to_string()));
6576 idents.push(self.parse_ident()?);
6579 if fixed_crate_name {
6580 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6581 let mut fixed_name = format!("{}", ident.name);
6582 for part in idents {
6583 fixed_name.push_str(&format!("_{}", part.name));
6585 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6587 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6588 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6589 err.multipart_suggestion(suggestion_msg, replacement);
6595 /// Parse extern crate links
6599 /// extern crate foo;
6600 /// extern crate bar as foo;
6601 fn parse_item_extern_crate(&mut self,
6603 visibility: Visibility,
6604 attrs: Vec<Attribute>)
6605 -> PResult<'a, P<Item>> {
6606 // Accept `extern crate name-like-this` for better diagnostics
6607 let orig_name = self.parse_crate_name_with_dashes()?;
6608 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6609 (rename, Some(orig_name.name))
6613 self.expect(&token::Semi)?;
6615 let span = lo.to(self.prev_span);
6616 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6619 /// Parse `extern` for foreign ABIs
6622 /// `extern` is expected to have been
6623 /// consumed before calling this method
6629 fn parse_item_foreign_mod(&mut self,
6631 opt_abi: Option<Abi>,
6632 visibility: Visibility,
6633 mut attrs: Vec<Attribute>)
6634 -> PResult<'a, P<Item>> {
6635 self.expect(&token::OpenDelim(token::Brace))?;
6637 let abi = opt_abi.unwrap_or(Abi::C);
6639 attrs.extend(self.parse_inner_attributes()?);
6641 let mut foreign_items = vec![];
6642 while let Some(item) = self.parse_foreign_item()? {
6643 foreign_items.push(item);
6645 self.expect(&token::CloseDelim(token::Brace))?;
6647 let prev_span = self.prev_span;
6648 let m = ast::ForeignMod {
6650 items: foreign_items
6652 let invalid = keywords::Invalid.ident();
6653 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6656 /// Parse type Foo = Bar;
6658 /// existential type Foo: Bar;
6660 /// return None without modifying the parser state
6661 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6662 // This parses the grammar:
6663 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6664 if self.check_keyword(keywords::Type) ||
6665 self.check_keyword(keywords::Existential) &&
6666 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6667 let existential = self.eat_keyword(keywords::Existential);
6668 assert!(self.eat_keyword(keywords::Type));
6669 Some(self.parse_existential_or_alias(existential))
6675 /// Parse type alias or existential type
6676 fn parse_existential_or_alias(
6679 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6680 let ident = self.parse_ident()?;
6681 let mut tps = self.parse_generics()?;
6682 tps.where_clause = self.parse_where_clause()?;
6683 let alias = if existential {
6684 self.expect(&token::Colon)?;
6685 let bounds = self.parse_generic_bounds()?;
6686 AliasKind::Existential(bounds)
6688 self.expect(&token::Eq)?;
6689 let ty = self.parse_ty()?;
6692 self.expect(&token::Semi)?;
6693 Ok((ident, alias, tps))
6696 /// Parse the part of an "enum" decl following the '{'
6697 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6698 let mut variants = Vec::new();
6699 let mut all_nullary = true;
6700 let mut any_disr = None;
6701 while self.token != token::CloseDelim(token::Brace) {
6702 let variant_attrs = self.parse_outer_attributes()?;
6703 let vlo = self.span;
6706 let mut disr_expr = None;
6707 let ident = self.parse_ident()?;
6708 if self.check(&token::OpenDelim(token::Brace)) {
6709 // Parse a struct variant.
6710 all_nullary = false;
6711 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6712 ast::DUMMY_NODE_ID);
6713 } else if self.check(&token::OpenDelim(token::Paren)) {
6714 all_nullary = false;
6715 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6716 ast::DUMMY_NODE_ID);
6717 } else if self.eat(&token::Eq) {
6718 disr_expr = Some(AnonConst {
6719 id: ast::DUMMY_NODE_ID,
6720 value: self.parse_expr()?,
6722 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6723 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6725 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6728 let vr = ast::Variant_ {
6730 attrs: variant_attrs,
6734 variants.push(respan(vlo.to(self.prev_span), vr));
6736 if !self.eat(&token::Comma) { break; }
6738 self.expect(&token::CloseDelim(token::Brace))?;
6740 Some(disr_span) if !all_nullary =>
6741 self.span_err(disr_span,
6742 "discriminator values can only be used with a field-less enum"),
6746 Ok(ast::EnumDef { variants: variants })
6749 /// Parse an "enum" declaration
6750 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6751 let id = self.parse_ident()?;
6752 let mut generics = self.parse_generics()?;
6753 generics.where_clause = self.parse_where_clause()?;
6754 self.expect(&token::OpenDelim(token::Brace))?;
6756 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6757 self.recover_stmt();
6758 self.eat(&token::CloseDelim(token::Brace));
6761 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6764 /// Parses a string as an ABI spec on an extern type or module. Consumes
6765 /// the `extern` keyword, if one is found.
6766 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6768 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6770 self.expect_no_suffix(sp, "ABI spec", suf);
6772 match abi::lookup(&s.as_str()) {
6773 Some(abi) => Ok(Some(abi)),
6775 let prev_span = self.prev_span;
6776 let mut err = struct_span_err!(
6777 self.sess.span_diagnostic,
6780 "invalid ABI: found `{}`",
6782 err.span_label(prev_span, "invalid ABI");
6783 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6794 fn is_static_global(&mut self) -> bool {
6795 if self.check_keyword(keywords::Static) {
6796 // Check if this could be a closure
6797 !self.look_ahead(1, |token| {
6798 if token.is_keyword(keywords::Move) {
6802 token::BinOp(token::Or) | token::OrOr => true,
6813 attrs: Vec<Attribute>,
6814 macros_allowed: bool,
6815 attributes_allowed: bool,
6816 ) -> PResult<'a, Option<P<Item>>> {
6817 let (ret, tokens) = self.collect_tokens(|this| {
6818 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
6821 // Once we've parsed an item and recorded the tokens we got while
6822 // parsing we may want to store `tokens` into the item we're about to
6823 // return. Note, though, that we specifically didn't capture tokens
6824 // related to outer attributes. The `tokens` field here may later be
6825 // used with procedural macros to convert this item back into a token
6826 // stream, but during expansion we may be removing attributes as we go
6829 // If we've got inner attributes then the `tokens` we've got above holds
6830 // these inner attributes. If an inner attribute is expanded we won't
6831 // actually remove it from the token stream, so we'll just keep yielding
6832 // it (bad!). To work around this case for now we just avoid recording
6833 // `tokens` if we detect any inner attributes. This should help keep
6834 // expansion correct, but we should fix this bug one day!
6837 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6838 i.tokens = Some(tokens);
6845 /// Parse one of the items allowed by the flags.
6846 /// NB: this function no longer parses the items inside an
6848 fn parse_item_implementation(
6850 attrs: Vec<Attribute>,
6851 macros_allowed: bool,
6852 attributes_allowed: bool,
6853 ) -> PResult<'a, Option<P<Item>>> {
6854 maybe_whole!(self, NtItem, |item| {
6855 let mut item = item.into_inner();
6856 let mut attrs = attrs;
6857 mem::swap(&mut item.attrs, &mut attrs);
6858 item.attrs.extend(attrs);
6864 let visibility = self.parse_visibility(false)?;
6866 if self.eat_keyword(keywords::Use) {
6868 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6869 self.expect(&token::Semi)?;
6871 let span = lo.to(self.prev_span);
6872 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6873 return Ok(Some(item));
6876 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6877 self.bump(); // `extern`
6878 if self.eat_keyword(keywords::Crate) {
6879 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6882 let opt_abi = self.parse_opt_abi()?;
6884 if self.eat_keyword(keywords::Fn) {
6885 // EXTERN FUNCTION ITEM
6886 let fn_span = self.prev_span;
6887 let abi = opt_abi.unwrap_or(Abi::C);
6888 let (ident, item_, extra_attrs) =
6889 self.parse_item_fn(Unsafety::Normal,
6891 respan(fn_span, Constness::NotConst),
6893 let prev_span = self.prev_span;
6894 let item = self.mk_item(lo.to(prev_span),
6898 maybe_append(attrs, extra_attrs));
6899 return Ok(Some(item));
6900 } else if self.check(&token::OpenDelim(token::Brace)) {
6901 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6907 if self.is_static_global() {
6910 let m = if self.eat_keyword(keywords::Mut) {
6913 Mutability::Immutable
6915 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6916 let prev_span = self.prev_span;
6917 let item = self.mk_item(lo.to(prev_span),
6921 maybe_append(attrs, extra_attrs));
6922 return Ok(Some(item));
6924 if self.eat_keyword(keywords::Const) {
6925 let const_span = self.prev_span;
6926 if self.check_keyword(keywords::Fn)
6927 || (self.check_keyword(keywords::Unsafe)
6928 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6929 // CONST FUNCTION ITEM
6930 let unsafety = self.parse_unsafety();
6932 let (ident, item_, extra_attrs) =
6933 self.parse_item_fn(unsafety,
6935 respan(const_span, Constness::Const),
6937 let prev_span = self.prev_span;
6938 let item = self.mk_item(lo.to(prev_span),
6942 maybe_append(attrs, extra_attrs));
6943 return Ok(Some(item));
6947 if self.eat_keyword(keywords::Mut) {
6948 let prev_span = self.prev_span;
6949 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6950 .help("did you mean to declare a static?")
6953 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6954 let prev_span = self.prev_span;
6955 let item = self.mk_item(lo.to(prev_span),
6959 maybe_append(attrs, extra_attrs));
6960 return Ok(Some(item));
6963 // `unsafe async fn` or `async fn`
6965 self.check_keyword(keywords::Unsafe) &&
6966 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
6968 self.check_keyword(keywords::Async) &&
6969 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
6972 // ASYNC FUNCTION ITEM
6973 let unsafety = self.parse_unsafety();
6974 self.expect_keyword(keywords::Async)?;
6975 self.expect_keyword(keywords::Fn)?;
6976 let fn_span = self.prev_span;
6977 let (ident, item_, extra_attrs) =
6978 self.parse_item_fn(unsafety,
6980 closure_id: ast::DUMMY_NODE_ID,
6981 return_impl_trait_id: ast::DUMMY_NODE_ID,
6983 respan(fn_span, Constness::NotConst),
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 self.check_keyword(keywords::Unsafe) &&
6994 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6995 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6997 // UNSAFE TRAIT ITEM
6998 self.bump(); // `unsafe`
6999 let is_auto = if self.eat_keyword(keywords::Trait) {
7002 self.expect_keyword(keywords::Auto)?;
7003 self.expect_keyword(keywords::Trait)?;
7006 let (ident, item_, extra_attrs) =
7007 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7008 let prev_span = self.prev_span;
7009 let item = self.mk_item(lo.to(prev_span),
7013 maybe_append(attrs, extra_attrs));
7014 return Ok(Some(item));
7016 if self.check_keyword(keywords::Impl) ||
7017 self.check_keyword(keywords::Unsafe) &&
7018 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7019 self.check_keyword(keywords::Default) &&
7020 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7021 self.check_keyword(keywords::Default) &&
7022 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7024 let defaultness = self.parse_defaultness();
7025 let unsafety = self.parse_unsafety();
7026 self.expect_keyword(keywords::Impl)?;
7027 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7028 let span = lo.to(self.prev_span);
7029 return Ok(Some(self.mk_item(span, ident, item, visibility,
7030 maybe_append(attrs, extra_attrs))));
7032 if self.check_keyword(keywords::Fn) {
7035 let fn_span = self.prev_span;
7036 let (ident, item_, extra_attrs) =
7037 self.parse_item_fn(Unsafety::Normal,
7039 respan(fn_span, Constness::NotConst),
7041 let prev_span = self.prev_span;
7042 let item = self.mk_item(lo.to(prev_span),
7046 maybe_append(attrs, extra_attrs));
7047 return Ok(Some(item));
7049 if self.check_keyword(keywords::Unsafe)
7050 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7051 // UNSAFE FUNCTION ITEM
7052 self.bump(); // `unsafe`
7053 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7054 self.check(&token::OpenDelim(token::Brace));
7055 let abi = if self.eat_keyword(keywords::Extern) {
7056 self.parse_opt_abi()?.unwrap_or(Abi::C)
7060 self.expect_keyword(keywords::Fn)?;
7061 let fn_span = self.prev_span;
7062 let (ident, item_, extra_attrs) =
7063 self.parse_item_fn(Unsafety::Unsafe,
7065 respan(fn_span, Constness::NotConst),
7067 let prev_span = self.prev_span;
7068 let item = self.mk_item(lo.to(prev_span),
7072 maybe_append(attrs, extra_attrs));
7073 return Ok(Some(item));
7075 if self.eat_keyword(keywords::Mod) {
7077 let (ident, item_, extra_attrs) =
7078 self.parse_item_mod(&attrs[..])?;
7079 let prev_span = self.prev_span;
7080 let item = self.mk_item(lo.to(prev_span),
7084 maybe_append(attrs, extra_attrs));
7085 return Ok(Some(item));
7087 if let Some(type_) = self.eat_type() {
7088 let (ident, alias, generics) = type_?;
7090 let item_ = match alias {
7091 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7092 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7094 let prev_span = self.prev_span;
7095 let item = self.mk_item(lo.to(prev_span),
7100 return Ok(Some(item));
7102 if self.eat_keyword(keywords::Enum) {
7104 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7105 let prev_span = self.prev_span;
7106 let item = self.mk_item(lo.to(prev_span),
7110 maybe_append(attrs, extra_attrs));
7111 return Ok(Some(item));
7113 if self.check_keyword(keywords::Trait)
7114 || (self.check_keyword(keywords::Auto)
7115 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7117 let is_auto = if self.eat_keyword(keywords::Trait) {
7120 self.expect_keyword(keywords::Auto)?;
7121 self.expect_keyword(keywords::Trait)?;
7125 let (ident, item_, extra_attrs) =
7126 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7127 let prev_span = self.prev_span;
7128 let item = self.mk_item(lo.to(prev_span),
7132 maybe_append(attrs, extra_attrs));
7133 return Ok(Some(item));
7135 if self.eat_keyword(keywords::Struct) {
7137 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7138 let prev_span = self.prev_span;
7139 let item = self.mk_item(lo.to(prev_span),
7143 maybe_append(attrs, extra_attrs));
7144 return Ok(Some(item));
7146 if self.is_union_item() {
7149 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7150 let prev_span = self.prev_span;
7151 let item = self.mk_item(lo.to(prev_span),
7155 maybe_append(attrs, extra_attrs));
7156 return Ok(Some(item));
7158 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7159 return Ok(Some(macro_def));
7162 // Verify whether we have encountered a struct or method definition where the user forgot to
7163 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7164 if visibility.node.is_pub() &&
7165 self.check_ident() &&
7166 self.look_ahead(1, |t| *t != token::Not)
7168 // Space between `pub` keyword and the identifier
7171 // ^^^ `sp` points here
7172 let sp = self.prev_span.between(self.span);
7173 let full_sp = self.prev_span.to(self.span);
7174 let ident_sp = self.span;
7175 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7176 // possible public struct definition where `struct` was forgotten
7177 let ident = self.parse_ident().unwrap();
7178 let msg = format!("add `struct` here to parse `{}` as a public struct",
7180 let mut err = self.diagnostic()
7181 .struct_span_err(sp, "missing `struct` for struct definition");
7182 err.span_suggestion_short_with_applicability(
7183 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7186 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7187 let ident = self.parse_ident().unwrap();
7188 self.consume_block(token::Paren);
7189 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7190 self.check(&token::OpenDelim(token::Brace))
7192 ("fn", "method", false)
7193 } else if self.check(&token::Colon) {
7197 ("fn` or `struct", "method or struct", true)
7200 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7201 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7203 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7207 err.span_suggestion_short_with_applicability(
7208 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7211 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7212 err.span_suggestion_with_applicability(
7214 "if you meant to call a macro, try",
7215 format!("{}!", snippet),
7216 // this is the `ambiguous` conditional branch
7217 Applicability::MaybeIncorrect
7220 err.help("if you meant to call a macro, remove the `pub` \
7221 and add a trailing `!` after the identifier");
7227 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7230 /// Parse a foreign item.
7231 crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
7232 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
7234 let attrs = self.parse_outer_attributes()?;
7236 let visibility = self.parse_visibility(false)?;
7238 // FOREIGN STATIC ITEM
7239 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7240 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7241 if self.token.is_keyword(keywords::Const) {
7243 .struct_span_err(self.span, "extern items cannot be `const`")
7244 .span_suggestion_with_applicability(
7246 "try using a static value",
7247 "static".to_owned(),
7248 Applicability::MachineApplicable
7251 self.bump(); // `static` or `const`
7252 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
7254 // FOREIGN FUNCTION ITEM
7255 if self.check_keyword(keywords::Fn) {
7256 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
7258 // FOREIGN TYPE ITEM
7259 if self.check_keyword(keywords::Type) {
7260 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
7263 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7267 ident: keywords::Invalid.ident(),
7268 span: lo.to(self.prev_span),
7269 id: ast::DUMMY_NODE_ID,
7272 node: ForeignItemKind::Macro(mac),
7277 if !attrs.is_empty() {
7278 self.expected_item_err(&attrs);
7286 /// This is the fall-through for parsing items.
7287 fn parse_macro_use_or_failure(
7289 attrs: Vec<Attribute> ,
7290 macros_allowed: bool,
7291 attributes_allowed: bool,
7293 visibility: Visibility
7294 ) -> PResult<'a, Option<P<Item>>> {
7295 if macros_allowed && self.token.is_path_start() {
7296 // MACRO INVOCATION ITEM
7298 let prev_span = self.prev_span;
7299 self.complain_if_pub_macro(&visibility.node, prev_span);
7301 let mac_lo = self.span;
7304 let pth = self.parse_path(PathStyle::Mod)?;
7305 self.expect(&token::Not)?;
7307 // a 'special' identifier (like what `macro_rules!` uses)
7308 // is optional. We should eventually unify invoc syntax
7310 let id = if self.token.is_ident() {
7313 keywords::Invalid.ident() // no special identifier
7315 // eat a matched-delimiter token tree:
7316 let (delim, tts) = self.expect_delimited_token_tree()?;
7317 if delim != MacDelimiter::Brace {
7318 if !self.eat(&token::Semi) {
7319 self.span_err(self.prev_span,
7320 "macros that expand to items must either \
7321 be surrounded with braces or followed by \
7326 let hi = self.prev_span;
7327 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7328 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7329 return Ok(Some(item));
7332 // FAILURE TO PARSE ITEM
7333 match visibility.node {
7334 VisibilityKind::Inherited => {}
7336 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7340 if !attributes_allowed && !attrs.is_empty() {
7341 self.expected_item_err(&attrs);
7346 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7347 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7348 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7350 if self.token.is_path_start() && !self.is_extern_non_path() {
7351 let prev_span = self.prev_span;
7353 let pth = self.parse_path(PathStyle::Mod)?;
7355 if pth.segments.len() == 1 {
7356 if !self.eat(&token::Not) {
7357 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7360 self.expect(&token::Not)?;
7363 if let Some(vis) = vis {
7364 self.complain_if_pub_macro(&vis.node, prev_span);
7369 // eat a matched-delimiter token tree:
7370 let (delim, tts) = self.expect_delimited_token_tree()?;
7371 if delim != MacDelimiter::Brace {
7372 self.expect(&token::Semi)?
7375 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7381 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7382 where F: FnOnce(&mut Self) -> PResult<'a, R>
7384 // Record all tokens we parse when parsing this item.
7385 let mut tokens = Vec::new();
7386 let prev_collecting = match self.token_cursor.frame.last_token {
7387 LastToken::Collecting(ref mut list) => {
7388 Some(mem::replace(list, Vec::new()))
7390 LastToken::Was(ref mut last) => {
7391 tokens.extend(last.take());
7395 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7396 let prev = self.token_cursor.stack.len();
7398 let last_token = if self.token_cursor.stack.len() == prev {
7399 &mut self.token_cursor.frame.last_token
7401 &mut self.token_cursor.stack[prev].last_token
7404 // Pull our the toekns that we've collected from the call to `f` above
7405 let mut collected_tokens = match *last_token {
7406 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7407 LastToken::Was(_) => panic!("our vector went away?"),
7410 // If we're not at EOF our current token wasn't actually consumed by
7411 // `f`, but it'll still be in our list that we pulled out. In that case
7413 let extra_token = if self.token != token::Eof {
7414 collected_tokens.pop()
7419 // If we were previously collecting tokens, then this was a recursive
7420 // call. In that case we need to record all the tokens we collected in
7421 // our parent list as well. To do that we push a clone of our stream
7422 // onto the previous list.
7423 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7424 match prev_collecting {
7426 list.push(stream.clone());
7427 list.extend(extra_token);
7428 *last_token = LastToken::Collecting(list);
7431 *last_token = LastToken::Was(extra_token);
7438 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7439 let attrs = self.parse_outer_attributes()?;
7440 self.parse_item_(attrs, true, false)
7444 fn is_import_coupler(&mut self) -> bool {
7445 self.check(&token::ModSep) &&
7446 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7447 *t == token::BinOp(token::Star))
7452 /// USE_TREE = [`::`] `*` |
7453 /// [`::`] `{` USE_TREE_LIST `}` |
7455 /// PATH `::` `{` USE_TREE_LIST `}` |
7456 /// PATH [`as` IDENT]
7457 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7460 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7461 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7462 self.check(&token::BinOp(token::Star)) ||
7463 self.is_import_coupler() {
7464 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7465 if self.eat(&token::ModSep) {
7466 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7469 if self.eat(&token::BinOp(token::Star)) {
7472 UseTreeKind::Nested(self.parse_use_tree_list()?)
7475 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7476 prefix = self.parse_path(PathStyle::Mod)?;
7478 if self.eat(&token::ModSep) {
7479 if self.eat(&token::BinOp(token::Star)) {
7482 UseTreeKind::Nested(self.parse_use_tree_list()?)
7485 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7489 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7492 /// Parse UseTreeKind::Nested(list)
7494 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7495 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7496 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7497 &token::CloseDelim(token::Brace),
7498 SeqSep::trailing_allowed(token::Comma), |this| {
7499 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7503 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7504 if self.eat_keyword(keywords::As) {
7506 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7508 Ok(Some(ident.gensym()))
7510 _ => self.parse_ident().map(Some),
7517 /// Parses a source module as a crate. This is the main
7518 /// entry point for the parser.
7519 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7522 attrs: self.parse_inner_attributes()?,
7523 module: self.parse_mod_items(&token::Eof, lo)?,
7524 span: lo.to(self.span),
7528 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7529 let ret = match self.token {
7530 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7531 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7538 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7539 match self.parse_optional_str() {
7540 Some((s, style, suf)) => {
7541 let sp = self.prev_span;
7542 self.expect_no_suffix(sp, "string literal", suf);
7546 let msg = "expected string literal";
7547 let mut err = self.fatal(msg);
7548 err.span_label(self.span, msg);