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, Guard, 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};
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, DelimSpan, 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: DelimSpan, 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.open)
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.close)
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 delim_span = DelimSpan::from_single(sp);
365 let body = TokenTree::Delimited(delim_span, Delimited {
366 delim: token::Bracket,
367 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
368 TokenTree::Token(sp, token::Eq),
369 TokenTree::Token(sp, token::Literal(
370 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
371 .iter().cloned().collect::<TokenStream>().into(),
374 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(delim_span, &Delimited {
375 delim: token::NoDelim,
376 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
377 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
378 .iter().cloned().collect::<TokenStream>().into()
380 [TokenTree::Token(sp, token::Pound), body]
381 .iter().cloned().collect::<TokenStream>().into()
389 #[derive(Clone, PartialEq)]
390 crate enum TokenType {
392 Keyword(keywords::Keyword),
401 fn to_string(&self) -> String {
403 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
404 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
405 TokenType::Operator => "an operator".to_string(),
406 TokenType::Lifetime => "lifetime".to_string(),
407 TokenType::Ident => "identifier".to_string(),
408 TokenType::Path => "path".to_string(),
409 TokenType::Type => "type".to_string(),
414 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
415 /// `IDENT<<u8 as Trait>::AssocTy>`.
417 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
418 /// that IDENT is not the ident of a fn trait
419 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
420 t == &token::ModSep || t == &token::Lt ||
421 t == &token::BinOp(token::Shl)
424 /// Information about the path to a module.
425 pub struct ModulePath {
428 pub result: Result<ModulePathSuccess, Error>,
431 pub struct ModulePathSuccess {
433 pub directory_ownership: DirectoryOwnership,
438 FileNotFoundForModule {
440 default_path: String,
441 secondary_path: String,
446 default_path: String,
447 secondary_path: String,
450 InclusiveRangeWithNoEnd,
454 fn span_err<S: Into<MultiSpan>>(self,
456 handler: &errors::Handler) -> DiagnosticBuilder {
458 Error::FileNotFoundForModule { ref mod_name,
462 let mut err = struct_span_err!(handler, sp, E0583,
463 "file not found for module `{}`", mod_name);
464 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
470 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
471 let mut err = struct_span_err!(handler, sp, E0584,
472 "file for module `{}` found at both {} and {}",
476 err.help("delete or rename one of them to remove the ambiguity");
479 Error::UselessDocComment => {
480 let mut err = struct_span_err!(handler, sp, E0585,
481 "found a documentation comment that doesn't document anything");
482 err.help("doc comments must come before what they document, maybe a comment was \
483 intended with `//`?");
486 Error::InclusiveRangeWithNoEnd => {
487 let mut err = struct_span_err!(handler, sp, E0586,
488 "inclusive range with no end");
489 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
499 AttributesParsed(ThinVec<Attribute>),
500 AlreadyParsed(P<Expr>),
503 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
504 fn from(o: Option<ThinVec<Attribute>>) -> Self {
505 if let Some(attrs) = o {
506 LhsExpr::AttributesParsed(attrs)
508 LhsExpr::NotYetParsed
513 impl From<P<Expr>> for LhsExpr {
514 fn from(expr: P<Expr>) -> Self {
515 LhsExpr::AlreadyParsed(expr)
519 /// Create a placeholder argument.
520 fn dummy_arg(span: Span) -> Arg {
521 let ident = Ident::new(keywords::Invalid.name(), span);
523 id: ast::DUMMY_NODE_ID,
524 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
530 id: ast::DUMMY_NODE_ID
532 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
535 #[derive(Copy, Clone, Debug)]
536 enum TokenExpectType {
541 impl<'a> Parser<'a> {
542 pub fn new(sess: &'a ParseSess,
544 directory: Option<Directory<'a>>,
545 recurse_into_file_modules: bool,
546 desugar_doc_comments: bool)
548 let mut parser = Parser {
550 token: token::Whitespace,
551 span: syntax_pos::DUMMY_SP,
552 prev_span: syntax_pos::DUMMY_SP,
554 prev_token_kind: PrevTokenKind::Other,
555 restrictions: Restrictions::empty(),
556 recurse_into_file_modules,
557 directory: Directory {
558 path: Cow::from(PathBuf::new()),
559 ownership: DirectoryOwnership::Owned { relative: None }
561 root_module_name: None,
562 expected_tokens: Vec::new(),
563 token_cursor: TokenCursor {
564 frame: TokenCursorFrame::new(DelimSpan::dummy(), &Delimited {
565 delim: token::NoDelim,
570 desugar_doc_comments,
574 let tok = parser.next_tok();
575 parser.token = tok.tok;
576 parser.span = tok.sp;
578 if let Some(directory) = directory {
579 parser.directory = directory;
580 } else if !parser.span.is_dummy() {
581 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
583 parser.directory.path = Cow::from(path);
587 parser.process_potential_macro_variable();
591 fn next_tok(&mut self) -> TokenAndSpan {
592 let mut next = if self.desugar_doc_comments {
593 self.token_cursor.next_desugared()
595 self.token_cursor.next()
597 if next.sp.is_dummy() {
598 // Tweak the location for better diagnostics, but keep syntactic context intact.
599 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
604 /// Convert the current token to a string using self's reader
605 pub fn this_token_to_string(&self) -> String {
606 pprust::token_to_string(&self.token)
609 fn token_descr(&self) -> Option<&'static str> {
610 Some(match &self.token {
611 t if t.is_special_ident() => "reserved identifier",
612 t if t.is_used_keyword() => "keyword",
613 t if t.is_unused_keyword() => "reserved keyword",
614 token::DocComment(..) => "doc comment",
619 fn this_token_descr(&self) -> String {
620 if let Some(prefix) = self.token_descr() {
621 format!("{} `{}`", prefix, self.this_token_to_string())
623 format!("`{}`", self.this_token_to_string())
627 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
628 let token_str = pprust::token_to_string(t);
629 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
632 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
633 match self.expect_one_of(&[], &[]) {
635 Ok(_) => unreachable!(),
639 /// Expect and consume the token t. Signal an error if
640 /// the next token is not t.
641 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
642 if self.expected_tokens.is_empty() {
643 if self.token == *t {
647 let token_str = pprust::token_to_string(t);
648 let this_token_str = self.this_token_descr();
649 let mut err = self.fatal(&format!("expected `{}`, found {}",
653 let sp = if self.token == token::Token::Eof {
654 // EOF, don't want to point at the following char, but rather the last token
657 self.sess.source_map().next_point(self.prev_span)
659 let label_exp = format!("expected `{}`", token_str);
660 let cm = self.sess.source_map();
661 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
662 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
663 // When the spans are in the same line, it means that the only content
664 // between them is whitespace, point only at the found token.
665 err.span_label(self.span, label_exp);
668 err.span_label(sp, label_exp);
669 err.span_label(self.span, "unexpected token");
675 self.expect_one_of(slice::from_ref(t), &[])
679 /// Expect next token to be edible or inedible token. If edible,
680 /// then consume it; if inedible, then return without consuming
681 /// anything. Signal a fatal error if next token is unexpected.
682 pub fn expect_one_of(&mut self,
683 edible: &[token::Token],
684 inedible: &[token::Token]) -> PResult<'a, ()>{
685 fn tokens_to_string(tokens: &[TokenType]) -> String {
686 let mut i = tokens.iter();
687 // This might be a sign we need a connect method on Iterator.
689 .map_or(String::new(), |t| t.to_string());
690 i.enumerate().fold(b, |mut b, (i, a)| {
691 if tokens.len() > 2 && i == tokens.len() - 2 {
693 } else if tokens.len() == 2 && i == tokens.len() - 2 {
698 b.push_str(&a.to_string());
702 if edible.contains(&self.token) {
705 } else if inedible.contains(&self.token) {
706 // leave it in the input
709 let mut expected = edible.iter()
710 .map(|x| TokenType::Token(x.clone()))
711 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
712 .chain(self.expected_tokens.iter().cloned())
713 .collect::<Vec<_>>();
714 expected.sort_by_cached_key(|x| x.to_string());
716 let expect = tokens_to_string(&expected[..]);
717 let actual = self.this_token_to_string();
718 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
719 let short_expect = if expected.len() > 6 {
720 format!("{} possible tokens", expected.len())
724 (format!("expected one of {}, found `{}`", expect, actual),
725 (self.sess.source_map().next_point(self.prev_span),
726 format!("expected one of {} here", short_expect)))
727 } else if expected.is_empty() {
728 (format!("unexpected token: `{}`", actual),
729 (self.prev_span, "unexpected token after this".to_string()))
731 (format!("expected {}, found `{}`", expect, actual),
732 (self.sess.source_map().next_point(self.prev_span),
733 format!("expected {} here", expect)))
735 let mut err = self.fatal(&msg_exp);
736 if self.token.is_ident_named("and") {
737 err.span_suggestion_short_with_applicability(
739 "use `&&` instead of `and` for the boolean operator",
741 Applicability::MaybeIncorrect,
744 if self.token.is_ident_named("or") {
745 err.span_suggestion_short_with_applicability(
747 "use `||` instead of `or` for the boolean operator",
749 Applicability::MaybeIncorrect,
752 let sp = if self.token == token::Token::Eof {
753 // This is EOF, don't want to point at the following char, but rather the last token
759 let cm = self.sess.source_map();
760 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
761 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
762 // When the spans are in the same line, it means that the only content between
763 // them is whitespace, point at the found token in that case:
765 // X | () => { syntax error };
766 // | ^^^^^ expected one of 8 possible tokens here
768 // instead of having:
770 // X | () => { syntax error };
771 // | -^^^^^ unexpected token
773 // | expected one of 8 possible tokens here
774 err.span_label(self.span, label_exp);
776 _ if self.prev_span == syntax_pos::DUMMY_SP => {
777 // Account for macro context where the previous span might not be
778 // available to avoid incorrect output (#54841).
779 err.span_label(self.span, "unexpected token");
782 err.span_label(sp, label_exp);
783 err.span_label(self.span, "unexpected token");
790 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
791 fn interpolated_or_expr_span(&self,
792 expr: PResult<'a, P<Expr>>)
793 -> PResult<'a, (Span, P<Expr>)> {
795 if self.prev_token_kind == PrevTokenKind::Interpolated {
803 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
804 let mut err = self.struct_span_err(self.span,
805 &format!("expected identifier, found {}",
806 self.this_token_descr()));
807 if let Some(token_descr) = self.token_descr() {
808 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
810 err.span_label(self.span, "expected identifier");
811 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
812 err.span_suggestion_with_applicability(
816 Applicability::MachineApplicable,
823 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
824 self.parse_ident_common(true)
827 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
829 token::Ident(ident, _) => {
830 if self.token.is_reserved_ident() {
831 let mut err = self.expected_ident_found();
838 let span = self.span;
840 Ok(Ident::new(ident.name, span))
843 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
844 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
846 self.expected_ident_found()
852 /// Check if the next token is `tok`, and return `true` if so.
854 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
856 crate fn check(&mut self, tok: &token::Token) -> bool {
857 let is_present = self.token == *tok;
858 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
862 /// Consume token 'tok' if it exists. Returns true if the given
863 /// token was present, false otherwise.
864 pub fn eat(&mut self, tok: &token::Token) -> bool {
865 let is_present = self.check(tok);
866 if is_present { self.bump() }
870 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
871 self.expected_tokens.push(TokenType::Keyword(kw));
872 self.token.is_keyword(kw)
875 /// If the next token is the given keyword, eat it and return
876 /// true. Otherwise, return false.
877 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
878 if self.check_keyword(kw) {
886 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
887 if self.token.is_keyword(kw) {
895 /// If the given word is not a keyword, signal an error.
896 /// If the next token is not the given word, signal an error.
897 /// Otherwise, eat it.
898 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
899 if !self.eat_keyword(kw) {
906 fn check_ident(&mut self) -> bool {
907 if self.token.is_ident() {
910 self.expected_tokens.push(TokenType::Ident);
915 fn check_path(&mut self) -> bool {
916 if self.token.is_path_start() {
919 self.expected_tokens.push(TokenType::Path);
924 fn check_type(&mut self) -> bool {
925 if self.token.can_begin_type() {
928 self.expected_tokens.push(TokenType::Type);
933 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
934 /// and continue. If a `+` is not seen, return false.
936 /// This is using when token splitting += into +.
937 /// See issue 47856 for an example of when this may occur.
938 fn eat_plus(&mut self) -> bool {
939 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
941 token::BinOp(token::Plus) => {
945 token::BinOpEq(token::Plus) => {
946 let span = self.span.with_lo(self.span.lo() + BytePos(1));
947 self.bump_with(token::Eq, span);
955 /// Checks to see if the next token is either `+` or `+=`.
956 /// Otherwise returns false.
957 fn check_plus(&mut self) -> bool {
958 if self.token.is_like_plus() {
962 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
967 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
968 /// `&` and continue. If an `&` is not seen, signal an error.
969 fn expect_and(&mut self) -> PResult<'a, ()> {
970 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
972 token::BinOp(token::And) => {
977 let span = self.span.with_lo(self.span.lo() + BytePos(1));
978 Ok(self.bump_with(token::BinOp(token::And), span))
980 _ => self.unexpected()
984 /// Expect and consume an `|`. If `||` is seen, replace it with a single
985 /// `|` and continue. If an `|` is not seen, signal an error.
986 fn expect_or(&mut self) -> PResult<'a, ()> {
987 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
989 token::BinOp(token::Or) => {
994 let span = self.span.with_lo(self.span.lo() + BytePos(1));
995 Ok(self.bump_with(token::BinOp(token::Or), span))
997 _ => self.unexpected()
1001 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1003 None => {/* everything ok */}
1005 let text = suf.as_str();
1006 if text.is_empty() {
1007 self.span_bug(sp, "found empty literal suffix in Some")
1009 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
1014 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
1015 /// `<` and continue. If a `<` is not seen, return false.
1017 /// This is meant to be used when parsing generics on a path to get the
1019 fn eat_lt(&mut self) -> bool {
1020 self.expected_tokens.push(TokenType::Token(token::Lt));
1026 token::BinOp(token::Shl) => {
1027 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1028 self.bump_with(token::Lt, span);
1035 fn expect_lt(&mut self) -> PResult<'a, ()> {
1043 /// Expect and consume a GT. if a >> is seen, replace it
1044 /// with a single > and continue. If a GT is not seen,
1045 /// signal an error.
1046 fn expect_gt(&mut self) -> PResult<'a, ()> {
1047 self.expected_tokens.push(TokenType::Token(token::Gt));
1053 token::BinOp(token::Shr) => {
1054 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1055 Ok(self.bump_with(token::Gt, span))
1057 token::BinOpEq(token::Shr) => {
1058 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1059 Ok(self.bump_with(token::Ge, span))
1062 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1063 Ok(self.bump_with(token::Eq, span))
1065 _ => self.unexpected()
1069 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1070 /// passes through any errors encountered. Used for error recovery.
1071 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1072 let handler = self.diagnostic();
1074 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1076 TokenExpectType::Expect,
1077 |p| Ok(p.parse_token_tree())) {
1078 handler.cancel(err);
1082 /// Parse a sequence, including the closing delimiter. The function
1083 /// f must consume tokens until reaching the next separator or
1084 /// closing bracket.
1085 pub fn parse_seq_to_end<T, F>(&mut self,
1089 -> PResult<'a, Vec<T>> where
1090 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1092 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1097 /// Parse a sequence, not including the closing delimiter. The function
1098 /// f must consume tokens until reaching the next separator or
1099 /// closing bracket.
1100 pub fn parse_seq_to_before_end<T, F>(&mut self,
1104 -> PResult<'a, Vec<T>>
1105 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1107 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1110 fn parse_seq_to_before_tokens<T, F>(
1112 kets: &[&token::Token],
1114 expect: TokenExpectType,
1116 ) -> PResult<'a, Vec<T>>
1117 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1119 let mut first: bool = true;
1121 while !kets.iter().any(|k| {
1123 TokenExpectType::Expect => self.check(k),
1124 TokenExpectType::NoExpect => self.token == **k,
1128 token::CloseDelim(..) | token::Eof => break,
1131 if let Some(ref t) = sep.sep {
1135 if let Err(mut e) = self.expect(t) {
1136 // Attempt to keep parsing if it was a similar separator
1137 if let Some(ref tokens) = t.similar_tokens() {
1138 if tokens.contains(&self.token) {
1143 // Attempt to keep parsing if it was an omitted separator
1157 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1159 TokenExpectType::Expect => self.check(k),
1160 TokenExpectType::NoExpect => self.token == **k,
1173 /// Parse a sequence, including the closing delimiter. The function
1174 /// f must consume tokens until reaching the next separator or
1175 /// closing bracket.
1176 fn parse_unspanned_seq<T, F>(&mut self,
1181 -> PResult<'a, Vec<T>> where
1182 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1185 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1190 /// Advance the parser by one token
1191 pub fn bump(&mut self) {
1192 if self.prev_token_kind == PrevTokenKind::Eof {
1193 // Bumping after EOF is a bad sign, usually an infinite loop.
1194 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1197 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1199 // Record last token kind for possible error recovery.
1200 self.prev_token_kind = match self.token {
1201 token::DocComment(..) => PrevTokenKind::DocComment,
1202 token::Comma => PrevTokenKind::Comma,
1203 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1204 token::Interpolated(..) => PrevTokenKind::Interpolated,
1205 token::Eof => PrevTokenKind::Eof,
1206 token::Ident(..) => PrevTokenKind::Ident,
1207 _ => PrevTokenKind::Other,
1210 let next = self.next_tok();
1211 self.span = next.sp;
1212 self.token = next.tok;
1213 self.expected_tokens.clear();
1214 // check after each token
1215 self.process_potential_macro_variable();
1218 /// Advance the parser using provided token as a next one. Use this when
1219 /// consuming a part of a token. For example a single `<` from `<<`.
1220 fn bump_with(&mut self, next: token::Token, span: Span) {
1221 self.prev_span = self.span.with_hi(span.lo());
1222 // It would be incorrect to record the kind of the current token, but
1223 // fortunately for tokens currently using `bump_with`, the
1224 // prev_token_kind will be of no use anyway.
1225 self.prev_token_kind = PrevTokenKind::Other;
1228 self.expected_tokens.clear();
1231 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1232 F: FnOnce(&token::Token) -> R,
1235 return f(&self.token)
1238 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1239 Some(tree) => match tree {
1240 TokenTree::Token(_, tok) => tok,
1241 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1243 None => token::CloseDelim(self.token_cursor.frame.delim),
1247 fn look_ahead_span(&self, dist: usize) -> Span {
1252 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1253 Some(TokenTree::Token(span, _)) => span,
1254 Some(TokenTree::Delimited(span, _)) => span.entire(),
1255 None => self.look_ahead_span(dist - 1),
1258 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1259 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1261 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1262 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1264 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1265 err.span_err(sp, self.diagnostic())
1267 fn bug(&self, m: &str) -> ! {
1268 self.sess.span_diagnostic.span_bug(self.span, m)
1270 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1271 self.sess.span_diagnostic.span_err(sp, m)
1273 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1274 self.sess.span_diagnostic.struct_span_err(sp, m)
1276 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1277 self.sess.span_diagnostic.span_bug(sp, m)
1279 crate fn abort_if_errors(&self) {
1280 self.sess.span_diagnostic.abort_if_errors();
1283 fn cancel(&self, err: &mut DiagnosticBuilder) {
1284 self.sess.span_diagnostic.cancel(err)
1287 crate fn diagnostic(&self) -> &'a errors::Handler {
1288 &self.sess.span_diagnostic
1291 /// Is the current token one of the keywords that signals a bare function
1293 fn token_is_bare_fn_keyword(&mut self) -> bool {
1294 self.check_keyword(keywords::Fn) ||
1295 self.check_keyword(keywords::Unsafe) ||
1296 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1299 /// parse a `TyKind::BareFn` type:
1300 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1303 [unsafe] [extern "ABI"] fn (S) -> T
1313 let unsafety = self.parse_unsafety();
1314 let abi = if self.eat_keyword(keywords::Extern) {
1315 self.parse_opt_abi()?.unwrap_or(Abi::C)
1320 self.expect_keyword(keywords::Fn)?;
1321 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1322 let ret_ty = self.parse_ret_ty(false)?;
1323 let decl = P(FnDecl {
1328 Ok(TyKind::BareFn(P(BareFnTy {
1336 /// Parse asyncness: `async` or nothing
1337 fn parse_asyncness(&mut self) -> IsAsync {
1338 if self.eat_keyword(keywords::Async) {
1340 closure_id: ast::DUMMY_NODE_ID,
1341 return_impl_trait_id: ast::DUMMY_NODE_ID,
1348 /// Parse unsafety: `unsafe` or nothing.
1349 fn parse_unsafety(&mut self) -> Unsafety {
1350 if self.eat_keyword(keywords::Unsafe) {
1357 /// Parse the items in a trait declaration
1358 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1359 maybe_whole!(self, NtTraitItem, |x| x);
1360 let attrs = self.parse_outer_attributes()?;
1361 let (mut item, tokens) = self.collect_tokens(|this| {
1362 this.parse_trait_item_(at_end, attrs)
1364 // See `parse_item` for why this clause is here.
1365 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1366 item.tokens = Some(tokens);
1371 fn parse_trait_item_(&mut self,
1373 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1376 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1377 self.parse_trait_item_assoc_ty()?
1378 } else if self.is_const_item() {
1379 self.expect_keyword(keywords::Const)?;
1380 let ident = self.parse_ident()?;
1381 self.expect(&token::Colon)?;
1382 let ty = self.parse_ty()?;
1383 let default = if self.eat(&token::Eq) {
1384 let expr = self.parse_expr()?;
1385 self.expect(&token::Semi)?;
1388 self.expect(&token::Semi)?;
1391 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1392 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1393 // trait item macro.
1394 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1396 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1398 let ident = self.parse_ident()?;
1399 let mut generics = self.parse_generics()?;
1401 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1402 // This is somewhat dubious; We don't want to allow
1403 // argument names to be left off if there is a
1406 // We don't allow argument names to be left off in edition 2018.
1407 p.parse_arg_general(p.span.rust_2018())
1409 generics.where_clause = self.parse_where_clause()?;
1411 let sig = ast::MethodSig {
1421 let body = match self.token {
1425 debug!("parse_trait_methods(): parsing required method");
1428 token::OpenDelim(token::Brace) => {
1429 debug!("parse_trait_methods(): parsing provided method");
1431 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1432 attrs.extend(inner_attrs.iter().cloned());
1435 token::Interpolated(ref nt) => {
1437 token::NtBlock(..) => {
1439 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1440 attrs.extend(inner_attrs.iter().cloned());
1444 let token_str = self.this_token_descr();
1445 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1447 err.span_label(self.span, "expected `;` or `{`");
1453 let token_str = self.this_token_descr();
1454 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1456 err.span_label(self.span, "expected `;` or `{`");
1460 (ident, ast::TraitItemKind::Method(sig, body), generics)
1464 id: ast::DUMMY_NODE_ID,
1469 span: lo.to(self.prev_span),
1474 /// Parse optional return type [ -> TY ] in function decl
1475 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1476 if self.eat(&token::RArrow) {
1477 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1479 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1484 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1485 self.parse_ty_common(true, true)
1488 /// Parse a type in restricted contexts where `+` is not permitted.
1489 /// Example 1: `&'a TYPE`
1490 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1491 /// Example 2: `value1 as TYPE + value2`
1492 /// `+` is prohibited to avoid interactions with expression grammar.
1493 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1494 self.parse_ty_common(false, true)
1497 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1498 -> PResult<'a, P<Ty>> {
1499 maybe_whole!(self, NtTy, |x| x);
1502 let mut impl_dyn_multi = false;
1503 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1504 // `(TYPE)` is a parenthesized type.
1505 // `(TYPE,)` is a tuple with a single field of type TYPE.
1506 let mut ts = vec![];
1507 let mut last_comma = false;
1508 while self.token != token::CloseDelim(token::Paren) {
1509 ts.push(self.parse_ty()?);
1510 if self.eat(&token::Comma) {
1517 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1518 self.expect(&token::CloseDelim(token::Paren))?;
1520 if ts.len() == 1 && !last_comma {
1521 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1522 let maybe_bounds = allow_plus && self.token.is_like_plus();
1524 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1525 TyKind::Path(None, ref path) if maybe_bounds => {
1526 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1528 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1529 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1530 let path = match bounds[0] {
1531 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1532 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1534 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1537 _ => TyKind::Paren(P(ty))
1542 } else if self.eat(&token::Not) {
1545 } else if self.eat(&token::BinOp(token::Star)) {
1547 TyKind::Ptr(self.parse_ptr()?)
1548 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1550 let t = self.parse_ty()?;
1551 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1552 let t = match self.maybe_parse_fixed_length_of_vec()? {
1553 None => TyKind::Slice(t),
1554 Some(length) => TyKind::Array(t, AnonConst {
1555 id: ast::DUMMY_NODE_ID,
1559 self.expect(&token::CloseDelim(token::Bracket))?;
1561 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1564 self.parse_borrowed_pointee()?
1565 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1567 // In order to not be ambiguous, the type must be surrounded by parens.
1568 self.expect(&token::OpenDelim(token::Paren))?;
1570 id: ast::DUMMY_NODE_ID,
1571 value: self.parse_expr()?,
1573 self.expect(&token::CloseDelim(token::Paren))?;
1575 } else if self.eat_keyword(keywords::Underscore) {
1576 // A type to be inferred `_`
1578 } else if self.token_is_bare_fn_keyword() {
1579 // Function pointer type
1580 self.parse_ty_bare_fn(Vec::new())?
1581 } else if self.check_keyword(keywords::For) {
1582 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1583 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1584 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1586 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1587 if self.token_is_bare_fn_keyword() {
1588 self.parse_ty_bare_fn(lifetime_defs)?
1590 let path = self.parse_path(PathStyle::Type)?;
1591 let parse_plus = allow_plus && self.check_plus();
1592 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1594 } else if self.eat_keyword(keywords::Impl) {
1595 // Always parse bounds greedily for better error recovery.
1596 let bounds = self.parse_generic_bounds()?;
1597 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1598 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1599 } else if self.check_keyword(keywords::Dyn) &&
1600 (self.span.rust_2018() ||
1601 self.look_ahead(1, |t| t.can_begin_bound() &&
1602 !can_continue_type_after_non_fn_ident(t))) {
1603 self.bump(); // `dyn`
1604 // Always parse bounds greedily for better error recovery.
1605 let bounds = self.parse_generic_bounds()?;
1606 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1607 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1608 } else if self.check(&token::Question) ||
1609 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1610 // Bound list (trait object type)
1611 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1612 TraitObjectSyntax::None)
1613 } else if self.eat_lt() {
1615 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1616 TyKind::Path(Some(qself), path)
1617 } else if self.token.is_path_start() {
1619 let path = self.parse_path(PathStyle::Type)?;
1620 if self.eat(&token::Not) {
1621 // Macro invocation in type position
1622 let (delim, tts) = self.expect_delimited_token_tree()?;
1623 let node = Mac_ { path, tts, delim };
1624 TyKind::Mac(respan(lo.to(self.prev_span), node))
1626 // Just a type path or bound list (trait object type) starting with a trait.
1628 // `Trait1 + Trait2 + 'a`
1629 if allow_plus && self.check_plus() {
1630 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1632 TyKind::Path(None, path)
1636 let msg = format!("expected type, found {}", self.this_token_descr());
1637 return Err(self.fatal(&msg));
1640 let span = lo.to(self.prev_span);
1641 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1643 // Try to recover from use of `+` with incorrect priority.
1644 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1645 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1646 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1651 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1652 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1653 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1654 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1656 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1657 bounds.append(&mut self.parse_generic_bounds()?);
1659 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1662 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1663 if !allow_plus && impl_dyn_multi {
1664 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1665 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1666 .span_suggestion_with_applicability(
1668 "use parentheses to disambiguate",
1670 Applicability::MachineApplicable
1675 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1676 // Do not add `+` to expected tokens.
1677 if !allow_plus || !self.token.is_like_plus() {
1682 let bounds = self.parse_generic_bounds()?;
1683 let sum_span = ty.span.to(self.prev_span);
1685 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1686 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1689 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1690 let sum_with_parens = pprust::to_string(|s| {
1691 use print::pprust::PrintState;
1694 s.print_opt_lifetime(lifetime)?;
1695 s.print_mutability(mut_ty.mutbl)?;
1697 s.print_type(&mut_ty.ty)?;
1698 s.print_type_bounds(" +", &bounds)?;
1701 err.span_suggestion_with_applicability(
1703 "try adding parentheses",
1705 Applicability::MachineApplicable
1708 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1709 err.span_label(sum_span, "perhaps you forgot parentheses?");
1712 err.span_label(sum_span, "expected a path");
1719 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1720 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1722 // Do not add `::` to expected tokens.
1723 if !allow_recovery || self.token != token::ModSep {
1726 let ty = match base.to_ty() {
1728 None => return Ok(base),
1731 self.bump(); // `::`
1732 let mut segments = Vec::new();
1733 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1735 let span = ty.span.to(self.prev_span);
1736 let path_span = span.to(span); // use an empty path since `position` == 0
1737 let recovered = base.to_recovered(
1738 Some(QSelf { ty, path_span, position: 0 }),
1739 ast::Path { segments, span },
1743 .struct_span_err(span, "missing angle brackets in associated item path")
1744 .span_suggestion_with_applicability( // this is a best-effort recovery
1745 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1751 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1752 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1753 let mutbl = self.parse_mutability();
1754 let ty = self.parse_ty_no_plus()?;
1755 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1758 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1759 let mutbl = if self.eat_keyword(keywords::Mut) {
1761 } else if self.eat_keyword(keywords::Const) {
1762 Mutability::Immutable
1764 let span = self.prev_span;
1766 "expected mut or const in raw pointer type (use \
1767 `*mut T` or `*const T` as appropriate)");
1768 Mutability::Immutable
1770 let t = self.parse_ty_no_plus()?;
1771 Ok(MutTy { ty: t, mutbl: mutbl })
1774 fn is_named_argument(&mut self) -> bool {
1775 let offset = match self.token {
1776 token::Interpolated(ref nt) => match nt.0 {
1777 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1780 token::BinOp(token::And) | token::AndAnd => 1,
1781 _ if self.token.is_keyword(keywords::Mut) => 1,
1785 self.look_ahead(offset, |t| t.is_ident()) &&
1786 self.look_ahead(offset + 1, |t| t == &token::Colon)
1789 /// Skip unexpected attributes and doc comments in this position and emit an appropriate error.
1790 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1791 if let token::DocComment(_) = self.token {
1792 let mut err = self.diagnostic().struct_span_err(
1794 &format!("documentation comments cannot be applied to {}", applied_to),
1796 err.span_label(self.span, "doc comments are not allowed here");
1799 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1800 *t == token::OpenDelim(token::Bracket)
1803 // Skip every token until next possible arg.
1804 while self.token != token::CloseDelim(token::Bracket) {
1807 let sp = lo.to(self.span);
1809 let mut err = self.diagnostic().struct_span_err(
1811 &format!("attributes cannot be applied to {}", applied_to),
1813 err.span_label(sp, "attributes are not allowed here");
1818 /// This version of parse arg doesn't necessarily require
1819 /// identifier names.
1820 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1821 maybe_whole!(self, NtArg, |x| x);
1823 if let Ok(Some(_)) = self.parse_self_arg() {
1824 let mut err = self.struct_span_err(self.prev_span,
1825 "unexpected `self` argument in function");
1826 err.span_label(self.prev_span,
1827 "`self` is only valid as the first argument of an associated function");
1831 let (pat, ty) = if require_name || self.is_named_argument() {
1832 debug!("parse_arg_general parse_pat (require_name:{})",
1834 self.eat_incorrect_doc_comment("method arguments");
1835 let pat = self.parse_pat(Some("argument name"))?;
1837 if let Err(mut err) = self.expect(&token::Colon) {
1838 // If we find a pattern followed by an identifier, it could be an (incorrect)
1839 // C-style parameter declaration.
1840 if self.check_ident() && self.look_ahead(1, |t| {
1841 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1843 let ident = self.parse_ident().unwrap();
1844 let span = pat.span.with_hi(ident.span.hi());
1846 err.span_suggestion_with_applicability(
1848 "declare the type after the parameter binding",
1849 String::from("<identifier>: <type>"),
1850 Applicability::HasPlaceholders,
1857 self.eat_incorrect_doc_comment("a method argument's type");
1858 (pat, self.parse_ty()?)
1860 debug!("parse_arg_general ident_to_pat");
1861 let parser_snapshot_before_ty = self.clone();
1862 self.eat_incorrect_doc_comment("a method argument's type");
1863 let mut ty = self.parse_ty();
1864 if ty.is_ok() && self.token == token::Colon {
1865 // This wasn't actually a type, but a pattern looking like a type,
1866 // so we are going to rollback and re-parse for recovery.
1867 ty = self.unexpected();
1871 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1873 id: ast::DUMMY_NODE_ID,
1874 node: PatKind::Ident(
1875 BindingMode::ByValue(Mutability::Immutable), ident, None),
1881 // Recover from attempting to parse the argument as a type without pattern.
1883 mem::replace(self, parser_snapshot_before_ty);
1884 let pat = self.parse_pat(Some("argument name"))?;
1885 self.expect(&token::Colon)?;
1886 let ty = self.parse_ty()?;
1888 let mut err = self.diagnostic().struct_span_err_with_code(
1890 "patterns aren't allowed in methods without bodies",
1891 DiagnosticId::Error("E0642".into()),
1893 err.span_suggestion_short_with_applicability(
1895 "give this argument a name or use an underscore to ignore it",
1897 Applicability::MachineApplicable,
1901 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1903 node: PatKind::Wild,
1905 id: ast::DUMMY_NODE_ID
1912 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1915 /// Parse a single function argument
1916 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1917 self.parse_arg_general(true)
1920 /// Parse an argument in a lambda header e.g. |arg, arg|
1921 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1922 let pat = self.parse_pat(Some("argument name"))?;
1923 let t = if self.eat(&token::Colon) {
1927 id: ast::DUMMY_NODE_ID,
1928 node: TyKind::Infer,
1929 span: self.prev_span,
1935 id: ast::DUMMY_NODE_ID
1939 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1940 if self.eat(&token::Semi) {
1941 Ok(Some(self.parse_expr()?))
1947 /// Matches token_lit = LIT_INTEGER | ...
1948 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1949 let out = match self.token {
1950 token::Interpolated(ref nt) => match nt.0 {
1951 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1952 ExprKind::Lit(ref lit) => { lit.node.clone() }
1953 _ => { return self.unexpected_last(&self.token); }
1955 _ => { return self.unexpected_last(&self.token); }
1957 token::Literal(lit, suf) => {
1958 let diag = Some((self.span, &self.sess.span_diagnostic));
1959 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1963 self.expect_no_suffix(sp, lit.literal_name(), suf)
1968 _ => { return self.unexpected_last(&self.token); }
1975 /// Matches lit = true | false | token_lit
1976 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1978 let lit = if self.eat_keyword(keywords::True) {
1980 } else if self.eat_keyword(keywords::False) {
1981 LitKind::Bool(false)
1983 let lit = self.parse_lit_token()?;
1986 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
1989 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1990 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1991 maybe_whole_expr!(self);
1993 let minus_lo = self.span;
1994 let minus_present = self.eat(&token::BinOp(token::Minus));
1996 let literal = self.parse_lit()?;
1997 let hi = self.prev_span;
1998 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2001 let minus_hi = self.prev_span;
2002 let unary = self.mk_unary(UnOp::Neg, expr);
2003 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2009 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2011 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2012 let span = self.span;
2014 Ok(Ident::new(ident.name, span))
2016 _ => self.parse_ident(),
2020 /// Parses qualified path.
2021 /// Assumes that the leading `<` has been parsed already.
2023 /// `qualified_path = <type [as trait_ref]>::path`
2028 /// `<T as U>::F::a<S>` (without disambiguator)
2029 /// `<T as U>::F::a::<S>` (with disambiguator)
2030 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2031 let lo = self.prev_span;
2032 let ty = self.parse_ty()?;
2034 // `path` will contain the prefix of the path up to the `>`,
2035 // if any (e.g., `U` in the `<T as U>::*` examples
2036 // above). `path_span` has the span of that path, or an empty
2037 // span in the case of something like `<T>::Bar`.
2038 let (mut path, path_span);
2039 if self.eat_keyword(keywords::As) {
2040 let path_lo = self.span;
2041 path = self.parse_path(PathStyle::Type)?;
2042 path_span = path_lo.to(self.prev_span);
2044 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2045 path_span = self.span.to(self.span);
2048 self.expect(&token::Gt)?;
2049 self.expect(&token::ModSep)?;
2051 let qself = QSelf { ty, path_span, position: path.segments.len() };
2052 self.parse_path_segments(&mut path.segments, style, true)?;
2054 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2057 /// Parses simple paths.
2059 /// `path = [::] segment+`
2060 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2063 /// `a::b::C<D>` (without disambiguator)
2064 /// `a::b::C::<D>` (with disambiguator)
2065 /// `Fn(Args)` (without disambiguator)
2066 /// `Fn::(Args)` (with disambiguator)
2067 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2068 self.parse_path_common(style, true)
2071 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2072 -> PResult<'a, ast::Path> {
2073 maybe_whole!(self, NtPath, |path| {
2074 if style == PathStyle::Mod &&
2075 path.segments.iter().any(|segment| segment.args.is_some()) {
2076 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2081 let lo = self.meta_var_span.unwrap_or(self.span);
2082 let mut segments = Vec::new();
2083 let mod_sep_ctxt = self.span.ctxt();
2084 if self.eat(&token::ModSep) {
2085 segments.push(PathSegment::crate_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2087 self.parse_path_segments(&mut segments, style, enable_warning)?;
2089 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2092 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2093 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2094 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2095 let meta_ident = match self.token {
2096 token::Interpolated(ref nt) => match nt.0 {
2097 token::NtMeta(ref meta) => match meta.node {
2098 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2105 if let Some(path) = meta_ident {
2109 self.parse_path(style)
2112 fn parse_path_segments(&mut self,
2113 segments: &mut Vec<PathSegment>,
2115 enable_warning: bool)
2116 -> PResult<'a, ()> {
2118 segments.push(self.parse_path_segment(style, enable_warning)?);
2120 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2126 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2127 -> PResult<'a, PathSegment> {
2128 let ident = self.parse_path_segment_ident()?;
2130 let is_args_start = |token: &token::Token| match *token {
2131 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2134 let check_args_start = |this: &mut Self| {
2135 this.expected_tokens.extend_from_slice(
2136 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2138 is_args_start(&this.token)
2141 Ok(if style == PathStyle::Type && check_args_start(self) ||
2142 style != PathStyle::Mod && self.check(&token::ModSep)
2143 && self.look_ahead(1, |t| is_args_start(t)) {
2144 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2146 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2147 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2148 .span_label(self.prev_span, "try removing `::`").emit();
2151 let args = if self.eat_lt() {
2153 let (args, bindings) = self.parse_generic_args()?;
2155 let span = lo.to(self.prev_span);
2156 AngleBracketedArgs { args, bindings, span }.into()
2160 let inputs = self.parse_seq_to_before_tokens(
2161 &[&token::CloseDelim(token::Paren)],
2162 SeqSep::trailing_allowed(token::Comma),
2163 TokenExpectType::Expect,
2166 let span = lo.to(self.prev_span);
2167 let output = if self.eat(&token::RArrow) {
2168 Some(self.parse_ty_common(false, false)?)
2172 ParenthesisedArgs { inputs, output, span }.into()
2175 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2177 // Generic arguments are not found.
2178 PathSegment::from_ident(ident)
2182 crate fn check_lifetime(&mut self) -> bool {
2183 self.expected_tokens.push(TokenType::Lifetime);
2184 self.token.is_lifetime()
2187 /// Parse single lifetime 'a or panic.
2188 crate fn expect_lifetime(&mut self) -> Lifetime {
2189 if let Some(ident) = self.token.lifetime() {
2190 let span = self.span;
2192 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2194 self.span_bug(self.span, "not a lifetime")
2198 fn eat_label(&mut self) -> Option<Label> {
2199 if let Some(ident) = self.token.lifetime() {
2200 let span = self.span;
2202 Some(Label { ident: Ident::new(ident.name, span) })
2208 /// Parse mutability (`mut` or nothing).
2209 fn parse_mutability(&mut self) -> Mutability {
2210 if self.eat_keyword(keywords::Mut) {
2213 Mutability::Immutable
2217 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2218 if let token::Literal(token::Integer(name), None) = self.token {
2220 Ok(Ident::new(name, self.prev_span))
2222 self.parse_ident_common(false)
2226 /// Parse ident (COLON expr)?
2227 fn parse_field(&mut self) -> PResult<'a, Field> {
2228 let attrs = self.parse_outer_attributes()?;
2231 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2232 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2233 let fieldname = self.parse_field_name()?;
2235 (fieldname, self.parse_expr()?, false)
2237 let fieldname = self.parse_ident_common(false)?;
2239 // Mimic `x: x` for the `x` field shorthand.
2240 let path = ast::Path::from_ident(fieldname);
2241 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2242 (fieldname, expr, true)
2246 span: lo.to(expr.span),
2249 attrs: attrs.into(),
2253 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2254 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2257 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2258 ExprKind::Unary(unop, expr)
2261 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2262 ExprKind::Binary(binop, lhs, rhs)
2265 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2266 ExprKind::Call(f, args)
2269 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2270 ExprKind::Index(expr, idx)
2273 fn mk_range(&mut self,
2274 start: Option<P<Expr>>,
2275 end: Option<P<Expr>>,
2276 limits: RangeLimits)
2277 -> PResult<'a, ast::ExprKind> {
2278 if end.is_none() && limits == RangeLimits::Closed {
2279 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2281 Ok(ExprKind::Range(start, end, limits))
2285 fn mk_assign_op(&mut self, binop: ast::BinOp,
2286 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2287 ExprKind::AssignOp(binop, lhs, rhs)
2290 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2292 id: ast::DUMMY_NODE_ID,
2293 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2299 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2300 let delim = match self.token {
2301 token::OpenDelim(delim) => delim,
2303 let msg = "expected open delimiter";
2304 let mut err = self.fatal(msg);
2305 err.span_label(self.span, msg);
2309 let delimited = match self.parse_token_tree() {
2310 TokenTree::Delimited(_, delimited) => delimited,
2311 _ => unreachable!(),
2313 let delim = match delim {
2314 token::Paren => MacDelimiter::Parenthesis,
2315 token::Bracket => MacDelimiter::Bracket,
2316 token::Brace => MacDelimiter::Brace,
2317 token::NoDelim => self.bug("unexpected no delimiter"),
2319 Ok((delim, delimited.stream().into()))
2322 /// At the bottom (top?) of the precedence hierarchy,
2323 /// parse things like parenthesized exprs,
2324 /// macros, return, etc.
2326 /// NB: This does not parse outer attributes,
2327 /// and is private because it only works
2328 /// correctly if called from parse_dot_or_call_expr().
2329 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2330 maybe_whole_expr!(self);
2332 // Outer attributes are already parsed and will be
2333 // added to the return value after the fact.
2335 // Therefore, prevent sub-parser from parsing
2336 // attributes by giving them a empty "already parsed" list.
2337 let mut attrs = ThinVec::new();
2340 let mut hi = self.span;
2344 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2346 token::OpenDelim(token::Paren) => {
2349 attrs.extend(self.parse_inner_attributes()?);
2351 // (e) is parenthesized e
2352 // (e,) is a tuple with only one field, e
2353 let mut es = vec![];
2354 let mut trailing_comma = false;
2355 while self.token != token::CloseDelim(token::Paren) {
2356 es.push(self.parse_expr()?);
2357 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2358 if self.eat(&token::Comma) {
2359 trailing_comma = true;
2361 trailing_comma = false;
2367 hi = self.prev_span;
2368 ex = if es.len() == 1 && !trailing_comma {
2369 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2374 token::OpenDelim(token::Brace) => {
2375 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2377 token::BinOp(token::Or) | token::OrOr => {
2378 return self.parse_lambda_expr(attrs);
2380 token::OpenDelim(token::Bracket) => {
2383 attrs.extend(self.parse_inner_attributes()?);
2385 if self.eat(&token::CloseDelim(token::Bracket)) {
2387 ex = ExprKind::Array(Vec::new());
2390 let first_expr = self.parse_expr()?;
2391 if self.eat(&token::Semi) {
2392 // Repeating array syntax: [ 0; 512 ]
2393 let count = AnonConst {
2394 id: ast::DUMMY_NODE_ID,
2395 value: self.parse_expr()?,
2397 self.expect(&token::CloseDelim(token::Bracket))?;
2398 ex = ExprKind::Repeat(first_expr, count);
2399 } else if self.eat(&token::Comma) {
2400 // Vector with two or more elements.
2401 let remaining_exprs = self.parse_seq_to_end(
2402 &token::CloseDelim(token::Bracket),
2403 SeqSep::trailing_allowed(token::Comma),
2404 |p| Ok(p.parse_expr()?)
2406 let mut exprs = vec![first_expr];
2407 exprs.extend(remaining_exprs);
2408 ex = ExprKind::Array(exprs);
2410 // Vector with one element.
2411 self.expect(&token::CloseDelim(token::Bracket))?;
2412 ex = ExprKind::Array(vec![first_expr]);
2415 hi = self.prev_span;
2419 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2421 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2423 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2425 if self.is_async_block() { // check for `async {` and `async move {`
2426 return self.parse_async_block(attrs);
2428 return self.parse_lambda_expr(attrs);
2431 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2432 return self.parse_lambda_expr(attrs);
2434 if self.eat_keyword(keywords::If) {
2435 return self.parse_if_expr(attrs);
2437 if self.eat_keyword(keywords::For) {
2438 let lo = self.prev_span;
2439 return self.parse_for_expr(None, lo, attrs);
2441 if self.eat_keyword(keywords::While) {
2442 let lo = self.prev_span;
2443 return self.parse_while_expr(None, lo, attrs);
2445 if let Some(label) = self.eat_label() {
2446 let lo = label.ident.span;
2447 self.expect(&token::Colon)?;
2448 if self.eat_keyword(keywords::While) {
2449 return self.parse_while_expr(Some(label), lo, attrs)
2451 if self.eat_keyword(keywords::For) {
2452 return self.parse_for_expr(Some(label), lo, attrs)
2454 if self.eat_keyword(keywords::Loop) {
2455 return self.parse_loop_expr(Some(label), lo, attrs)
2457 if self.token == token::OpenDelim(token::Brace) {
2458 return self.parse_block_expr(Some(label),
2460 BlockCheckMode::Default,
2463 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2464 let mut err = self.fatal(msg);
2465 err.span_label(self.span, msg);
2468 if self.eat_keyword(keywords::Loop) {
2469 let lo = self.prev_span;
2470 return self.parse_loop_expr(None, lo, attrs);
2472 if self.eat_keyword(keywords::Continue) {
2473 let label = self.eat_label();
2474 let ex = ExprKind::Continue(label);
2475 let hi = self.prev_span;
2476 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2478 if self.eat_keyword(keywords::Match) {
2479 let match_sp = self.prev_span;
2480 return self.parse_match_expr(attrs).map_err(|mut err| {
2481 err.span_label(match_sp, "while parsing this match expression");
2485 if self.eat_keyword(keywords::Unsafe) {
2486 return self.parse_block_expr(
2489 BlockCheckMode::Unsafe(ast::UserProvided),
2492 if self.is_do_catch_block() {
2493 let mut db = self.fatal("found removed `do catch` syntax");
2494 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2497 if self.is_try_block() {
2499 assert!(self.eat_keyword(keywords::Try));
2500 return self.parse_try_block(lo, attrs);
2502 if self.eat_keyword(keywords::Return) {
2503 if self.token.can_begin_expr() {
2504 let e = self.parse_expr()?;
2506 ex = ExprKind::Ret(Some(e));
2508 ex = ExprKind::Ret(None);
2510 } else if self.eat_keyword(keywords::Break) {
2511 let label = self.eat_label();
2512 let e = if self.token.can_begin_expr()
2513 && !(self.token == token::OpenDelim(token::Brace)
2514 && self.restrictions.contains(
2515 Restrictions::NO_STRUCT_LITERAL)) {
2516 Some(self.parse_expr()?)
2520 ex = ExprKind::Break(label, e);
2521 hi = self.prev_span;
2522 } else if self.eat_keyword(keywords::Yield) {
2523 if self.token.can_begin_expr() {
2524 let e = self.parse_expr()?;
2526 ex = ExprKind::Yield(Some(e));
2528 ex = ExprKind::Yield(None);
2530 } else if self.token.is_keyword(keywords::Let) {
2531 // Catch this syntax error here, instead of in `parse_ident`, so
2532 // that we can explicitly mention that let is not to be used as an expression
2533 let mut db = self.fatal("expected expression, found statement (`let`)");
2534 db.span_label(self.span, "expected expression");
2535 db.note("variable declaration using `let` is a statement");
2537 } else if self.token.is_path_start() {
2538 let pth = self.parse_path(PathStyle::Expr)?;
2540 // `!`, as an operator, is prefix, so we know this isn't that
2541 if self.eat(&token::Not) {
2542 // MACRO INVOCATION expression
2543 let (delim, tts) = self.expect_delimited_token_tree()?;
2544 let hi = self.prev_span;
2545 let node = Mac_ { path: pth, tts, delim };
2546 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2548 if self.check(&token::OpenDelim(token::Brace)) {
2549 // This is a struct literal, unless we're prohibited
2550 // from parsing struct literals here.
2551 let prohibited = self.restrictions.contains(
2552 Restrictions::NO_STRUCT_LITERAL
2555 return self.parse_struct_expr(lo, pth, attrs);
2560 ex = ExprKind::Path(None, pth);
2562 match self.parse_literal_maybe_minus() {
2565 ex = expr.node.clone();
2568 self.cancel(&mut err);
2569 let msg = format!("expected expression, found {}",
2570 self.this_token_descr());
2571 let mut err = self.fatal(&msg);
2572 err.span_label(self.span, "expected expression");
2580 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2581 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2586 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2587 -> PResult<'a, P<Expr>> {
2588 let struct_sp = lo.to(self.prev_span);
2590 let mut fields = Vec::new();
2591 let mut base = None;
2593 attrs.extend(self.parse_inner_attributes()?);
2595 while self.token != token::CloseDelim(token::Brace) {
2596 if self.eat(&token::DotDot) {
2597 let exp_span = self.prev_span;
2598 match self.parse_expr() {
2604 self.recover_stmt();
2607 if self.token == token::Comma {
2608 let mut err = self.sess.span_diagnostic.mut_span_err(
2609 exp_span.to(self.prev_span),
2610 "cannot use a comma after the base struct",
2612 err.span_suggestion_short_with_applicability(
2614 "remove this comma",
2616 Applicability::MachineApplicable
2618 err.note("the base struct must always be the last field");
2620 self.recover_stmt();
2625 match self.parse_field() {
2626 Ok(f) => fields.push(f),
2628 e.span_label(struct_sp, "while parsing this struct");
2631 // If the next token is a comma, then try to parse
2632 // what comes next as additional fields, rather than
2633 // bailing out until next `}`.
2634 if self.token != token::Comma {
2635 self.recover_stmt();
2641 match self.expect_one_of(&[token::Comma],
2642 &[token::CloseDelim(token::Brace)]) {
2646 self.recover_stmt();
2652 let span = lo.to(self.span);
2653 self.expect(&token::CloseDelim(token::Brace))?;
2654 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2657 fn parse_or_use_outer_attributes(&mut self,
2658 already_parsed_attrs: Option<ThinVec<Attribute>>)
2659 -> PResult<'a, ThinVec<Attribute>> {
2660 if let Some(attrs) = already_parsed_attrs {
2663 self.parse_outer_attributes().map(|a| a.into())
2667 /// Parse a block or unsafe block
2668 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2669 lo: Span, blk_mode: BlockCheckMode,
2670 outer_attrs: ThinVec<Attribute>)
2671 -> PResult<'a, P<Expr>> {
2672 self.expect(&token::OpenDelim(token::Brace))?;
2674 let mut attrs = outer_attrs;
2675 attrs.extend(self.parse_inner_attributes()?);
2677 let blk = self.parse_block_tail(lo, blk_mode)?;
2678 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2681 /// parse a.b or a(13) or a[4] or just a
2682 fn parse_dot_or_call_expr(&mut self,
2683 already_parsed_attrs: Option<ThinVec<Attribute>>)
2684 -> PResult<'a, P<Expr>> {
2685 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2687 let b = self.parse_bottom_expr();
2688 let (span, b) = self.interpolated_or_expr_span(b)?;
2689 self.parse_dot_or_call_expr_with(b, span, attrs)
2692 fn parse_dot_or_call_expr_with(&mut self,
2695 mut attrs: ThinVec<Attribute>)
2696 -> PResult<'a, P<Expr>> {
2697 // Stitch the list of outer attributes onto the return value.
2698 // A little bit ugly, but the best way given the current code
2700 self.parse_dot_or_call_expr_with_(e0, lo)
2702 expr.map(|mut expr| {
2703 attrs.extend::<Vec<_>>(expr.attrs.into());
2706 ExprKind::If(..) | ExprKind::IfLet(..) => {
2707 if !expr.attrs.is_empty() {
2708 // Just point to the first attribute in there...
2709 let span = expr.attrs[0].span;
2712 "attributes are not yet allowed on `if` \
2723 // Assuming we have just parsed `.`, continue parsing into an expression.
2724 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2725 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2726 Ok(match self.token {
2727 token::OpenDelim(token::Paren) => {
2728 // Method call `expr.f()`
2729 let mut args = self.parse_unspanned_seq(
2730 &token::OpenDelim(token::Paren),
2731 &token::CloseDelim(token::Paren),
2732 SeqSep::trailing_allowed(token::Comma),
2733 |p| Ok(p.parse_expr()?)
2735 args.insert(0, self_arg);
2737 let span = lo.to(self.prev_span);
2738 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2741 // Field access `expr.f`
2742 if let Some(args) = segment.args {
2743 self.span_err(args.span(),
2744 "field expressions may not have generic arguments");
2747 let span = lo.to(self.prev_span);
2748 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2753 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2758 while self.eat(&token::Question) {
2759 let hi = self.prev_span;
2760 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2764 if self.eat(&token::Dot) {
2766 token::Ident(..) => {
2767 e = self.parse_dot_suffix(e, lo)?;
2769 token::Literal(token::Integer(name), _) => {
2770 let span = self.span;
2772 let field = ExprKind::Field(e, Ident::new(name, span));
2773 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2775 token::Literal(token::Float(n), _suf) => {
2777 let fstr = n.as_str();
2778 let mut err = self.diagnostic()
2779 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
2780 err.span_label(self.prev_span, "unexpected token");
2781 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2782 let float = match fstr.parse::<f64>().ok() {
2786 let sugg = pprust::to_string(|s| {
2787 use print::pprust::PrintState;
2791 s.print_usize(float.trunc() as usize)?;
2794 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2796 err.span_suggestion_with_applicability(
2797 lo.to(self.prev_span),
2798 "try parenthesizing the first index",
2800 Applicability::MachineApplicable
2807 // FIXME Could factor this out into non_fatal_unexpected or something.
2808 let actual = self.this_token_to_string();
2809 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2814 if self.expr_is_complete(&e) { break; }
2817 token::OpenDelim(token::Paren) => {
2818 let es = self.parse_unspanned_seq(
2819 &token::OpenDelim(token::Paren),
2820 &token::CloseDelim(token::Paren),
2821 SeqSep::trailing_allowed(token::Comma),
2822 |p| Ok(p.parse_expr()?)
2824 hi = self.prev_span;
2826 let nd = self.mk_call(e, es);
2827 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2831 // Could be either an index expression or a slicing expression.
2832 token::OpenDelim(token::Bracket) => {
2834 let ix = self.parse_expr()?;
2836 self.expect(&token::CloseDelim(token::Bracket))?;
2837 let index = self.mk_index(e, ix);
2838 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2846 crate fn process_potential_macro_variable(&mut self) {
2847 let (token, span) = match self.token {
2848 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2849 self.look_ahead(1, |t| t.is_ident()) => {
2851 let name = match self.token {
2852 token::Ident(ident, _) => ident,
2855 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2856 err.span_label(self.span, "unknown macro variable");
2860 token::Interpolated(ref nt) => {
2861 self.meta_var_span = Some(self.span);
2862 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2863 // and lifetime tokens, so the former are never encountered during normal parsing.
2865 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2866 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2876 /// parse a single token tree from the input.
2877 crate fn parse_token_tree(&mut self) -> TokenTree {
2879 token::OpenDelim(..) => {
2880 let frame = mem::replace(&mut self.token_cursor.frame,
2881 self.token_cursor.stack.pop().unwrap());
2882 self.span = frame.span.entire();
2884 TokenTree::Delimited(frame.span, Delimited {
2886 tts: frame.tree_cursor.original_stream().into(),
2889 token::CloseDelim(_) | token::Eof => unreachable!(),
2891 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2893 TokenTree::Token(span, token)
2898 // parse a stream of tokens into a list of TokenTree's,
2900 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2901 let mut tts = Vec::new();
2902 while self.token != token::Eof {
2903 tts.push(self.parse_token_tree());
2908 pub fn parse_tokens(&mut self) -> TokenStream {
2909 let mut result = Vec::new();
2912 token::Eof | token::CloseDelim(..) => break,
2913 _ => result.push(self.parse_token_tree().into()),
2916 TokenStream::concat(result)
2919 /// Parse a prefix-unary-operator expr
2920 fn parse_prefix_expr(&mut self,
2921 already_parsed_attrs: Option<ThinVec<Attribute>>)
2922 -> PResult<'a, P<Expr>> {
2923 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2925 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2926 let (hi, ex) = match self.token {
2929 let e = self.parse_prefix_expr(None);
2930 let (span, e) = self.interpolated_or_expr_span(e)?;
2931 (lo.to(span), self.mk_unary(UnOp::Not, e))
2933 // Suggest `!` for bitwise negation when encountering a `~`
2936 let e = self.parse_prefix_expr(None);
2937 let (span, e) = self.interpolated_or_expr_span(e)?;
2938 let span_of_tilde = lo;
2939 let mut err = self.diagnostic()
2940 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2941 err.span_suggestion_short_with_applicability(
2943 "use `!` to perform bitwise negation",
2945 Applicability::MachineApplicable
2948 (lo.to(span), self.mk_unary(UnOp::Not, e))
2950 token::BinOp(token::Minus) => {
2952 let e = self.parse_prefix_expr(None);
2953 let (span, e) = self.interpolated_or_expr_span(e)?;
2954 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2956 token::BinOp(token::Star) => {
2958 let e = self.parse_prefix_expr(None);
2959 let (span, e) = self.interpolated_or_expr_span(e)?;
2960 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2962 token::BinOp(token::And) | token::AndAnd => {
2964 let m = self.parse_mutability();
2965 let e = self.parse_prefix_expr(None);
2966 let (span, e) = self.interpolated_or_expr_span(e)?;
2967 (lo.to(span), ExprKind::AddrOf(m, e))
2969 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2971 let place = self.parse_expr_res(
2972 Restrictions::NO_STRUCT_LITERAL,
2975 let blk = self.parse_block()?;
2976 let span = blk.span;
2977 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2978 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2980 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2982 let e = self.parse_prefix_expr(None);
2983 let (span, e) = self.interpolated_or_expr_span(e)?;
2984 (lo.to(span), ExprKind::Box(e))
2986 token::Ident(..) if self.token.is_ident_named("not") => {
2987 // `not` is just an ordinary identifier in Rust-the-language,
2988 // but as `rustc`-the-compiler, we can issue clever diagnostics
2989 // for confused users who really want to say `!`
2990 let token_cannot_continue_expr = |t: &token::Token| match *t {
2991 // These tokens can start an expression after `!`, but
2992 // can't continue an expression after an ident
2993 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2994 token::Literal(..) | token::Pound => true,
2995 token::Interpolated(ref nt) => match nt.0 {
2996 token::NtIdent(..) | token::NtExpr(..) |
2997 token::NtBlock(..) | token::NtPath(..) => true,
3002 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3003 if cannot_continue_expr {
3005 // Emit the error ...
3006 let mut err = self.diagnostic()
3007 .struct_span_err(self.span,
3008 &format!("unexpected {} after identifier",
3009 self.this_token_descr()));
3010 // span the `not` plus trailing whitespace to avoid
3011 // trailing whitespace after the `!` in our suggestion
3012 let to_replace = self.sess.source_map()
3013 .span_until_non_whitespace(lo.to(self.span));
3014 err.span_suggestion_short_with_applicability(
3016 "use `!` to perform logical negation",
3018 Applicability::MachineApplicable
3021 // —and recover! (just as if we were in the block
3022 // for the `token::Not` arm)
3023 let e = self.parse_prefix_expr(None);
3024 let (span, e) = self.interpolated_or_expr_span(e)?;
3025 (lo.to(span), self.mk_unary(UnOp::Not, e))
3027 return self.parse_dot_or_call_expr(Some(attrs));
3030 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3032 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3035 /// Parse an associative expression
3037 /// This parses an expression accounting for associativity and precedence of the operators in
3039 fn parse_assoc_expr(&mut self,
3040 already_parsed_attrs: Option<ThinVec<Attribute>>)
3041 -> PResult<'a, P<Expr>> {
3042 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3045 /// Parse an associative expression with operators of at least `min_prec` precedence
3046 fn parse_assoc_expr_with(&mut self,
3049 -> PResult<'a, P<Expr>> {
3050 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3053 let attrs = match lhs {
3054 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3057 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3058 return self.parse_prefix_range_expr(attrs);
3060 self.parse_prefix_expr(attrs)?
3064 if self.expr_is_complete(&lhs) {
3065 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3068 self.expected_tokens.push(TokenType::Operator);
3069 while let Some(op) = AssocOp::from_token(&self.token) {
3071 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3072 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3073 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3074 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3075 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3076 (PrevTokenKind::Interpolated, _) => self.prev_span,
3077 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3078 if path.segments.len() == 1 => self.prev_span,
3082 let cur_op_span = self.span;
3083 let restrictions = if op.is_assign_like() {
3084 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3088 if op.precedence() < min_prec {
3091 // Check for deprecated `...` syntax
3092 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3093 self.err_dotdotdot_syntax(self.span);
3097 if op.is_comparison() {
3098 self.check_no_chained_comparison(&lhs, &op);
3101 if op == AssocOp::As {
3102 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3104 } else if op == AssocOp::Colon {
3105 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3108 err.span_label(self.span,
3109 "expecting a type here because of type ascription");
3110 let cm = self.sess.source_map();
3111 let cur_pos = cm.lookup_char_pos(self.span.lo());
3112 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3113 if cur_pos.line != op_pos.line {
3114 err.span_suggestion_with_applicability(
3116 "try using a semicolon",
3118 Applicability::MaybeIncorrect // speculative
3125 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3126 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3127 // generalise it to the Fixity::None code.
3129 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3130 // two variants are handled with `parse_prefix_range_expr` call above.
3131 let rhs = if self.is_at_start_of_range_notation_rhs() {
3132 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3133 LhsExpr::NotYetParsed)?)
3137 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3142 let limits = if op == AssocOp::DotDot {
3143 RangeLimits::HalfOpen
3148 let r = try!(self.mk_range(Some(lhs), rhs, limits));
3149 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3153 let rhs = match op.fixity() {
3154 Fixity::Right => self.with_res(
3155 restrictions - Restrictions::STMT_EXPR,
3157 this.parse_assoc_expr_with(op.precedence(),
3158 LhsExpr::NotYetParsed)
3160 Fixity::Left => self.with_res(
3161 restrictions - Restrictions::STMT_EXPR,
3163 this.parse_assoc_expr_with(op.precedence() + 1,
3164 LhsExpr::NotYetParsed)
3166 // We currently have no non-associative operators that are not handled above by
3167 // the special cases. The code is here only for future convenience.
3168 Fixity::None => self.with_res(
3169 restrictions - Restrictions::STMT_EXPR,
3171 this.parse_assoc_expr_with(op.precedence() + 1,
3172 LhsExpr::NotYetParsed)
3176 let span = lhs_span.to(rhs.span);
3178 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3179 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3180 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3181 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3182 AssocOp::Greater | AssocOp::GreaterEqual => {
3183 let ast_op = op.to_ast_binop().unwrap();
3184 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3185 self.mk_expr(span, binary, ThinVec::new())
3188 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3189 AssocOp::ObsoleteInPlace =>
3190 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3191 AssocOp::AssignOp(k) => {
3193 token::Plus => BinOpKind::Add,
3194 token::Minus => BinOpKind::Sub,
3195 token::Star => BinOpKind::Mul,
3196 token::Slash => BinOpKind::Div,
3197 token::Percent => BinOpKind::Rem,
3198 token::Caret => BinOpKind::BitXor,
3199 token::And => BinOpKind::BitAnd,
3200 token::Or => BinOpKind::BitOr,
3201 token::Shl => BinOpKind::Shl,
3202 token::Shr => BinOpKind::Shr,
3204 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3205 self.mk_expr(span, aopexpr, ThinVec::new())
3207 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3208 self.bug("AssocOp should have been handled by special case")
3212 if op.fixity() == Fixity::None { break }
3217 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3218 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3219 -> PResult<'a, P<Expr>> {
3220 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3221 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3224 // Save the state of the parser before parsing type normally, in case there is a
3225 // LessThan comparison after this cast.
3226 let parser_snapshot_before_type = self.clone();
3227 match self.parse_ty_no_plus() {
3229 Ok(mk_expr(self, rhs))
3231 Err(mut type_err) => {
3232 // Rewind to before attempting to parse the type with generics, to recover
3233 // from situations like `x as usize < y` in which we first tried to parse
3234 // `usize < y` as a type with generic arguments.
3235 let parser_snapshot_after_type = self.clone();
3236 mem::replace(self, parser_snapshot_before_type);
3238 match self.parse_path(PathStyle::Expr) {
3240 let (op_noun, op_verb) = match self.token {
3241 token::Lt => ("comparison", "comparing"),
3242 token::BinOp(token::Shl) => ("shift", "shifting"),
3244 // We can end up here even without `<` being the next token, for
3245 // example because `parse_ty_no_plus` returns `Err` on keywords,
3246 // but `parse_path` returns `Ok` on them due to error recovery.
3247 // Return original error and parser state.
3248 mem::replace(self, parser_snapshot_after_type);
3249 return Err(type_err);
3253 // Successfully parsed the type path leaving a `<` yet to parse.
3256 // Report non-fatal diagnostics, keep `x as usize` as an expression
3257 // in AST and continue parsing.
3258 let msg = format!("`<` is interpreted as a start of generic \
3259 arguments for `{}`, not a {}", path, op_noun);
3260 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3261 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3262 "interpreted as generic arguments");
3263 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3265 let expr = mk_expr(self, P(Ty {
3267 node: TyKind::Path(None, path),
3268 id: ast::DUMMY_NODE_ID
3271 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3272 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3273 err.span_suggestion_with_applicability(
3275 &format!("try {} the cast value", op_verb),
3276 format!("({})", expr_str),
3277 Applicability::MachineApplicable
3283 Err(mut path_err) => {
3284 // Couldn't parse as a path, return original error and parser state.
3286 mem::replace(self, parser_snapshot_after_type);
3294 /// Produce an error if comparison operators are chained (RFC #558).
3295 /// We only need to check lhs, not rhs, because all comparison ops
3296 /// have same precedence and are left-associative
3297 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3298 debug_assert!(outer_op.is_comparison(),
3299 "check_no_chained_comparison: {:?} is not comparison",
3302 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3303 // respan to include both operators
3304 let op_span = op.span.to(self.span);
3305 let mut err = self.diagnostic().struct_span_err(op_span,
3306 "chained comparison operators require parentheses");
3307 if op.node == BinOpKind::Lt &&
3308 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3309 *outer_op == AssocOp::Greater // even in a case like the following:
3310 { // Foo<Bar<Baz<Qux, ()>>>
3312 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3313 err.help("or use `(...)` if you meant to specify fn arguments");
3321 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3322 fn parse_prefix_range_expr(&mut self,
3323 already_parsed_attrs: Option<ThinVec<Attribute>>)
3324 -> PResult<'a, P<Expr>> {
3325 // Check for deprecated `...` syntax
3326 if self.token == token::DotDotDot {
3327 self.err_dotdotdot_syntax(self.span);
3330 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3331 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3333 let tok = self.token.clone();
3334 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3336 let mut hi = self.span;
3338 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3339 // RHS must be parsed with more associativity than the dots.
3340 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3341 Some(self.parse_assoc_expr_with(next_prec,
3342 LhsExpr::NotYetParsed)
3350 let limits = if tok == token::DotDot {
3351 RangeLimits::HalfOpen
3356 let r = try!(self.mk_range(None,
3359 Ok(self.mk_expr(lo.to(hi), r, attrs))
3362 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3363 if self.token.can_begin_expr() {
3364 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3365 if self.token == token::OpenDelim(token::Brace) {
3366 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3374 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3375 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3376 if self.check_keyword(keywords::Let) {
3377 return self.parse_if_let_expr(attrs);
3379 let lo = self.prev_span;
3380 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3382 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3383 // verify that the last statement is either an implicit return (no `;`) or an explicit
3384 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3385 // the dead code lint.
3386 if self.eat_keyword(keywords::Else) || !cond.returns() {
3387 let sp = self.sess.source_map().next_point(lo);
3388 let mut err = self.diagnostic()
3389 .struct_span_err(sp, "missing condition for `if` statemement");
3390 err.span_label(sp, "expected if condition here");
3393 let not_block = self.token != token::OpenDelim(token::Brace);
3394 let thn = self.parse_block().map_err(|mut err| {
3396 err.span_label(lo, "this `if` statement has a condition, but no block");
3400 let mut els: Option<P<Expr>> = None;
3401 let mut hi = thn.span;
3402 if self.eat_keyword(keywords::Else) {
3403 let elexpr = self.parse_else_expr()?;
3407 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3410 /// Parse an 'if let' expression ('if' token already eaten)
3411 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3412 -> PResult<'a, P<Expr>> {
3413 let lo = self.prev_span;
3414 self.expect_keyword(keywords::Let)?;
3415 let pats = self.parse_pats()?;
3416 self.expect(&token::Eq)?;
3417 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3418 let thn = self.parse_block()?;
3419 let (hi, els) = if self.eat_keyword(keywords::Else) {
3420 let expr = self.parse_else_expr()?;
3421 (expr.span, Some(expr))
3425 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3428 // `move |args| expr`
3429 fn parse_lambda_expr(&mut self,
3430 attrs: ThinVec<Attribute>)
3431 -> PResult<'a, P<Expr>>
3434 let movability = if self.eat_keyword(keywords::Static) {
3439 let asyncness = if self.span.rust_2018() {
3440 self.parse_asyncness()
3444 let capture_clause = if self.eat_keyword(keywords::Move) {
3449 let decl = self.parse_fn_block_decl()?;
3450 let decl_hi = self.prev_span;
3451 let body = match decl.output {
3452 FunctionRetTy::Default(_) => {
3453 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3454 self.parse_expr_res(restrictions, None)?
3457 // If an explicit return type is given, require a
3458 // block to appear (RFC 968).
3459 let body_lo = self.span;
3460 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3466 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3470 // `else` token already eaten
3471 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3472 if self.eat_keyword(keywords::If) {
3473 return self.parse_if_expr(ThinVec::new());
3475 let blk = self.parse_block()?;
3476 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3480 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3481 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3483 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3484 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3486 let pat = self.parse_top_level_pat()?;
3487 if !self.eat_keyword(keywords::In) {
3488 let in_span = self.prev_span.between(self.span);
3489 let mut err = self.sess.span_diagnostic
3490 .struct_span_err(in_span, "missing `in` in `for` loop");
3491 err.span_suggestion_short_with_applicability(
3492 in_span, "try adding `in` here", " in ".into(),
3493 // has been misleading, at least in the past (closed Issue #48492)
3494 Applicability::MaybeIncorrect
3498 let in_span = self.prev_span;
3499 if self.eat_keyword(keywords::In) {
3500 // a common typo: `for _ in in bar {}`
3501 let mut err = self.sess.span_diagnostic.struct_span_err(
3503 "expected iterable, found keyword `in`",
3505 err.span_suggestion_short_with_applicability(
3506 in_span.until(self.prev_span),
3507 "remove the duplicated `in`",
3509 Applicability::MachineApplicable,
3511 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3512 err.note("for more information on the status of emplacement syntax, see <\
3513 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3516 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3517 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3518 attrs.extend(iattrs);
3520 let hi = self.prev_span;
3521 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3524 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3525 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3527 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3528 if self.token.is_keyword(keywords::Let) {
3529 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3531 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3532 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3533 attrs.extend(iattrs);
3534 let span = span_lo.to(body.span);
3535 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3538 /// Parse a 'while let' expression ('while' token already eaten)
3539 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3541 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3542 self.expect_keyword(keywords::Let)?;
3543 let pats = self.parse_pats()?;
3544 self.expect(&token::Eq)?;
3545 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3546 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3547 attrs.extend(iattrs);
3548 let span = span_lo.to(body.span);
3549 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3552 // parse `loop {...}`, `loop` token already eaten
3553 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3555 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3556 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3557 attrs.extend(iattrs);
3558 let span = span_lo.to(body.span);
3559 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3562 /// Parse an `async move {...}` expression
3563 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3564 -> PResult<'a, P<Expr>>
3566 let span_lo = self.span;
3567 self.expect_keyword(keywords::Async)?;
3568 let capture_clause = if self.eat_keyword(keywords::Move) {
3573 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3574 attrs.extend(iattrs);
3576 span_lo.to(body.span),
3577 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3580 /// Parse a `try {...}` expression (`try` token already eaten)
3581 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3582 -> PResult<'a, P<Expr>>
3584 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3585 attrs.extend(iattrs);
3586 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3589 // `match` token already eaten
3590 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3591 let match_span = self.prev_span;
3592 let lo = self.prev_span;
3593 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3595 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3596 if self.token == token::Token::Semi {
3597 e.span_suggestion_short_with_applicability(
3599 "try removing this `match`",
3601 Applicability::MaybeIncorrect // speculative
3606 attrs.extend(self.parse_inner_attributes()?);
3608 let mut arms: Vec<Arm> = Vec::new();
3609 while self.token != token::CloseDelim(token::Brace) {
3610 match self.parse_arm() {
3611 Ok(arm) => arms.push(arm),
3613 // Recover by skipping to the end of the block.
3615 self.recover_stmt();
3616 let span = lo.to(self.span);
3617 if self.token == token::CloseDelim(token::Brace) {
3620 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3626 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3629 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3630 maybe_whole!(self, NtArm, |x| x);
3632 let attrs = self.parse_outer_attributes()?;
3633 // Allow a '|' before the pats (RFC 1925)
3634 self.eat(&token::BinOp(token::Or));
3635 let pats = self.parse_pats()?;
3636 let guard = if self.eat_keyword(keywords::If) {
3637 Some(Guard::If(self.parse_expr()?))
3641 let arrow_span = self.span;
3642 self.expect(&token::FatArrow)?;
3643 let arm_start_span = self.span;
3645 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3646 .map_err(|mut err| {
3647 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3651 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3652 && self.token != token::CloseDelim(token::Brace);
3655 let cm = self.sess.source_map();
3656 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3657 .map_err(|mut err| {
3658 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3659 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3660 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3661 && expr_lines.lines.len() == 2
3662 && self.token == token::FatArrow => {
3663 // We check whether there's any trailing code in the parse span,
3664 // if there isn't, we very likely have the following:
3667 // | -- - missing comma
3673 // | parsed until here as `"y" & X`
3674 err.span_suggestion_short_with_applicability(
3675 cm.next_point(arm_start_span),
3676 "missing a comma here to end this `match` arm",
3678 Applicability::MachineApplicable
3682 err.span_label(arrow_span,
3683 "while parsing the `match` arm starting here");
3689 self.eat(&token::Comma);
3700 /// Parse an expression
3701 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3702 self.parse_expr_res(Restrictions::empty(), None)
3705 /// Evaluate the closure with restrictions in place.
3707 /// After the closure is evaluated, restrictions are reset.
3708 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3709 where F: FnOnce(&mut Self) -> T
3711 let old = self.restrictions;
3712 self.restrictions = r;
3714 self.restrictions = old;
3719 /// Parse an expression, subject to the given restrictions
3720 fn parse_expr_res(&mut self, r: Restrictions,
3721 already_parsed_attrs: Option<ThinVec<Attribute>>)
3722 -> PResult<'a, P<Expr>> {
3723 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3726 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3727 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3728 if self.eat(&token::Eq) {
3729 Ok(Some(self.parse_expr()?))
3731 Ok(Some(self.parse_expr()?))
3737 /// Parse patterns, separated by '|' s
3738 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3739 let mut pats = Vec::new();
3741 pats.push(self.parse_top_level_pat()?);
3743 if self.token == token::OrOr {
3744 let mut err = self.struct_span_err(self.span,
3745 "unexpected token `||` after pattern");
3746 err.span_suggestion_with_applicability(
3748 "use a single `|` to specify multiple patterns",
3750 Applicability::MachineApplicable
3754 } else if self.eat(&token::BinOp(token::Or)) {
3762 // Parses a parenthesized list of patterns like
3763 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3764 // - a vector of the patterns that were parsed
3765 // - an option indicating the index of the `..` element
3766 // - a boolean indicating whether a trailing comma was present.
3767 // Trailing commas are significant because (p) and (p,) are different patterns.
3768 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3769 self.expect(&token::OpenDelim(token::Paren))?;
3770 let result = self.parse_pat_list()?;
3771 self.expect(&token::CloseDelim(token::Paren))?;
3775 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3776 let mut fields = Vec::new();
3777 let mut ddpos = None;
3778 let mut trailing_comma = false;
3780 if self.eat(&token::DotDot) {
3781 if ddpos.is_none() {
3782 ddpos = Some(fields.len());
3784 // Emit a friendly error, ignore `..` and continue parsing
3785 self.span_err(self.prev_span,
3786 "`..` can only be used once per tuple or tuple struct pattern");
3788 } else if !self.check(&token::CloseDelim(token::Paren)) {
3789 fields.push(self.parse_pat(None)?);
3794 trailing_comma = self.eat(&token::Comma);
3795 if !trailing_comma {
3800 if ddpos == Some(fields.len()) && trailing_comma {
3801 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3802 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3805 Ok((fields, ddpos, trailing_comma))
3808 fn parse_pat_vec_elements(
3810 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3811 let mut before = Vec::new();
3812 let mut slice = None;
3813 let mut after = Vec::new();
3814 let mut first = true;
3815 let mut before_slice = true;
3817 while self.token != token::CloseDelim(token::Bracket) {
3821 self.expect(&token::Comma)?;
3823 if self.token == token::CloseDelim(token::Bracket)
3824 && (before_slice || !after.is_empty()) {
3830 if self.eat(&token::DotDot) {
3832 if self.check(&token::Comma) ||
3833 self.check(&token::CloseDelim(token::Bracket)) {
3834 slice = Some(P(Pat {
3835 id: ast::DUMMY_NODE_ID,
3836 node: PatKind::Wild,
3837 span: self.prev_span,
3839 before_slice = false;
3845 let subpat = self.parse_pat(None)?;
3846 if before_slice && self.eat(&token::DotDot) {
3847 slice = Some(subpat);
3848 before_slice = false;
3849 } else if before_slice {
3850 before.push(subpat);
3856 Ok((before, slice, after))
3862 attrs: Vec<Attribute>
3863 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3864 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3866 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3867 // Parsing a pattern of the form "fieldname: pat"
3868 let fieldname = self.parse_field_name()?;
3870 let pat = self.parse_pat(None)?;
3872 (pat, fieldname, false)
3874 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3875 let is_box = self.eat_keyword(keywords::Box);
3876 let boxed_span = self.span;
3877 let is_ref = self.eat_keyword(keywords::Ref);
3878 let is_mut = self.eat_keyword(keywords::Mut);
3879 let fieldname = self.parse_ident()?;
3880 hi = self.prev_span;
3882 let bind_type = match (is_ref, is_mut) {
3883 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3884 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3885 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3886 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3888 let fieldpat = P(Pat {
3889 id: ast::DUMMY_NODE_ID,
3890 node: PatKind::Ident(bind_type, fieldname, None),
3891 span: boxed_span.to(hi),
3894 let subpat = if is_box {
3896 id: ast::DUMMY_NODE_ID,
3897 node: PatKind::Box(fieldpat),
3903 (subpat, fieldname, true)
3906 Ok(source_map::Spanned {
3908 node: ast::FieldPat {
3912 attrs: attrs.into(),
3917 /// Parse the fields of a struct-like pattern
3918 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3919 let mut fields = Vec::new();
3920 let mut etc = false;
3921 let mut ate_comma = true;
3922 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3923 let mut etc_span = None;
3925 while self.token != token::CloseDelim(token::Brace) {
3926 let attrs = self.parse_outer_attributes()?;
3929 // check that a comma comes after every field
3931 let err = self.struct_span_err(self.prev_span, "expected `,`");
3932 if let Some(mut delayed) = delayed_err {
3939 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3941 let mut etc_sp = self.span;
3943 if self.token == token::DotDotDot { // Issue #46718
3944 // Accept `...` as if it were `..` to avoid further errors
3945 let mut err = self.struct_span_err(self.span,
3946 "expected field pattern, found `...`");
3947 err.span_suggestion_with_applicability(
3949 "to omit remaining fields, use one fewer `.`",
3951 Applicability::MachineApplicable
3955 self.bump(); // `..` || `...`
3957 if self.token == token::CloseDelim(token::Brace) {
3958 etc_span = Some(etc_sp);
3961 let token_str = self.this_token_descr();
3962 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3964 err.span_label(self.span, "expected `}`");
3965 let mut comma_sp = None;
3966 if self.token == token::Comma { // Issue #49257
3967 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3968 err.span_label(etc_sp,
3969 "`..` must be at the end and cannot have a trailing comma");
3970 comma_sp = Some(self.span);
3975 etc_span = Some(etc_sp.until(self.span));
3976 if self.token == token::CloseDelim(token::Brace) {
3977 // If the struct looks otherwise well formed, recover and continue.
3978 if let Some(sp) = comma_sp {
3979 err.span_suggestion_short_with_applicability(
3981 "remove this comma",
3983 Applicability::MachineApplicable,
3988 } else if self.token.is_ident() && ate_comma {
3989 // Accept fields coming after `..,`.
3990 // This way we avoid "pattern missing fields" errors afterwards.
3991 // We delay this error until the end in order to have a span for a
3993 if let Some(mut delayed_err) = delayed_err {
3997 delayed_err = Some(err);
4000 if let Some(mut err) = delayed_err {
4007 fields.push(match self.parse_pat_field(lo, attrs) {
4010 if let Some(mut delayed_err) = delayed_err {
4016 ate_comma = self.eat(&token::Comma);
4019 if let Some(mut err) = delayed_err {
4020 if let Some(etc_span) = etc_span {
4021 err.multipart_suggestion(
4022 "move the `..` to the end of the field list",
4024 (etc_span, String::new()),
4025 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4031 return Ok((fields, etc));
4034 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4035 if self.token.is_path_start() {
4037 let (qself, path) = if self.eat_lt() {
4038 // Parse a qualified path
4039 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4042 // Parse an unqualified path
4043 (None, self.parse_path(PathStyle::Expr)?)
4045 let hi = self.prev_span;
4046 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4048 self.parse_literal_maybe_minus()
4052 // helper function to decide whether to parse as ident binding or to try to do
4053 // something more complex like range patterns
4054 fn parse_as_ident(&mut self) -> bool {
4055 self.look_ahead(1, |t| match *t {
4056 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4057 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4058 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4059 // range pattern branch
4060 token::DotDot => None,
4062 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4063 token::Comma | token::CloseDelim(token::Bracket) => true,
4068 /// A wrapper around `parse_pat` with some special error handling for the
4069 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4070 /// to subpatterns within such).
4071 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4072 let pat = self.parse_pat(None)?;
4073 if self.token == token::Comma {
4074 // An unexpected comma after a top-level pattern is a clue that the
4075 // user (perhaps more accustomed to some other language) forgot the
4076 // parentheses in what should have been a tuple pattern; return a
4077 // suggestion-enhanced error here rather than choking on the comma
4079 let comma_span = self.span;
4081 if let Err(mut err) = self.parse_pat_list() {
4082 // We didn't expect this to work anyway; we just wanted
4083 // to advance to the end of the comma-sequence so we know
4084 // the span to suggest parenthesizing
4087 let seq_span = pat.span.to(self.prev_span);
4088 let mut err = self.struct_span_err(comma_span,
4089 "unexpected `,` in pattern");
4090 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4091 err.span_suggestion_with_applicability(
4093 "try adding parentheses",
4094 format!("({})", seq_snippet),
4095 Applicability::MachineApplicable
4103 /// Parse a pattern.
4104 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4105 self.parse_pat_with_range_pat(true, expected)
4108 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
4110 fn parse_pat_with_range_pat(
4112 allow_range_pat: bool,
4113 expected: Option<&'static str>,
4114 ) -> PResult<'a, P<Pat>> {
4115 maybe_whole!(self, NtPat, |x| x);
4120 token::BinOp(token::And) | token::AndAnd => {
4121 // Parse &pat / &mut pat
4123 let mutbl = self.parse_mutability();
4124 if let token::Lifetime(ident) = self.token {
4125 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4127 err.span_label(self.span, "unexpected lifetime");
4130 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4131 pat = PatKind::Ref(subpat, mutbl);
4133 token::OpenDelim(token::Paren) => {
4134 // Parse (pat,pat,pat,...) as tuple pattern
4135 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4136 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4137 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4139 PatKind::Tuple(fields, ddpos)
4142 token::OpenDelim(token::Bracket) => {
4143 // Parse [pat,pat,...] as slice pattern
4145 let (before, slice, after) = self.parse_pat_vec_elements()?;
4146 self.expect(&token::CloseDelim(token::Bracket))?;
4147 pat = PatKind::Slice(before, slice, after);
4149 // At this point, token != &, &&, (, [
4150 _ => if self.eat_keyword(keywords::Underscore) {
4152 pat = PatKind::Wild;
4153 } else if self.eat_keyword(keywords::Mut) {
4154 // Parse mut ident @ pat / mut ref ident @ pat
4155 let mutref_span = self.prev_span.to(self.span);
4156 let binding_mode = if self.eat_keyword(keywords::Ref) {
4158 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4159 .span_suggestion_with_applicability(
4161 "try switching the order",
4163 Applicability::MachineApplicable
4165 BindingMode::ByRef(Mutability::Mutable)
4167 BindingMode::ByValue(Mutability::Mutable)
4169 pat = self.parse_pat_ident(binding_mode)?;
4170 } else if self.eat_keyword(keywords::Ref) {
4171 // Parse ref ident @ pat / ref mut ident @ pat
4172 let mutbl = self.parse_mutability();
4173 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4174 } else if self.eat_keyword(keywords::Box) {
4176 let subpat = self.parse_pat_with_range_pat(false, None)?;
4177 pat = PatKind::Box(subpat);
4178 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4179 self.parse_as_ident() {
4180 // Parse ident @ pat
4181 // This can give false positives and parse nullary enums,
4182 // they are dealt with later in resolve
4183 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4184 pat = self.parse_pat_ident(binding_mode)?;
4185 } else if self.token.is_path_start() {
4186 // Parse pattern starting with a path
4187 let (qself, path) = if self.eat_lt() {
4188 // Parse a qualified path
4189 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4192 // Parse an unqualified path
4193 (None, self.parse_path(PathStyle::Expr)?)
4196 token::Not if qself.is_none() => {
4197 // Parse macro invocation
4199 let (delim, tts) = self.expect_delimited_token_tree()?;
4200 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4201 pat = PatKind::Mac(mac);
4203 token::DotDotDot | token::DotDotEq | token::DotDot => {
4204 let end_kind = match self.token {
4205 token::DotDot => RangeEnd::Excluded,
4206 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4207 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4208 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4211 let op_span = self.span;
4213 let span = lo.to(self.prev_span);
4214 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4216 let end = self.parse_pat_range_end()?;
4217 let op = Spanned { span: op_span, node: end_kind };
4218 pat = PatKind::Range(begin, end, op);
4220 token::OpenDelim(token::Brace) => {
4221 if qself.is_some() {
4222 let msg = "unexpected `{` after qualified path";
4223 let mut err = self.fatal(msg);
4224 err.span_label(self.span, msg);
4227 // Parse struct pattern
4229 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4231 self.recover_stmt();
4235 pat = PatKind::Struct(path, fields, etc);
4237 token::OpenDelim(token::Paren) => {
4238 if qself.is_some() {
4239 let msg = "unexpected `(` after qualified path";
4240 let mut err = self.fatal(msg);
4241 err.span_label(self.span, msg);
4244 // Parse tuple struct or enum pattern
4245 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4246 pat = PatKind::TupleStruct(path, fields, ddpos)
4248 _ => pat = PatKind::Path(qself, path),
4251 // Try to parse everything else as literal with optional minus
4252 match self.parse_literal_maybe_minus() {
4254 let op_span = self.span;
4255 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4256 self.check(&token::DotDotDot) {
4257 let end_kind = if self.eat(&token::DotDotDot) {
4258 RangeEnd::Included(RangeSyntax::DotDotDot)
4259 } else if self.eat(&token::DotDotEq) {
4260 RangeEnd::Included(RangeSyntax::DotDotEq)
4261 } else if self.eat(&token::DotDot) {
4264 panic!("impossible case: we already matched \
4265 on a range-operator token")
4267 let end = self.parse_pat_range_end()?;
4268 let op = Spanned { span: op_span, node: end_kind };
4269 pat = PatKind::Range(begin, end, op);
4271 pat = PatKind::Lit(begin);
4275 self.cancel(&mut err);
4276 let expected = expected.unwrap_or("pattern");
4278 "expected {}, found {}",
4280 self.this_token_descr(),
4282 let mut err = self.fatal(&msg);
4283 err.span_label(self.span, format!("expected {}", expected));
4290 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4291 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4293 if !allow_range_pat {
4296 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4298 PatKind::Range(..) => {
4299 let mut err = self.struct_span_err(
4301 "the range pattern here has ambiguous interpretation",
4303 err.span_suggestion_with_applicability(
4305 "add parentheses to clarify the precedence",
4306 format!("({})", pprust::pat_to_string(&pat)),
4307 // "ambiguous interpretation" implies that we have to be guessing
4308 Applicability::MaybeIncorrect
4319 /// Parse ident or ident @ pat
4320 /// used by the copy foo and ref foo patterns to give a good
4321 /// error message when parsing mistakes like ref foo(a,b)
4322 fn parse_pat_ident(&mut self,
4323 binding_mode: ast::BindingMode)
4324 -> PResult<'a, PatKind> {
4325 let ident = self.parse_ident()?;
4326 let sub = if self.eat(&token::At) {
4327 Some(self.parse_pat(Some("binding pattern"))?)
4332 // just to be friendly, if they write something like
4334 // we end up here with ( as the current token. This shortly
4335 // leads to a parse error. Note that if there is no explicit
4336 // binding mode then we do not end up here, because the lookahead
4337 // will direct us over to parse_enum_variant()
4338 if self.token == token::OpenDelim(token::Paren) {
4339 return Err(self.span_fatal(
4341 "expected identifier, found enum pattern"))
4344 Ok(PatKind::Ident(binding_mode, ident, sub))
4347 /// Parse a local variable declaration
4348 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4349 let lo = self.prev_span;
4350 let pat = self.parse_top_level_pat()?;
4352 let (err, ty) = if self.eat(&token::Colon) {
4353 // Save the state of the parser before parsing type normally, in case there is a `:`
4354 // instead of an `=` typo.
4355 let parser_snapshot_before_type = self.clone();
4356 let colon_sp = self.prev_span;
4357 match self.parse_ty() {
4358 Ok(ty) => (None, Some(ty)),
4360 // Rewind to before attempting to parse the type and continue parsing
4361 let parser_snapshot_after_type = self.clone();
4362 mem::replace(self, parser_snapshot_before_type);
4364 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4365 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4366 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4372 let init = match (self.parse_initializer(err.is_some()), err) {
4373 (Ok(init), None) => { // init parsed, ty parsed
4376 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4377 // Could parse the type as if it were the initializer, it is likely there was a
4378 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4379 err.span_suggestion_short_with_applicability(
4381 "use `=` if you meant to assign",
4383 Applicability::MachineApplicable
4386 // As this was parsed successfully, continue as if the code has been fixed for the
4387 // rest of the file. It will still fail due to the emitted error, but we avoid
4391 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4393 // Couldn't parse the type nor the initializer, only raise the type error and
4394 // return to the parser state before parsing the type as the initializer.
4395 // let x: <parse_error>;
4396 mem::replace(self, snapshot);
4399 (Err(err), None) => { // init error, ty parsed
4400 // Couldn't parse the initializer and we're not attempting to recover a failed
4401 // parse of the type, return the error.
4405 let hi = if self.token == token::Semi {
4414 id: ast::DUMMY_NODE_ID,
4420 /// Parse a structure field
4421 fn parse_name_and_ty(&mut self,
4424 attrs: Vec<Attribute>)
4425 -> PResult<'a, StructField> {
4426 let name = self.parse_ident()?;
4427 self.expect(&token::Colon)?;
4428 let ty = self.parse_ty()?;
4430 span: lo.to(self.prev_span),
4433 id: ast::DUMMY_NODE_ID,
4439 /// Emit an expected item after attributes error.
4440 fn expected_item_err(&self, attrs: &[Attribute]) {
4441 let message = match attrs.last() {
4442 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4443 _ => "expected item after attributes",
4446 self.span_err(self.prev_span, message);
4449 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4450 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4451 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4452 Ok(self.parse_stmt_(true))
4455 // Eat tokens until we can be relatively sure we reached the end of the
4456 // statement. This is something of a best-effort heuristic.
4458 // We terminate when we find an unmatched `}` (without consuming it).
4459 fn recover_stmt(&mut self) {
4460 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4463 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4464 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4465 // approximate - it can mean we break too early due to macros, but that
4466 // should only lead to sub-optimal recovery, not inaccurate parsing).
4468 // If `break_on_block` is `Break`, then we will stop consuming tokens
4469 // after finding (and consuming) a brace-delimited block.
4470 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4471 let mut brace_depth = 0;
4472 let mut bracket_depth = 0;
4473 let mut in_block = false;
4474 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4475 break_on_semi, break_on_block);
4477 debug!("recover_stmt_ loop {:?}", self.token);
4479 token::OpenDelim(token::DelimToken::Brace) => {
4482 if break_on_block == BlockMode::Break &&
4484 bracket_depth == 0 {
4488 token::OpenDelim(token::DelimToken::Bracket) => {
4492 token::CloseDelim(token::DelimToken::Brace) => {
4493 if brace_depth == 0 {
4494 debug!("recover_stmt_ return - close delim {:?}", self.token);
4499 if in_block && bracket_depth == 0 && brace_depth == 0 {
4500 debug!("recover_stmt_ return - block end {:?}", self.token);
4504 token::CloseDelim(token::DelimToken::Bracket) => {
4506 if bracket_depth < 0 {
4512 debug!("recover_stmt_ return - Eof");
4517 if break_on_semi == SemiColonMode::Break &&
4519 bracket_depth == 0 {
4520 debug!("recover_stmt_ return - Semi");
4531 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4532 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4534 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4539 fn is_async_block(&mut self) -> bool {
4540 self.token.is_keyword(keywords::Async) &&
4543 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4544 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4546 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4551 fn is_do_catch_block(&mut self) -> bool {
4552 self.token.is_keyword(keywords::Do) &&
4553 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4554 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4555 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4558 fn is_try_block(&mut self) -> bool {
4559 self.token.is_keyword(keywords::Try) &&
4560 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4561 self.span.rust_2018() &&
4562 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4563 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4566 fn is_union_item(&self) -> bool {
4567 self.token.is_keyword(keywords::Union) &&
4568 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4571 fn is_crate_vis(&self) -> bool {
4572 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4575 fn is_extern_non_path(&self) -> bool {
4576 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4579 fn is_existential_type_decl(&self) -> bool {
4580 self.token.is_keyword(keywords::Existential) &&
4581 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4584 fn is_auto_trait_item(&mut self) -> bool {
4586 (self.token.is_keyword(keywords::Auto)
4587 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4588 || // unsafe auto trait
4589 (self.token.is_keyword(keywords::Unsafe) &&
4590 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4591 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4594 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4595 -> PResult<'a, Option<P<Item>>> {
4596 let token_lo = self.span;
4597 let (ident, def) = match self.token {
4598 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4600 let ident = self.parse_ident()?;
4601 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4602 match self.parse_token_tree() {
4603 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4604 _ => unreachable!(),
4606 } else if self.check(&token::OpenDelim(token::Paren)) {
4607 let args = self.parse_token_tree();
4608 let body = if self.check(&token::OpenDelim(token::Brace)) {
4609 self.parse_token_tree()
4614 TokenStream::concat(vec![
4616 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4624 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4626 token::Ident(ident, _) if ident.name == "macro_rules" &&
4627 self.look_ahead(1, |t| *t == token::Not) => {
4628 let prev_span = self.prev_span;
4629 self.complain_if_pub_macro(&vis.node, prev_span);
4633 let ident = self.parse_ident()?;
4634 let (delim, tokens) = self.expect_delimited_token_tree()?;
4635 if delim != MacDelimiter::Brace {
4636 if !self.eat(&token::Semi) {
4637 let msg = "macros that expand to items must either \
4638 be surrounded with braces or followed by a semicolon";
4639 self.span_err(self.prev_span, msg);
4643 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4645 _ => return Ok(None),
4648 let span = lo.to(self.prev_span);
4649 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4652 fn parse_stmt_without_recovery(&mut self,
4653 macro_legacy_warnings: bool)
4654 -> PResult<'a, Option<Stmt>> {
4655 maybe_whole!(self, NtStmt, |x| Some(x));
4657 let attrs = self.parse_outer_attributes()?;
4660 Ok(Some(if self.eat_keyword(keywords::Let) {
4662 id: ast::DUMMY_NODE_ID,
4663 node: StmtKind::Local(self.parse_local(attrs.into())?),
4664 span: lo.to(self.prev_span),
4666 } else if let Some(macro_def) = self.eat_macro_def(
4668 &source_map::respan(lo, VisibilityKind::Inherited),
4672 id: ast::DUMMY_NODE_ID,
4673 node: StmtKind::Item(macro_def),
4674 span: lo.to(self.prev_span),
4676 // Starts like a simple path, being careful to avoid contextual keywords
4677 // such as a union items, item with `crate` visibility or auto trait items.
4678 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4679 // like a path (1 token), but it fact not a path.
4680 // `union::b::c` - path, `union U { ... }` - not a path.
4681 // `crate::b::c` - path, `crate struct S;` - not a path.
4682 // `extern::b::c` - path, `extern crate c;` - not a path.
4683 } else if self.token.is_path_start() &&
4684 !self.token.is_qpath_start() &&
4685 !self.is_union_item() &&
4686 !self.is_crate_vis() &&
4687 !self.is_extern_non_path() &&
4688 !self.is_existential_type_decl() &&
4689 !self.is_auto_trait_item() {
4690 let pth = self.parse_path(PathStyle::Expr)?;
4692 if !self.eat(&token::Not) {
4693 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4694 self.parse_struct_expr(lo, pth, ThinVec::new())?
4696 let hi = self.prev_span;
4697 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4700 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4701 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4702 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4705 return Ok(Some(Stmt {
4706 id: ast::DUMMY_NODE_ID,
4707 node: StmtKind::Expr(expr),
4708 span: lo.to(self.prev_span),
4712 // it's a macro invocation
4713 let id = match self.token {
4714 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4715 _ => self.parse_ident()?,
4718 // check that we're pointing at delimiters (need to check
4719 // again after the `if`, because of `parse_ident`
4720 // consuming more tokens).
4722 token::OpenDelim(_) => {}
4724 // we only expect an ident if we didn't parse one
4726 let ident_str = if id.name == keywords::Invalid.name() {
4731 let tok_str = self.this_token_descr();
4732 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4735 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4740 let (delim, tts) = self.expect_delimited_token_tree()?;
4741 let hi = self.prev_span;
4743 let style = if delim == MacDelimiter::Brace {
4744 MacStmtStyle::Braces
4746 MacStmtStyle::NoBraces
4749 if id.name == keywords::Invalid.name() {
4750 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4751 let node = if delim == MacDelimiter::Brace ||
4752 self.token == token::Semi || self.token == token::Eof {
4753 StmtKind::Mac(P((mac, style, attrs.into())))
4755 // We used to incorrectly stop parsing macro-expanded statements here.
4756 // If the next token will be an error anyway but could have parsed with the
4757 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4758 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4759 // These can continue an expression, so we can't stop parsing and warn.
4760 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4761 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4762 token::BinOp(token::And) | token::BinOp(token::Or) |
4763 token::AndAnd | token::OrOr |
4764 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4767 self.warn_missing_semicolon();
4768 StmtKind::Mac(P((mac, style, attrs.into())))
4770 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4771 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4772 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4776 id: ast::DUMMY_NODE_ID,
4781 // if it has a special ident, it's definitely an item
4783 // Require a semicolon or braces.
4784 if style != MacStmtStyle::Braces {
4785 if !self.eat(&token::Semi) {
4786 self.span_err(self.prev_span,
4787 "macros that expand to items must \
4788 either be surrounded with braces or \
4789 followed by a semicolon");
4792 let span = lo.to(hi);
4794 id: ast::DUMMY_NODE_ID,
4796 node: StmtKind::Item({
4798 span, id /*id is good here*/,
4799 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4800 respan(lo, VisibilityKind::Inherited),
4806 // FIXME: Bad copy of attrs
4807 let old_directory_ownership =
4808 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4809 let item = self.parse_item_(attrs.clone(), false, true)?;
4810 self.directory.ownership = old_directory_ownership;
4814 id: ast::DUMMY_NODE_ID,
4815 span: lo.to(i.span),
4816 node: StmtKind::Item(i),
4819 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4820 if !attrs.is_empty() {
4821 if s.prev_token_kind == PrevTokenKind::DocComment {
4822 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4823 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4824 s.span_err(s.span, "expected statement after outer attribute");
4829 // Do not attempt to parse an expression if we're done here.
4830 if self.token == token::Semi {
4831 unused_attrs(&attrs, self);
4836 if self.token == token::CloseDelim(token::Brace) {
4837 unused_attrs(&attrs, self);
4841 // Remainder are line-expr stmts.
4842 let e = self.parse_expr_res(
4843 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4845 id: ast::DUMMY_NODE_ID,
4846 span: lo.to(e.span),
4847 node: StmtKind::Expr(e),
4854 /// Is this expression a successfully-parsed statement?
4855 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4856 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4857 !classify::expr_requires_semi_to_be_stmt(e)
4860 /// Parse a block. No inner attrs are allowed.
4861 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4862 maybe_whole!(self, NtBlock, |x| x);
4866 if !self.eat(&token::OpenDelim(token::Brace)) {
4868 let tok = self.this_token_descr();
4869 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4870 let do_not_suggest_help =
4871 self.token.is_keyword(keywords::In) || self.token == token::Colon;
4873 if self.token.is_ident_named("and") {
4874 e.span_suggestion_short_with_applicability(
4876 "use `&&` instead of `and` for the boolean operator",
4878 Applicability::MaybeIncorrect,
4881 if self.token.is_ident_named("or") {
4882 e.span_suggestion_short_with_applicability(
4884 "use `||` instead of `or` for the boolean operator",
4886 Applicability::MaybeIncorrect,
4890 // Check to see if the user has written something like
4895 // Which is valid in other languages, but not Rust.
4896 match self.parse_stmt_without_recovery(false) {
4898 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4899 || do_not_suggest_help {
4900 // if the next token is an open brace (e.g., `if a b {`), the place-
4901 // inside-a-block suggestion would be more likely wrong than right
4902 e.span_label(sp, "expected `{`");
4905 let mut stmt_span = stmt.span;
4906 // expand the span to include the semicolon, if it exists
4907 if self.eat(&token::Semi) {
4908 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4910 let sugg = pprust::to_string(|s| {
4911 use print::pprust::{PrintState, INDENT_UNIT};
4912 s.ibox(INDENT_UNIT)?;
4914 s.print_stmt(&stmt)?;
4915 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4917 e.span_suggestion_with_applicability(
4919 "try placing this code inside a block",
4921 // speculative, has been misleading in the past (closed Issue #46836)
4922 Applicability::MaybeIncorrect
4926 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4927 self.cancel(&mut e);
4931 e.span_label(sp, "expected `{`");
4935 self.parse_block_tail(lo, BlockCheckMode::Default)
4938 /// Parse a block. Inner attrs are allowed.
4939 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4940 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4943 self.expect(&token::OpenDelim(token::Brace))?;
4944 Ok((self.parse_inner_attributes()?,
4945 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4948 /// Parse the rest of a block expression or function body
4949 /// Precondition: already parsed the '{'.
4950 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4951 let mut stmts = vec![];
4952 let mut recovered = false;
4954 while !self.eat(&token::CloseDelim(token::Brace)) {
4955 let stmt = match self.parse_full_stmt(false) {
4958 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4959 self.eat(&token::CloseDelim(token::Brace));
4965 if let Some(stmt) = stmt {
4967 } else if self.token == token::Eof {
4970 // Found only `;` or `}`.
4976 id: ast::DUMMY_NODE_ID,
4978 span: lo.to(self.prev_span),
4983 /// Parse a statement, including the trailing semicolon.
4984 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4985 // skip looking for a trailing semicolon when we have an interpolated statement
4986 maybe_whole!(self, NtStmt, |x| Some(x));
4988 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4990 None => return Ok(None),
4994 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4995 // expression without semicolon
4996 if classify::expr_requires_semi_to_be_stmt(expr) {
4997 // Just check for errors and recover; do not eat semicolon yet.
4999 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5002 self.recover_stmt();
5006 StmtKind::Local(..) => {
5007 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5008 if macro_legacy_warnings && self.token != token::Semi {
5009 self.warn_missing_semicolon();
5011 self.expect_one_of(&[], &[token::Semi])?;
5017 if self.eat(&token::Semi) {
5018 stmt = stmt.add_trailing_semicolon();
5021 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5025 fn warn_missing_semicolon(&self) {
5026 self.diagnostic().struct_span_warn(self.span, {
5027 &format!("expected `;`, found {}", self.this_token_descr())
5029 "This was erroneously allowed and will become a hard error in a future release"
5033 fn err_dotdotdot_syntax(&self, span: Span) {
5034 self.diagnostic().struct_span_err(span, {
5035 "unexpected token: `...`"
5036 }).span_suggestion_with_applicability(
5037 span, "use `..` for an exclusive range", "..".to_owned(),
5038 Applicability::MaybeIncorrect
5039 ).span_suggestion_with_applicability(
5040 span, "or `..=` for an inclusive range", "..=".to_owned(),
5041 Applicability::MaybeIncorrect
5045 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5046 // BOUND = TY_BOUND | LT_BOUND
5047 // LT_BOUND = LIFETIME (e.g. `'a`)
5048 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5049 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
5050 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
5051 let mut bounds = Vec::new();
5053 // This needs to be synchronized with `Token::can_begin_bound`.
5054 let is_bound_start = self.check_path() || self.check_lifetime() ||
5055 self.check(&token::Question) ||
5056 self.check_keyword(keywords::For) ||
5057 self.check(&token::OpenDelim(token::Paren));
5060 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5061 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5062 if self.token.is_lifetime() {
5063 if let Some(question_span) = question {
5064 self.span_err(question_span,
5065 "`?` may only modify trait bounds, not lifetime bounds");
5067 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5069 self.expect(&token::CloseDelim(token::Paren))?;
5070 self.span_err(self.prev_span,
5071 "parenthesized lifetime bounds are not supported");
5074 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5075 let path = self.parse_path(PathStyle::Type)?;
5077 self.expect(&token::CloseDelim(token::Paren))?;
5079 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
5080 let modifier = if question.is_some() {
5081 TraitBoundModifier::Maybe
5083 TraitBoundModifier::None
5085 bounds.push(GenericBound::Trait(poly_trait, modifier));
5091 if !allow_plus || !self.eat_plus() {
5099 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
5100 self.parse_generic_bounds_common(true)
5103 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5104 // BOUND = LT_BOUND (e.g. `'a`)
5105 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5106 let mut lifetimes = Vec::new();
5107 while self.check_lifetime() {
5108 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5110 if !self.eat_plus() {
5117 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
5118 fn parse_ty_param(&mut self,
5119 preceding_attrs: Vec<Attribute>)
5120 -> PResult<'a, GenericParam> {
5121 let ident = self.parse_ident()?;
5123 // Parse optional colon and param bounds.
5124 let bounds = if self.eat(&token::Colon) {
5125 self.parse_generic_bounds()?
5130 let default = if self.eat(&token::Eq) {
5131 Some(self.parse_ty()?)
5138 id: ast::DUMMY_NODE_ID,
5139 attrs: preceding_attrs.into(),
5141 kind: GenericParamKind::Type {
5147 /// Parses the following grammar:
5148 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5149 fn parse_trait_item_assoc_ty(&mut self)
5150 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5151 let ident = self.parse_ident()?;
5152 let mut generics = self.parse_generics()?;
5154 // Parse optional colon and param bounds.
5155 let bounds = if self.eat(&token::Colon) {
5156 self.parse_generic_bounds()?
5160 generics.where_clause = self.parse_where_clause()?;
5162 let default = if self.eat(&token::Eq) {
5163 Some(self.parse_ty()?)
5167 self.expect(&token::Semi)?;
5169 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5172 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5173 /// trailing comma and erroneous trailing attributes.
5174 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5175 let mut lifetimes = Vec::new();
5176 let mut params = Vec::new();
5177 let mut seen_ty_param: Option<Span> = None;
5178 let mut last_comma_span = None;
5179 let mut bad_lifetime_pos = vec![];
5180 let mut suggestions = vec![];
5182 let attrs = self.parse_outer_attributes()?;
5183 if self.check_lifetime() {
5184 let lifetime = self.expect_lifetime();
5185 // Parse lifetime parameter.
5186 let bounds = if self.eat(&token::Colon) {
5187 self.parse_lt_param_bounds()
5191 lifetimes.push(ast::GenericParam {
5192 ident: lifetime.ident,
5194 attrs: attrs.into(),
5196 kind: ast::GenericParamKind::Lifetime,
5198 if let Some(sp) = seen_ty_param {
5199 let param_span = self.prev_span;
5200 let ate_comma = self.eat(&token::Comma);
5201 let remove_sp = if ate_comma {
5202 param_span.until(self.span)
5204 last_comma_span.unwrap_or(param_span).to(param_span)
5206 bad_lifetime_pos.push(param_span);
5208 if let Ok(snippet) = self.sess.source_map().span_to_snippet(param_span) {
5209 suggestions.push((remove_sp, String::new()));
5210 suggestions.push((sp.shrink_to_lo(), format!("{}, ", snippet)));
5213 last_comma_span = Some(self.prev_span);
5217 } else if self.check_ident() {
5218 // Parse type parameter.
5219 params.push(self.parse_ty_param(attrs)?);
5220 if seen_ty_param.is_none() {
5221 seen_ty_param = Some(self.prev_span);
5224 // Check for trailing attributes and stop parsing.
5225 if !attrs.is_empty() {
5226 let param_kind = if seen_ty_param.is_some() { "type" } else { "lifetime" };
5227 self.span_err(attrs[0].span,
5228 &format!("trailing attribute after {} parameters", param_kind));
5233 if !self.eat(&token::Comma) {
5236 last_comma_span = Some(self.prev_span);
5238 if !bad_lifetime_pos.is_empty() {
5239 let mut err = self.struct_span_err(
5241 "lifetime parameters must be declared prior to type parameters",
5243 if !suggestions.is_empty() {
5244 err.multipart_suggestion_with_applicability(
5245 "move the lifetime parameter prior to the first type parameter",
5247 Applicability::MachineApplicable,
5252 lifetimes.extend(params); // ensure the correct order of lifetimes and type params
5256 /// Parse a set of optional generic type parameter declarations. Where
5257 /// clauses are not parsed here, and must be added later via
5258 /// `parse_where_clause()`.
5260 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5261 /// | ( < lifetimes , typaramseq ( , )? > )
5262 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5263 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5264 maybe_whole!(self, NtGenerics, |x| x);
5266 let span_lo = self.span;
5268 let params = self.parse_generic_params()?;
5272 where_clause: WhereClause {
5273 id: ast::DUMMY_NODE_ID,
5274 predicates: Vec::new(),
5275 span: syntax_pos::DUMMY_SP,
5277 span: span_lo.to(self.prev_span),
5280 Ok(ast::Generics::default())
5284 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5285 /// possibly including trailing comma.
5286 fn parse_generic_args(&mut self)
5287 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5288 let mut args = Vec::new();
5289 let mut bindings = Vec::new();
5290 let mut seen_type = false;
5291 let mut seen_binding = false;
5293 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5294 // Parse lifetime argument.
5295 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5296 if seen_type || seen_binding {
5297 self.span_err(self.prev_span,
5298 "lifetime parameters must be declared prior to type parameters");
5300 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5301 // Parse associated type binding.
5303 let ident = self.parse_ident()?;
5305 let ty = self.parse_ty()?;
5306 bindings.push(TypeBinding {
5307 id: ast::DUMMY_NODE_ID,
5310 span: lo.to(self.prev_span),
5312 seen_binding = true;
5313 } else if self.check_type() {
5314 // Parse type argument.
5315 let ty_param = self.parse_ty()?;
5317 self.span_err(ty_param.span,
5318 "type parameters must be declared prior to associated type bindings");
5320 args.push(GenericArg::Type(ty_param));
5326 if !self.eat(&token::Comma) {
5330 Ok((args, bindings))
5333 /// Parses an optional `where` clause and places it in `generics`.
5335 /// ```ignore (only-for-syntax-highlight)
5336 /// where T : Trait<U, V> + 'b, 'a : 'b
5338 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5339 maybe_whole!(self, NtWhereClause, |x| x);
5341 let mut where_clause = WhereClause {
5342 id: ast::DUMMY_NODE_ID,
5343 predicates: Vec::new(),
5344 span: syntax_pos::DUMMY_SP,
5347 if !self.eat_keyword(keywords::Where) {
5348 return Ok(where_clause);
5350 let lo = self.prev_span;
5352 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5353 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5354 // change we parse those generics now, but report an error.
5355 if self.choose_generics_over_qpath() {
5356 let generics = self.parse_generics()?;
5357 self.span_err(generics.span,
5358 "generic parameters on `where` clauses are reserved for future use");
5363 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5364 let lifetime = self.expect_lifetime();
5365 // Bounds starting with a colon are mandatory, but possibly empty.
5366 self.expect(&token::Colon)?;
5367 let bounds = self.parse_lt_param_bounds();
5368 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5369 ast::WhereRegionPredicate {
5370 span: lo.to(self.prev_span),
5375 } else if self.check_type() {
5376 // Parse optional `for<'a, 'b>`.
5377 // This `for` is parsed greedily and applies to the whole predicate,
5378 // the bounded type can have its own `for` applying only to it.
5379 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5380 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5381 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5382 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5384 // Parse type with mandatory colon and (possibly empty) bounds,
5385 // or with mandatory equality sign and the second type.
5386 let ty = self.parse_ty()?;
5387 if self.eat(&token::Colon) {
5388 let bounds = self.parse_generic_bounds()?;
5389 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5390 ast::WhereBoundPredicate {
5391 span: lo.to(self.prev_span),
5392 bound_generic_params: lifetime_defs,
5397 // FIXME: Decide what should be used here, `=` or `==`.
5398 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5399 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5400 let rhs_ty = self.parse_ty()?;
5401 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5402 ast::WhereEqPredicate {
5403 span: lo.to(self.prev_span),
5406 id: ast::DUMMY_NODE_ID,
5410 return self.unexpected();
5416 if !self.eat(&token::Comma) {
5421 where_clause.span = lo.to(self.prev_span);
5425 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5426 -> PResult<'a, (Vec<Arg> , bool)> {
5427 self.expect(&token::OpenDelim(token::Paren))?;
5430 let mut variadic = false;
5431 let args: Vec<Option<Arg>> =
5432 self.parse_seq_to_before_end(
5433 &token::CloseDelim(token::Paren),
5434 SeqSep::trailing_allowed(token::Comma),
5436 if p.token == token::DotDotDot {
5440 if p.token != token::CloseDelim(token::Paren) {
5443 "`...` must be last in argument list for variadic function");
5447 let span = p.prev_span;
5448 if p.token == token::CloseDelim(token::Paren) {
5449 // continue parsing to present any further errors
5452 "only foreign functions are allowed to be variadic"
5454 Ok(Some(dummy_arg(span)))
5456 // this function definition looks beyond recovery, stop parsing
5458 "only foreign functions are allowed to be variadic");
5463 match p.parse_arg_general(named_args) {
5464 Ok(arg) => Ok(Some(arg)),
5467 let lo = p.prev_span;
5468 // Skip every token until next possible arg or end.
5469 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5470 // Create a placeholder argument for proper arg count (#34264).
5471 let span = lo.to(p.prev_span);
5472 Ok(Some(dummy_arg(span)))
5479 self.eat(&token::CloseDelim(token::Paren));
5481 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5483 if variadic && args.is_empty() {
5485 "variadic function must be declared with at least one named argument");
5488 Ok((args, variadic))
5491 /// Parse the argument list and result type of a function declaration
5492 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5494 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5495 let ret_ty = self.parse_ret_ty(true)?;
5504 /// Returns the parsed optional self argument and whether a self shortcut was used.
5505 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5506 let expect_ident = |this: &mut Self| match this.token {
5507 // Preserve hygienic context.
5508 token::Ident(ident, _) =>
5509 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5512 let isolated_self = |this: &mut Self, n| {
5513 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5514 this.look_ahead(n + 1, |t| t != &token::ModSep)
5517 // Parse optional self parameter of a method.
5518 // Only a limited set of initial token sequences is considered self parameters, anything
5519 // else is parsed as a normal function parameter list, so some lookahead is required.
5520 let eself_lo = self.span;
5521 let (eself, eself_ident, eself_hi) = match self.token {
5522 token::BinOp(token::And) => {
5528 (if isolated_self(self, 1) {
5530 SelfKind::Region(None, Mutability::Immutable)
5531 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5532 isolated_self(self, 2) {
5535 SelfKind::Region(None, Mutability::Mutable)
5536 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5537 isolated_self(self, 2) {
5539 let lt = self.expect_lifetime();
5540 SelfKind::Region(Some(lt), Mutability::Immutable)
5541 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5542 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5543 isolated_self(self, 3) {
5545 let lt = self.expect_lifetime();
5547 SelfKind::Region(Some(lt), Mutability::Mutable)
5550 }, expect_ident(self), self.prev_span)
5552 token::BinOp(token::Star) => {
5557 // Emit special error for `self` cases.
5558 (if isolated_self(self, 1) {
5560 self.span_err(self.span, "cannot pass `self` by raw pointer");
5561 SelfKind::Value(Mutability::Immutable)
5562 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5563 isolated_self(self, 2) {
5566 self.span_err(self.span, "cannot pass `self` by raw pointer");
5567 SelfKind::Value(Mutability::Immutable)
5570 }, expect_ident(self), self.prev_span)
5572 token::Ident(..) => {
5573 if isolated_self(self, 0) {
5576 let eself_ident = expect_ident(self);
5577 let eself_hi = self.prev_span;
5578 (if self.eat(&token::Colon) {
5579 let ty = self.parse_ty()?;
5580 SelfKind::Explicit(ty, Mutability::Immutable)
5582 SelfKind::Value(Mutability::Immutable)
5583 }, eself_ident, eself_hi)
5584 } else if self.token.is_keyword(keywords::Mut) &&
5585 isolated_self(self, 1) {
5589 let eself_ident = expect_ident(self);
5590 let eself_hi = self.prev_span;
5591 (if self.eat(&token::Colon) {
5592 let ty = self.parse_ty()?;
5593 SelfKind::Explicit(ty, Mutability::Mutable)
5595 SelfKind::Value(Mutability::Mutable)
5596 }, eself_ident, eself_hi)
5601 _ => return Ok(None),
5604 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5605 Ok(Some(Arg::from_self(eself, eself_ident)))
5608 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5609 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5610 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5612 self.expect(&token::OpenDelim(token::Paren))?;
5614 // Parse optional self argument
5615 let self_arg = self.parse_self_arg()?;
5617 // Parse the rest of the function parameter list.
5618 let sep = SeqSep::trailing_allowed(token::Comma);
5619 let fn_inputs = if let Some(self_arg) = self_arg {
5620 if self.check(&token::CloseDelim(token::Paren)) {
5622 } else if self.eat(&token::Comma) {
5623 let mut fn_inputs = vec![self_arg];
5624 fn_inputs.append(&mut self.parse_seq_to_before_end(
5625 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5629 return self.unexpected();
5632 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5635 // Parse closing paren and return type.
5636 self.expect(&token::CloseDelim(token::Paren))?;
5639 output: self.parse_ret_ty(true)?,
5644 // parse the |arg, arg| header on a lambda
5645 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5646 let inputs_captures = {
5647 if self.eat(&token::OrOr) {
5650 self.expect(&token::BinOp(token::Or))?;
5651 let args = self.parse_seq_to_before_tokens(
5652 &[&token::BinOp(token::Or), &token::OrOr],
5653 SeqSep::trailing_allowed(token::Comma),
5654 TokenExpectType::NoExpect,
5655 |p| p.parse_fn_block_arg()
5661 let output = self.parse_ret_ty(true)?;
5664 inputs: inputs_captures,
5670 /// Parse the name and optional generic types of a function header.
5671 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5672 let id = self.parse_ident()?;
5673 let generics = self.parse_generics()?;
5677 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5678 attrs: Vec<Attribute>) -> P<Item> {
5682 id: ast::DUMMY_NODE_ID,
5690 /// Parse an item-position function declaration.
5691 fn parse_item_fn(&mut self,
5694 constness: Spanned<Constness>,
5696 -> PResult<'a, ItemInfo> {
5697 let (ident, mut generics) = self.parse_fn_header()?;
5698 let decl = self.parse_fn_decl(false)?;
5699 generics.where_clause = self.parse_where_clause()?;
5700 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5701 let header = FnHeader { unsafety, asyncness, constness, abi };
5702 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5705 /// true if we are looking at `const ID`, false for things like `const fn` etc
5706 fn is_const_item(&mut self) -> bool {
5707 self.token.is_keyword(keywords::Const) &&
5708 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5709 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5712 /// parses all the "front matter" for a `fn` declaration, up to
5713 /// and including the `fn` keyword:
5717 /// - `const unsafe fn`
5720 fn parse_fn_front_matter(&mut self)
5728 let is_const_fn = self.eat_keyword(keywords::Const);
5729 let const_span = self.prev_span;
5730 let unsafety = self.parse_unsafety();
5731 let asyncness = self.parse_asyncness();
5732 let (constness, unsafety, abi) = if is_const_fn {
5733 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5735 let abi = if self.eat_keyword(keywords::Extern) {
5736 self.parse_opt_abi()?.unwrap_or(Abi::C)
5740 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5742 self.expect_keyword(keywords::Fn)?;
5743 Ok((constness, unsafety, asyncness, abi))
5746 /// Parse an impl item.
5747 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5748 maybe_whole!(self, NtImplItem, |x| x);
5749 let attrs = self.parse_outer_attributes()?;
5750 let (mut item, tokens) = self.collect_tokens(|this| {
5751 this.parse_impl_item_(at_end, attrs)
5754 // See `parse_item` for why this clause is here.
5755 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5756 item.tokens = Some(tokens);
5761 fn parse_impl_item_(&mut self,
5763 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5765 let vis = self.parse_visibility(false)?;
5766 let defaultness = self.parse_defaultness();
5767 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5768 let (name, alias, generics) = type_?;
5769 let kind = match alias {
5770 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5771 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5773 (name, kind, generics)
5774 } else if self.is_const_item() {
5775 // This parses the grammar:
5776 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5777 self.expect_keyword(keywords::Const)?;
5778 let name = self.parse_ident()?;
5779 self.expect(&token::Colon)?;
5780 let typ = self.parse_ty()?;
5781 self.expect(&token::Eq)?;
5782 let expr = self.parse_expr()?;
5783 self.expect(&token::Semi)?;
5784 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5786 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5787 attrs.extend(inner_attrs);
5788 (name, node, generics)
5792 id: ast::DUMMY_NODE_ID,
5793 span: lo.to(self.prev_span),
5804 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5805 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5810 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5812 VisibilityKind::Inherited => Ok(()),
5814 let is_macro_rules: bool = match self.token {
5815 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5819 let mut err = self.diagnostic()
5820 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5821 err.span_suggestion_with_applicability(
5823 "try exporting the macro",
5824 "#[macro_export]".to_owned(),
5825 Applicability::MaybeIncorrect // speculative
5829 let mut err = self.diagnostic()
5830 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5831 err.help("try adjusting the macro to put `pub` inside the invocation");
5838 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5839 -> DiagnosticBuilder<'a>
5841 let expected_kinds = if item_type == "extern" {
5842 "missing `fn`, `type`, or `static`"
5844 "missing `fn`, `type`, or `const`"
5847 // Given this code `path(`, it seems like this is not
5848 // setting the visibility of a macro invocation, but rather
5849 // a mistyped method declaration.
5850 // Create a diagnostic pointing out that `fn` is missing.
5852 // x | pub path(&self) {
5853 // | ^ missing `fn`, `type`, or `const`
5855 // ^^ `sp` below will point to this
5856 let sp = prev_span.between(self.prev_span);
5857 let mut err = self.diagnostic().struct_span_err(
5859 &format!("{} for {}-item declaration",
5860 expected_kinds, item_type));
5861 err.span_label(sp, expected_kinds);
5865 /// Parse a method or a macro invocation in a trait impl.
5866 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5867 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5868 ast::ImplItemKind)> {
5869 // code copied from parse_macro_use_or_failure... abstraction!
5870 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5872 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5873 ast::ImplItemKind::Macro(mac)))
5875 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5876 let ident = self.parse_ident()?;
5877 let mut generics = self.parse_generics()?;
5878 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5879 generics.where_clause = self.parse_where_clause()?;
5881 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5882 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5883 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5884 ast::MethodSig { header, decl },
5890 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5891 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5892 let ident = self.parse_ident()?;
5893 let mut tps = self.parse_generics()?;
5895 // Parse optional colon and supertrait bounds.
5896 let bounds = if self.eat(&token::Colon) {
5897 self.parse_generic_bounds()?
5902 if self.eat(&token::Eq) {
5903 // it's a trait alias
5904 let bounds = self.parse_generic_bounds()?;
5905 tps.where_clause = self.parse_where_clause()?;
5906 self.expect(&token::Semi)?;
5907 if unsafety != Unsafety::Normal {
5908 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5910 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5912 // it's a normal trait
5913 tps.where_clause = self.parse_where_clause()?;
5914 self.expect(&token::OpenDelim(token::Brace))?;
5915 let mut trait_items = vec![];
5916 while !self.eat(&token::CloseDelim(token::Brace)) {
5917 let mut at_end = false;
5918 match self.parse_trait_item(&mut at_end) {
5919 Ok(item) => trait_items.push(item),
5923 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5928 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5932 fn choose_generics_over_qpath(&self) -> bool {
5933 // There's an ambiguity between generic parameters and qualified paths in impls.
5934 // If we see `<` it may start both, so we have to inspect some following tokens.
5935 // The following combinations can only start generics,
5936 // but not qualified paths (with one exception):
5937 // `<` `>` - empty generic parameters
5938 // `<` `#` - generic parameters with attributes
5939 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5940 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5941 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5942 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5943 // The only truly ambiguous case is
5944 // `<` IDENT `>` `::` IDENT ...
5945 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5946 // because this is what almost always expected in practice, qualified paths in impls
5947 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5948 self.token == token::Lt &&
5949 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5950 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5951 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5952 t == &token::Colon || t == &token::Eq))
5955 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5956 self.expect(&token::OpenDelim(token::Brace))?;
5957 let attrs = self.parse_inner_attributes()?;
5959 let mut impl_items = Vec::new();
5960 while !self.eat(&token::CloseDelim(token::Brace)) {
5961 let mut at_end = false;
5962 match self.parse_impl_item(&mut at_end) {
5963 Ok(impl_item) => impl_items.push(impl_item),
5967 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5972 Ok((impl_items, attrs))
5975 /// Parses an implementation item, `impl` keyword is already parsed.
5976 /// impl<'a, T> TYPE { /* impl items */ }
5977 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5978 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5979 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5980 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5981 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5982 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5983 -> PResult<'a, ItemInfo> {
5984 // First, parse generic parameters if necessary.
5985 let mut generics = if self.choose_generics_over_qpath() {
5986 self.parse_generics()?
5988 ast::Generics::default()
5991 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5992 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5994 ast::ImplPolarity::Negative
5996 ast::ImplPolarity::Positive
5999 // Parse both types and traits as a type, then reinterpret if necessary.
6000 let ty_first = self.parse_ty()?;
6002 // If `for` is missing we try to recover.
6003 let has_for = self.eat_keyword(keywords::For);
6004 let missing_for_span = self.prev_span.between(self.span);
6006 let ty_second = if self.token == token::DotDot {
6007 // We need to report this error after `cfg` expansion for compatibility reasons
6008 self.bump(); // `..`, do not add it to expected tokens
6009 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
6010 } else if has_for || self.token.can_begin_type() {
6011 Some(self.parse_ty()?)
6016 generics.where_clause = self.parse_where_clause()?;
6018 let (impl_items, attrs) = self.parse_impl_body()?;
6020 let item_kind = match ty_second {
6021 Some(ty_second) => {
6022 // impl Trait for Type
6024 self.span_err(missing_for_span, "missing `for` in a trait impl");
6027 let ty_first = ty_first.into_inner();
6028 let path = match ty_first.node {
6029 // This notably includes paths passed through `ty` macro fragments (#46438).
6030 TyKind::Path(None, path) => path,
6032 self.span_err(ty_first.span, "expected a trait, found type");
6033 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
6036 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6038 ItemKind::Impl(unsafety, polarity, defaultness,
6039 generics, Some(trait_ref), ty_second, impl_items)
6043 ItemKind::Impl(unsafety, polarity, defaultness,
6044 generics, None, ty_first, impl_items)
6048 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6051 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6052 if self.eat_keyword(keywords::For) {
6054 let params = self.parse_generic_params()?;
6056 // We rely on AST validation to rule out invalid cases: There must not be type
6057 // parameters, and the lifetime parameters must not have bounds.
6064 /// Parse struct Foo { ... }
6065 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6066 let class_name = self.parse_ident()?;
6068 let mut generics = self.parse_generics()?;
6070 // There is a special case worth noting here, as reported in issue #17904.
6071 // If we are parsing a tuple struct it is the case that the where clause
6072 // should follow the field list. Like so:
6074 // struct Foo<T>(T) where T: Copy;
6076 // If we are parsing a normal record-style struct it is the case
6077 // that the where clause comes before the body, and after the generics.
6078 // So if we look ahead and see a brace or a where-clause we begin
6079 // parsing a record style struct.
6081 // Otherwise if we look ahead and see a paren we parse a tuple-style
6084 let vdata = if self.token.is_keyword(keywords::Where) {
6085 generics.where_clause = self.parse_where_clause()?;
6086 if self.eat(&token::Semi) {
6087 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6088 VariantData::Unit(ast::DUMMY_NODE_ID)
6090 // If we see: `struct Foo<T> where T: Copy { ... }`
6091 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6093 // No `where` so: `struct Foo<T>;`
6094 } else if self.eat(&token::Semi) {
6095 VariantData::Unit(ast::DUMMY_NODE_ID)
6096 // Record-style struct definition
6097 } else if self.token == token::OpenDelim(token::Brace) {
6098 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6099 // Tuple-style struct definition with optional where-clause.
6100 } else if self.token == token::OpenDelim(token::Paren) {
6101 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6102 generics.where_clause = self.parse_where_clause()?;
6103 self.expect(&token::Semi)?;
6106 let token_str = self.this_token_descr();
6107 let mut err = self.fatal(&format!(
6108 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6111 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6115 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6118 /// Parse union Foo { ... }
6119 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6120 let class_name = self.parse_ident()?;
6122 let mut generics = self.parse_generics()?;
6124 let vdata = if self.token.is_keyword(keywords::Where) {
6125 generics.where_clause = self.parse_where_clause()?;
6126 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6127 } else if self.token == token::OpenDelim(token::Brace) {
6128 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6130 let token_str = self.this_token_descr();
6131 let mut err = self.fatal(&format!(
6132 "expected `where` or `{{` after union name, found {}", token_str));
6133 err.span_label(self.span, "expected `where` or `{` after union name");
6137 Ok((class_name, ItemKind::Union(vdata, generics), None))
6140 fn consume_block(&mut self, delim: token::DelimToken) {
6141 let mut brace_depth = 0;
6142 if !self.eat(&token::OpenDelim(delim)) {
6146 if self.eat(&token::OpenDelim(delim)) {
6148 } else if self.eat(&token::CloseDelim(delim)) {
6149 if brace_depth == 0 {
6155 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
6163 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6164 let mut fields = Vec::new();
6165 if self.eat(&token::OpenDelim(token::Brace)) {
6166 while self.token != token::CloseDelim(token::Brace) {
6167 let field = self.parse_struct_decl_field().map_err(|e| {
6168 self.recover_stmt();
6172 Ok(field) => fields.push(field),
6178 self.eat(&token::CloseDelim(token::Brace));
6180 let token_str = self.this_token_descr();
6181 let mut err = self.fatal(&format!(
6182 "expected `where`, or `{{` after struct name, found {}", token_str));
6183 err.span_label(self.span, "expected `where`, or `{` after struct name");
6190 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6191 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6192 // Unit like structs are handled in parse_item_struct function
6193 let fields = self.parse_unspanned_seq(
6194 &token::OpenDelim(token::Paren),
6195 &token::CloseDelim(token::Paren),
6196 SeqSep::trailing_allowed(token::Comma),
6198 let attrs = p.parse_outer_attributes()?;
6200 let vis = p.parse_visibility(true)?;
6201 let ty = p.parse_ty()?;
6203 span: lo.to(ty.span),
6206 id: ast::DUMMY_NODE_ID,
6215 /// Parse a structure field declaration
6216 fn parse_single_struct_field(&mut self,
6219 attrs: Vec<Attribute> )
6220 -> PResult<'a, StructField> {
6221 let mut seen_comma: bool = false;
6222 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6223 if self.token == token::Comma {
6230 token::CloseDelim(token::Brace) => {}
6231 token::DocComment(_) => {
6232 let previous_span = self.prev_span;
6233 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6234 self.bump(); // consume the doc comment
6235 let comma_after_doc_seen = self.eat(&token::Comma);
6236 // `seen_comma` is always false, because we are inside doc block
6237 // condition is here to make code more readable
6238 if seen_comma == false && comma_after_doc_seen == true {
6241 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6244 if seen_comma == false {
6245 let sp = self.sess.source_map().next_point(previous_span);
6246 err.span_suggestion_with_applicability(
6248 "missing comma here",
6250 Applicability::MachineApplicable
6257 let sp = self.sess.source_map().next_point(self.prev_span);
6258 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6259 self.this_token_descr()));
6260 if self.token.is_ident() {
6261 // This is likely another field; emit the diagnostic and keep going
6262 err.span_suggestion_with_applicability(
6264 "try adding a comma",
6266 Applicability::MachineApplicable,
6277 /// Parse an element of a struct definition
6278 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6279 let attrs = self.parse_outer_attributes()?;
6281 let vis = self.parse_visibility(false)?;
6282 self.parse_single_struct_field(lo, vis, attrs)
6285 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, `pub(self)` for `pub(in self)`
6286 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6287 /// a function definition, it's not a tuple struct field) and the contents within the parens
6288 /// isn't valid, emit a proper diagnostic.
6289 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6290 maybe_whole!(self, NtVis, |x| x);
6292 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6293 if self.is_crate_vis() {
6294 self.bump(); // `crate`
6295 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6298 if !self.eat_keyword(keywords::Pub) {
6299 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6300 // keyword to grab a span from for inherited visibility; an empty span at the
6301 // beginning of the current token would seem to be the "Schelling span".
6302 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6304 let lo = self.prev_span;
6306 if self.check(&token::OpenDelim(token::Paren)) {
6307 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6308 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6309 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6310 // by the following tokens.
6311 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6314 self.bump(); // `crate`
6315 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6317 lo.to(self.prev_span),
6318 VisibilityKind::Crate(CrateSugar::PubCrate),
6321 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6324 self.bump(); // `in`
6325 let path = self.parse_path(PathStyle::Mod)?; // `path`
6326 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6327 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6329 id: ast::DUMMY_NODE_ID,
6332 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6333 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6334 t.is_keyword(keywords::SelfValue))
6336 // `pub(self)` or `pub(super)`
6338 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6339 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6340 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6342 id: ast::DUMMY_NODE_ID,
6345 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6346 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6348 let msg = "incorrect visibility restriction";
6349 let suggestion = r##"some possible visibility restrictions are:
6350 `pub(crate)`: visible only on the current crate
6351 `pub(super)`: visible only in the current module's parent
6352 `pub(in path::to::module)`: visible only on the specified path"##;
6353 let path = self.parse_path(PathStyle::Mod)?;
6354 let sp = self.prev_span;
6355 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6356 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6357 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6358 err.help(suggestion);
6359 err.span_suggestion_with_applicability(
6360 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6362 err.emit(); // emit diagnostic, but continue with public visibility
6366 Ok(respan(lo, VisibilityKind::Public))
6369 /// Parse defaultness: `default` or nothing.
6370 fn parse_defaultness(&mut self) -> Defaultness {
6371 // `pub` is included for better error messages
6372 if self.check_keyword(keywords::Default) &&
6373 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6374 t.is_keyword(keywords::Const) ||
6375 t.is_keyword(keywords::Fn) ||
6376 t.is_keyword(keywords::Unsafe) ||
6377 t.is_keyword(keywords::Extern) ||
6378 t.is_keyword(keywords::Type) ||
6379 t.is_keyword(keywords::Pub)) {
6380 self.bump(); // `default`
6381 Defaultness::Default
6387 /// Given a termination token, parse all of the items in a module
6388 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6389 let mut items = vec![];
6390 while let Some(item) = self.parse_item()? {
6394 if !self.eat(term) {
6395 let token_str = self.this_token_descr();
6396 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6397 if self.token == token::Semi {
6398 let msg = "consider removing this semicolon";
6399 err.span_suggestion_short_with_applicability(
6400 self.span, msg, String::new(), Applicability::MachineApplicable
6402 if !items.is_empty() { // Issue #51603
6403 let previous_item = &items[items.len()-1];
6404 let previous_item_kind_name = match previous_item.node {
6405 // say "braced struct" because tuple-structs and
6406 // braceless-empty-struct declarations do take a semicolon
6407 ItemKind::Struct(..) => Some("braced struct"),
6408 ItemKind::Enum(..) => Some("enum"),
6409 ItemKind::Trait(..) => Some("trait"),
6410 ItemKind::Union(..) => Some("union"),
6413 if let Some(name) = previous_item_kind_name {
6414 err.help(&format!("{} declarations are not followed by a semicolon",
6419 err.span_label(self.span, "expected item");
6424 let hi = if self.span.is_dummy() {
6431 inner: inner_lo.to(hi),
6437 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6438 let id = match self.token {
6439 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
6443 _ => self.parse_ident()?,
6445 self.expect(&token::Colon)?;
6446 let ty = self.parse_ty()?;
6447 self.expect(&token::Eq)?;
6448 let e = self.parse_expr()?;
6449 self.expect(&token::Semi)?;
6450 let item = match m {
6451 Some(m) => ItemKind::Static(ty, m, e),
6452 None => ItemKind::Const(ty, e),
6454 Ok((id, item, None))
6457 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6458 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6459 let (in_cfg, outer_attrs) = {
6460 let mut strip_unconfigured = ::config::StripUnconfigured {
6462 features: None, // don't perform gated feature checking
6464 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6465 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6468 let id_span = self.span;
6469 let id = self.parse_ident()?;
6470 if self.eat(&token::Semi) {
6471 if in_cfg && self.recurse_into_file_modules {
6472 // This mod is in an external file. Let's go get it!
6473 let ModulePathSuccess { path, directory_ownership, warn } =
6474 self.submod_path(id, &outer_attrs, id_span)?;
6475 let (module, mut attrs) =
6476 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6477 // Record that we fetched the mod from an external file
6479 let attr = Attribute {
6480 id: attr::mk_attr_id(),
6481 style: ast::AttrStyle::Outer,
6482 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6483 tokens: TokenStream::empty(),
6484 is_sugared_doc: false,
6485 span: syntax_pos::DUMMY_SP,
6487 attr::mark_known(&attr);
6490 Ok((id, ItemKind::Mod(module), Some(attrs)))
6492 let placeholder = ast::Mod {
6493 inner: syntax_pos::DUMMY_SP,
6497 Ok((id, ItemKind::Mod(placeholder), None))
6500 let old_directory = self.directory.clone();
6501 self.push_directory(id, &outer_attrs);
6503 self.expect(&token::OpenDelim(token::Brace))?;
6504 let mod_inner_lo = self.span;
6505 let attrs = self.parse_inner_attributes()?;
6506 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6508 self.directory = old_directory;
6509 Ok((id, ItemKind::Mod(module), Some(attrs)))
6513 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6514 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6515 self.directory.path.to_mut().push(&path.as_str());
6516 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6518 // We have to push on the current module name in the case of relative
6519 // paths in order to ensure that any additional module paths from inline
6520 // `mod x { ... }` come after the relative extension.
6522 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6523 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6524 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6525 if let Some(ident) = relative.take() { // remove the relative offset
6526 self.directory.path.to_mut().push(ident.as_str());
6529 self.directory.path.to_mut().push(&id.as_str());
6533 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6534 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6537 // On windows, the base path might have the form
6538 // `\\?\foo\bar` in which case it does not tolerate
6539 // mixed `/` and `\` separators, so canonicalize
6542 let s = s.replace("/", "\\");
6543 Some(dir_path.join(s))
6549 /// Returns either a path to a module, or .
6550 pub fn default_submod_path(
6552 relative: Option<ast::Ident>,
6554 source_map: &SourceMap) -> ModulePath
6556 // If we're in a foo.rs file instead of a mod.rs file,
6557 // we need to look for submodules in
6558 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6559 // `./<id>.rs` and `./<id>/mod.rs`.
6560 let relative_prefix_string;
6561 let relative_prefix = if let Some(ident) = relative {
6562 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6563 &relative_prefix_string
6568 let mod_name = id.to_string();
6569 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6570 let secondary_path_str = format!("{}{}{}mod.rs",
6571 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6572 let default_path = dir_path.join(&default_path_str);
6573 let secondary_path = dir_path.join(&secondary_path_str);
6574 let default_exists = source_map.file_exists(&default_path);
6575 let secondary_exists = source_map.file_exists(&secondary_path);
6577 let result = match (default_exists, secondary_exists) {
6578 (true, false) => Ok(ModulePathSuccess {
6580 directory_ownership: DirectoryOwnership::Owned {
6585 (false, true) => Ok(ModulePathSuccess {
6586 path: secondary_path,
6587 directory_ownership: DirectoryOwnership::Owned {
6592 (false, false) => Err(Error::FileNotFoundForModule {
6593 mod_name: mod_name.clone(),
6594 default_path: default_path_str,
6595 secondary_path: secondary_path_str,
6596 dir_path: dir_path.display().to_string(),
6598 (true, true) => Err(Error::DuplicatePaths {
6599 mod_name: mod_name.clone(),
6600 default_path: default_path_str,
6601 secondary_path: secondary_path_str,
6607 path_exists: default_exists || secondary_exists,
6612 fn submod_path(&mut self,
6614 outer_attrs: &[Attribute],
6616 -> PResult<'a, ModulePathSuccess> {
6617 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6618 return Ok(ModulePathSuccess {
6619 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6620 // All `#[path]` files are treated as though they are a `mod.rs` file.
6621 // This means that `mod foo;` declarations inside `#[path]`-included
6622 // files are siblings,
6624 // Note that this will produce weirdness when a file named `foo.rs` is
6625 // `#[path]` included and contains a `mod foo;` declaration.
6626 // If you encounter this, it's your own darn fault :P
6627 Some(_) => DirectoryOwnership::Owned { relative: None },
6628 _ => DirectoryOwnership::UnownedViaMod(true),
6635 let relative = match self.directory.ownership {
6636 DirectoryOwnership::Owned { relative } => relative,
6637 DirectoryOwnership::UnownedViaBlock |
6638 DirectoryOwnership::UnownedViaMod(_) => None,
6640 let paths = Parser::default_submod_path(
6641 id, relative, &self.directory.path, self.sess.source_map());
6643 match self.directory.ownership {
6644 DirectoryOwnership::Owned { .. } => {
6645 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6647 DirectoryOwnership::UnownedViaBlock => {
6649 "Cannot declare a non-inline module inside a block \
6650 unless it has a path attribute";
6651 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6652 if paths.path_exists {
6653 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6655 err.span_note(id_sp, &msg);
6659 DirectoryOwnership::UnownedViaMod(warn) => {
6661 if let Ok(result) = paths.result {
6662 return Ok(ModulePathSuccess { warn: true, ..result });
6665 let mut err = self.diagnostic().struct_span_err(id_sp,
6666 "cannot declare a new module at this location");
6667 if !id_sp.is_dummy() {
6668 let src_path = self.sess.source_map().span_to_filename(id_sp);
6669 if let FileName::Real(src_path) = src_path {
6670 if let Some(stem) = src_path.file_stem() {
6671 let mut dest_path = src_path.clone();
6672 dest_path.set_file_name(stem);
6673 dest_path.push("mod.rs");
6674 err.span_note(id_sp,
6675 &format!("maybe move this module `{}` to its own \
6676 directory via `{}`", src_path.display(),
6677 dest_path.display()));
6681 if paths.path_exists {
6682 err.span_note(id_sp,
6683 &format!("... or maybe `use` the module `{}` instead \
6684 of possibly redeclaring it",
6692 /// Read a module from a source file.
6693 fn eval_src_mod(&mut self,
6695 directory_ownership: DirectoryOwnership,
6698 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6699 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6700 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6701 let mut err = String::from("circular modules: ");
6702 let len = included_mod_stack.len();
6703 for p in &included_mod_stack[i.. len] {
6704 err.push_str(&p.to_string_lossy());
6705 err.push_str(" -> ");
6707 err.push_str(&path.to_string_lossy());
6708 return Err(self.span_fatal(id_sp, &err[..]));
6710 included_mod_stack.push(path.clone());
6711 drop(included_mod_stack);
6714 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6715 p0.cfg_mods = self.cfg_mods;
6716 let mod_inner_lo = p0.span;
6717 let mod_attrs = p0.parse_inner_attributes()?;
6718 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6720 self.sess.included_mod_stack.borrow_mut().pop();
6724 /// Parse a function declaration from a foreign module
6725 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6726 -> PResult<'a, ForeignItem> {
6727 self.expect_keyword(keywords::Fn)?;
6729 let (ident, mut generics) = self.parse_fn_header()?;
6730 let decl = self.parse_fn_decl(true)?;
6731 generics.where_clause = self.parse_where_clause()?;
6733 self.expect(&token::Semi)?;
6734 Ok(ast::ForeignItem {
6737 node: ForeignItemKind::Fn(decl, generics),
6738 id: ast::DUMMY_NODE_ID,
6744 /// Parse a static item from a foreign module.
6745 /// Assumes that the `static` keyword is already parsed.
6746 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6747 -> PResult<'a, ForeignItem> {
6748 let mutbl = self.eat_keyword(keywords::Mut);
6749 let ident = self.parse_ident()?;
6750 self.expect(&token::Colon)?;
6751 let ty = self.parse_ty()?;
6753 self.expect(&token::Semi)?;
6757 node: ForeignItemKind::Static(ty, mutbl),
6758 id: ast::DUMMY_NODE_ID,
6764 /// Parse a type from a foreign module
6765 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6766 -> PResult<'a, ForeignItem> {
6767 self.expect_keyword(keywords::Type)?;
6769 let ident = self.parse_ident()?;
6771 self.expect(&token::Semi)?;
6772 Ok(ast::ForeignItem {
6775 node: ForeignItemKind::Ty,
6776 id: ast::DUMMY_NODE_ID,
6782 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6783 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6784 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6786 let mut ident = self.parse_ident()?;
6787 let mut idents = vec![];
6788 let mut replacement = vec![];
6789 let mut fixed_crate_name = false;
6790 // Accept `extern crate name-like-this` for better diagnostics
6791 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6792 if self.token == dash { // Do not include `-` as part of the expected tokens list
6793 while self.eat(&dash) {
6794 fixed_crate_name = true;
6795 replacement.push((self.prev_span, "_".to_string()));
6796 idents.push(self.parse_ident()?);
6799 if fixed_crate_name {
6800 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6801 let mut fixed_name = format!("{}", ident.name);
6802 for part in idents {
6803 fixed_name.push_str(&format!("_{}", part.name));
6805 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6807 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6808 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6809 err.multipart_suggestion(suggestion_msg, replacement);
6815 /// Parse extern crate links
6819 /// extern crate foo;
6820 /// extern crate bar as foo;
6821 fn parse_item_extern_crate(&mut self,
6823 visibility: Visibility,
6824 attrs: Vec<Attribute>)
6825 -> PResult<'a, P<Item>> {
6826 // Accept `extern crate name-like-this` for better diagnostics
6827 let orig_name = self.parse_crate_name_with_dashes()?;
6828 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6829 (rename, Some(orig_name.name))
6833 self.expect(&token::Semi)?;
6835 let span = lo.to(self.prev_span);
6836 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6839 /// Parse `extern` for foreign ABIs
6842 /// `extern` is expected to have been
6843 /// consumed before calling this method
6849 fn parse_item_foreign_mod(&mut self,
6851 opt_abi: Option<Abi>,
6852 visibility: Visibility,
6853 mut attrs: Vec<Attribute>)
6854 -> PResult<'a, P<Item>> {
6855 self.expect(&token::OpenDelim(token::Brace))?;
6857 let abi = opt_abi.unwrap_or(Abi::C);
6859 attrs.extend(self.parse_inner_attributes()?);
6861 let mut foreign_items = vec![];
6862 while !self.eat(&token::CloseDelim(token::Brace)) {
6863 foreign_items.push(self.parse_foreign_item()?);
6866 let prev_span = self.prev_span;
6867 let m = ast::ForeignMod {
6869 items: foreign_items
6871 let invalid = keywords::Invalid.ident();
6872 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6875 /// Parse `type Foo = Bar;`
6877 /// `existential type Foo: Bar;`
6879 /// `return None` without modifying the parser state
6880 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6881 // This parses the grammar:
6882 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6883 if self.check_keyword(keywords::Type) ||
6884 self.check_keyword(keywords::Existential) &&
6885 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6886 let existential = self.eat_keyword(keywords::Existential);
6887 assert!(self.eat_keyword(keywords::Type));
6888 Some(self.parse_existential_or_alias(existential))
6894 /// Parse type alias or existential type
6895 fn parse_existential_or_alias(
6898 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6899 let ident = self.parse_ident()?;
6900 let mut tps = self.parse_generics()?;
6901 tps.where_clause = self.parse_where_clause()?;
6902 let alias = if existential {
6903 self.expect(&token::Colon)?;
6904 let bounds = self.parse_generic_bounds()?;
6905 AliasKind::Existential(bounds)
6907 self.expect(&token::Eq)?;
6908 let ty = self.parse_ty()?;
6911 self.expect(&token::Semi)?;
6912 Ok((ident, alias, tps))
6915 /// Parse the part of an "enum" decl following the '{'
6916 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6917 let mut variants = Vec::new();
6918 let mut all_nullary = true;
6919 let mut any_disr = None;
6920 while self.token != token::CloseDelim(token::Brace) {
6921 let variant_attrs = self.parse_outer_attributes()?;
6922 let vlo = self.span;
6925 let mut disr_expr = None;
6926 let ident = self.parse_ident()?;
6927 if self.check(&token::OpenDelim(token::Brace)) {
6928 // Parse a struct variant.
6929 all_nullary = false;
6930 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6931 ast::DUMMY_NODE_ID);
6932 } else if self.check(&token::OpenDelim(token::Paren)) {
6933 all_nullary = false;
6934 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6935 ast::DUMMY_NODE_ID);
6936 } else if self.eat(&token::Eq) {
6937 disr_expr = Some(AnonConst {
6938 id: ast::DUMMY_NODE_ID,
6939 value: self.parse_expr()?,
6941 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6942 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6944 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6947 let vr = ast::Variant_ {
6949 attrs: variant_attrs,
6953 variants.push(respan(vlo.to(self.prev_span), vr));
6955 if !self.eat(&token::Comma) { break; }
6957 self.expect(&token::CloseDelim(token::Brace))?;
6959 Some(disr_span) if !all_nullary =>
6960 self.span_err(disr_span,
6961 "discriminator values can only be used with a field-less enum"),
6965 Ok(ast::EnumDef { variants })
6968 /// Parse an "enum" declaration
6969 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6970 let id = self.parse_ident()?;
6971 let mut generics = self.parse_generics()?;
6972 generics.where_clause = self.parse_where_clause()?;
6973 self.expect(&token::OpenDelim(token::Brace))?;
6975 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6976 self.recover_stmt();
6977 self.eat(&token::CloseDelim(token::Brace));
6980 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6983 /// Parses a string as an ABI spec on an extern type or module. Consumes
6984 /// the `extern` keyword, if one is found.
6985 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6987 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6989 self.expect_no_suffix(sp, "ABI spec", suf);
6991 match abi::lookup(&s.as_str()) {
6992 Some(abi) => Ok(Some(abi)),
6994 let prev_span = self.prev_span;
6995 let mut err = struct_span_err!(
6996 self.sess.span_diagnostic,
6999 "invalid ABI: found `{}`",
7001 err.span_label(prev_span, "invalid ABI");
7002 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7013 fn is_static_global(&mut self) -> bool {
7014 if self.check_keyword(keywords::Static) {
7015 // Check if this could be a closure
7016 !self.look_ahead(1, |token| {
7017 if token.is_keyword(keywords::Move) {
7021 token::BinOp(token::Or) | token::OrOr => true,
7032 attrs: Vec<Attribute>,
7033 macros_allowed: bool,
7034 attributes_allowed: bool,
7035 ) -> PResult<'a, Option<P<Item>>> {
7036 let (ret, tokens) = self.collect_tokens(|this| {
7037 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
7040 // Once we've parsed an item and recorded the tokens we got while
7041 // parsing we may want to store `tokens` into the item we're about to
7042 // return. Note, though, that we specifically didn't capture tokens
7043 // related to outer attributes. The `tokens` field here may later be
7044 // used with procedural macros to convert this item back into a token
7045 // stream, but during expansion we may be removing attributes as we go
7048 // If we've got inner attributes then the `tokens` we've got above holds
7049 // these inner attributes. If an inner attribute is expanded we won't
7050 // actually remove it from the token stream, so we'll just keep yielding
7051 // it (bad!). To work around this case for now we just avoid recording
7052 // `tokens` if we detect any inner attributes. This should help keep
7053 // expansion correct, but we should fix this bug one day!
7056 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7057 i.tokens = Some(tokens);
7064 /// Parse one of the items allowed by the flags.
7065 fn parse_item_implementation(
7067 attrs: Vec<Attribute>,
7068 macros_allowed: bool,
7069 attributes_allowed: bool,
7070 ) -> PResult<'a, Option<P<Item>>> {
7071 maybe_whole!(self, NtItem, |item| {
7072 let mut item = item.into_inner();
7073 let mut attrs = attrs;
7074 mem::swap(&mut item.attrs, &mut attrs);
7075 item.attrs.extend(attrs);
7081 let visibility = self.parse_visibility(false)?;
7083 if self.eat_keyword(keywords::Use) {
7085 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7086 self.expect(&token::Semi)?;
7088 let span = lo.to(self.prev_span);
7089 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7090 return Ok(Some(item));
7093 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
7094 self.bump(); // `extern`
7095 if self.eat_keyword(keywords::Crate) {
7096 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7099 let opt_abi = self.parse_opt_abi()?;
7101 if self.eat_keyword(keywords::Fn) {
7102 // EXTERN FUNCTION ITEM
7103 let fn_span = self.prev_span;
7104 let abi = opt_abi.unwrap_or(Abi::C);
7105 let (ident, item_, extra_attrs) =
7106 self.parse_item_fn(Unsafety::Normal,
7108 respan(fn_span, Constness::NotConst),
7110 let prev_span = self.prev_span;
7111 let item = self.mk_item(lo.to(prev_span),
7115 maybe_append(attrs, extra_attrs));
7116 return Ok(Some(item));
7117 } else if self.check(&token::OpenDelim(token::Brace)) {
7118 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7124 if self.is_static_global() {
7127 let m = if self.eat_keyword(keywords::Mut) {
7130 Mutability::Immutable
7132 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7133 let prev_span = self.prev_span;
7134 let item = self.mk_item(lo.to(prev_span),
7138 maybe_append(attrs, extra_attrs));
7139 return Ok(Some(item));
7141 if self.eat_keyword(keywords::Const) {
7142 let const_span = self.prev_span;
7143 if self.check_keyword(keywords::Fn)
7144 || (self.check_keyword(keywords::Unsafe)
7145 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7146 // CONST FUNCTION ITEM
7147 let unsafety = self.parse_unsafety();
7149 let (ident, item_, extra_attrs) =
7150 self.parse_item_fn(unsafety,
7152 respan(const_span, Constness::Const),
7154 let prev_span = self.prev_span;
7155 let item = self.mk_item(lo.to(prev_span),
7159 maybe_append(attrs, extra_attrs));
7160 return Ok(Some(item));
7164 if self.eat_keyword(keywords::Mut) {
7165 let prev_span = self.prev_span;
7166 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
7167 .help("did you mean to declare a static?")
7170 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7171 let prev_span = self.prev_span;
7172 let item = self.mk_item(lo.to(prev_span),
7176 maybe_append(attrs, extra_attrs));
7177 return Ok(Some(item));
7180 // `unsafe async fn` or `async fn`
7182 self.check_keyword(keywords::Unsafe) &&
7183 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7185 self.check_keyword(keywords::Async) &&
7186 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7189 // ASYNC FUNCTION ITEM
7190 let unsafety = self.parse_unsafety();
7191 self.expect_keyword(keywords::Async)?;
7192 self.expect_keyword(keywords::Fn)?;
7193 let fn_span = self.prev_span;
7194 let (ident, item_, extra_attrs) =
7195 self.parse_item_fn(unsafety,
7197 closure_id: ast::DUMMY_NODE_ID,
7198 return_impl_trait_id: ast::DUMMY_NODE_ID,
7200 respan(fn_span, Constness::NotConst),
7202 let prev_span = self.prev_span;
7203 let item = self.mk_item(lo.to(prev_span),
7207 maybe_append(attrs, extra_attrs));
7208 return Ok(Some(item));
7210 if self.check_keyword(keywords::Unsafe) &&
7211 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7212 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7214 // UNSAFE TRAIT ITEM
7215 self.bump(); // `unsafe`
7216 let is_auto = if self.eat_keyword(keywords::Trait) {
7219 self.expect_keyword(keywords::Auto)?;
7220 self.expect_keyword(keywords::Trait)?;
7223 let (ident, item_, extra_attrs) =
7224 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7225 let prev_span = self.prev_span;
7226 let item = self.mk_item(lo.to(prev_span),
7230 maybe_append(attrs, extra_attrs));
7231 return Ok(Some(item));
7233 if self.check_keyword(keywords::Impl) ||
7234 self.check_keyword(keywords::Unsafe) &&
7235 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7236 self.check_keyword(keywords::Default) &&
7237 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7238 self.check_keyword(keywords::Default) &&
7239 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7241 let defaultness = self.parse_defaultness();
7242 let unsafety = self.parse_unsafety();
7243 self.expect_keyword(keywords::Impl)?;
7244 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7245 let span = lo.to(self.prev_span);
7246 return Ok(Some(self.mk_item(span, ident, item, visibility,
7247 maybe_append(attrs, extra_attrs))));
7249 if self.check_keyword(keywords::Fn) {
7252 let fn_span = self.prev_span;
7253 let (ident, item_, extra_attrs) =
7254 self.parse_item_fn(Unsafety::Normal,
7256 respan(fn_span, Constness::NotConst),
7258 let prev_span = self.prev_span;
7259 let item = self.mk_item(lo.to(prev_span),
7263 maybe_append(attrs, extra_attrs));
7264 return Ok(Some(item));
7266 if self.check_keyword(keywords::Unsafe)
7267 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7268 // UNSAFE FUNCTION ITEM
7269 self.bump(); // `unsafe`
7270 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7271 self.check(&token::OpenDelim(token::Brace));
7272 let abi = if self.eat_keyword(keywords::Extern) {
7273 self.parse_opt_abi()?.unwrap_or(Abi::C)
7277 self.expect_keyword(keywords::Fn)?;
7278 let fn_span = self.prev_span;
7279 let (ident, item_, extra_attrs) =
7280 self.parse_item_fn(Unsafety::Unsafe,
7282 respan(fn_span, Constness::NotConst),
7284 let prev_span = self.prev_span;
7285 let item = self.mk_item(lo.to(prev_span),
7289 maybe_append(attrs, extra_attrs));
7290 return Ok(Some(item));
7292 if self.eat_keyword(keywords::Mod) {
7294 let (ident, item_, extra_attrs) =
7295 self.parse_item_mod(&attrs[..])?;
7296 let prev_span = self.prev_span;
7297 let item = self.mk_item(lo.to(prev_span),
7301 maybe_append(attrs, extra_attrs));
7302 return Ok(Some(item));
7304 if let Some(type_) = self.eat_type() {
7305 let (ident, alias, generics) = type_?;
7307 let item_ = match alias {
7308 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7309 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7311 let prev_span = self.prev_span;
7312 let item = self.mk_item(lo.to(prev_span),
7317 return Ok(Some(item));
7319 if self.eat_keyword(keywords::Enum) {
7321 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7322 let prev_span = self.prev_span;
7323 let item = self.mk_item(lo.to(prev_span),
7327 maybe_append(attrs, extra_attrs));
7328 return Ok(Some(item));
7330 if self.check_keyword(keywords::Trait)
7331 || (self.check_keyword(keywords::Auto)
7332 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7334 let is_auto = if self.eat_keyword(keywords::Trait) {
7337 self.expect_keyword(keywords::Auto)?;
7338 self.expect_keyword(keywords::Trait)?;
7342 let (ident, item_, extra_attrs) =
7343 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7344 let prev_span = self.prev_span;
7345 let item = self.mk_item(lo.to(prev_span),
7349 maybe_append(attrs, extra_attrs));
7350 return Ok(Some(item));
7352 if self.eat_keyword(keywords::Struct) {
7354 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7355 let prev_span = self.prev_span;
7356 let item = self.mk_item(lo.to(prev_span),
7360 maybe_append(attrs, extra_attrs));
7361 return Ok(Some(item));
7363 if self.is_union_item() {
7366 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7367 let prev_span = self.prev_span;
7368 let item = self.mk_item(lo.to(prev_span),
7372 maybe_append(attrs, extra_attrs));
7373 return Ok(Some(item));
7375 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7376 return Ok(Some(macro_def));
7379 // Verify whether we have encountered a struct or method definition where the user forgot to
7380 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7381 if visibility.node.is_pub() &&
7382 self.check_ident() &&
7383 self.look_ahead(1, |t| *t != token::Not)
7385 // Space between `pub` keyword and the identifier
7388 // ^^^ `sp` points here
7389 let sp = self.prev_span.between(self.span);
7390 let full_sp = self.prev_span.to(self.span);
7391 let ident_sp = self.span;
7392 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7393 // possible public struct definition where `struct` was forgotten
7394 let ident = self.parse_ident().unwrap();
7395 let msg = format!("add `struct` here to parse `{}` as a public struct",
7397 let mut err = self.diagnostic()
7398 .struct_span_err(sp, "missing `struct` for struct definition");
7399 err.span_suggestion_short_with_applicability(
7400 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7403 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7404 let ident = self.parse_ident().unwrap();
7405 self.consume_block(token::Paren);
7406 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7407 self.check(&token::OpenDelim(token::Brace))
7409 ("fn", "method", false)
7410 } else if self.check(&token::Colon) {
7414 ("fn` or `struct", "method or struct", true)
7417 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7418 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7420 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7424 err.span_suggestion_short_with_applicability(
7425 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7428 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7429 err.span_suggestion_with_applicability(
7431 "if you meant to call a macro, try",
7432 format!("{}!", snippet),
7433 // this is the `ambiguous` conditional branch
7434 Applicability::MaybeIncorrect
7437 err.help("if you meant to call a macro, remove the `pub` \
7438 and add a trailing `!` after the identifier");
7444 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7447 /// Parse a foreign item.
7448 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7449 maybe_whole!(self, NtForeignItem, |ni| ni);
7451 let attrs = self.parse_outer_attributes()?;
7453 let visibility = self.parse_visibility(false)?;
7455 // FOREIGN STATIC ITEM
7456 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7457 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7458 if self.token.is_keyword(keywords::Const) {
7460 .struct_span_err(self.span, "extern items cannot be `const`")
7461 .span_suggestion_with_applicability(
7463 "try using a static value",
7464 "static".to_owned(),
7465 Applicability::MachineApplicable
7468 self.bump(); // `static` or `const`
7469 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7471 // FOREIGN FUNCTION ITEM
7472 if self.check_keyword(keywords::Fn) {
7473 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7475 // FOREIGN TYPE ITEM
7476 if self.check_keyword(keywords::Type) {
7477 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7480 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7484 ident: keywords::Invalid.ident(),
7485 span: lo.to(self.prev_span),
7486 id: ast::DUMMY_NODE_ID,
7489 node: ForeignItemKind::Macro(mac),
7494 if !attrs.is_empty() {
7495 self.expected_item_err(&attrs);
7503 /// This is the fall-through for parsing items.
7504 fn parse_macro_use_or_failure(
7506 attrs: Vec<Attribute> ,
7507 macros_allowed: bool,
7508 attributes_allowed: bool,
7510 visibility: Visibility
7511 ) -> PResult<'a, Option<P<Item>>> {
7512 if macros_allowed && self.token.is_path_start() {
7513 // MACRO INVOCATION ITEM
7515 let prev_span = self.prev_span;
7516 self.complain_if_pub_macro(&visibility.node, prev_span);
7518 let mac_lo = self.span;
7521 let pth = self.parse_path(PathStyle::Mod)?;
7522 self.expect(&token::Not)?;
7524 // a 'special' identifier (like what `macro_rules!` uses)
7525 // is optional. We should eventually unify invoc syntax
7527 let id = if self.token.is_ident() {
7530 keywords::Invalid.ident() // no special identifier
7532 // eat a matched-delimiter token tree:
7533 let (delim, tts) = self.expect_delimited_token_tree()?;
7534 if delim != MacDelimiter::Brace {
7535 if !self.eat(&token::Semi) {
7536 self.span_err(self.prev_span,
7537 "macros that expand to items must either \
7538 be surrounded with braces or followed by \
7543 let hi = self.prev_span;
7544 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7545 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7546 return Ok(Some(item));
7549 // FAILURE TO PARSE ITEM
7550 match visibility.node {
7551 VisibilityKind::Inherited => {}
7553 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7557 if !attributes_allowed && !attrs.is_empty() {
7558 self.expected_item_err(&attrs);
7563 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7564 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7565 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7567 if self.token.is_path_start() && !self.is_extern_non_path() {
7568 let prev_span = self.prev_span;
7570 let pth = self.parse_path(PathStyle::Mod)?;
7572 if pth.segments.len() == 1 {
7573 if !self.eat(&token::Not) {
7574 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7577 self.expect(&token::Not)?;
7580 if let Some(vis) = vis {
7581 self.complain_if_pub_macro(&vis.node, prev_span);
7586 // eat a matched-delimiter token tree:
7587 let (delim, tts) = self.expect_delimited_token_tree()?;
7588 if delim != MacDelimiter::Brace {
7589 self.expect(&token::Semi)?
7592 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7598 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7599 where F: FnOnce(&mut Self) -> PResult<'a, R>
7601 // Record all tokens we parse when parsing this item.
7602 let mut tokens = Vec::new();
7603 let prev_collecting = match self.token_cursor.frame.last_token {
7604 LastToken::Collecting(ref mut list) => {
7605 Some(mem::replace(list, Vec::new()))
7607 LastToken::Was(ref mut last) => {
7608 tokens.extend(last.take());
7612 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7613 let prev = self.token_cursor.stack.len();
7615 let last_token = if self.token_cursor.stack.len() == prev {
7616 &mut self.token_cursor.frame.last_token
7618 &mut self.token_cursor.stack[prev].last_token
7621 // Pull our the toekns that we've collected from the call to `f` above
7622 let mut collected_tokens = match *last_token {
7623 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7624 LastToken::Was(_) => panic!("our vector went away?"),
7627 // If we're not at EOF our current token wasn't actually consumed by
7628 // `f`, but it'll still be in our list that we pulled out. In that case
7630 let extra_token = if self.token != token::Eof {
7631 collected_tokens.pop()
7636 // If we were previously collecting tokens, then this was a recursive
7637 // call. In that case we need to record all the tokens we collected in
7638 // our parent list as well. To do that we push a clone of our stream
7639 // onto the previous list.
7640 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7641 match prev_collecting {
7643 list.push(stream.clone());
7644 list.extend(extra_token);
7645 *last_token = LastToken::Collecting(list);
7648 *last_token = LastToken::Was(extra_token);
7655 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7656 let attrs = self.parse_outer_attributes()?;
7657 self.parse_item_(attrs, true, false)
7661 fn is_import_coupler(&mut self) -> bool {
7662 self.check(&token::ModSep) &&
7663 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7664 *t == token::BinOp(token::Star))
7669 /// USE_TREE = [`::`] `*` |
7670 /// [`::`] `{` USE_TREE_LIST `}` |
7672 /// PATH `::` `{` USE_TREE_LIST `}` |
7673 /// PATH [`as` IDENT]
7674 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7677 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7678 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7679 self.check(&token::BinOp(token::Star)) ||
7680 self.is_import_coupler() {
7681 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7682 let mod_sep_ctxt = self.span.ctxt();
7683 if self.eat(&token::ModSep) {
7684 prefix.segments.push(
7685 PathSegment::crate_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7689 if self.eat(&token::BinOp(token::Star)) {
7692 UseTreeKind::Nested(self.parse_use_tree_list()?)
7695 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7696 prefix = self.parse_path(PathStyle::Mod)?;
7698 if self.eat(&token::ModSep) {
7699 if self.eat(&token::BinOp(token::Star)) {
7702 UseTreeKind::Nested(self.parse_use_tree_list()?)
7705 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7709 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7712 /// Parse UseTreeKind::Nested(list)
7714 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7715 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7716 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7717 &token::CloseDelim(token::Brace),
7718 SeqSep::trailing_allowed(token::Comma), |this| {
7719 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7723 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7724 if self.eat_keyword(keywords::As) {
7726 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7728 Ok(Some(ident.gensym()))
7730 _ => self.parse_ident().map(Some),
7737 /// Parses a source module as a crate. This is the main
7738 /// entry point for the parser.
7739 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7742 attrs: self.parse_inner_attributes()?,
7743 module: self.parse_mod_items(&token::Eof, lo)?,
7744 span: lo.to(self.span),
7748 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7749 let ret = match self.token {
7750 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7751 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7758 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7759 match self.parse_optional_str() {
7760 Some((s, style, suf)) => {
7761 let sp = self.prev_span;
7762 self.expect_no_suffix(sp, "string literal", suf);
7766 let msg = "expected string literal";
7767 let mut err = self.fatal(msg);
7768 err.span_label(self.span, msg);