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, edition::Edition};
47 use errors::{self, Applicability, DiagnosticBuilder, DiagnosticId};
48 use parse::{self, SeqSep, classify, token};
49 use parse::lexer::TokenAndSpan;
50 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
57 use tokenstream::{self, Delimited, 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",
618 fn this_token_descr(&self) -> String {
619 if let Some(prefix) = self.token_descr() {
620 format!("{} `{}`", prefix, self.this_token_to_string())
622 format!("`{}`", self.this_token_to_string())
626 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
627 let token_str = pprust::token_to_string(t);
628 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
631 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
632 match self.expect_one_of(&[], &[]) {
634 Ok(_) => unreachable!(),
638 /// Expect and consume the token t. Signal an error if
639 /// the next token is not t.
640 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
641 if self.expected_tokens.is_empty() {
642 if self.token == *t {
646 let token_str = pprust::token_to_string(t);
647 let this_token_str = self.this_token_to_string();
648 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
652 let sp = if self.token == token::Token::Eof {
653 // EOF, don't want to point at the following char, but rather the last token
656 self.sess.source_map().next_point(self.prev_span)
658 let label_exp = format!("expected `{}`", token_str);
659 let cm = self.sess.source_map();
660 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
661 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
662 // When the spans are in the same line, it means that the only content
663 // between them is whitespace, point only at the found token.
664 err.span_label(self.span, label_exp);
667 err.span_label(sp, label_exp);
668 err.span_label(self.span, "unexpected token");
674 self.expect_one_of(slice::from_ref(t), &[])
678 /// Expect next token to be edible or inedible token. If edible,
679 /// then consume it; if inedible, then return without consuming
680 /// anything. Signal a fatal error if next token is unexpected.
681 pub fn expect_one_of(&mut self,
682 edible: &[token::Token],
683 inedible: &[token::Token]) -> PResult<'a, ()>{
684 fn tokens_to_string(tokens: &[TokenType]) -> String {
685 let mut i = tokens.iter();
686 // This might be a sign we need a connect method on Iterator.
688 .map_or(String::new(), |t| t.to_string());
689 i.enumerate().fold(b, |mut b, (i, a)| {
690 if tokens.len() > 2 && i == tokens.len() - 2 {
692 } else if tokens.len() == 2 && i == tokens.len() - 2 {
697 b.push_str(&a.to_string());
701 if edible.contains(&self.token) {
704 } else if inedible.contains(&self.token) {
705 // leave it in the input
708 let mut expected = edible.iter()
709 .map(|x| TokenType::Token(x.clone()))
710 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
711 .chain(self.expected_tokens.iter().cloned())
712 .collect::<Vec<_>>();
713 expected.sort_by_cached_key(|x| x.to_string());
715 let expect = tokens_to_string(&expected[..]);
716 let actual = self.this_token_to_string();
717 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
718 let short_expect = if expected.len() > 6 {
719 format!("{} possible tokens", expected.len())
723 (format!("expected one of {}, found `{}`", expect, actual),
724 (self.sess.source_map().next_point(self.prev_span),
725 format!("expected one of {} here", short_expect)))
726 } else if expected.is_empty() {
727 (format!("unexpected token: `{}`", actual),
728 (self.prev_span, "unexpected token after this".to_string()))
730 (format!("expected {}, found `{}`", expect, actual),
731 (self.sess.source_map().next_point(self.prev_span),
732 format!("expected {} here", expect)))
734 let mut err = self.fatal(&msg_exp);
735 if self.token.is_ident_named("and") {
736 err.span_suggestion_short_with_applicability(
738 "use `&&` instead of `and` for the boolean operator",
740 Applicability::MaybeIncorrect,
743 if self.token.is_ident_named("or") {
744 err.span_suggestion_short_with_applicability(
746 "use `||` instead of `or` for the boolean operator",
748 Applicability::MaybeIncorrect,
751 let sp = if self.token == token::Token::Eof {
752 // This is EOF, don't want to point at the following char, but rather the last token
758 let cm = self.sess.source_map();
759 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
760 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
761 // When the spans are in the same line, it means that the only content between
762 // them is whitespace, point at the found token in that case:
764 // X | () => { syntax error };
765 // | ^^^^^ expected one of 8 possible tokens here
767 // instead of having:
769 // X | () => { syntax error };
770 // | -^^^^^ unexpected token
772 // | expected one of 8 possible tokens here
773 err.span_label(self.span, label_exp);
775 _ if self.prev_span == syntax_pos::DUMMY_SP => {
776 // Account for macro context where the previous span might not be
777 // available to avoid incorrect output (#54841).
778 err.span_label(self.span, "unexpected token");
781 err.span_label(sp, label_exp);
782 err.span_label(self.span, "unexpected token");
789 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
790 fn interpolated_or_expr_span(&self,
791 expr: PResult<'a, P<Expr>>)
792 -> PResult<'a, (Span, P<Expr>)> {
794 if self.prev_token_kind == PrevTokenKind::Interpolated {
802 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
803 let mut err = self.struct_span_err(self.span,
804 &format!("expected identifier, found {}",
805 self.this_token_descr()));
806 if let Some(token_descr) = self.token_descr() {
807 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
809 err.span_label(self.span, "expected identifier");
810 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
811 err.span_suggestion_with_applicability(
815 Applicability::MachineApplicable,
822 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
823 self.parse_ident_common(true)
826 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
828 token::Ident(ident, _) => {
829 if self.token.is_reserved_ident() {
830 let mut err = self.expected_ident_found();
837 let span = self.span;
839 Ok(Ident::new(ident.name, span))
842 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
843 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
845 self.expected_ident_found()
851 /// Check if the next token is `tok`, and return `true` if so.
853 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
855 crate fn check(&mut self, tok: &token::Token) -> bool {
856 let is_present = self.token == *tok;
857 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
861 /// Consume token 'tok' if it exists. Returns true if the given
862 /// token was present, false otherwise.
863 pub fn eat(&mut self, tok: &token::Token) -> bool {
864 let is_present = self.check(tok);
865 if is_present { self.bump() }
869 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
870 self.expected_tokens.push(TokenType::Keyword(kw));
871 self.token.is_keyword(kw)
874 /// If the next token is the given keyword, eat it and return
875 /// true. Otherwise, return false.
876 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
877 if self.check_keyword(kw) {
885 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
886 if self.token.is_keyword(kw) {
894 /// If the given word is not a keyword, signal an error.
895 /// If the next token is not the given word, signal an error.
896 /// Otherwise, eat it.
897 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
898 if !self.eat_keyword(kw) {
905 fn check_ident(&mut self) -> bool {
906 if self.token.is_ident() {
909 self.expected_tokens.push(TokenType::Ident);
914 fn check_path(&mut self) -> bool {
915 if self.token.is_path_start() {
918 self.expected_tokens.push(TokenType::Path);
923 fn check_type(&mut self) -> bool {
924 if self.token.can_begin_type() {
927 self.expected_tokens.push(TokenType::Type);
932 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
933 /// and continue. If a `+` is not seen, return false.
935 /// This is using when token splitting += into +.
936 /// See issue 47856 for an example of when this may occur.
937 fn eat_plus(&mut self) -> bool {
938 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
940 token::BinOp(token::Plus) => {
944 token::BinOpEq(token::Plus) => {
945 let span = self.span.with_lo(self.span.lo() + BytePos(1));
946 self.bump_with(token::Eq, span);
954 /// Checks to see if the next token is either `+` or `+=`.
955 /// Otherwise returns false.
956 fn check_plus(&mut self) -> bool {
957 if self.token.is_like_plus() {
961 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
966 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
967 /// `&` and continue. If an `&` is not seen, signal an error.
968 fn expect_and(&mut self) -> PResult<'a, ()> {
969 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
971 token::BinOp(token::And) => {
976 let span = self.span.with_lo(self.span.lo() + BytePos(1));
977 Ok(self.bump_with(token::BinOp(token::And), span))
979 _ => self.unexpected()
983 /// Expect and consume an `|`. If `||` is seen, replace it with a single
984 /// `|` and continue. If an `|` is not seen, signal an error.
985 fn expect_or(&mut self) -> PResult<'a, ()> {
986 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
988 token::BinOp(token::Or) => {
993 let span = self.span.with_lo(self.span.lo() + BytePos(1));
994 Ok(self.bump_with(token::BinOp(token::Or), span))
996 _ => self.unexpected()
1000 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1002 None => {/* everything ok */}
1004 let text = suf.as_str();
1005 if text.is_empty() {
1006 self.span_bug(sp, "found empty literal suffix in Some")
1008 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
1013 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
1014 /// `<` and continue. If a `<` is not seen, return false.
1016 /// This is meant to be used when parsing generics on a path to get the
1018 fn eat_lt(&mut self) -> bool {
1019 self.expected_tokens.push(TokenType::Token(token::Lt));
1025 token::BinOp(token::Shl) => {
1026 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1027 self.bump_with(token::Lt, span);
1034 fn expect_lt(&mut self) -> PResult<'a, ()> {
1042 /// Expect and consume a GT. if a >> is seen, replace it
1043 /// with a single > and continue. If a GT is not seen,
1044 /// signal an error.
1045 fn expect_gt(&mut self) -> PResult<'a, ()> {
1046 self.expected_tokens.push(TokenType::Token(token::Gt));
1052 token::BinOp(token::Shr) => {
1053 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1054 Ok(self.bump_with(token::Gt, span))
1056 token::BinOpEq(token::Shr) => {
1057 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1058 Ok(self.bump_with(token::Ge, span))
1061 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1062 Ok(self.bump_with(token::Eq, span))
1064 _ => self.unexpected()
1068 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1069 /// passes through any errors encountered. Used for error recovery.
1070 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1071 let handler = self.diagnostic();
1073 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1075 TokenExpectType::Expect,
1076 |p| Ok(p.parse_token_tree())) {
1077 handler.cancel(err);
1081 /// Parse a sequence, including the closing delimiter. The function
1082 /// f must consume tokens until reaching the next separator or
1083 /// closing bracket.
1084 pub fn parse_seq_to_end<T, F>(&mut self,
1088 -> PResult<'a, Vec<T>> where
1089 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1091 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1096 /// Parse a sequence, not including the closing delimiter. The function
1097 /// f must consume tokens until reaching the next separator or
1098 /// closing bracket.
1099 pub fn parse_seq_to_before_end<T, F>(&mut self,
1103 -> PResult<'a, Vec<T>>
1104 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1106 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1109 fn parse_seq_to_before_tokens<T, F>(
1111 kets: &[&token::Token],
1113 expect: TokenExpectType,
1115 ) -> PResult<'a, Vec<T>>
1116 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1118 let mut first: bool = true;
1120 while !kets.iter().any(|k| {
1122 TokenExpectType::Expect => self.check(k),
1123 TokenExpectType::NoExpect => self.token == **k,
1127 token::CloseDelim(..) | token::Eof => break,
1130 if let Some(ref t) = sep.sep {
1134 if let Err(mut e) = self.expect(t) {
1135 // Attempt to keep parsing if it was a similar separator
1136 if let Some(ref tokens) = t.similar_tokens() {
1137 if tokens.contains(&self.token) {
1142 // Attempt to keep parsing if it was an omitted separator
1156 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1158 TokenExpectType::Expect => self.check(k),
1159 TokenExpectType::NoExpect => self.token == **k,
1172 /// Parse a sequence, including the closing delimiter. The function
1173 /// f must consume tokens until reaching the next separator or
1174 /// closing bracket.
1175 fn parse_unspanned_seq<T, F>(&mut self,
1180 -> PResult<'a, Vec<T>> where
1181 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1184 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1189 /// Advance the parser by one token
1190 pub fn bump(&mut self) {
1191 if self.prev_token_kind == PrevTokenKind::Eof {
1192 // Bumping after EOF is a bad sign, usually an infinite loop.
1193 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1196 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1198 // Record last token kind for possible error recovery.
1199 self.prev_token_kind = match self.token {
1200 token::DocComment(..) => PrevTokenKind::DocComment,
1201 token::Comma => PrevTokenKind::Comma,
1202 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1203 token::Interpolated(..) => PrevTokenKind::Interpolated,
1204 token::Eof => PrevTokenKind::Eof,
1205 token::Ident(..) => PrevTokenKind::Ident,
1206 _ => PrevTokenKind::Other,
1209 let next = self.next_tok();
1210 self.span = next.sp;
1211 self.token = next.tok;
1212 self.expected_tokens.clear();
1213 // check after each token
1214 self.process_potential_macro_variable();
1217 /// Advance the parser using provided token as a next one. Use this when
1218 /// consuming a part of a token. For example a single `<` from `<<`.
1219 fn bump_with(&mut self, next: token::Token, span: Span) {
1220 self.prev_span = self.span.with_hi(span.lo());
1221 // It would be incorrect to record the kind of the current token, but
1222 // fortunately for tokens currently using `bump_with`, the
1223 // prev_token_kind will be of no use anyway.
1224 self.prev_token_kind = PrevTokenKind::Other;
1227 self.expected_tokens.clear();
1230 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1231 F: FnOnce(&token::Token) -> R,
1234 return f(&self.token)
1237 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1238 Some(tree) => match tree {
1239 TokenTree::Token(_, tok) => tok,
1240 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1242 None => token::CloseDelim(self.token_cursor.frame.delim),
1246 fn look_ahead_span(&self, dist: usize) -> Span {
1251 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1252 Some(TokenTree::Token(span, _)) => span,
1253 Some(TokenTree::Delimited(span, _)) => span.entire(),
1254 None => self.look_ahead_span(dist - 1),
1257 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1258 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1260 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1261 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1263 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1264 err.span_err(sp, self.diagnostic())
1266 fn bug(&self, m: &str) -> ! {
1267 self.sess.span_diagnostic.span_bug(self.span, m)
1269 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1270 self.sess.span_diagnostic.span_err(sp, m)
1272 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1273 self.sess.span_diagnostic.struct_span_err(sp, m)
1275 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1276 self.sess.span_diagnostic.span_bug(sp, m)
1278 crate fn abort_if_errors(&self) {
1279 self.sess.span_diagnostic.abort_if_errors();
1282 fn cancel(&self, err: &mut DiagnosticBuilder) {
1283 self.sess.span_diagnostic.cancel(err)
1286 crate fn diagnostic(&self) -> &'a errors::Handler {
1287 &self.sess.span_diagnostic
1290 /// Is the current token one of the keywords that signals a bare function
1292 fn token_is_bare_fn_keyword(&mut self) -> bool {
1293 self.check_keyword(keywords::Fn) ||
1294 self.check_keyword(keywords::Unsafe) ||
1295 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1298 /// parse a TyKind::BareFn type:
1299 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1302 [unsafe] [extern "ABI"] fn (S) -> T
1312 let unsafety = self.parse_unsafety();
1313 let abi = if self.eat_keyword(keywords::Extern) {
1314 self.parse_opt_abi()?.unwrap_or(Abi::C)
1319 self.expect_keyword(keywords::Fn)?;
1320 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1321 let ret_ty = self.parse_ret_ty(false)?;
1322 let decl = P(FnDecl {
1327 Ok(TyKind::BareFn(P(BareFnTy {
1335 /// Parse asyncness: `async` or nothing
1336 fn parse_asyncness(&mut self) -> IsAsync {
1337 if self.eat_keyword(keywords::Async) {
1339 closure_id: ast::DUMMY_NODE_ID,
1340 return_impl_trait_id: ast::DUMMY_NODE_ID,
1347 /// Parse unsafety: `unsafe` or nothing.
1348 fn parse_unsafety(&mut self) -> Unsafety {
1349 if self.eat_keyword(keywords::Unsafe) {
1356 /// Parse the items in a trait declaration
1357 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1358 maybe_whole!(self, NtTraitItem, |x| x);
1359 let attrs = self.parse_outer_attributes()?;
1360 let (mut item, tokens) = self.collect_tokens(|this| {
1361 this.parse_trait_item_(at_end, attrs)
1363 // See `parse_item` for why this clause is here.
1364 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1365 item.tokens = Some(tokens);
1370 fn parse_trait_item_(&mut self,
1372 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1375 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1376 self.parse_trait_item_assoc_ty()?
1377 } else if self.is_const_item() {
1378 self.expect_keyword(keywords::Const)?;
1379 let ident = self.parse_ident()?;
1380 self.expect(&token::Colon)?;
1381 let ty = self.parse_ty()?;
1382 let default = if self.eat(&token::Eq) {
1383 let expr = self.parse_expr()?;
1384 self.expect(&token::Semi)?;
1387 self.expect(&token::Semi)?;
1390 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1391 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1392 // trait item macro.
1393 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1395 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1397 let ident = self.parse_ident()?;
1398 let mut generics = self.parse_generics()?;
1400 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1401 // This is somewhat dubious; We don't want to allow
1402 // argument names to be left off if there is a
1405 // We don't allow argument names to be left off in edition 2018.
1406 if p.span.edition() >= Edition::Edition2018 {
1407 p.parse_arg_general(true)
1409 p.parse_arg_general(false)
1412 generics.where_clause = self.parse_where_clause()?;
1414 let sig = ast::MethodSig {
1424 let body = match self.token {
1428 debug!("parse_trait_methods(): parsing required method");
1431 token::OpenDelim(token::Brace) => {
1432 debug!("parse_trait_methods(): parsing provided method");
1434 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1435 attrs.extend(inner_attrs.iter().cloned());
1438 token::Interpolated(ref nt) => {
1440 token::NtBlock(..) => {
1442 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1443 attrs.extend(inner_attrs.iter().cloned());
1447 let token_str = self.this_token_to_string();
1448 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1450 err.span_label(self.span, "expected `;` or `{`");
1456 let token_str = self.this_token_to_string();
1457 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1459 err.span_label(self.span, "expected `;` or `{`");
1463 (ident, ast::TraitItemKind::Method(sig, body), generics)
1467 id: ast::DUMMY_NODE_ID,
1472 span: lo.to(self.prev_span),
1477 /// Parse optional return type [ -> TY ] in function decl
1478 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1479 if self.eat(&token::RArrow) {
1480 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1482 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1487 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1488 self.parse_ty_common(true, true)
1491 /// Parse a type in restricted contexts where `+` is not permitted.
1492 /// Example 1: `&'a TYPE`
1493 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1494 /// Example 2: `value1 as TYPE + value2`
1495 /// `+` is prohibited to avoid interactions with expression grammar.
1496 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1497 self.parse_ty_common(false, true)
1500 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1501 -> PResult<'a, P<Ty>> {
1502 maybe_whole!(self, NtTy, |x| x);
1505 let mut impl_dyn_multi = false;
1506 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1507 // `(TYPE)` is a parenthesized type.
1508 // `(TYPE,)` is a tuple with a single field of type TYPE.
1509 let mut ts = vec![];
1510 let mut last_comma = false;
1511 while self.token != token::CloseDelim(token::Paren) {
1512 ts.push(self.parse_ty()?);
1513 if self.eat(&token::Comma) {
1520 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1521 self.expect(&token::CloseDelim(token::Paren))?;
1523 if ts.len() == 1 && !last_comma {
1524 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1525 let maybe_bounds = allow_plus && self.token.is_like_plus();
1527 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1528 TyKind::Path(None, ref path) if maybe_bounds => {
1529 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1531 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1532 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1533 let path = match bounds[0] {
1534 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1535 _ => self.bug("unexpected lifetime bound"),
1537 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1540 _ => TyKind::Paren(P(ty))
1545 } else if self.eat(&token::Not) {
1548 } else if self.eat(&token::BinOp(token::Star)) {
1550 TyKind::Ptr(self.parse_ptr()?)
1551 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1553 let t = self.parse_ty()?;
1554 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1555 let t = match self.maybe_parse_fixed_length_of_vec()? {
1556 None => TyKind::Slice(t),
1557 Some(length) => TyKind::Array(t, AnonConst {
1558 id: ast::DUMMY_NODE_ID,
1562 self.expect(&token::CloseDelim(token::Bracket))?;
1564 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1567 self.parse_borrowed_pointee()?
1568 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1570 // In order to not be ambiguous, the type must be surrounded by parens.
1571 self.expect(&token::OpenDelim(token::Paren))?;
1573 id: ast::DUMMY_NODE_ID,
1574 value: self.parse_expr()?,
1576 self.expect(&token::CloseDelim(token::Paren))?;
1578 } else if self.eat_keyword(keywords::Underscore) {
1579 // A type to be inferred `_`
1581 } else if self.token_is_bare_fn_keyword() {
1582 // Function pointer type
1583 self.parse_ty_bare_fn(Vec::new())?
1584 } else if self.check_keyword(keywords::For) {
1585 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1586 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1587 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1589 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1590 if self.token_is_bare_fn_keyword() {
1591 self.parse_ty_bare_fn(lifetime_defs)?
1593 let path = self.parse_path(PathStyle::Type)?;
1594 let parse_plus = allow_plus && self.check_plus();
1595 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1597 } else if self.eat_keyword(keywords::Impl) {
1598 // Always parse bounds greedily for better error recovery.
1599 let bounds = self.parse_generic_bounds()?;
1600 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1601 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1602 } else if self.check_keyword(keywords::Dyn) &&
1603 (self.span.edition() == Edition::Edition2018 ||
1604 self.look_ahead(1, |t| t.can_begin_bound() &&
1605 !can_continue_type_after_non_fn_ident(t))) {
1606 self.bump(); // `dyn`
1607 // Always parse bounds greedily for better error recovery.
1608 let bounds = self.parse_generic_bounds()?;
1609 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1610 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1611 } else if self.check(&token::Question) ||
1612 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1613 // Bound list (trait object type)
1614 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1615 TraitObjectSyntax::None)
1616 } else if self.eat_lt() {
1618 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1619 TyKind::Path(Some(qself), path)
1620 } else if self.token.is_path_start() {
1622 let path = self.parse_path(PathStyle::Type)?;
1623 if self.eat(&token::Not) {
1624 // Macro invocation in type position
1625 let (delim, tts) = self.expect_delimited_token_tree()?;
1626 let node = Mac_ { path, tts, delim };
1627 TyKind::Mac(respan(lo.to(self.prev_span), node))
1629 // Just a type path or bound list (trait object type) starting with a trait.
1631 // `Trait1 + Trait2 + 'a`
1632 if allow_plus && self.check_plus() {
1633 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1635 TyKind::Path(None, path)
1639 let msg = format!("expected type, found {}", self.this_token_descr());
1640 return Err(self.fatal(&msg));
1643 let span = lo.to(self.prev_span);
1644 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1646 // Try to recover from use of `+` with incorrect priority.
1647 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1648 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1649 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1654 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1655 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1656 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1657 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1659 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1660 bounds.append(&mut self.parse_generic_bounds()?);
1662 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1665 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1666 if !allow_plus && impl_dyn_multi {
1667 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1668 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1669 .span_suggestion_with_applicability(
1671 "use parentheses to disambiguate",
1673 Applicability::MachineApplicable
1678 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1679 // Do not add `+` to expected tokens.
1680 if !allow_plus || !self.token.is_like_plus() {
1685 let bounds = self.parse_generic_bounds()?;
1686 let sum_span = ty.span.to(self.prev_span);
1688 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1689 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1692 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1693 let sum_with_parens = pprust::to_string(|s| {
1694 use print::pprust::PrintState;
1697 s.print_opt_lifetime(lifetime)?;
1698 s.print_mutability(mut_ty.mutbl)?;
1700 s.print_type(&mut_ty.ty)?;
1701 s.print_type_bounds(" +", &bounds)?;
1704 err.span_suggestion_with_applicability(
1706 "try adding parentheses",
1708 Applicability::MachineApplicable
1711 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1712 err.span_label(sum_span, "perhaps you forgot parentheses?");
1715 err.span_label(sum_span, "expected a path");
1722 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1723 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1725 // Do not add `::` to expected tokens.
1726 if !allow_recovery || self.token != token::ModSep {
1729 let ty = match base.to_ty() {
1731 None => return Ok(base),
1734 self.bump(); // `::`
1735 let mut segments = Vec::new();
1736 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1738 let span = ty.span.to(self.prev_span);
1739 let path_span = span.to(span); // use an empty path since `position` == 0
1740 let recovered = base.to_recovered(
1741 Some(QSelf { ty, path_span, position: 0 }),
1742 ast::Path { segments, span },
1746 .struct_span_err(span, "missing angle brackets in associated item path")
1747 .span_suggestion_with_applicability( // this is a best-effort recovery
1748 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1754 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1755 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1756 let mutbl = self.parse_mutability();
1757 let ty = self.parse_ty_no_plus()?;
1758 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1761 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1762 let mutbl = if self.eat_keyword(keywords::Mut) {
1764 } else if self.eat_keyword(keywords::Const) {
1765 Mutability::Immutable
1767 let span = self.prev_span;
1769 "expected mut or const in raw pointer type (use \
1770 `*mut T` or `*const T` as appropriate)");
1771 Mutability::Immutable
1773 let t = self.parse_ty_no_plus()?;
1774 Ok(MutTy { ty: t, mutbl: mutbl })
1777 fn is_named_argument(&mut self) -> bool {
1778 let offset = match self.token {
1779 token::Interpolated(ref nt) => match nt.0 {
1780 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1783 token::BinOp(token::And) | token::AndAnd => 1,
1784 _ if self.token.is_keyword(keywords::Mut) => 1,
1788 self.look_ahead(offset, |t| t.is_ident()) &&
1789 self.look_ahead(offset + 1, |t| t == &token::Colon)
1792 /// This version of parse arg doesn't necessarily require
1793 /// identifier names.
1794 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1795 maybe_whole!(self, NtArg, |x| x);
1797 let (pat, ty) = if require_name || self.is_named_argument() {
1798 debug!("parse_arg_general parse_pat (require_name:{})",
1800 let pat = self.parse_pat()?;
1802 if let Err(mut err) = self.expect(&token::Colon) {
1803 // If we find a pattern followed by an identifier, it could be an (incorrect)
1804 // C-style parameter declaration.
1805 if self.check_ident() && self.look_ahead(1, |t| {
1806 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1808 let ident = self.parse_ident().unwrap();
1809 let span = pat.span.with_hi(ident.span.hi());
1811 err.span_suggestion_with_applicability(
1813 "declare the type after the parameter binding",
1814 String::from("<identifier>: <type>"),
1815 Applicability::HasPlaceholders,
1822 (pat, self.parse_ty()?)
1824 debug!("parse_arg_general ident_to_pat");
1825 let parser_snapshot_before_ty = self.clone();
1826 let mut ty = self.parse_ty();
1827 if ty.is_ok() && self.token == token::Colon {
1828 // This wasn't actually a type, but a pattern looking like a type,
1829 // so we are going to rollback and re-parse for recovery.
1830 ty = self.unexpected();
1834 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1836 id: ast::DUMMY_NODE_ID,
1837 node: PatKind::Ident(
1838 BindingMode::ByValue(Mutability::Immutable), ident, None),
1844 // Recover from attempting to parse the argument as a type without pattern.
1846 mem::replace(self, parser_snapshot_before_ty);
1847 let pat = self.parse_pat()?;
1848 self.expect(&token::Colon)?;
1849 let ty = self.parse_ty()?;
1851 let mut err = self.diagnostic().struct_span_err_with_code(
1853 "patterns aren't allowed in methods without bodies",
1854 DiagnosticId::Error("E0642".into()),
1856 err.span_suggestion_short_with_applicability(
1858 "give this argument a name or use an underscore to ignore it",
1860 Applicability::MachineApplicable,
1864 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1866 node: PatKind::Wild,
1868 id: ast::DUMMY_NODE_ID
1875 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1878 /// Parse a single function argument
1879 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1880 self.parse_arg_general(true)
1883 /// Parse an argument in a lambda header e.g. |arg, arg|
1884 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1885 let pat = self.parse_pat()?;
1886 let t = if self.eat(&token::Colon) {
1890 id: ast::DUMMY_NODE_ID,
1891 node: TyKind::Infer,
1892 span: self.prev_span,
1898 id: ast::DUMMY_NODE_ID
1902 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1903 if self.eat(&token::Semi) {
1904 Ok(Some(self.parse_expr()?))
1910 /// Matches token_lit = LIT_INTEGER | ...
1911 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1912 let out = match self.token {
1913 token::Interpolated(ref nt) => match nt.0 {
1914 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1915 ExprKind::Lit(ref lit) => { lit.node.clone() }
1916 _ => { return self.unexpected_last(&self.token); }
1918 _ => { return self.unexpected_last(&self.token); }
1920 token::Literal(lit, suf) => {
1921 let diag = Some((self.span, &self.sess.span_diagnostic));
1922 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1926 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1931 _ => { return self.unexpected_last(&self.token); }
1938 /// Matches lit = true | false | token_lit
1939 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1941 let lit = if self.eat_keyword(keywords::True) {
1943 } else if self.eat_keyword(keywords::False) {
1944 LitKind::Bool(false)
1946 let lit = self.parse_lit_token()?;
1949 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
1952 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1953 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1954 maybe_whole_expr!(self);
1956 let minus_lo = self.span;
1957 let minus_present = self.eat(&token::BinOp(token::Minus));
1959 let literal = P(self.parse_lit()?);
1960 let hi = self.prev_span;
1961 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1964 let minus_hi = self.prev_span;
1965 let unary = self.mk_unary(UnOp::Neg, expr);
1966 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1972 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1974 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1975 let span = self.span;
1977 Ok(Ident::new(ident.name, span))
1979 _ => self.parse_ident(),
1983 /// Parses qualified path.
1984 /// Assumes that the leading `<` has been parsed already.
1986 /// `qualified_path = <type [as trait_ref]>::path`
1991 /// `<T as U>::F::a<S>` (without disambiguator)
1992 /// `<T as U>::F::a::<S>` (with disambiguator)
1993 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1994 let lo = self.prev_span;
1995 let ty = self.parse_ty()?;
1997 // `path` will contain the prefix of the path up to the `>`,
1998 // if any (e.g., `U` in the `<T as U>::*` examples
1999 // above). `path_span` has the span of that path, or an empty
2000 // span in the case of something like `<T>::Bar`.
2001 let (mut path, path_span);
2002 if self.eat_keyword(keywords::As) {
2003 let path_lo = self.span;
2004 path = self.parse_path(PathStyle::Type)?;
2005 path_span = path_lo.to(self.prev_span);
2007 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2008 path_span = self.span.to(self.span);
2011 self.expect(&token::Gt)?;
2012 self.expect(&token::ModSep)?;
2014 let qself = QSelf { ty, path_span, position: path.segments.len() };
2015 self.parse_path_segments(&mut path.segments, style, true)?;
2017 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2020 /// Parses simple paths.
2022 /// `path = [::] segment+`
2023 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2026 /// `a::b::C<D>` (without disambiguator)
2027 /// `a::b::C::<D>` (with disambiguator)
2028 /// `Fn(Args)` (without disambiguator)
2029 /// `Fn::(Args)` (with disambiguator)
2030 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2031 self.parse_path_common(style, true)
2034 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2035 -> PResult<'a, ast::Path> {
2036 maybe_whole!(self, NtPath, |path| {
2037 if style == PathStyle::Mod &&
2038 path.segments.iter().any(|segment| segment.args.is_some()) {
2039 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2044 let lo = self.meta_var_span.unwrap_or(self.span);
2045 let mut segments = Vec::new();
2046 if self.eat(&token::ModSep) {
2047 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
2049 self.parse_path_segments(&mut segments, style, enable_warning)?;
2051 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2054 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2055 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2056 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2057 let meta_ident = match self.token {
2058 token::Interpolated(ref nt) => match nt.0 {
2059 token::NtMeta(ref meta) => match meta.node {
2060 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2067 if let Some(path) = meta_ident {
2071 self.parse_path(style)
2074 fn parse_path_segments(&mut self,
2075 segments: &mut Vec<PathSegment>,
2077 enable_warning: bool)
2078 -> PResult<'a, ()> {
2080 segments.push(self.parse_path_segment(style, enable_warning)?);
2082 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2088 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2089 -> PResult<'a, PathSegment> {
2090 let ident = self.parse_path_segment_ident()?;
2092 let is_args_start = |token: &token::Token| match *token {
2093 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2096 let check_args_start = |this: &mut Self| {
2097 this.expected_tokens.extend_from_slice(
2098 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2100 is_args_start(&this.token)
2103 Ok(if style == PathStyle::Type && check_args_start(self) ||
2104 style != PathStyle::Mod && self.check(&token::ModSep)
2105 && self.look_ahead(1, |t| is_args_start(t)) {
2106 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2108 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2109 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2110 .span_label(self.prev_span, "try removing `::`").emit();
2113 let args = if self.eat_lt() {
2115 let (args, bindings) = self.parse_generic_args()?;
2117 let span = lo.to(self.prev_span);
2118 AngleBracketedArgs { args, bindings, span }.into()
2122 let inputs = self.parse_seq_to_before_tokens(
2123 &[&token::CloseDelim(token::Paren)],
2124 SeqSep::trailing_allowed(token::Comma),
2125 TokenExpectType::Expect,
2128 let span = lo.to(self.prev_span);
2129 let output = if self.eat(&token::RArrow) {
2130 Some(self.parse_ty_common(false, false)?)
2134 ParenthesisedArgs { inputs, output, span }.into()
2137 PathSegment { ident, args }
2139 // Generic arguments are not found.
2140 PathSegment::from_ident(ident)
2144 crate fn check_lifetime(&mut self) -> bool {
2145 self.expected_tokens.push(TokenType::Lifetime);
2146 self.token.is_lifetime()
2149 /// Parse single lifetime 'a or panic.
2150 crate fn expect_lifetime(&mut self) -> Lifetime {
2151 if let Some(ident) = self.token.lifetime() {
2152 let span = self.span;
2154 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2156 self.span_bug(self.span, "not a lifetime")
2160 fn eat_label(&mut self) -> Option<Label> {
2161 if let Some(ident) = self.token.lifetime() {
2162 let span = self.span;
2164 Some(Label { ident: Ident::new(ident.name, span) })
2170 /// Parse mutability (`mut` or nothing).
2171 fn parse_mutability(&mut self) -> Mutability {
2172 if self.eat_keyword(keywords::Mut) {
2175 Mutability::Immutable
2179 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2180 if let token::Literal(token::Integer(name), None) = self.token {
2182 Ok(Ident::new(name, self.prev_span))
2184 self.parse_ident_common(false)
2188 /// Parse ident (COLON expr)?
2189 fn parse_field(&mut self) -> PResult<'a, Field> {
2190 let attrs = self.parse_outer_attributes()?;
2193 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2194 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2195 let fieldname = self.parse_field_name()?;
2197 (fieldname, self.parse_expr()?, false)
2199 let fieldname = self.parse_ident_common(false)?;
2201 // Mimic `x: x` for the `x` field shorthand.
2202 let path = ast::Path::from_ident(fieldname);
2203 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2204 (fieldname, expr, true)
2208 span: lo.to(expr.span),
2211 attrs: attrs.into(),
2215 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2216 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2219 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2220 ExprKind::Unary(unop, expr)
2223 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2224 ExprKind::Binary(binop, lhs, rhs)
2227 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2228 ExprKind::Call(f, args)
2231 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2232 ExprKind::Index(expr, idx)
2235 fn mk_range(&mut self,
2236 start: Option<P<Expr>>,
2237 end: Option<P<Expr>>,
2238 limits: RangeLimits)
2239 -> PResult<'a, ast::ExprKind> {
2240 if end.is_none() && limits == RangeLimits::Closed {
2241 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2243 Ok(ExprKind::Range(start, end, limits))
2247 fn mk_assign_op(&mut self, binop: ast::BinOp,
2248 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2249 ExprKind::AssignOp(binop, lhs, rhs)
2252 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2254 id: ast::DUMMY_NODE_ID,
2255 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2261 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2262 let delim = match self.token {
2263 token::OpenDelim(delim) => delim,
2265 let msg = "expected open delimiter";
2266 let mut err = self.fatal(msg);
2267 err.span_label(self.span, msg);
2271 let delimited = match self.parse_token_tree() {
2272 TokenTree::Delimited(_, delimited) => delimited,
2273 _ => unreachable!(),
2275 let delim = match delim {
2276 token::Paren => MacDelimiter::Parenthesis,
2277 token::Bracket => MacDelimiter::Bracket,
2278 token::Brace => MacDelimiter::Brace,
2279 token::NoDelim => self.bug("unexpected no delimiter"),
2281 Ok((delim, delimited.stream().into()))
2284 /// At the bottom (top?) of the precedence hierarchy,
2285 /// parse things like parenthesized exprs,
2286 /// macros, return, etc.
2288 /// NB: This does not parse outer attributes,
2289 /// and is private because it only works
2290 /// correctly if called from parse_dot_or_call_expr().
2291 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2292 maybe_whole_expr!(self);
2294 // Outer attributes are already parsed and will be
2295 // added to the return value after the fact.
2297 // Therefore, prevent sub-parser from parsing
2298 // attributes by giving them a empty "already parsed" list.
2299 let mut attrs = ThinVec::new();
2302 let mut hi = self.span;
2306 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2308 token::OpenDelim(token::Paren) => {
2311 attrs.extend(self.parse_inner_attributes()?);
2313 // (e) is parenthesized e
2314 // (e,) is a tuple with only one field, e
2315 let mut es = vec![];
2316 let mut trailing_comma = false;
2317 while self.token != token::CloseDelim(token::Paren) {
2318 es.push(self.parse_expr()?);
2319 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2320 if self.eat(&token::Comma) {
2321 trailing_comma = true;
2323 trailing_comma = false;
2329 hi = self.prev_span;
2330 ex = if es.len() == 1 && !trailing_comma {
2331 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2336 token::OpenDelim(token::Brace) => {
2337 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2339 token::BinOp(token::Or) | token::OrOr => {
2340 return self.parse_lambda_expr(attrs);
2342 token::OpenDelim(token::Bracket) => {
2345 attrs.extend(self.parse_inner_attributes()?);
2347 if self.eat(&token::CloseDelim(token::Bracket)) {
2349 ex = ExprKind::Array(Vec::new());
2352 let first_expr = self.parse_expr()?;
2353 if self.eat(&token::Semi) {
2354 // Repeating array syntax: [ 0; 512 ]
2355 let count = AnonConst {
2356 id: ast::DUMMY_NODE_ID,
2357 value: self.parse_expr()?,
2359 self.expect(&token::CloseDelim(token::Bracket))?;
2360 ex = ExprKind::Repeat(first_expr, count);
2361 } else if self.eat(&token::Comma) {
2362 // Vector with two or more elements.
2363 let remaining_exprs = self.parse_seq_to_end(
2364 &token::CloseDelim(token::Bracket),
2365 SeqSep::trailing_allowed(token::Comma),
2366 |p| Ok(p.parse_expr()?)
2368 let mut exprs = vec![first_expr];
2369 exprs.extend(remaining_exprs);
2370 ex = ExprKind::Array(exprs);
2372 // Vector with one element.
2373 self.expect(&token::CloseDelim(token::Bracket))?;
2374 ex = ExprKind::Array(vec![first_expr]);
2377 hi = self.prev_span;
2381 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2383 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2385 if self.span.edition() >= Edition::Edition2018 &&
2386 self.check_keyword(keywords::Async)
2388 if self.is_async_block() { // check for `async {` and `async move {`
2389 return self.parse_async_block(attrs);
2391 return self.parse_lambda_expr(attrs);
2394 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2395 return self.parse_lambda_expr(attrs);
2397 if self.eat_keyword(keywords::If) {
2398 return self.parse_if_expr(attrs);
2400 if self.eat_keyword(keywords::For) {
2401 let lo = self.prev_span;
2402 return self.parse_for_expr(None, lo, attrs);
2404 if self.eat_keyword(keywords::While) {
2405 let lo = self.prev_span;
2406 return self.parse_while_expr(None, lo, attrs);
2408 if let Some(label) = self.eat_label() {
2409 let lo = label.ident.span;
2410 self.expect(&token::Colon)?;
2411 if self.eat_keyword(keywords::While) {
2412 return self.parse_while_expr(Some(label), lo, attrs)
2414 if self.eat_keyword(keywords::For) {
2415 return self.parse_for_expr(Some(label), lo, attrs)
2417 if self.eat_keyword(keywords::Loop) {
2418 return self.parse_loop_expr(Some(label), lo, attrs)
2420 if self.token == token::OpenDelim(token::Brace) {
2421 return self.parse_block_expr(Some(label),
2423 BlockCheckMode::Default,
2426 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2427 let mut err = self.fatal(msg);
2428 err.span_label(self.span, msg);
2431 if self.eat_keyword(keywords::Loop) {
2432 let lo = self.prev_span;
2433 return self.parse_loop_expr(None, lo, attrs);
2435 if self.eat_keyword(keywords::Continue) {
2436 let label = self.eat_label();
2437 let ex = ExprKind::Continue(label);
2438 let hi = self.prev_span;
2439 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2441 if self.eat_keyword(keywords::Match) {
2442 return self.parse_match_expr(attrs);
2444 if self.eat_keyword(keywords::Unsafe) {
2445 return self.parse_block_expr(
2448 BlockCheckMode::Unsafe(ast::UserProvided),
2451 if self.is_do_catch_block() {
2452 let mut db = self.fatal("found removed `do catch` syntax");
2453 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2456 if self.is_try_block() {
2458 assert!(self.eat_keyword(keywords::Try));
2459 return self.parse_try_block(lo, attrs);
2461 if self.eat_keyword(keywords::Return) {
2462 if self.token.can_begin_expr() {
2463 let e = self.parse_expr()?;
2465 ex = ExprKind::Ret(Some(e));
2467 ex = ExprKind::Ret(None);
2469 } else if self.eat_keyword(keywords::Break) {
2470 let label = self.eat_label();
2471 let e = if self.token.can_begin_expr()
2472 && !(self.token == token::OpenDelim(token::Brace)
2473 && self.restrictions.contains(
2474 Restrictions::NO_STRUCT_LITERAL)) {
2475 Some(self.parse_expr()?)
2479 ex = ExprKind::Break(label, e);
2480 hi = self.prev_span;
2481 } else if self.eat_keyword(keywords::Yield) {
2482 if self.token.can_begin_expr() {
2483 let e = self.parse_expr()?;
2485 ex = ExprKind::Yield(Some(e));
2487 ex = ExprKind::Yield(None);
2489 } else if self.token.is_keyword(keywords::Let) {
2490 // Catch this syntax error here, instead of in `parse_ident`, so
2491 // that we can explicitly mention that let is not to be used as an expression
2492 let mut db = self.fatal("expected expression, found statement (`let`)");
2493 db.span_label(self.span, "expected expression");
2494 db.note("variable declaration using `let` is a statement");
2496 } else if self.token.is_path_start() {
2497 let pth = self.parse_path(PathStyle::Expr)?;
2499 // `!`, as an operator, is prefix, so we know this isn't that
2500 if self.eat(&token::Not) {
2501 // MACRO INVOCATION expression
2502 let (delim, tts) = self.expect_delimited_token_tree()?;
2503 let hi = self.prev_span;
2504 let node = Mac_ { path: pth, tts, delim };
2505 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2507 if self.check(&token::OpenDelim(token::Brace)) {
2508 // This is a struct literal, unless we're prohibited
2509 // from parsing struct literals here.
2510 let prohibited = self.restrictions.contains(
2511 Restrictions::NO_STRUCT_LITERAL
2514 return self.parse_struct_expr(lo, pth, attrs);
2519 ex = ExprKind::Path(None, pth);
2521 match self.parse_literal_maybe_minus() {
2524 ex = expr.node.clone();
2527 self.cancel(&mut err);
2528 let msg = format!("expected expression, found {}",
2529 self.this_token_descr());
2530 let mut err = self.fatal(&msg);
2531 err.span_label(self.span, "expected expression");
2539 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2540 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2545 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2546 -> PResult<'a, P<Expr>> {
2547 let struct_sp = lo.to(self.prev_span);
2549 let mut fields = Vec::new();
2550 let mut base = None;
2552 attrs.extend(self.parse_inner_attributes()?);
2554 while self.token != token::CloseDelim(token::Brace) {
2555 if self.eat(&token::DotDot) {
2556 let exp_span = self.prev_span;
2557 match self.parse_expr() {
2563 self.recover_stmt();
2566 if self.token == token::Comma {
2567 let mut err = self.sess.span_diagnostic.mut_span_err(
2568 exp_span.to(self.prev_span),
2569 "cannot use a comma after the base struct",
2571 err.span_suggestion_short_with_applicability(
2573 "remove this comma",
2575 Applicability::MachineApplicable
2577 err.note("the base struct must always be the last field");
2579 self.recover_stmt();
2584 match self.parse_field() {
2585 Ok(f) => fields.push(f),
2587 e.span_label(struct_sp, "while parsing this struct");
2590 // If the next token is a comma, then try to parse
2591 // what comes next as additional fields, rather than
2592 // bailing out until next `}`.
2593 if self.token != token::Comma {
2594 self.recover_stmt();
2600 match self.expect_one_of(&[token::Comma],
2601 &[token::CloseDelim(token::Brace)]) {
2605 self.recover_stmt();
2611 let span = lo.to(self.span);
2612 self.expect(&token::CloseDelim(token::Brace))?;
2613 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2616 fn parse_or_use_outer_attributes(&mut self,
2617 already_parsed_attrs: Option<ThinVec<Attribute>>)
2618 -> PResult<'a, ThinVec<Attribute>> {
2619 if let Some(attrs) = already_parsed_attrs {
2622 self.parse_outer_attributes().map(|a| a.into())
2626 /// Parse a block or unsafe block
2627 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2628 lo: Span, blk_mode: BlockCheckMode,
2629 outer_attrs: ThinVec<Attribute>)
2630 -> PResult<'a, P<Expr>> {
2631 self.expect(&token::OpenDelim(token::Brace))?;
2633 let mut attrs = outer_attrs;
2634 attrs.extend(self.parse_inner_attributes()?);
2636 let blk = self.parse_block_tail(lo, blk_mode)?;
2637 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2640 /// parse a.b or a(13) or a[4] or just a
2641 fn parse_dot_or_call_expr(&mut self,
2642 already_parsed_attrs: Option<ThinVec<Attribute>>)
2643 -> PResult<'a, P<Expr>> {
2644 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2646 let b = self.parse_bottom_expr();
2647 let (span, b) = self.interpolated_or_expr_span(b)?;
2648 self.parse_dot_or_call_expr_with(b, span, attrs)
2651 fn parse_dot_or_call_expr_with(&mut self,
2654 mut attrs: ThinVec<Attribute>)
2655 -> PResult<'a, P<Expr>> {
2656 // Stitch the list of outer attributes onto the return value.
2657 // A little bit ugly, but the best way given the current code
2659 self.parse_dot_or_call_expr_with_(e0, lo)
2661 expr.map(|mut expr| {
2662 attrs.extend::<Vec<_>>(expr.attrs.into());
2665 ExprKind::If(..) | ExprKind::IfLet(..) => {
2666 if !expr.attrs.is_empty() {
2667 // Just point to the first attribute in there...
2668 let span = expr.attrs[0].span;
2671 "attributes are not yet allowed on `if` \
2682 // Assuming we have just parsed `.`, continue parsing into an expression.
2683 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2684 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2685 Ok(match self.token {
2686 token::OpenDelim(token::Paren) => {
2687 // Method call `expr.f()`
2688 let mut args = self.parse_unspanned_seq(
2689 &token::OpenDelim(token::Paren),
2690 &token::CloseDelim(token::Paren),
2691 SeqSep::trailing_allowed(token::Comma),
2692 |p| Ok(p.parse_expr()?)
2694 args.insert(0, self_arg);
2696 let span = lo.to(self.prev_span);
2697 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2700 // Field access `expr.f`
2701 if let Some(args) = segment.args {
2702 self.span_err(args.span(),
2703 "field expressions may not have generic arguments");
2706 let span = lo.to(self.prev_span);
2707 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2712 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2717 while self.eat(&token::Question) {
2718 let hi = self.prev_span;
2719 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2723 if self.eat(&token::Dot) {
2725 token::Ident(..) => {
2726 e = self.parse_dot_suffix(e, lo)?;
2728 token::Literal(token::Integer(name), _) => {
2729 let span = self.span;
2731 let field = ExprKind::Field(e, Ident::new(name, span));
2732 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2734 token::Literal(token::Float(n), _suf) => {
2736 let fstr = n.as_str();
2737 let mut err = self.diagnostic()
2738 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
2739 err.span_label(self.prev_span, "unexpected token");
2740 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2741 let float = match fstr.parse::<f64>().ok() {
2745 let sugg = pprust::to_string(|s| {
2746 use print::pprust::PrintState;
2750 s.print_usize(float.trunc() as usize)?;
2753 s.s.word(fstr.splitn(2, ".").last().unwrap())
2755 err.span_suggestion_with_applicability(
2756 lo.to(self.prev_span),
2757 "try parenthesizing the first index",
2759 Applicability::MachineApplicable
2766 // FIXME Could factor this out into non_fatal_unexpected or something.
2767 let actual = self.this_token_to_string();
2768 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2773 if self.expr_is_complete(&e) { break; }
2776 token::OpenDelim(token::Paren) => {
2777 let es = self.parse_unspanned_seq(
2778 &token::OpenDelim(token::Paren),
2779 &token::CloseDelim(token::Paren),
2780 SeqSep::trailing_allowed(token::Comma),
2781 |p| Ok(p.parse_expr()?)
2783 hi = self.prev_span;
2785 let nd = self.mk_call(e, es);
2786 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2790 // Could be either an index expression or a slicing expression.
2791 token::OpenDelim(token::Bracket) => {
2793 let ix = self.parse_expr()?;
2795 self.expect(&token::CloseDelim(token::Bracket))?;
2796 let index = self.mk_index(e, ix);
2797 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2805 crate fn process_potential_macro_variable(&mut self) {
2806 let (token, span) = match self.token {
2807 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2808 self.look_ahead(1, |t| t.is_ident()) => {
2810 let name = match self.token {
2811 token::Ident(ident, _) => ident,
2814 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2815 err.span_label(self.span, "unknown macro variable");
2819 token::Interpolated(ref nt) => {
2820 self.meta_var_span = Some(self.span);
2821 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2822 // and lifetime tokens, so the former are never encountered during normal parsing.
2824 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2825 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2835 /// parse a single token tree from the input.
2836 crate fn parse_token_tree(&mut self) -> TokenTree {
2838 token::OpenDelim(..) => {
2839 let frame = mem::replace(&mut self.token_cursor.frame,
2840 self.token_cursor.stack.pop().unwrap());
2841 self.span = frame.span.entire();
2843 TokenTree::Delimited(frame.span, Delimited {
2845 tts: frame.tree_cursor.original_stream().into(),
2848 token::CloseDelim(_) | token::Eof => unreachable!(),
2850 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2852 TokenTree::Token(span, token)
2857 // parse a stream of tokens into a list of TokenTree's,
2859 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2860 let mut tts = Vec::new();
2861 while self.token != token::Eof {
2862 tts.push(self.parse_token_tree());
2867 pub fn parse_tokens(&mut self) -> TokenStream {
2868 let mut result = Vec::new();
2871 token::Eof | token::CloseDelim(..) => break,
2872 _ => result.push(self.parse_token_tree().into()),
2875 TokenStream::concat(result)
2878 /// Parse a prefix-unary-operator expr
2879 fn parse_prefix_expr(&mut self,
2880 already_parsed_attrs: Option<ThinVec<Attribute>>)
2881 -> PResult<'a, P<Expr>> {
2882 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2884 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2885 let (hi, ex) = match self.token {
2888 let e = self.parse_prefix_expr(None);
2889 let (span, e) = self.interpolated_or_expr_span(e)?;
2890 (lo.to(span), self.mk_unary(UnOp::Not, e))
2892 // Suggest `!` for bitwise negation when encountering a `~`
2895 let e = self.parse_prefix_expr(None);
2896 let (span, e) = self.interpolated_or_expr_span(e)?;
2897 let span_of_tilde = lo;
2898 let mut err = self.diagnostic()
2899 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2900 err.span_suggestion_short_with_applicability(
2902 "use `!` to perform bitwise negation",
2904 Applicability::MachineApplicable
2907 (lo.to(span), self.mk_unary(UnOp::Not, e))
2909 token::BinOp(token::Minus) => {
2911 let e = self.parse_prefix_expr(None);
2912 let (span, e) = self.interpolated_or_expr_span(e)?;
2913 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2915 token::BinOp(token::Star) => {
2917 let e = self.parse_prefix_expr(None);
2918 let (span, e) = self.interpolated_or_expr_span(e)?;
2919 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2921 token::BinOp(token::And) | token::AndAnd => {
2923 let m = self.parse_mutability();
2924 let e = self.parse_prefix_expr(None);
2925 let (span, e) = self.interpolated_or_expr_span(e)?;
2926 (lo.to(span), ExprKind::AddrOf(m, e))
2928 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2930 let place = self.parse_expr_res(
2931 Restrictions::NO_STRUCT_LITERAL,
2934 let blk = self.parse_block()?;
2935 let span = blk.span;
2936 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2937 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2939 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2941 let e = self.parse_prefix_expr(None);
2942 let (span, e) = self.interpolated_or_expr_span(e)?;
2943 (lo.to(span), ExprKind::Box(e))
2945 token::Ident(..) if self.token.is_ident_named("not") => {
2946 // `not` is just an ordinary identifier in Rust-the-language,
2947 // but as `rustc`-the-compiler, we can issue clever diagnostics
2948 // for confused users who really want to say `!`
2949 let token_cannot_continue_expr = |t: &token::Token| match *t {
2950 // These tokens can start an expression after `!`, but
2951 // can't continue an expression after an ident
2952 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2953 token::Literal(..) | token::Pound => true,
2954 token::Interpolated(ref nt) => match nt.0 {
2955 token::NtIdent(..) | token::NtExpr(..) |
2956 token::NtBlock(..) | token::NtPath(..) => true,
2961 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2962 if cannot_continue_expr {
2964 // Emit the error ...
2965 let mut err = self.diagnostic()
2966 .struct_span_err(self.span,
2967 &format!("unexpected {} after identifier",
2968 self.this_token_descr()));
2969 // span the `not` plus trailing whitespace to avoid
2970 // trailing whitespace after the `!` in our suggestion
2971 let to_replace = self.sess.source_map()
2972 .span_until_non_whitespace(lo.to(self.span));
2973 err.span_suggestion_short_with_applicability(
2975 "use `!` to perform logical negation",
2977 Applicability::MachineApplicable
2980 // —and recover! (just as if we were in the block
2981 // for the `token::Not` arm)
2982 let e = self.parse_prefix_expr(None);
2983 let (span, e) = self.interpolated_or_expr_span(e)?;
2984 (lo.to(span), self.mk_unary(UnOp::Not, e))
2986 return self.parse_dot_or_call_expr(Some(attrs));
2989 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2991 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2994 /// Parse an associative expression
2996 /// This parses an expression accounting for associativity and precedence of the operators in
2998 fn parse_assoc_expr(&mut self,
2999 already_parsed_attrs: Option<ThinVec<Attribute>>)
3000 -> PResult<'a, P<Expr>> {
3001 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3004 /// Parse an associative expression with operators of at least `min_prec` precedence
3005 fn parse_assoc_expr_with(&mut self,
3008 -> PResult<'a, P<Expr>> {
3009 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3012 let attrs = match lhs {
3013 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3016 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3017 return self.parse_prefix_range_expr(attrs);
3019 self.parse_prefix_expr(attrs)?
3023 if self.expr_is_complete(&lhs) {
3024 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3027 self.expected_tokens.push(TokenType::Operator);
3028 while let Some(op) = AssocOp::from_token(&self.token) {
3030 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3031 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3032 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3033 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3034 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3035 (PrevTokenKind::Interpolated, _) => self.prev_span,
3036 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3037 if path.segments.len() == 1 => self.prev_span,
3041 let cur_op_span = self.span;
3042 let restrictions = if op.is_assign_like() {
3043 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3047 if op.precedence() < min_prec {
3050 // Check for deprecated `...` syntax
3051 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3052 self.err_dotdotdot_syntax(self.span);
3056 if op.is_comparison() {
3057 self.check_no_chained_comparison(&lhs, &op);
3060 if op == AssocOp::As {
3061 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3063 } else if op == AssocOp::Colon {
3064 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3067 err.span_label(self.span,
3068 "expecting a type here because of type ascription");
3069 let cm = self.sess.source_map();
3070 let cur_pos = cm.lookup_char_pos(self.span.lo());
3071 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3072 if cur_pos.line != op_pos.line {
3073 err.span_suggestion_with_applicability(
3075 "try using a semicolon",
3077 Applicability::MaybeIncorrect // speculative
3084 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3085 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3086 // generalise it to the Fixity::None code.
3088 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3089 // two variants are handled with `parse_prefix_range_expr` call above.
3090 let rhs = if self.is_at_start_of_range_notation_rhs() {
3091 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3092 LhsExpr::NotYetParsed)?)
3096 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3101 let limits = if op == AssocOp::DotDot {
3102 RangeLimits::HalfOpen
3107 let r = try!(self.mk_range(Some(lhs), rhs, limits));
3108 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3112 let rhs = match op.fixity() {
3113 Fixity::Right => self.with_res(
3114 restrictions - Restrictions::STMT_EXPR,
3116 this.parse_assoc_expr_with(op.precedence(),
3117 LhsExpr::NotYetParsed)
3119 Fixity::Left => self.with_res(
3120 restrictions - Restrictions::STMT_EXPR,
3122 this.parse_assoc_expr_with(op.precedence() + 1,
3123 LhsExpr::NotYetParsed)
3125 // We currently have no non-associative operators that are not handled above by
3126 // the special cases. The code is here only for future convenience.
3127 Fixity::None => self.with_res(
3128 restrictions - Restrictions::STMT_EXPR,
3130 this.parse_assoc_expr_with(op.precedence() + 1,
3131 LhsExpr::NotYetParsed)
3135 let span = lhs_span.to(rhs.span);
3137 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3138 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3139 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3140 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3141 AssocOp::Greater | AssocOp::GreaterEqual => {
3142 let ast_op = op.to_ast_binop().unwrap();
3143 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3144 self.mk_expr(span, binary, ThinVec::new())
3147 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3148 AssocOp::ObsoleteInPlace =>
3149 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3150 AssocOp::AssignOp(k) => {
3152 token::Plus => BinOpKind::Add,
3153 token::Minus => BinOpKind::Sub,
3154 token::Star => BinOpKind::Mul,
3155 token::Slash => BinOpKind::Div,
3156 token::Percent => BinOpKind::Rem,
3157 token::Caret => BinOpKind::BitXor,
3158 token::And => BinOpKind::BitAnd,
3159 token::Or => BinOpKind::BitOr,
3160 token::Shl => BinOpKind::Shl,
3161 token::Shr => BinOpKind::Shr,
3163 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3164 self.mk_expr(span, aopexpr, ThinVec::new())
3166 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3167 self.bug("AssocOp should have been handled by special case")
3171 if op.fixity() == Fixity::None { break }
3176 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3177 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3178 -> PResult<'a, P<Expr>> {
3179 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3180 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3183 // Save the state of the parser before parsing type normally, in case there is a
3184 // LessThan comparison after this cast.
3185 let parser_snapshot_before_type = self.clone();
3186 match self.parse_ty_no_plus() {
3188 Ok(mk_expr(self, rhs))
3190 Err(mut type_err) => {
3191 // Rewind to before attempting to parse the type with generics, to recover
3192 // from situations like `x as usize < y` in which we first tried to parse
3193 // `usize < y` as a type with generic arguments.
3194 let parser_snapshot_after_type = self.clone();
3195 mem::replace(self, parser_snapshot_before_type);
3197 match self.parse_path(PathStyle::Expr) {
3199 let (op_noun, op_verb) = match self.token {
3200 token::Lt => ("comparison", "comparing"),
3201 token::BinOp(token::Shl) => ("shift", "shifting"),
3203 // We can end up here even without `<` being the next token, for
3204 // example because `parse_ty_no_plus` returns `Err` on keywords,
3205 // but `parse_path` returns `Ok` on them due to error recovery.
3206 // Return original error and parser state.
3207 mem::replace(self, parser_snapshot_after_type);
3208 return Err(type_err);
3212 // Successfully parsed the type path leaving a `<` yet to parse.
3215 // Report non-fatal diagnostics, keep `x as usize` as an expression
3216 // in AST and continue parsing.
3217 let msg = format!("`<` is interpreted as a start of generic \
3218 arguments for `{}`, not a {}", path, op_noun);
3219 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3220 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3221 "interpreted as generic arguments");
3222 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3224 let expr = mk_expr(self, P(Ty {
3226 node: TyKind::Path(None, path),
3227 id: ast::DUMMY_NODE_ID
3230 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3231 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3232 err.span_suggestion_with_applicability(
3234 &format!("try {} the cast value", op_verb),
3235 format!("({})", expr_str),
3236 Applicability::MachineApplicable
3242 Err(mut path_err) => {
3243 // Couldn't parse as a path, return original error and parser state.
3245 mem::replace(self, parser_snapshot_after_type);
3253 /// Produce an error if comparison operators are chained (RFC #558).
3254 /// We only need to check lhs, not rhs, because all comparison ops
3255 /// have same precedence and are left-associative
3256 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3257 debug_assert!(outer_op.is_comparison(),
3258 "check_no_chained_comparison: {:?} is not comparison",
3261 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3262 // respan to include both operators
3263 let op_span = op.span.to(self.span);
3264 let mut err = self.diagnostic().struct_span_err(op_span,
3265 "chained comparison operators require parentheses");
3266 if op.node == BinOpKind::Lt &&
3267 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3268 *outer_op == AssocOp::Greater // even in a case like the following:
3269 { // Foo<Bar<Baz<Qux, ()>>>
3271 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3272 err.help("or use `(...)` if you meant to specify fn arguments");
3280 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3281 fn parse_prefix_range_expr(&mut self,
3282 already_parsed_attrs: Option<ThinVec<Attribute>>)
3283 -> PResult<'a, P<Expr>> {
3284 // Check for deprecated `...` syntax
3285 if self.token == token::DotDotDot {
3286 self.err_dotdotdot_syntax(self.span);
3289 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3290 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3292 let tok = self.token.clone();
3293 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3295 let mut hi = self.span;
3297 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3298 // RHS must be parsed with more associativity than the dots.
3299 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3300 Some(self.parse_assoc_expr_with(next_prec,
3301 LhsExpr::NotYetParsed)
3309 let limits = if tok == token::DotDot {
3310 RangeLimits::HalfOpen
3315 let r = try!(self.mk_range(None,
3318 Ok(self.mk_expr(lo.to(hi), r, attrs))
3321 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3322 if self.token.can_begin_expr() {
3323 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3324 if self.token == token::OpenDelim(token::Brace) {
3325 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3333 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3334 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3335 if self.check_keyword(keywords::Let) {
3336 return self.parse_if_let_expr(attrs);
3338 let lo = self.prev_span;
3339 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3341 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3342 // verify that the last statement is either an implicit return (no `;`) or an explicit
3343 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3344 // the dead code lint.
3345 if self.eat_keyword(keywords::Else) || !cond.returns() {
3346 let sp = self.sess.source_map().next_point(lo);
3347 let mut err = self.diagnostic()
3348 .struct_span_err(sp, "missing condition for `if` statemement");
3349 err.span_label(sp, "expected if condition here");
3352 let not_block = self.token != token::OpenDelim(token::Brace);
3353 let thn = self.parse_block().map_err(|mut err| {
3355 err.span_label(lo, "this `if` statement has a condition, but no block");
3359 let mut els: Option<P<Expr>> = None;
3360 let mut hi = thn.span;
3361 if self.eat_keyword(keywords::Else) {
3362 let elexpr = self.parse_else_expr()?;
3366 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3369 /// Parse an 'if let' expression ('if' token already eaten)
3370 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3371 -> PResult<'a, P<Expr>> {
3372 let lo = self.prev_span;
3373 self.expect_keyword(keywords::Let)?;
3374 let pats = self.parse_pats()?;
3375 self.expect(&token::Eq)?;
3376 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3377 let thn = self.parse_block()?;
3378 let (hi, els) = if self.eat_keyword(keywords::Else) {
3379 let expr = self.parse_else_expr()?;
3380 (expr.span, Some(expr))
3384 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3387 // `move |args| expr`
3388 fn parse_lambda_expr(&mut self,
3389 attrs: ThinVec<Attribute>)
3390 -> PResult<'a, P<Expr>>
3393 let movability = if self.eat_keyword(keywords::Static) {
3398 let asyncness = if self.span.edition() >= Edition::Edition2018 {
3399 self.parse_asyncness()
3403 let capture_clause = if self.eat_keyword(keywords::Move) {
3408 let decl = self.parse_fn_block_decl()?;
3409 let decl_hi = self.prev_span;
3410 let body = match decl.output {
3411 FunctionRetTy::Default(_) => {
3412 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3413 self.parse_expr_res(restrictions, None)?
3416 // If an explicit return type is given, require a
3417 // block to appear (RFC 968).
3418 let body_lo = self.span;
3419 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3425 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3429 // `else` token already eaten
3430 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3431 if self.eat_keyword(keywords::If) {
3432 return self.parse_if_expr(ThinVec::new());
3434 let blk = self.parse_block()?;
3435 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3439 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3440 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3442 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3443 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3445 let pat = self.parse_top_level_pat()?;
3446 if !self.eat_keyword(keywords::In) {
3447 let in_span = self.prev_span.between(self.span);
3448 let mut err = self.sess.span_diagnostic
3449 .struct_span_err(in_span, "missing `in` in `for` loop");
3450 err.span_suggestion_short_with_applicability(
3451 in_span, "try adding `in` here", " in ".into(),
3452 // has been misleading, at least in the past (closed Issue #48492)
3453 Applicability::MaybeIncorrect
3457 let in_span = self.prev_span;
3458 if self.eat_keyword(keywords::In) {
3459 // a common typo: `for _ in in bar {}`
3460 let mut err = self.sess.span_diagnostic.struct_span_err(
3462 "expected iterable, found keyword `in`",
3464 err.span_suggestion_short_with_applicability(
3465 in_span.until(self.prev_span),
3466 "remove the duplicated `in`",
3468 Applicability::MachineApplicable,
3470 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3471 err.note("for more information on the status of emplacement syntax, see <\
3472 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3475 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3476 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3477 attrs.extend(iattrs);
3479 let hi = self.prev_span;
3480 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3483 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3484 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3486 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3487 if self.token.is_keyword(keywords::Let) {
3488 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3490 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3491 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3492 attrs.extend(iattrs);
3493 let span = span_lo.to(body.span);
3494 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3497 /// Parse a 'while let' expression ('while' token already eaten)
3498 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3500 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3501 self.expect_keyword(keywords::Let)?;
3502 let pats = self.parse_pats()?;
3503 self.expect(&token::Eq)?;
3504 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3505 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3506 attrs.extend(iattrs);
3507 let span = span_lo.to(body.span);
3508 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3511 // parse `loop {...}`, `loop` token already eaten
3512 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3514 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3515 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3516 attrs.extend(iattrs);
3517 let span = span_lo.to(body.span);
3518 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3521 /// Parse an `async move {...}` expression
3522 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3523 -> PResult<'a, P<Expr>>
3525 let span_lo = self.span;
3526 self.expect_keyword(keywords::Async)?;
3527 let capture_clause = if self.eat_keyword(keywords::Move) {
3532 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3533 attrs.extend(iattrs);
3535 span_lo.to(body.span),
3536 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3539 /// Parse a `try {...}` expression (`try` token already eaten)
3540 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3541 -> PResult<'a, P<Expr>>
3543 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3544 attrs.extend(iattrs);
3545 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3548 // `match` token already eaten
3549 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3550 let match_span = self.prev_span;
3551 let lo = self.prev_span;
3552 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3554 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3555 if self.token == token::Token::Semi {
3556 e.span_suggestion_short_with_applicability(
3558 "try removing this `match`",
3560 Applicability::MaybeIncorrect // speculative
3565 attrs.extend(self.parse_inner_attributes()?);
3567 let mut arms: Vec<Arm> = Vec::new();
3568 while self.token != token::CloseDelim(token::Brace) {
3569 match self.parse_arm() {
3570 Ok(arm) => arms.push(arm),
3572 // Recover by skipping to the end of the block.
3574 self.recover_stmt();
3575 let span = lo.to(self.span);
3576 if self.token == token::CloseDelim(token::Brace) {
3579 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3585 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3588 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3589 maybe_whole!(self, NtArm, |x| x);
3591 let attrs = self.parse_outer_attributes()?;
3592 // Allow a '|' before the pats (RFC 1925)
3593 self.eat(&token::BinOp(token::Or));
3594 let pats = self.parse_pats()?;
3595 let guard = if self.eat_keyword(keywords::If) {
3596 Some(Guard::If(self.parse_expr()?))
3600 let arrow_span = self.span;
3601 self.expect(&token::FatArrow)?;
3602 let arm_start_span = self.span;
3604 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3605 .map_err(|mut err| {
3606 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3610 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3611 && self.token != token::CloseDelim(token::Brace);
3614 let cm = self.sess.source_map();
3615 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3616 .map_err(|mut err| {
3617 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3618 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3619 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3620 && expr_lines.lines.len() == 2
3621 && self.token == token::FatArrow => {
3622 // We check whether there's any trailing code in the parse span,
3623 // if there isn't, we very likely have the following:
3626 // | -- - missing comma
3632 // | parsed until here as `"y" & X`
3633 err.span_suggestion_short_with_applicability(
3634 cm.next_point(arm_start_span),
3635 "missing a comma here to end this `match` arm",
3637 Applicability::MachineApplicable
3641 err.span_label(arrow_span,
3642 "while parsing the `match` arm starting here");
3648 self.eat(&token::Comma);
3659 /// Parse an expression
3660 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3661 self.parse_expr_res(Restrictions::empty(), None)
3664 /// Evaluate the closure with restrictions in place.
3666 /// After the closure is evaluated, restrictions are reset.
3667 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3668 where F: FnOnce(&mut Self) -> T
3670 let old = self.restrictions;
3671 self.restrictions = r;
3673 self.restrictions = old;
3678 /// Parse an expression, subject to the given restrictions
3679 fn parse_expr_res(&mut self, r: Restrictions,
3680 already_parsed_attrs: Option<ThinVec<Attribute>>)
3681 -> PResult<'a, P<Expr>> {
3682 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3685 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3686 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3687 if self.eat(&token::Eq) {
3688 Ok(Some(self.parse_expr()?))
3690 Ok(Some(self.parse_expr()?))
3696 /// Parse patterns, separated by '|' s
3697 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3698 let mut pats = Vec::new();
3700 pats.push(self.parse_top_level_pat()?);
3702 if self.token == token::OrOr {
3703 let mut err = self.struct_span_err(self.span,
3704 "unexpected token `||` after pattern");
3705 err.span_suggestion_with_applicability(
3707 "use a single `|` to specify multiple patterns",
3709 Applicability::MachineApplicable
3713 } else if self.eat(&token::BinOp(token::Or)) {
3721 // Parses a parenthesized list of patterns like
3722 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3723 // - a vector of the patterns that were parsed
3724 // - an option indicating the index of the `..` element
3725 // - a boolean indicating whether a trailing comma was present.
3726 // Trailing commas are significant because (p) and (p,) are different patterns.
3727 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3728 self.expect(&token::OpenDelim(token::Paren))?;
3729 let result = self.parse_pat_list()?;
3730 self.expect(&token::CloseDelim(token::Paren))?;
3734 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3735 let mut fields = Vec::new();
3736 let mut ddpos = None;
3737 let mut trailing_comma = false;
3739 if self.eat(&token::DotDot) {
3740 if ddpos.is_none() {
3741 ddpos = Some(fields.len());
3743 // Emit a friendly error, ignore `..` and continue parsing
3744 self.span_err(self.prev_span,
3745 "`..` can only be used once per tuple or tuple struct pattern");
3747 } else if !self.check(&token::CloseDelim(token::Paren)) {
3748 fields.push(self.parse_pat()?);
3753 trailing_comma = self.eat(&token::Comma);
3754 if !trailing_comma {
3759 if ddpos == Some(fields.len()) && trailing_comma {
3760 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3761 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3764 Ok((fields, ddpos, trailing_comma))
3767 fn parse_pat_vec_elements(
3769 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3770 let mut before = Vec::new();
3771 let mut slice = None;
3772 let mut after = Vec::new();
3773 let mut first = true;
3774 let mut before_slice = true;
3776 while self.token != token::CloseDelim(token::Bracket) {
3780 self.expect(&token::Comma)?;
3782 if self.token == token::CloseDelim(token::Bracket)
3783 && (before_slice || !after.is_empty()) {
3789 if self.eat(&token::DotDot) {
3791 if self.check(&token::Comma) ||
3792 self.check(&token::CloseDelim(token::Bracket)) {
3793 slice = Some(P(Pat {
3794 id: ast::DUMMY_NODE_ID,
3795 node: PatKind::Wild,
3796 span: self.prev_span,
3798 before_slice = false;
3804 let subpat = self.parse_pat()?;
3805 if before_slice && self.eat(&token::DotDot) {
3806 slice = Some(subpat);
3807 before_slice = false;
3808 } else if before_slice {
3809 before.push(subpat);
3815 Ok((before, slice, after))
3821 attrs: Vec<Attribute>
3822 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3823 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3825 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3826 // Parsing a pattern of the form "fieldname: pat"
3827 let fieldname = self.parse_field_name()?;
3829 let pat = self.parse_pat()?;
3831 (pat, fieldname, false)
3833 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3834 let is_box = self.eat_keyword(keywords::Box);
3835 let boxed_span = self.span;
3836 let is_ref = self.eat_keyword(keywords::Ref);
3837 let is_mut = self.eat_keyword(keywords::Mut);
3838 let fieldname = self.parse_ident()?;
3839 hi = self.prev_span;
3841 let bind_type = match (is_ref, is_mut) {
3842 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3843 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3844 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3845 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3847 let fieldpat = P(Pat {
3848 id: ast::DUMMY_NODE_ID,
3849 node: PatKind::Ident(bind_type, fieldname, None),
3850 span: boxed_span.to(hi),
3853 let subpat = if is_box {
3855 id: ast::DUMMY_NODE_ID,
3856 node: PatKind::Box(fieldpat),
3862 (subpat, fieldname, true)
3865 Ok(source_map::Spanned {
3867 node: ast::FieldPat {
3871 attrs: attrs.into(),
3876 /// Parse the fields of a struct-like pattern
3877 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3878 let mut fields = Vec::new();
3879 let mut etc = false;
3880 let mut ate_comma = true;
3881 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3882 let mut etc_span = None;
3884 while self.token != token::CloseDelim(token::Brace) {
3885 let attrs = self.parse_outer_attributes()?;
3888 // check that a comma comes after every field
3890 let err = self.struct_span_err(self.prev_span, "expected `,`");
3891 if let Some(mut delayed) = delayed_err {
3898 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3900 let mut etc_sp = self.span;
3902 if self.token == token::DotDotDot { // Issue #46718
3903 // Accept `...` as if it were `..` to avoid further errors
3904 let mut err = self.struct_span_err(self.span,
3905 "expected field pattern, found `...`");
3906 err.span_suggestion_with_applicability(
3908 "to omit remaining fields, use one fewer `.`",
3910 Applicability::MachineApplicable
3914 self.bump(); // `..` || `...`:w
3916 if self.token == token::CloseDelim(token::Brace) {
3917 etc_span = Some(etc_sp);
3920 let token_str = self.this_token_to_string();
3921 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3923 err.span_label(self.span, "expected `}`");
3924 let mut comma_sp = None;
3925 if self.token == token::Comma { // Issue #49257
3926 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3927 err.span_label(etc_sp,
3928 "`..` must be at the end and cannot have a trailing comma");
3929 comma_sp = Some(self.span);
3934 etc_span = Some(etc_sp);
3935 if self.token == token::CloseDelim(token::Brace) {
3936 // If the struct looks otherwise well formed, recover and continue.
3937 if let Some(sp) = comma_sp {
3938 err.span_suggestion_short_with_applicability(
3940 "remove this comma",
3942 Applicability::MachineApplicable,
3947 } else if self.token.is_ident() && ate_comma {
3948 // Accept fields coming after `..,`.
3949 // This way we avoid "pattern missing fields" errors afterwards.
3950 // We delay this error until the end in order to have a span for a
3952 if let Some(mut delayed_err) = delayed_err {
3956 delayed_err = Some(err);
3959 if let Some(mut err) = delayed_err {
3966 fields.push(match self.parse_pat_field(lo, attrs) {
3969 if let Some(mut delayed_err) = delayed_err {
3975 ate_comma = self.eat(&token::Comma);
3978 if let Some(mut err) = delayed_err {
3979 if let Some(etc_span) = etc_span {
3980 err.multipart_suggestion(
3981 "move the `..` to the end of the field list",
3983 (etc_span, String::new()),
3984 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3990 return Ok((fields, etc));
3993 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3994 if self.token.is_path_start() {
3996 let (qself, path) = if self.eat_lt() {
3997 // Parse a qualified path
3998 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4001 // Parse an unqualified path
4002 (None, self.parse_path(PathStyle::Expr)?)
4004 let hi = self.prev_span;
4005 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4007 self.parse_literal_maybe_minus()
4011 // helper function to decide whether to parse as ident binding or to try to do
4012 // something more complex like range patterns
4013 fn parse_as_ident(&mut self) -> bool {
4014 self.look_ahead(1, |t| match *t {
4015 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4016 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4017 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4018 // range pattern branch
4019 token::DotDot => None,
4021 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4022 token::Comma | token::CloseDelim(token::Bracket) => true,
4027 /// A wrapper around `parse_pat` with some special error handling for the
4028 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4029 /// to subpatterns within such).
4030 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4031 let pat = self.parse_pat()?;
4032 if self.token == token::Comma {
4033 // An unexpected comma after a top-level pattern is a clue that the
4034 // user (perhaps more accustomed to some other language) forgot the
4035 // parentheses in what should have been a tuple pattern; return a
4036 // suggestion-enhanced error here rather than choking on the comma
4038 let comma_span = self.span;
4040 if let Err(mut err) = self.parse_pat_list() {
4041 // We didn't expect this to work anyway; we just wanted
4042 // to advance to the end of the comma-sequence so we know
4043 // the span to suggest parenthesizing
4046 let seq_span = pat.span.to(self.prev_span);
4047 let mut err = self.struct_span_err(comma_span,
4048 "unexpected `,` in pattern");
4049 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4050 err.span_suggestion_with_applicability(
4052 "try adding parentheses",
4053 format!("({})", seq_snippet),
4054 Applicability::MachineApplicable
4062 /// Parse a pattern.
4063 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
4064 self.parse_pat_with_range_pat(true)
4067 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
4069 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
4070 maybe_whole!(self, NtPat, |x| x);
4075 token::BinOp(token::And) | token::AndAnd => {
4076 // Parse &pat / &mut pat
4078 let mutbl = self.parse_mutability();
4079 if let token::Lifetime(ident) = self.token {
4080 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4082 err.span_label(self.span, "unexpected lifetime");
4085 let subpat = self.parse_pat_with_range_pat(false)?;
4086 pat = PatKind::Ref(subpat, mutbl);
4088 token::OpenDelim(token::Paren) => {
4089 // Parse (pat,pat,pat,...) as tuple pattern
4090 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4091 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4092 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4094 PatKind::Tuple(fields, ddpos)
4097 token::OpenDelim(token::Bracket) => {
4098 // Parse [pat,pat,...] as slice pattern
4100 let (before, slice, after) = self.parse_pat_vec_elements()?;
4101 self.expect(&token::CloseDelim(token::Bracket))?;
4102 pat = PatKind::Slice(before, slice, after);
4104 // At this point, token != &, &&, (, [
4105 _ => if self.eat_keyword(keywords::Underscore) {
4107 pat = PatKind::Wild;
4108 } else if self.eat_keyword(keywords::Mut) {
4109 // Parse mut ident @ pat / mut ref ident @ pat
4110 let mutref_span = self.prev_span.to(self.span);
4111 let binding_mode = if self.eat_keyword(keywords::Ref) {
4113 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4114 .span_suggestion_with_applicability(
4116 "try switching the order",
4118 Applicability::MachineApplicable
4120 BindingMode::ByRef(Mutability::Mutable)
4122 BindingMode::ByValue(Mutability::Mutable)
4124 pat = self.parse_pat_ident(binding_mode)?;
4125 } else if self.eat_keyword(keywords::Ref) {
4126 // Parse ref ident @ pat / ref mut ident @ pat
4127 let mutbl = self.parse_mutability();
4128 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4129 } else if self.eat_keyword(keywords::Box) {
4131 let subpat = self.parse_pat_with_range_pat(false)?;
4132 pat = PatKind::Box(subpat);
4133 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4134 self.parse_as_ident() {
4135 // Parse ident @ pat
4136 // This can give false positives and parse nullary enums,
4137 // they are dealt with later in resolve
4138 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4139 pat = self.parse_pat_ident(binding_mode)?;
4140 } else if self.token.is_path_start() {
4141 // Parse pattern starting with a path
4142 let (qself, path) = if self.eat_lt() {
4143 // Parse a qualified path
4144 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4147 // Parse an unqualified path
4148 (None, self.parse_path(PathStyle::Expr)?)
4151 token::Not if qself.is_none() => {
4152 // Parse macro invocation
4154 let (delim, tts) = self.expect_delimited_token_tree()?;
4155 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4156 pat = PatKind::Mac(mac);
4158 token::DotDotDot | token::DotDotEq | token::DotDot => {
4159 let end_kind = match self.token {
4160 token::DotDot => RangeEnd::Excluded,
4161 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4162 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4163 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4166 let op_span = self.span;
4168 let span = lo.to(self.prev_span);
4169 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4171 let end = self.parse_pat_range_end()?;
4172 let op = Spanned { span: op_span, node: end_kind };
4173 pat = PatKind::Range(begin, end, op);
4175 token::OpenDelim(token::Brace) => {
4176 if qself.is_some() {
4177 let msg = "unexpected `{` after qualified path";
4178 let mut err = self.fatal(msg);
4179 err.span_label(self.span, msg);
4182 // Parse struct pattern
4184 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4186 self.recover_stmt();
4190 pat = PatKind::Struct(path, fields, etc);
4192 token::OpenDelim(token::Paren) => {
4193 if qself.is_some() {
4194 let msg = "unexpected `(` after qualified path";
4195 let mut err = self.fatal(msg);
4196 err.span_label(self.span, msg);
4199 // Parse tuple struct or enum pattern
4200 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4201 pat = PatKind::TupleStruct(path, fields, ddpos)
4203 _ => pat = PatKind::Path(qself, path),
4206 // Try to parse everything else as literal with optional minus
4207 match self.parse_literal_maybe_minus() {
4209 let op_span = self.span;
4210 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4211 self.check(&token::DotDotDot) {
4212 let end_kind = if self.eat(&token::DotDotDot) {
4213 RangeEnd::Included(RangeSyntax::DotDotDot)
4214 } else if self.eat(&token::DotDotEq) {
4215 RangeEnd::Included(RangeSyntax::DotDotEq)
4216 } else if self.eat(&token::DotDot) {
4219 panic!("impossible case: we already matched \
4220 on a range-operator token")
4222 let end = self.parse_pat_range_end()?;
4223 let op = Spanned { span: op_span, node: end_kind };
4224 pat = PatKind::Range(begin, end, op);
4226 pat = PatKind::Lit(begin);
4230 self.cancel(&mut err);
4231 let msg = format!("expected pattern, found {}", self.this_token_descr());
4232 let mut err = self.fatal(&msg);
4233 err.span_label(self.span, "expected pattern");
4240 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4241 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4243 if !allow_range_pat {
4246 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4248 PatKind::Range(..) => {
4249 let mut err = self.struct_span_err(
4251 "the range pattern here has ambiguous interpretation",
4253 err.span_suggestion_with_applicability(
4255 "add parentheses to clarify the precedence",
4256 format!("({})", pprust::pat_to_string(&pat)),
4257 // "ambiguous interpretation" implies that we have to be guessing
4258 Applicability::MaybeIncorrect
4269 /// Parse ident or ident @ pat
4270 /// used by the copy foo and ref foo patterns to give a good
4271 /// error message when parsing mistakes like ref foo(a,b)
4272 fn parse_pat_ident(&mut self,
4273 binding_mode: ast::BindingMode)
4274 -> PResult<'a, PatKind> {
4275 let ident = self.parse_ident()?;
4276 let sub = if self.eat(&token::At) {
4277 Some(self.parse_pat()?)
4282 // just to be friendly, if they write something like
4284 // we end up here with ( as the current token. This shortly
4285 // leads to a parse error. Note that if there is no explicit
4286 // binding mode then we do not end up here, because the lookahead
4287 // will direct us over to parse_enum_variant()
4288 if self.token == token::OpenDelim(token::Paren) {
4289 return Err(self.span_fatal(
4291 "expected identifier, found enum pattern"))
4294 Ok(PatKind::Ident(binding_mode, ident, sub))
4297 /// Parse a local variable declaration
4298 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4299 let lo = self.prev_span;
4300 let pat = self.parse_top_level_pat()?;
4302 let (err, ty) = if self.eat(&token::Colon) {
4303 // Save the state of the parser before parsing type normally, in case there is a `:`
4304 // instead of an `=` typo.
4305 let parser_snapshot_before_type = self.clone();
4306 let colon_sp = self.prev_span;
4307 match self.parse_ty() {
4308 Ok(ty) => (None, Some(ty)),
4310 // Rewind to before attempting to parse the type and continue parsing
4311 let parser_snapshot_after_type = self.clone();
4312 mem::replace(self, parser_snapshot_before_type);
4314 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4315 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4316 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4322 let init = match (self.parse_initializer(err.is_some()), err) {
4323 (Ok(init), None) => { // init parsed, ty parsed
4326 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4327 // Could parse the type as if it were the initializer, it is likely there was a
4328 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4329 err.span_suggestion_short_with_applicability(
4331 "use `=` if you meant to assign",
4333 Applicability::MachineApplicable
4336 // As this was parsed successfully, continue as if the code has been fixed for the
4337 // rest of the file. It will still fail due to the emitted error, but we avoid
4341 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4343 // Couldn't parse the type nor the initializer, only raise the type error and
4344 // return to the parser state before parsing the type as the initializer.
4345 // let x: <parse_error>;
4346 mem::replace(self, snapshot);
4349 (Err(err), None) => { // init error, ty parsed
4350 // Couldn't parse the initializer and we're not attempting to recover a failed
4351 // parse of the type, return the error.
4355 let hi = if self.token == token::Semi {
4364 id: ast::DUMMY_NODE_ID,
4370 /// Parse a structure field
4371 fn parse_name_and_ty(&mut self,
4374 attrs: Vec<Attribute>)
4375 -> PResult<'a, StructField> {
4376 let name = self.parse_ident()?;
4377 self.expect(&token::Colon)?;
4378 let ty = self.parse_ty()?;
4380 span: lo.to(self.prev_span),
4383 id: ast::DUMMY_NODE_ID,
4389 /// Emit an expected item after attributes error.
4390 fn expected_item_err(&self, attrs: &[Attribute]) {
4391 let message = match attrs.last() {
4392 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4393 _ => "expected item after attributes",
4396 self.span_err(self.prev_span, message);
4399 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4400 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4401 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4402 Ok(self.parse_stmt_(true))
4405 // Eat tokens until we can be relatively sure we reached the end of the
4406 // statement. This is something of a best-effort heuristic.
4408 // We terminate when we find an unmatched `}` (without consuming it).
4409 fn recover_stmt(&mut self) {
4410 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4413 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4414 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4415 // approximate - it can mean we break too early due to macros, but that
4416 // should only lead to sub-optimal recovery, not inaccurate parsing).
4418 // If `break_on_block` is `Break`, then we will stop consuming tokens
4419 // after finding (and consuming) a brace-delimited block.
4420 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4421 let mut brace_depth = 0;
4422 let mut bracket_depth = 0;
4423 let mut in_block = false;
4424 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4425 break_on_semi, break_on_block);
4427 debug!("recover_stmt_ loop {:?}", self.token);
4429 token::OpenDelim(token::DelimToken::Brace) => {
4432 if break_on_block == BlockMode::Break &&
4434 bracket_depth == 0 {
4438 token::OpenDelim(token::DelimToken::Bracket) => {
4442 token::CloseDelim(token::DelimToken::Brace) => {
4443 if brace_depth == 0 {
4444 debug!("recover_stmt_ return - close delim {:?}", self.token);
4449 if in_block && bracket_depth == 0 && brace_depth == 0 {
4450 debug!("recover_stmt_ return - block end {:?}", self.token);
4454 token::CloseDelim(token::DelimToken::Bracket) => {
4456 if bracket_depth < 0 {
4462 debug!("recover_stmt_ return - Eof");
4467 if break_on_semi == SemiColonMode::Break &&
4469 bracket_depth == 0 {
4470 debug!("recover_stmt_ return - Semi");
4481 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4482 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4484 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4489 fn is_async_block(&mut self) -> bool {
4490 self.token.is_keyword(keywords::Async) &&
4493 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4494 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4496 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4501 fn is_do_catch_block(&mut self) -> bool {
4502 self.token.is_keyword(keywords::Do) &&
4503 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4504 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4505 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4508 fn is_try_block(&mut self) -> bool {
4509 self.token.is_keyword(keywords::Try) &&
4510 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4512 self.span.edition() >= Edition::Edition2018 &&
4514 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4515 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4518 fn is_union_item(&self) -> bool {
4519 self.token.is_keyword(keywords::Union) &&
4520 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4523 fn is_crate_vis(&self) -> bool {
4524 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4527 fn is_extern_non_path(&self) -> bool {
4528 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4531 fn is_existential_type_decl(&self) -> bool {
4532 self.token.is_keyword(keywords::Existential) &&
4533 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4536 fn is_auto_trait_item(&mut self) -> bool {
4538 (self.token.is_keyword(keywords::Auto)
4539 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4540 || // unsafe auto trait
4541 (self.token.is_keyword(keywords::Unsafe) &&
4542 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4543 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4546 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4547 -> PResult<'a, Option<P<Item>>> {
4548 let token_lo = self.span;
4549 let (ident, def) = match self.token {
4550 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4552 let ident = self.parse_ident()?;
4553 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4554 match self.parse_token_tree() {
4555 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4556 _ => unreachable!(),
4558 } else if self.check(&token::OpenDelim(token::Paren)) {
4559 let args = self.parse_token_tree();
4560 let body = if self.check(&token::OpenDelim(token::Brace)) {
4561 self.parse_token_tree()
4566 TokenStream::concat(vec![
4568 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4576 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4578 token::Ident(ident, _) if ident.name == "macro_rules" &&
4579 self.look_ahead(1, |t| *t == token::Not) => {
4580 let prev_span = self.prev_span;
4581 self.complain_if_pub_macro(&vis.node, prev_span);
4585 let ident = self.parse_ident()?;
4586 let (delim, tokens) = self.expect_delimited_token_tree()?;
4587 if delim != MacDelimiter::Brace {
4588 if !self.eat(&token::Semi) {
4589 let msg = "macros that expand to items must either \
4590 be surrounded with braces or followed by a semicolon";
4591 self.span_err(self.prev_span, msg);
4595 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4597 _ => return Ok(None),
4600 let span = lo.to(self.prev_span);
4601 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4604 fn parse_stmt_without_recovery(&mut self,
4605 macro_legacy_warnings: bool)
4606 -> PResult<'a, Option<Stmt>> {
4607 maybe_whole!(self, NtStmt, |x| Some(x));
4609 let attrs = self.parse_outer_attributes()?;
4612 Ok(Some(if self.eat_keyword(keywords::Let) {
4614 id: ast::DUMMY_NODE_ID,
4615 node: StmtKind::Local(self.parse_local(attrs.into())?),
4616 span: lo.to(self.prev_span),
4618 } else if let Some(macro_def) = self.eat_macro_def(
4620 &source_map::respan(lo, VisibilityKind::Inherited),
4624 id: ast::DUMMY_NODE_ID,
4625 node: StmtKind::Item(macro_def),
4626 span: lo.to(self.prev_span),
4628 // Starts like a simple path, being careful to avoid contextual keywords
4629 // such as a union items, item with `crate` visibility or auto trait items.
4630 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4631 // like a path (1 token), but it fact not a path.
4632 // `union::b::c` - path, `union U { ... }` - not a path.
4633 // `crate::b::c` - path, `crate struct S;` - not a path.
4634 // `extern::b::c` - path, `extern crate c;` - not a path.
4635 } else if self.token.is_path_start() &&
4636 !self.token.is_qpath_start() &&
4637 !self.is_union_item() &&
4638 !self.is_crate_vis() &&
4639 !self.is_extern_non_path() &&
4640 !self.is_existential_type_decl() &&
4641 !self.is_auto_trait_item() {
4642 let pth = self.parse_path(PathStyle::Expr)?;
4644 if !self.eat(&token::Not) {
4645 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4646 self.parse_struct_expr(lo, pth, ThinVec::new())?
4648 let hi = self.prev_span;
4649 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4652 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4653 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4654 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4657 return Ok(Some(Stmt {
4658 id: ast::DUMMY_NODE_ID,
4659 node: StmtKind::Expr(expr),
4660 span: lo.to(self.prev_span),
4664 // it's a macro invocation
4665 let id = match self.token {
4666 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4667 _ => self.parse_ident()?,
4670 // check that we're pointing at delimiters (need to check
4671 // again after the `if`, because of `parse_ident`
4672 // consuming more tokens).
4674 token::OpenDelim(_) => {}
4676 // we only expect an ident if we didn't parse one
4678 let ident_str = if id.name == keywords::Invalid.name() {
4683 let tok_str = self.this_token_to_string();
4684 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4687 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4692 let (delim, tts) = self.expect_delimited_token_tree()?;
4693 let hi = self.prev_span;
4695 let style = if delim == MacDelimiter::Brace {
4696 MacStmtStyle::Braces
4698 MacStmtStyle::NoBraces
4701 if id.name == keywords::Invalid.name() {
4702 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4703 let node = if delim == MacDelimiter::Brace ||
4704 self.token == token::Semi || self.token == token::Eof {
4705 StmtKind::Mac(P((mac, style, attrs.into())))
4707 // We used to incorrectly stop parsing macro-expanded statements here.
4708 // If the next token will be an error anyway but could have parsed with the
4709 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4710 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4711 // These can continue an expression, so we can't stop parsing and warn.
4712 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4713 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4714 token::BinOp(token::And) | token::BinOp(token::Or) |
4715 token::AndAnd | token::OrOr |
4716 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4719 self.warn_missing_semicolon();
4720 StmtKind::Mac(P((mac, style, attrs.into())))
4722 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4723 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4724 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4728 id: ast::DUMMY_NODE_ID,
4733 // if it has a special ident, it's definitely an item
4735 // Require a semicolon or braces.
4736 if style != MacStmtStyle::Braces {
4737 if !self.eat(&token::Semi) {
4738 self.span_err(self.prev_span,
4739 "macros that expand to items must \
4740 either be surrounded with braces or \
4741 followed by a semicolon");
4744 let span = lo.to(hi);
4746 id: ast::DUMMY_NODE_ID,
4748 node: StmtKind::Item({
4750 span, id /*id is good here*/,
4751 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4752 respan(lo, VisibilityKind::Inherited),
4758 // FIXME: Bad copy of attrs
4759 let old_directory_ownership =
4760 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4761 let item = self.parse_item_(attrs.clone(), false, true)?;
4762 self.directory.ownership = old_directory_ownership;
4766 id: ast::DUMMY_NODE_ID,
4767 span: lo.to(i.span),
4768 node: StmtKind::Item(i),
4771 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4772 if !attrs.is_empty() {
4773 if s.prev_token_kind == PrevTokenKind::DocComment {
4774 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4775 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4776 s.span_err(s.span, "expected statement after outer attribute");
4781 // Do not attempt to parse an expression if we're done here.
4782 if self.token == token::Semi {
4783 unused_attrs(&attrs, self);
4788 if self.token == token::CloseDelim(token::Brace) {
4789 unused_attrs(&attrs, self);
4793 // Remainder are line-expr stmts.
4794 let e = self.parse_expr_res(
4795 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4797 id: ast::DUMMY_NODE_ID,
4798 span: lo.to(e.span),
4799 node: StmtKind::Expr(e),
4806 /// Is this expression a successfully-parsed statement?
4807 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4808 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4809 !classify::expr_requires_semi_to_be_stmt(e)
4812 /// Parse a block. No inner attrs are allowed.
4813 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4814 maybe_whole!(self, NtBlock, |x| x);
4818 if !self.eat(&token::OpenDelim(token::Brace)) {
4820 let tok = self.this_token_to_string();
4821 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4822 let do_not_suggest_help =
4823 self.token.is_keyword(keywords::In) || self.token == token::Colon;
4825 if self.token.is_ident_named("and") {
4826 e.span_suggestion_short_with_applicability(
4828 "use `&&` instead of `and` for the boolean operator",
4830 Applicability::MaybeIncorrect,
4833 if self.token.is_ident_named("or") {
4834 e.span_suggestion_short_with_applicability(
4836 "use `||` instead of `or` for the boolean operator",
4838 Applicability::MaybeIncorrect,
4842 // Check to see if the user has written something like
4847 // Which is valid in other languages, but not Rust.
4848 match self.parse_stmt_without_recovery(false) {
4850 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4851 || do_not_suggest_help {
4852 // if the next token is an open brace (e.g., `if a b {`), the place-
4853 // inside-a-block suggestion would be more likely wrong than right
4854 e.span_label(sp, "expected `{`");
4857 let mut stmt_span = stmt.span;
4858 // expand the span to include the semicolon, if it exists
4859 if self.eat(&token::Semi) {
4860 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4862 let sugg = pprust::to_string(|s| {
4863 use print::pprust::{PrintState, INDENT_UNIT};
4864 s.ibox(INDENT_UNIT)?;
4866 s.print_stmt(&stmt)?;
4867 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4869 e.span_suggestion_with_applicability(
4871 "try placing this code inside a block",
4873 // speculative, has been misleading in the past (closed Issue #46836)
4874 Applicability::MaybeIncorrect
4878 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4879 self.cancel(&mut e);
4886 self.parse_block_tail(lo, BlockCheckMode::Default)
4889 /// Parse a block. Inner attrs are allowed.
4890 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4891 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4894 self.expect(&token::OpenDelim(token::Brace))?;
4895 Ok((self.parse_inner_attributes()?,
4896 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4899 /// Parse the rest of a block expression or function body
4900 /// Precondition: already parsed the '{'.
4901 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4902 let mut stmts = vec![];
4903 let mut recovered = false;
4905 while !self.eat(&token::CloseDelim(token::Brace)) {
4906 let stmt = match self.parse_full_stmt(false) {
4909 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4910 self.eat(&token::CloseDelim(token::Brace));
4916 if let Some(stmt) = stmt {
4918 } else if self.token == token::Eof {
4921 // Found only `;` or `}`.
4927 id: ast::DUMMY_NODE_ID,
4929 span: lo.to(self.prev_span),
4934 /// Parse a statement, including the trailing semicolon.
4935 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4936 // skip looking for a trailing semicolon when we have an interpolated statement
4937 maybe_whole!(self, NtStmt, |x| Some(x));
4939 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4941 None => return Ok(None),
4945 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4946 // expression without semicolon
4947 if classify::expr_requires_semi_to_be_stmt(expr) {
4948 // Just check for errors and recover; do not eat semicolon yet.
4950 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4953 self.recover_stmt();
4957 StmtKind::Local(..) => {
4958 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4959 if macro_legacy_warnings && self.token != token::Semi {
4960 self.warn_missing_semicolon();
4962 self.expect_one_of(&[], &[token::Semi])?;
4968 if self.eat(&token::Semi) {
4969 stmt = stmt.add_trailing_semicolon();
4972 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4976 fn warn_missing_semicolon(&self) {
4977 self.diagnostic().struct_span_warn(self.span, {
4978 &format!("expected `;`, found `{}`", self.this_token_to_string())
4980 "This was erroneously allowed and will become a hard error in a future release"
4984 fn err_dotdotdot_syntax(&self, span: Span) {
4985 self.diagnostic().struct_span_err(span, {
4986 "unexpected token: `...`"
4987 }).span_suggestion_with_applicability(
4988 span, "use `..` for an exclusive range", "..".to_owned(),
4989 Applicability::MaybeIncorrect
4990 ).span_suggestion_with_applicability(
4991 span, "or `..=` for an inclusive range", "..=".to_owned(),
4992 Applicability::MaybeIncorrect
4996 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4997 // BOUND = TY_BOUND | LT_BOUND
4998 // LT_BOUND = LIFETIME (e.g. `'a`)
4999 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5000 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
5001 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
5002 let mut bounds = Vec::new();
5004 // This needs to be synchronized with `Token::can_begin_bound`.
5005 let is_bound_start = self.check_path() || self.check_lifetime() ||
5006 self.check(&token::Question) ||
5007 self.check_keyword(keywords::For) ||
5008 self.check(&token::OpenDelim(token::Paren));
5011 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5012 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5013 if self.token.is_lifetime() {
5014 if let Some(question_span) = question {
5015 self.span_err(question_span,
5016 "`?` may only modify trait bounds, not lifetime bounds");
5018 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5020 self.expect(&token::CloseDelim(token::Paren))?;
5021 self.span_err(self.prev_span,
5022 "parenthesized lifetime bounds are not supported");
5025 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5026 let path = self.parse_path(PathStyle::Type)?;
5028 self.expect(&token::CloseDelim(token::Paren))?;
5030 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
5031 let modifier = if question.is_some() {
5032 TraitBoundModifier::Maybe
5034 TraitBoundModifier::None
5036 bounds.push(GenericBound::Trait(poly_trait, modifier));
5042 if !allow_plus || !self.eat_plus() {
5050 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
5051 self.parse_generic_bounds_common(true)
5054 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5055 // BOUND = LT_BOUND (e.g. `'a`)
5056 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5057 let mut lifetimes = Vec::new();
5058 while self.check_lifetime() {
5059 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5061 if !self.eat_plus() {
5068 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
5069 fn parse_ty_param(&mut self,
5070 preceding_attrs: Vec<Attribute>)
5071 -> PResult<'a, GenericParam> {
5072 let ident = self.parse_ident()?;
5074 // Parse optional colon and param bounds.
5075 let bounds = if self.eat(&token::Colon) {
5076 self.parse_generic_bounds()?
5081 let default = if self.eat(&token::Eq) {
5082 Some(self.parse_ty()?)
5089 id: ast::DUMMY_NODE_ID,
5090 attrs: preceding_attrs.into(),
5092 kind: GenericParamKind::Type {
5098 /// Parses the following grammar:
5099 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5100 fn parse_trait_item_assoc_ty(&mut self)
5101 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5102 let ident = self.parse_ident()?;
5103 let mut generics = self.parse_generics()?;
5105 // Parse optional colon and param bounds.
5106 let bounds = if self.eat(&token::Colon) {
5107 self.parse_generic_bounds()?
5111 generics.where_clause = self.parse_where_clause()?;
5113 let default = if self.eat(&token::Eq) {
5114 Some(self.parse_ty()?)
5118 self.expect(&token::Semi)?;
5120 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5123 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5124 /// trailing comma and erroneous trailing attributes.
5125 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5126 let mut params = Vec::new();
5127 let mut seen_ty_param = false;
5129 let attrs = self.parse_outer_attributes()?;
5130 if self.check_lifetime() {
5131 let lifetime = self.expect_lifetime();
5132 // Parse lifetime parameter.
5133 let bounds = if self.eat(&token::Colon) {
5134 self.parse_lt_param_bounds()
5138 params.push(ast::GenericParam {
5139 ident: lifetime.ident,
5141 attrs: attrs.into(),
5143 kind: ast::GenericParamKind::Lifetime,
5146 self.span_err(self.prev_span,
5147 "lifetime parameters must be declared prior to type parameters");
5149 } else if self.check_ident() {
5150 // Parse type parameter.
5151 params.push(self.parse_ty_param(attrs)?);
5152 seen_ty_param = true;
5154 // Check for trailing attributes and stop parsing.
5155 if !attrs.is_empty() {
5156 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
5157 self.span_err(attrs[0].span,
5158 &format!("trailing attribute after {} parameters", param_kind));
5163 if !self.eat(&token::Comma) {
5170 /// Parse a set of optional generic type parameter declarations. Where
5171 /// clauses are not parsed here, and must be added later via
5172 /// `parse_where_clause()`.
5174 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5175 /// | ( < lifetimes , typaramseq ( , )? > )
5176 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5177 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5178 maybe_whole!(self, NtGenerics, |x| x);
5180 let span_lo = self.span;
5182 let params = self.parse_generic_params()?;
5186 where_clause: WhereClause {
5187 id: ast::DUMMY_NODE_ID,
5188 predicates: Vec::new(),
5189 span: syntax_pos::DUMMY_SP,
5191 span: span_lo.to(self.prev_span),
5194 Ok(ast::Generics::default())
5198 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5199 /// possibly including trailing comma.
5200 fn parse_generic_args(&mut self)
5201 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5202 let mut args = Vec::new();
5203 let mut bindings = Vec::new();
5204 let mut seen_type = false;
5205 let mut seen_binding = false;
5207 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5208 // Parse lifetime argument.
5209 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5210 if seen_type || seen_binding {
5211 self.span_err(self.prev_span,
5212 "lifetime parameters must be declared prior to type parameters");
5214 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5215 // Parse associated type binding.
5217 let ident = self.parse_ident()?;
5219 let ty = self.parse_ty()?;
5220 bindings.push(TypeBinding {
5221 id: ast::DUMMY_NODE_ID,
5224 span: lo.to(self.prev_span),
5226 seen_binding = true;
5227 } else if self.check_type() {
5228 // Parse type argument.
5229 let ty_param = self.parse_ty()?;
5231 self.span_err(ty_param.span,
5232 "type parameters must be declared prior to associated type bindings");
5234 args.push(GenericArg::Type(ty_param));
5240 if !self.eat(&token::Comma) {
5244 Ok((args, bindings))
5247 /// Parses an optional `where` clause and places it in `generics`.
5249 /// ```ignore (only-for-syntax-highlight)
5250 /// where T : Trait<U, V> + 'b, 'a : 'b
5252 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5253 maybe_whole!(self, NtWhereClause, |x| x);
5255 let mut where_clause = WhereClause {
5256 id: ast::DUMMY_NODE_ID,
5257 predicates: Vec::new(),
5258 span: syntax_pos::DUMMY_SP,
5261 if !self.eat_keyword(keywords::Where) {
5262 return Ok(where_clause);
5264 let lo = self.prev_span;
5266 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5267 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5268 // change we parse those generics now, but report an error.
5269 if self.choose_generics_over_qpath() {
5270 let generics = self.parse_generics()?;
5271 self.span_err(generics.span,
5272 "generic parameters on `where` clauses are reserved for future use");
5277 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5278 let lifetime = self.expect_lifetime();
5279 // Bounds starting with a colon are mandatory, but possibly empty.
5280 self.expect(&token::Colon)?;
5281 let bounds = self.parse_lt_param_bounds();
5282 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5283 ast::WhereRegionPredicate {
5284 span: lo.to(self.prev_span),
5289 } else if self.check_type() {
5290 // Parse optional `for<'a, 'b>`.
5291 // This `for` is parsed greedily and applies to the whole predicate,
5292 // the bounded type can have its own `for` applying only to it.
5293 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5294 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5295 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5296 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5298 // Parse type with mandatory colon and (possibly empty) bounds,
5299 // or with mandatory equality sign and the second type.
5300 let ty = self.parse_ty()?;
5301 if self.eat(&token::Colon) {
5302 let bounds = self.parse_generic_bounds()?;
5303 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5304 ast::WhereBoundPredicate {
5305 span: lo.to(self.prev_span),
5306 bound_generic_params: lifetime_defs,
5311 // FIXME: Decide what should be used here, `=` or `==`.
5312 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5313 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5314 let rhs_ty = self.parse_ty()?;
5315 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5316 ast::WhereEqPredicate {
5317 span: lo.to(self.prev_span),
5320 id: ast::DUMMY_NODE_ID,
5324 return self.unexpected();
5330 if !self.eat(&token::Comma) {
5335 where_clause.span = lo.to(self.prev_span);
5339 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5340 -> PResult<'a, (Vec<Arg> , bool)> {
5342 let mut variadic = false;
5343 let args: Vec<Option<Arg>> =
5344 self.parse_unspanned_seq(
5345 &token::OpenDelim(token::Paren),
5346 &token::CloseDelim(token::Paren),
5347 SeqSep::trailing_allowed(token::Comma),
5349 if p.token == token::DotDotDot {
5353 if p.token != token::CloseDelim(token::Paren) {
5356 "`...` must be last in argument list for variadic function");
5360 let span = p.prev_span;
5361 if p.token == token::CloseDelim(token::Paren) {
5362 // continue parsing to present any further errors
5365 "only foreign functions are allowed to be variadic"
5367 Ok(Some(dummy_arg(span)))
5369 // this function definition looks beyond recovery, stop parsing
5371 "only foreign functions are allowed to be variadic");
5376 match p.parse_arg_general(named_args) {
5377 Ok(arg) => Ok(Some(arg)),
5380 let lo = p.prev_span;
5381 // Skip every token until next possible arg or end.
5382 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5383 // Create a placeholder argument for proper arg count (#34264).
5384 let span = lo.to(p.prev_span);
5385 Ok(Some(dummy_arg(span)))
5392 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5394 if variadic && args.is_empty() {
5396 "variadic function must be declared with at least one named argument");
5399 Ok((args, variadic))
5402 /// Parse the argument list and result type of a function declaration
5403 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5405 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5406 let ret_ty = self.parse_ret_ty(true)?;
5415 /// Returns the parsed optional self argument and whether a self shortcut was used.
5416 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5417 let expect_ident = |this: &mut Self| match this.token {
5418 // Preserve hygienic context.
5419 token::Ident(ident, _) =>
5420 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5423 let isolated_self = |this: &mut Self, n| {
5424 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5425 this.look_ahead(n + 1, |t| t != &token::ModSep)
5428 // Parse optional self parameter of a method.
5429 // Only a limited set of initial token sequences is considered self parameters, anything
5430 // else is parsed as a normal function parameter list, so some lookahead is required.
5431 let eself_lo = self.span;
5432 let (eself, eself_ident, eself_hi) = match self.token {
5433 token::BinOp(token::And) => {
5439 (if isolated_self(self, 1) {
5441 SelfKind::Region(None, Mutability::Immutable)
5442 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5443 isolated_self(self, 2) {
5446 SelfKind::Region(None, Mutability::Mutable)
5447 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5448 isolated_self(self, 2) {
5450 let lt = self.expect_lifetime();
5451 SelfKind::Region(Some(lt), Mutability::Immutable)
5452 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5453 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5454 isolated_self(self, 3) {
5456 let lt = self.expect_lifetime();
5458 SelfKind::Region(Some(lt), Mutability::Mutable)
5461 }, expect_ident(self), self.prev_span)
5463 token::BinOp(token::Star) => {
5468 // Emit special error for `self` cases.
5469 (if isolated_self(self, 1) {
5471 self.span_err(self.span, "cannot pass `self` by raw pointer");
5472 SelfKind::Value(Mutability::Immutable)
5473 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5474 isolated_self(self, 2) {
5477 self.span_err(self.span, "cannot pass `self` by raw pointer");
5478 SelfKind::Value(Mutability::Immutable)
5481 }, expect_ident(self), self.prev_span)
5483 token::Ident(..) => {
5484 if isolated_self(self, 0) {
5487 let eself_ident = expect_ident(self);
5488 let eself_hi = self.prev_span;
5489 (if self.eat(&token::Colon) {
5490 let ty = self.parse_ty()?;
5491 SelfKind::Explicit(ty, Mutability::Immutable)
5493 SelfKind::Value(Mutability::Immutable)
5494 }, eself_ident, eself_hi)
5495 } else if self.token.is_keyword(keywords::Mut) &&
5496 isolated_self(self, 1) {
5500 let eself_ident = expect_ident(self);
5501 let eself_hi = self.prev_span;
5502 (if self.eat(&token::Colon) {
5503 let ty = self.parse_ty()?;
5504 SelfKind::Explicit(ty, Mutability::Mutable)
5506 SelfKind::Value(Mutability::Mutable)
5507 }, eself_ident, eself_hi)
5512 _ => return Ok(None),
5515 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5516 Ok(Some(Arg::from_self(eself, eself_ident)))
5519 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5520 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5521 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5523 self.expect(&token::OpenDelim(token::Paren))?;
5525 // Parse optional self argument
5526 let self_arg = self.parse_self_arg()?;
5528 // Parse the rest of the function parameter list.
5529 let sep = SeqSep::trailing_allowed(token::Comma);
5530 let fn_inputs = if let Some(self_arg) = self_arg {
5531 if self.check(&token::CloseDelim(token::Paren)) {
5533 } else if self.eat(&token::Comma) {
5534 let mut fn_inputs = vec![self_arg];
5535 fn_inputs.append(&mut self.parse_seq_to_before_end(
5536 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5540 return self.unexpected();
5543 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5546 // Parse closing paren and return type.
5547 self.expect(&token::CloseDelim(token::Paren))?;
5550 output: self.parse_ret_ty(true)?,
5555 // parse the |arg, arg| header on a lambda
5556 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5557 let inputs_captures = {
5558 if self.eat(&token::OrOr) {
5561 self.expect(&token::BinOp(token::Or))?;
5562 let args = self.parse_seq_to_before_tokens(
5563 &[&token::BinOp(token::Or), &token::OrOr],
5564 SeqSep::trailing_allowed(token::Comma),
5565 TokenExpectType::NoExpect,
5566 |p| p.parse_fn_block_arg()
5572 let output = self.parse_ret_ty(true)?;
5575 inputs: inputs_captures,
5581 /// Parse the name and optional generic types of a function header.
5582 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5583 let id = self.parse_ident()?;
5584 let generics = self.parse_generics()?;
5588 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5589 attrs: Vec<Attribute>) -> P<Item> {
5593 id: ast::DUMMY_NODE_ID,
5601 /// Parse an item-position function declaration.
5602 fn parse_item_fn(&mut self,
5605 constness: Spanned<Constness>,
5607 -> PResult<'a, ItemInfo> {
5608 let (ident, mut generics) = self.parse_fn_header()?;
5609 let decl = self.parse_fn_decl(false)?;
5610 generics.where_clause = self.parse_where_clause()?;
5611 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5612 let header = FnHeader { unsafety, asyncness, constness, abi };
5613 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5616 /// true if we are looking at `const ID`, false for things like `const fn` etc
5617 fn is_const_item(&mut self) -> bool {
5618 self.token.is_keyword(keywords::Const) &&
5619 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5620 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5623 /// parses all the "front matter" for a `fn` declaration, up to
5624 /// and including the `fn` keyword:
5628 /// - `const unsafe fn`
5631 fn parse_fn_front_matter(&mut self)
5639 let is_const_fn = self.eat_keyword(keywords::Const);
5640 let const_span = self.prev_span;
5641 let unsafety = self.parse_unsafety();
5642 let asyncness = self.parse_asyncness();
5643 let (constness, unsafety, abi) = if is_const_fn {
5644 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5646 let abi = if self.eat_keyword(keywords::Extern) {
5647 self.parse_opt_abi()?.unwrap_or(Abi::C)
5651 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5653 self.expect_keyword(keywords::Fn)?;
5654 Ok((constness, unsafety, asyncness, abi))
5657 /// Parse an impl item.
5658 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5659 maybe_whole!(self, NtImplItem, |x| x);
5660 let attrs = self.parse_outer_attributes()?;
5661 let (mut item, tokens) = self.collect_tokens(|this| {
5662 this.parse_impl_item_(at_end, attrs)
5665 // See `parse_item` for why this clause is here.
5666 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5667 item.tokens = Some(tokens);
5672 fn parse_impl_item_(&mut self,
5674 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5676 let vis = self.parse_visibility(false)?;
5677 let defaultness = self.parse_defaultness();
5678 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5679 let (name, alias, generics) = type_?;
5680 let kind = match alias {
5681 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5682 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5684 (name, kind, generics)
5685 } else if self.is_const_item() {
5686 // This parses the grammar:
5687 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5688 self.expect_keyword(keywords::Const)?;
5689 let name = self.parse_ident()?;
5690 self.expect(&token::Colon)?;
5691 let typ = self.parse_ty()?;
5692 self.expect(&token::Eq)?;
5693 let expr = self.parse_expr()?;
5694 self.expect(&token::Semi)?;
5695 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5697 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5698 attrs.extend(inner_attrs);
5699 (name, node, generics)
5703 id: ast::DUMMY_NODE_ID,
5704 span: lo.to(self.prev_span),
5715 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5716 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5721 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5723 VisibilityKind::Inherited => Ok(()),
5725 let is_macro_rules: bool = match self.token {
5726 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5730 let mut err = self.diagnostic()
5731 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5732 err.span_suggestion_with_applicability(
5734 "try exporting the macro",
5735 "#[macro_export]".to_owned(),
5736 Applicability::MaybeIncorrect // speculative
5740 let mut err = self.diagnostic()
5741 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5742 err.help("try adjusting the macro to put `pub` inside the invocation");
5749 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5750 -> DiagnosticBuilder<'a>
5752 let expected_kinds = if item_type == "extern" {
5753 "missing `fn`, `type`, or `static`"
5755 "missing `fn`, `type`, or `const`"
5758 // Given this code `path(`, it seems like this is not
5759 // setting the visibility of a macro invocation, but rather
5760 // a mistyped method declaration.
5761 // Create a diagnostic pointing out that `fn` is missing.
5763 // x | pub path(&self) {
5764 // | ^ missing `fn`, `type`, or `const`
5766 // ^^ `sp` below will point to this
5767 let sp = prev_span.between(self.prev_span);
5768 let mut err = self.diagnostic().struct_span_err(
5770 &format!("{} for {}-item declaration",
5771 expected_kinds, item_type));
5772 err.span_label(sp, expected_kinds);
5776 /// Parse a method or a macro invocation in a trait impl.
5777 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5778 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5779 ast::ImplItemKind)> {
5780 // code copied from parse_macro_use_or_failure... abstraction!
5781 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5783 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5784 ast::ImplItemKind::Macro(mac)))
5786 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5787 let ident = self.parse_ident()?;
5788 let mut generics = self.parse_generics()?;
5789 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5790 generics.where_clause = self.parse_where_clause()?;
5792 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5793 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5794 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5795 ast::MethodSig { header, decl },
5801 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5802 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5803 let ident = self.parse_ident()?;
5804 let mut tps = self.parse_generics()?;
5806 // Parse optional colon and supertrait bounds.
5807 let bounds = if self.eat(&token::Colon) {
5808 self.parse_generic_bounds()?
5813 if self.eat(&token::Eq) {
5814 // it's a trait alias
5815 let bounds = self.parse_generic_bounds()?;
5816 tps.where_clause = self.parse_where_clause()?;
5817 self.expect(&token::Semi)?;
5818 if unsafety != Unsafety::Normal {
5819 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5821 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5823 // it's a normal trait
5824 tps.where_clause = self.parse_where_clause()?;
5825 self.expect(&token::OpenDelim(token::Brace))?;
5826 let mut trait_items = vec![];
5827 while !self.eat(&token::CloseDelim(token::Brace)) {
5828 let mut at_end = false;
5829 match self.parse_trait_item(&mut at_end) {
5830 Ok(item) => trait_items.push(item),
5834 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5839 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5843 fn choose_generics_over_qpath(&self) -> bool {
5844 // There's an ambiguity between generic parameters and qualified paths in impls.
5845 // If we see `<` it may start both, so we have to inspect some following tokens.
5846 // The following combinations can only start generics,
5847 // but not qualified paths (with one exception):
5848 // `<` `>` - empty generic parameters
5849 // `<` `#` - generic parameters with attributes
5850 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5851 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5852 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5853 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5854 // The only truly ambiguous case is
5855 // `<` IDENT `>` `::` IDENT ...
5856 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5857 // because this is what almost always expected in practice, qualified paths in impls
5858 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5859 self.token == token::Lt &&
5860 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5861 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5862 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5863 t == &token::Colon || t == &token::Eq))
5866 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5867 self.expect(&token::OpenDelim(token::Brace))?;
5868 let attrs = self.parse_inner_attributes()?;
5870 let mut impl_items = Vec::new();
5871 while !self.eat(&token::CloseDelim(token::Brace)) {
5872 let mut at_end = false;
5873 match self.parse_impl_item(&mut at_end) {
5874 Ok(impl_item) => impl_items.push(impl_item),
5878 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5883 Ok((impl_items, attrs))
5886 /// Parses an implementation item, `impl` keyword is already parsed.
5887 /// impl<'a, T> TYPE { /* impl items */ }
5888 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5889 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5890 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5891 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5892 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5893 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5894 -> PResult<'a, ItemInfo> {
5895 // First, parse generic parameters if necessary.
5896 let mut generics = if self.choose_generics_over_qpath() {
5897 self.parse_generics()?
5899 ast::Generics::default()
5902 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5903 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5905 ast::ImplPolarity::Negative
5907 ast::ImplPolarity::Positive
5910 // Parse both types and traits as a type, then reinterpret if necessary.
5911 let ty_first = self.parse_ty()?;
5913 // If `for` is missing we try to recover.
5914 let has_for = self.eat_keyword(keywords::For);
5915 let missing_for_span = self.prev_span.between(self.span);
5917 let ty_second = if self.token == token::DotDot {
5918 // We need to report this error after `cfg` expansion for compatibility reasons
5919 self.bump(); // `..`, do not add it to expected tokens
5920 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5921 } else if has_for || self.token.can_begin_type() {
5922 Some(self.parse_ty()?)
5927 generics.where_clause = self.parse_where_clause()?;
5929 let (impl_items, attrs) = self.parse_impl_body()?;
5931 let item_kind = match ty_second {
5932 Some(ty_second) => {
5933 // impl Trait for Type
5935 self.span_err(missing_for_span, "missing `for` in a trait impl");
5938 let ty_first = ty_first.into_inner();
5939 let path = match ty_first.node {
5940 // This notably includes paths passed through `ty` macro fragments (#46438).
5941 TyKind::Path(None, path) => path,
5943 self.span_err(ty_first.span, "expected a trait, found type");
5944 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5947 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5949 ItemKind::Impl(unsafety, polarity, defaultness,
5950 generics, Some(trait_ref), ty_second, impl_items)
5954 ItemKind::Impl(unsafety, polarity, defaultness,
5955 generics, None, ty_first, impl_items)
5959 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5962 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5963 if self.eat_keyword(keywords::For) {
5965 let params = self.parse_generic_params()?;
5967 // We rely on AST validation to rule out invalid cases: There must not be type
5968 // parameters, and the lifetime parameters must not have bounds.
5975 /// Parse struct Foo { ... }
5976 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5977 let class_name = self.parse_ident()?;
5979 let mut generics = self.parse_generics()?;
5981 // There is a special case worth noting here, as reported in issue #17904.
5982 // If we are parsing a tuple struct it is the case that the where clause
5983 // should follow the field list. Like so:
5985 // struct Foo<T>(T) where T: Copy;
5987 // If we are parsing a normal record-style struct it is the case
5988 // that the where clause comes before the body, and after the generics.
5989 // So if we look ahead and see a brace or a where-clause we begin
5990 // parsing a record style struct.
5992 // Otherwise if we look ahead and see a paren we parse a tuple-style
5995 let vdata = if self.token.is_keyword(keywords::Where) {
5996 generics.where_clause = self.parse_where_clause()?;
5997 if self.eat(&token::Semi) {
5998 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5999 VariantData::Unit(ast::DUMMY_NODE_ID)
6001 // If we see: `struct Foo<T> where T: Copy { ... }`
6002 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6004 // No `where` so: `struct Foo<T>;`
6005 } else if self.eat(&token::Semi) {
6006 VariantData::Unit(ast::DUMMY_NODE_ID)
6007 // Record-style struct definition
6008 } else if self.token == token::OpenDelim(token::Brace) {
6009 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6010 // Tuple-style struct definition with optional where-clause.
6011 } else if self.token == token::OpenDelim(token::Paren) {
6012 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6013 generics.where_clause = self.parse_where_clause()?;
6014 self.expect(&token::Semi)?;
6017 let token_str = self.this_token_to_string();
6018 let mut err = self.fatal(&format!(
6019 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
6022 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6026 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6029 /// Parse union Foo { ... }
6030 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6031 let class_name = self.parse_ident()?;
6033 let mut generics = self.parse_generics()?;
6035 let vdata = if self.token.is_keyword(keywords::Where) {
6036 generics.where_clause = self.parse_where_clause()?;
6037 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6038 } else if self.token == token::OpenDelim(token::Brace) {
6039 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6041 let token_str = self.this_token_to_string();
6042 let mut err = self.fatal(&format!(
6043 "expected `where` or `{{` after union name, found `{}`", token_str));
6044 err.span_label(self.span, "expected `where` or `{` after union name");
6048 Ok((class_name, ItemKind::Union(vdata, generics), None))
6051 fn consume_block(&mut self, delim: token::DelimToken) {
6052 let mut brace_depth = 0;
6053 if !self.eat(&token::OpenDelim(delim)) {
6057 if self.eat(&token::OpenDelim(delim)) {
6059 } else if self.eat(&token::CloseDelim(delim)) {
6060 if brace_depth == 0 {
6066 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
6074 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6075 let mut fields = Vec::new();
6076 if self.eat(&token::OpenDelim(token::Brace)) {
6077 while self.token != token::CloseDelim(token::Brace) {
6078 let field = self.parse_struct_decl_field().map_err(|e| {
6079 self.recover_stmt();
6083 Ok(field) => fields.push(field),
6089 self.eat(&token::CloseDelim(token::Brace));
6091 let token_str = self.this_token_to_string();
6092 let mut err = self.fatal(&format!(
6093 "expected `where`, or `{{` after struct name, found `{}`", token_str));
6094 err.span_label(self.span, "expected `where`, or `{` after struct name");
6101 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6102 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6103 // Unit like structs are handled in parse_item_struct function
6104 let fields = self.parse_unspanned_seq(
6105 &token::OpenDelim(token::Paren),
6106 &token::CloseDelim(token::Paren),
6107 SeqSep::trailing_allowed(token::Comma),
6109 let attrs = p.parse_outer_attributes()?;
6111 let vis = p.parse_visibility(true)?;
6112 let ty = p.parse_ty()?;
6114 span: lo.to(ty.span),
6117 id: ast::DUMMY_NODE_ID,
6126 /// Parse a structure field declaration
6127 fn parse_single_struct_field(&mut self,
6130 attrs: Vec<Attribute> )
6131 -> PResult<'a, StructField> {
6132 let mut seen_comma: bool = false;
6133 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6134 if self.token == token::Comma {
6141 token::CloseDelim(token::Brace) => {}
6142 token::DocComment(_) => {
6143 let previous_span = self.prev_span;
6144 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6145 self.bump(); // consume the doc comment
6146 let comma_after_doc_seen = self.eat(&token::Comma);
6147 // `seen_comma` is always false, because we are inside doc block
6148 // condition is here to make code more readable
6149 if seen_comma == false && comma_after_doc_seen == true {
6152 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6155 if seen_comma == false {
6156 let sp = self.sess.source_map().next_point(previous_span);
6157 err.span_suggestion_with_applicability(
6159 "missing comma here",
6161 Applicability::MachineApplicable
6168 let sp = self.sess.source_map().next_point(self.prev_span);
6169 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
6170 self.this_token_to_string()));
6171 if self.token.is_ident() {
6172 // This is likely another field; emit the diagnostic and keep going
6173 err.span_suggestion_with_applicability(
6175 "try adding a comma",
6177 Applicability::MachineApplicable,
6188 /// Parse an element of a struct definition
6189 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6190 let attrs = self.parse_outer_attributes()?;
6192 let vis = self.parse_visibility(false)?;
6193 self.parse_single_struct_field(lo, vis, attrs)
6196 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6197 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6198 /// a function definition, it's not a tuple struct field) and the contents within the parens
6199 /// isn't valid, emit a proper diagnostic.
6200 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6201 maybe_whole!(self, NtVis, |x| x);
6203 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6204 if self.is_crate_vis() {
6205 self.bump(); // `crate`
6206 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6209 if !self.eat_keyword(keywords::Pub) {
6210 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6211 // keyword to grab a span from for inherited visibility; an empty span at the
6212 // beginning of the current token would seem to be the "Schelling span".
6213 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6215 let lo = self.prev_span;
6217 if self.check(&token::OpenDelim(token::Paren)) {
6218 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6219 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6220 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6221 // by the following tokens.
6222 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6225 self.bump(); // `crate`
6226 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6228 lo.to(self.prev_span),
6229 VisibilityKind::Crate(CrateSugar::PubCrate),
6232 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6235 self.bump(); // `in`
6236 let path = self.parse_path(PathStyle::Mod)?; // `path`
6237 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6238 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6240 id: ast::DUMMY_NODE_ID,
6243 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6244 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6245 t.is_keyword(keywords::SelfValue))
6247 // `pub(self)` or `pub(super)`
6249 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6250 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6251 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6253 id: ast::DUMMY_NODE_ID,
6256 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6257 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6259 let msg = "incorrect visibility restriction";
6260 let suggestion = r##"some possible visibility restrictions are:
6261 `pub(crate)`: visible only on the current crate
6262 `pub(super)`: visible only in the current module's parent
6263 `pub(in path::to::module)`: visible only on the specified path"##;
6264 let path = self.parse_path(PathStyle::Mod)?;
6265 let sp = self.prev_span;
6266 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6267 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6268 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6269 err.help(suggestion);
6270 err.span_suggestion_with_applicability(
6271 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6273 err.emit(); // emit diagnostic, but continue with public visibility
6277 Ok(respan(lo, VisibilityKind::Public))
6280 /// Parse defaultness: `default` or nothing.
6281 fn parse_defaultness(&mut self) -> Defaultness {
6282 // `pub` is included for better error messages
6283 if self.check_keyword(keywords::Default) &&
6284 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6285 t.is_keyword(keywords::Const) ||
6286 t.is_keyword(keywords::Fn) ||
6287 t.is_keyword(keywords::Unsafe) ||
6288 t.is_keyword(keywords::Extern) ||
6289 t.is_keyword(keywords::Type) ||
6290 t.is_keyword(keywords::Pub)) {
6291 self.bump(); // `default`
6292 Defaultness::Default
6298 /// Given a termination token, parse all of the items in a module
6299 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6300 let mut items = vec![];
6301 while let Some(item) = self.parse_item()? {
6305 if !self.eat(term) {
6306 let token_str = self.this_token_to_string();
6307 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6308 if token_str == ";" {
6309 let msg = "consider removing this semicolon";
6310 err.span_suggestion_short_with_applicability(
6311 self.span, msg, String::new(), Applicability::MachineApplicable
6313 if !items.is_empty() { // Issue #51603
6314 let previous_item = &items[items.len()-1];
6315 let previous_item_kind_name = match previous_item.node {
6316 // say "braced struct" because tuple-structs and
6317 // braceless-empty-struct declarations do take a semicolon
6318 ItemKind::Struct(..) => Some("braced struct"),
6319 ItemKind::Enum(..) => Some("enum"),
6320 ItemKind::Trait(..) => Some("trait"),
6321 ItemKind::Union(..) => Some("union"),
6324 if let Some(name) = previous_item_kind_name {
6325 err.help(&format!("{} declarations are not followed by a semicolon",
6330 err.span_label(self.span, "expected item");
6335 let hi = if self.span.is_dummy() {
6342 inner: inner_lo.to(hi),
6348 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6349 let id = match self.token {
6350 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
6354 _ => self.parse_ident()?,
6356 self.expect(&token::Colon)?;
6357 let ty = self.parse_ty()?;
6358 self.expect(&token::Eq)?;
6359 let e = self.parse_expr()?;
6360 self.expect(&token::Semi)?;
6361 let item = match m {
6362 Some(m) => ItemKind::Static(ty, m, e),
6363 None => ItemKind::Const(ty, e),
6365 Ok((id, item, None))
6368 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6369 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6370 let (in_cfg, outer_attrs) = {
6371 let mut strip_unconfigured = ::config::StripUnconfigured {
6373 features: None, // don't perform gated feature checking
6375 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6376 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6379 let id_span = self.span;
6380 let id = self.parse_ident()?;
6381 if self.eat(&token::Semi) {
6382 if in_cfg && self.recurse_into_file_modules {
6383 // This mod is in an external file. Let's go get it!
6384 let ModulePathSuccess { path, directory_ownership, warn } =
6385 self.submod_path(id, &outer_attrs, id_span)?;
6386 let (module, mut attrs) =
6387 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6388 // Record that we fetched the mod from an external file
6390 let attr = Attribute {
6391 id: attr::mk_attr_id(),
6392 style: ast::AttrStyle::Outer,
6393 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6394 tokens: TokenStream::empty(),
6395 is_sugared_doc: false,
6396 span: syntax_pos::DUMMY_SP,
6398 attr::mark_known(&attr);
6401 Ok((id, ItemKind::Mod(module), Some(attrs)))
6403 let placeholder = ast::Mod {
6404 inner: syntax_pos::DUMMY_SP,
6408 Ok((id, ItemKind::Mod(placeholder), None))
6411 let old_directory = self.directory.clone();
6412 self.push_directory(id, &outer_attrs);
6414 self.expect(&token::OpenDelim(token::Brace))?;
6415 let mod_inner_lo = self.span;
6416 let attrs = self.parse_inner_attributes()?;
6417 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6419 self.directory = old_directory;
6420 Ok((id, ItemKind::Mod(module), Some(attrs)))
6424 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6425 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6426 self.directory.path.to_mut().push(&path.as_str());
6427 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6429 self.directory.path.to_mut().push(&id.as_str());
6433 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6434 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6437 // On windows, the base path might have the form
6438 // `\\?\foo\bar` in which case it does not tolerate
6439 // mixed `/` and `\` separators, so canonicalize
6442 let s = s.replace("/", "\\");
6443 Some(dir_path.join(s))
6449 /// Returns either a path to a module, or .
6450 pub fn default_submod_path(
6452 relative: Option<ast::Ident>,
6454 source_map: &SourceMap) -> ModulePath
6456 // If we're in a foo.rs file instead of a mod.rs file,
6457 // we need to look for submodules in
6458 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6459 // `./<id>.rs` and `./<id>/mod.rs`.
6460 let relative_prefix_string;
6461 let relative_prefix = if let Some(ident) = relative {
6462 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6463 &relative_prefix_string
6468 let mod_name = id.to_string();
6469 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6470 let secondary_path_str = format!("{}{}{}mod.rs",
6471 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6472 let default_path = dir_path.join(&default_path_str);
6473 let secondary_path = dir_path.join(&secondary_path_str);
6474 let default_exists = source_map.file_exists(&default_path);
6475 let secondary_exists = source_map.file_exists(&secondary_path);
6477 let result = match (default_exists, secondary_exists) {
6478 (true, false) => Ok(ModulePathSuccess {
6480 directory_ownership: DirectoryOwnership::Owned {
6485 (false, true) => Ok(ModulePathSuccess {
6486 path: secondary_path,
6487 directory_ownership: DirectoryOwnership::Owned {
6492 (false, false) => Err(Error::FileNotFoundForModule {
6493 mod_name: mod_name.clone(),
6494 default_path: default_path_str,
6495 secondary_path: secondary_path_str,
6496 dir_path: dir_path.display().to_string(),
6498 (true, true) => Err(Error::DuplicatePaths {
6499 mod_name: mod_name.clone(),
6500 default_path: default_path_str,
6501 secondary_path: secondary_path_str,
6507 path_exists: default_exists || secondary_exists,
6512 fn submod_path(&mut self,
6514 outer_attrs: &[Attribute],
6516 -> PResult<'a, ModulePathSuccess> {
6517 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6518 return Ok(ModulePathSuccess {
6519 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6520 // All `#[path]` files are treated as though they are a `mod.rs` file.
6521 // This means that `mod foo;` declarations inside `#[path]`-included
6522 // files are siblings,
6524 // Note that this will produce weirdness when a file named `foo.rs` is
6525 // `#[path]` included and contains a `mod foo;` declaration.
6526 // If you encounter this, it's your own darn fault :P
6527 Some(_) => DirectoryOwnership::Owned { relative: None },
6528 _ => DirectoryOwnership::UnownedViaMod(true),
6535 let relative = match self.directory.ownership {
6536 DirectoryOwnership::Owned { relative } => {
6537 // Push the usage onto the list of non-mod.rs mod uses.
6538 // This is used later for feature-gate error reporting.
6539 if let Some(cur_file_ident) = relative {
6541 .non_modrs_mods.borrow_mut()
6542 .push((cur_file_ident, id_sp));
6546 DirectoryOwnership::UnownedViaBlock |
6547 DirectoryOwnership::UnownedViaMod(_) => None,
6549 let paths = Parser::default_submod_path(
6550 id, relative, &self.directory.path, self.sess.source_map());
6552 match self.directory.ownership {
6553 DirectoryOwnership::Owned { .. } => {
6554 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6556 DirectoryOwnership::UnownedViaBlock => {
6558 "Cannot declare a non-inline module inside a block \
6559 unless it has a path attribute";
6560 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6561 if paths.path_exists {
6562 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6564 err.span_note(id_sp, &msg);
6568 DirectoryOwnership::UnownedViaMod(warn) => {
6570 if let Ok(result) = paths.result {
6571 return Ok(ModulePathSuccess { warn: true, ..result });
6574 let mut err = self.diagnostic().struct_span_err(id_sp,
6575 "cannot declare a new module at this location");
6576 if !id_sp.is_dummy() {
6577 let src_path = self.sess.source_map().span_to_filename(id_sp);
6578 if let FileName::Real(src_path) = src_path {
6579 if let Some(stem) = src_path.file_stem() {
6580 let mut dest_path = src_path.clone();
6581 dest_path.set_file_name(stem);
6582 dest_path.push("mod.rs");
6583 err.span_note(id_sp,
6584 &format!("maybe move this module `{}` to its own \
6585 directory via `{}`", src_path.display(),
6586 dest_path.display()));
6590 if paths.path_exists {
6591 err.span_note(id_sp,
6592 &format!("... or maybe `use` the module `{}` instead \
6593 of possibly redeclaring it",
6601 /// Read a module from a source file.
6602 fn eval_src_mod(&mut self,
6604 directory_ownership: DirectoryOwnership,
6607 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6608 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6609 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6610 let mut err = String::from("circular modules: ");
6611 let len = included_mod_stack.len();
6612 for p in &included_mod_stack[i.. len] {
6613 err.push_str(&p.to_string_lossy());
6614 err.push_str(" -> ");
6616 err.push_str(&path.to_string_lossy());
6617 return Err(self.span_fatal(id_sp, &err[..]));
6619 included_mod_stack.push(path.clone());
6620 drop(included_mod_stack);
6623 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6624 p0.cfg_mods = self.cfg_mods;
6625 let mod_inner_lo = p0.span;
6626 let mod_attrs = p0.parse_inner_attributes()?;
6627 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6629 self.sess.included_mod_stack.borrow_mut().pop();
6633 /// Parse a function declaration from a foreign module
6634 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6635 -> PResult<'a, ForeignItem> {
6636 self.expect_keyword(keywords::Fn)?;
6638 let (ident, mut generics) = self.parse_fn_header()?;
6639 let decl = self.parse_fn_decl(true)?;
6640 generics.where_clause = self.parse_where_clause()?;
6642 self.expect(&token::Semi)?;
6643 Ok(ast::ForeignItem {
6646 node: ForeignItemKind::Fn(decl, generics),
6647 id: ast::DUMMY_NODE_ID,
6653 /// Parse a static item from a foreign module.
6654 /// Assumes that the `static` keyword is already parsed.
6655 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6656 -> PResult<'a, ForeignItem> {
6657 let mutbl = self.eat_keyword(keywords::Mut);
6658 let ident = self.parse_ident()?;
6659 self.expect(&token::Colon)?;
6660 let ty = self.parse_ty()?;
6662 self.expect(&token::Semi)?;
6666 node: ForeignItemKind::Static(ty, mutbl),
6667 id: ast::DUMMY_NODE_ID,
6673 /// Parse a type from a foreign module
6674 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6675 -> PResult<'a, ForeignItem> {
6676 self.expect_keyword(keywords::Type)?;
6678 let ident = self.parse_ident()?;
6680 self.expect(&token::Semi)?;
6681 Ok(ast::ForeignItem {
6684 node: ForeignItemKind::Ty,
6685 id: ast::DUMMY_NODE_ID,
6691 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6692 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6693 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6695 let mut ident = self.parse_ident()?;
6696 let mut idents = vec![];
6697 let mut replacement = vec![];
6698 let mut fixed_crate_name = false;
6699 // Accept `extern crate name-like-this` for better diagnostics
6700 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6701 if self.token == dash { // Do not include `-` as part of the expected tokens list
6702 while self.eat(&dash) {
6703 fixed_crate_name = true;
6704 replacement.push((self.prev_span, "_".to_string()));
6705 idents.push(self.parse_ident()?);
6708 if fixed_crate_name {
6709 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6710 let mut fixed_name = format!("{}", ident.name);
6711 for part in idents {
6712 fixed_name.push_str(&format!("_{}", part.name));
6714 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6716 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6717 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6718 err.multipart_suggestion(suggestion_msg, replacement);
6724 /// Parse extern crate links
6728 /// extern crate foo;
6729 /// extern crate bar as foo;
6730 fn parse_item_extern_crate(&mut self,
6732 visibility: Visibility,
6733 attrs: Vec<Attribute>)
6734 -> PResult<'a, P<Item>> {
6735 // Accept `extern crate name-like-this` for better diagnostics
6736 let orig_name = self.parse_crate_name_with_dashes()?;
6737 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6738 (rename, Some(orig_name.name))
6742 self.expect(&token::Semi)?;
6744 let span = lo.to(self.prev_span);
6745 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6748 /// Parse `extern` for foreign ABIs
6751 /// `extern` is expected to have been
6752 /// consumed before calling this method
6758 fn parse_item_foreign_mod(&mut self,
6760 opt_abi: Option<Abi>,
6761 visibility: Visibility,
6762 mut attrs: Vec<Attribute>)
6763 -> PResult<'a, P<Item>> {
6764 self.expect(&token::OpenDelim(token::Brace))?;
6766 let abi = opt_abi.unwrap_or(Abi::C);
6768 attrs.extend(self.parse_inner_attributes()?);
6770 let mut foreign_items = vec![];
6771 while !self.eat(&token::CloseDelim(token::Brace)) {
6772 foreign_items.push(self.parse_foreign_item()?);
6775 let prev_span = self.prev_span;
6776 let m = ast::ForeignMod {
6778 items: foreign_items
6780 let invalid = keywords::Invalid.ident();
6781 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6784 /// Parse type Foo = Bar;
6786 /// existential type Foo: Bar;
6788 /// return None without modifying the parser state
6789 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6790 // This parses the grammar:
6791 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6792 if self.check_keyword(keywords::Type) ||
6793 self.check_keyword(keywords::Existential) &&
6794 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6795 let existential = self.eat_keyword(keywords::Existential);
6796 assert!(self.eat_keyword(keywords::Type));
6797 Some(self.parse_existential_or_alias(existential))
6803 /// Parse type alias or existential type
6804 fn parse_existential_or_alias(
6807 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6808 let ident = self.parse_ident()?;
6809 let mut tps = self.parse_generics()?;
6810 tps.where_clause = self.parse_where_clause()?;
6811 let alias = if existential {
6812 self.expect(&token::Colon)?;
6813 let bounds = self.parse_generic_bounds()?;
6814 AliasKind::Existential(bounds)
6816 self.expect(&token::Eq)?;
6817 let ty = self.parse_ty()?;
6820 self.expect(&token::Semi)?;
6821 Ok((ident, alias, tps))
6824 /// Parse the part of an "enum" decl following the '{'
6825 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6826 let mut variants = Vec::new();
6827 let mut all_nullary = true;
6828 let mut any_disr = None;
6829 while self.token != token::CloseDelim(token::Brace) {
6830 let variant_attrs = self.parse_outer_attributes()?;
6831 let vlo = self.span;
6834 let mut disr_expr = None;
6835 let ident = self.parse_ident()?;
6836 if self.check(&token::OpenDelim(token::Brace)) {
6837 // Parse a struct variant.
6838 all_nullary = false;
6839 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6840 ast::DUMMY_NODE_ID);
6841 } else if self.check(&token::OpenDelim(token::Paren)) {
6842 all_nullary = false;
6843 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6844 ast::DUMMY_NODE_ID);
6845 } else if self.eat(&token::Eq) {
6846 disr_expr = Some(AnonConst {
6847 id: ast::DUMMY_NODE_ID,
6848 value: self.parse_expr()?,
6850 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6851 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6853 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6856 let vr = ast::Variant_ {
6858 attrs: variant_attrs,
6862 variants.push(respan(vlo.to(self.prev_span), vr));
6864 if !self.eat(&token::Comma) { break; }
6866 self.expect(&token::CloseDelim(token::Brace))?;
6868 Some(disr_span) if !all_nullary =>
6869 self.span_err(disr_span,
6870 "discriminator values can only be used with a field-less enum"),
6874 Ok(ast::EnumDef { variants: variants })
6877 /// Parse an "enum" declaration
6878 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6879 let id = self.parse_ident()?;
6880 let mut generics = self.parse_generics()?;
6881 generics.where_clause = self.parse_where_clause()?;
6882 self.expect(&token::OpenDelim(token::Brace))?;
6884 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6885 self.recover_stmt();
6886 self.eat(&token::CloseDelim(token::Brace));
6889 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6892 /// Parses a string as an ABI spec on an extern type or module. Consumes
6893 /// the `extern` keyword, if one is found.
6894 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6896 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6898 self.expect_no_suffix(sp, "ABI spec", suf);
6900 match abi::lookup(&s.as_str()) {
6901 Some(abi) => Ok(Some(abi)),
6903 let prev_span = self.prev_span;
6904 let mut err = struct_span_err!(
6905 self.sess.span_diagnostic,
6908 "invalid ABI: found `{}`",
6910 err.span_label(prev_span, "invalid ABI");
6911 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6922 fn is_static_global(&mut self) -> bool {
6923 if self.check_keyword(keywords::Static) {
6924 // Check if this could be a closure
6925 !self.look_ahead(1, |token| {
6926 if token.is_keyword(keywords::Move) {
6930 token::BinOp(token::Or) | token::OrOr => true,
6941 attrs: Vec<Attribute>,
6942 macros_allowed: bool,
6943 attributes_allowed: bool,
6944 ) -> PResult<'a, Option<P<Item>>> {
6945 let (ret, tokens) = self.collect_tokens(|this| {
6946 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
6949 // Once we've parsed an item and recorded the tokens we got while
6950 // parsing we may want to store `tokens` into the item we're about to
6951 // return. Note, though, that we specifically didn't capture tokens
6952 // related to outer attributes. The `tokens` field here may later be
6953 // used with procedural macros to convert this item back into a token
6954 // stream, but during expansion we may be removing attributes as we go
6957 // If we've got inner attributes then the `tokens` we've got above holds
6958 // these inner attributes. If an inner attribute is expanded we won't
6959 // actually remove it from the token stream, so we'll just keep yielding
6960 // it (bad!). To work around this case for now we just avoid recording
6961 // `tokens` if we detect any inner attributes. This should help keep
6962 // expansion correct, but we should fix this bug one day!
6965 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6966 i.tokens = Some(tokens);
6973 /// Parse one of the items allowed by the flags.
6974 fn parse_item_implementation(
6976 attrs: Vec<Attribute>,
6977 macros_allowed: bool,
6978 attributes_allowed: bool,
6979 ) -> PResult<'a, Option<P<Item>>> {
6980 maybe_whole!(self, NtItem, |item| {
6981 let mut item = item.into_inner();
6982 let mut attrs = attrs;
6983 mem::swap(&mut item.attrs, &mut attrs);
6984 item.attrs.extend(attrs);
6990 let visibility = self.parse_visibility(false)?;
6992 if self.eat_keyword(keywords::Use) {
6994 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6995 self.expect(&token::Semi)?;
6997 let span = lo.to(self.prev_span);
6998 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6999 return Ok(Some(item));
7002 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
7003 self.bump(); // `extern`
7004 if self.eat_keyword(keywords::Crate) {
7005 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7008 let opt_abi = self.parse_opt_abi()?;
7010 if self.eat_keyword(keywords::Fn) {
7011 // EXTERN FUNCTION ITEM
7012 let fn_span = self.prev_span;
7013 let abi = opt_abi.unwrap_or(Abi::C);
7014 let (ident, item_, extra_attrs) =
7015 self.parse_item_fn(Unsafety::Normal,
7017 respan(fn_span, Constness::NotConst),
7019 let prev_span = self.prev_span;
7020 let item = self.mk_item(lo.to(prev_span),
7024 maybe_append(attrs, extra_attrs));
7025 return Ok(Some(item));
7026 } else if self.check(&token::OpenDelim(token::Brace)) {
7027 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7033 if self.is_static_global() {
7036 let m = if self.eat_keyword(keywords::Mut) {
7039 Mutability::Immutable
7041 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7042 let prev_span = self.prev_span;
7043 let item = self.mk_item(lo.to(prev_span),
7047 maybe_append(attrs, extra_attrs));
7048 return Ok(Some(item));
7050 if self.eat_keyword(keywords::Const) {
7051 let const_span = self.prev_span;
7052 if self.check_keyword(keywords::Fn)
7053 || (self.check_keyword(keywords::Unsafe)
7054 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7055 // CONST FUNCTION ITEM
7056 let unsafety = self.parse_unsafety();
7058 let (ident, item_, extra_attrs) =
7059 self.parse_item_fn(unsafety,
7061 respan(const_span, Constness::Const),
7063 let prev_span = self.prev_span;
7064 let item = self.mk_item(lo.to(prev_span),
7068 maybe_append(attrs, extra_attrs));
7069 return Ok(Some(item));
7073 if self.eat_keyword(keywords::Mut) {
7074 let prev_span = self.prev_span;
7075 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
7076 .help("did you mean to declare a static?")
7079 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7080 let prev_span = self.prev_span;
7081 let item = self.mk_item(lo.to(prev_span),
7085 maybe_append(attrs, extra_attrs));
7086 return Ok(Some(item));
7089 // `unsafe async fn` or `async fn`
7091 self.check_keyword(keywords::Unsafe) &&
7092 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7094 self.check_keyword(keywords::Async) &&
7095 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7098 // ASYNC FUNCTION ITEM
7099 let unsafety = self.parse_unsafety();
7100 self.expect_keyword(keywords::Async)?;
7101 self.expect_keyword(keywords::Fn)?;
7102 let fn_span = self.prev_span;
7103 let (ident, item_, extra_attrs) =
7104 self.parse_item_fn(unsafety,
7106 closure_id: ast::DUMMY_NODE_ID,
7107 return_impl_trait_id: ast::DUMMY_NODE_ID,
7109 respan(fn_span, Constness::NotConst),
7111 let prev_span = self.prev_span;
7112 let item = self.mk_item(lo.to(prev_span),
7116 maybe_append(attrs, extra_attrs));
7117 return Ok(Some(item));
7119 if self.check_keyword(keywords::Unsafe) &&
7120 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7121 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7123 // UNSAFE TRAIT ITEM
7124 self.bump(); // `unsafe`
7125 let is_auto = if self.eat_keyword(keywords::Trait) {
7128 self.expect_keyword(keywords::Auto)?;
7129 self.expect_keyword(keywords::Trait)?;
7132 let (ident, item_, extra_attrs) =
7133 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7134 let prev_span = self.prev_span;
7135 let item = self.mk_item(lo.to(prev_span),
7139 maybe_append(attrs, extra_attrs));
7140 return Ok(Some(item));
7142 if self.check_keyword(keywords::Impl) ||
7143 self.check_keyword(keywords::Unsafe) &&
7144 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7145 self.check_keyword(keywords::Default) &&
7146 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7147 self.check_keyword(keywords::Default) &&
7148 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7150 let defaultness = self.parse_defaultness();
7151 let unsafety = self.parse_unsafety();
7152 self.expect_keyword(keywords::Impl)?;
7153 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7154 let span = lo.to(self.prev_span);
7155 return Ok(Some(self.mk_item(span, ident, item, visibility,
7156 maybe_append(attrs, extra_attrs))));
7158 if self.check_keyword(keywords::Fn) {
7161 let fn_span = self.prev_span;
7162 let (ident, item_, extra_attrs) =
7163 self.parse_item_fn(Unsafety::Normal,
7165 respan(fn_span, Constness::NotConst),
7167 let prev_span = self.prev_span;
7168 let item = self.mk_item(lo.to(prev_span),
7172 maybe_append(attrs, extra_attrs));
7173 return Ok(Some(item));
7175 if self.check_keyword(keywords::Unsafe)
7176 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7177 // UNSAFE FUNCTION ITEM
7178 self.bump(); // `unsafe`
7179 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7180 self.check(&token::OpenDelim(token::Brace));
7181 let abi = if self.eat_keyword(keywords::Extern) {
7182 self.parse_opt_abi()?.unwrap_or(Abi::C)
7186 self.expect_keyword(keywords::Fn)?;
7187 let fn_span = self.prev_span;
7188 let (ident, item_, extra_attrs) =
7189 self.parse_item_fn(Unsafety::Unsafe,
7191 respan(fn_span, Constness::NotConst),
7193 let prev_span = self.prev_span;
7194 let item = self.mk_item(lo.to(prev_span),
7198 maybe_append(attrs, extra_attrs));
7199 return Ok(Some(item));
7201 if self.eat_keyword(keywords::Mod) {
7203 let (ident, item_, extra_attrs) =
7204 self.parse_item_mod(&attrs[..])?;
7205 let prev_span = self.prev_span;
7206 let item = self.mk_item(lo.to(prev_span),
7210 maybe_append(attrs, extra_attrs));
7211 return Ok(Some(item));
7213 if let Some(type_) = self.eat_type() {
7214 let (ident, alias, generics) = type_?;
7216 let item_ = match alias {
7217 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7218 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7220 let prev_span = self.prev_span;
7221 let item = self.mk_item(lo.to(prev_span),
7226 return Ok(Some(item));
7228 if self.eat_keyword(keywords::Enum) {
7230 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7231 let prev_span = self.prev_span;
7232 let item = self.mk_item(lo.to(prev_span),
7236 maybe_append(attrs, extra_attrs));
7237 return Ok(Some(item));
7239 if self.check_keyword(keywords::Trait)
7240 || (self.check_keyword(keywords::Auto)
7241 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7243 let is_auto = if self.eat_keyword(keywords::Trait) {
7246 self.expect_keyword(keywords::Auto)?;
7247 self.expect_keyword(keywords::Trait)?;
7251 let (ident, item_, extra_attrs) =
7252 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7253 let prev_span = self.prev_span;
7254 let item = self.mk_item(lo.to(prev_span),
7258 maybe_append(attrs, extra_attrs));
7259 return Ok(Some(item));
7261 if self.eat_keyword(keywords::Struct) {
7263 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7264 let prev_span = self.prev_span;
7265 let item = self.mk_item(lo.to(prev_span),
7269 maybe_append(attrs, extra_attrs));
7270 return Ok(Some(item));
7272 if self.is_union_item() {
7275 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7276 let prev_span = self.prev_span;
7277 let item = self.mk_item(lo.to(prev_span),
7281 maybe_append(attrs, extra_attrs));
7282 return Ok(Some(item));
7284 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7285 return Ok(Some(macro_def));
7288 // Verify whether we have encountered a struct or method definition where the user forgot to
7289 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7290 if visibility.node.is_pub() &&
7291 self.check_ident() &&
7292 self.look_ahead(1, |t| *t != token::Not)
7294 // Space between `pub` keyword and the identifier
7297 // ^^^ `sp` points here
7298 let sp = self.prev_span.between(self.span);
7299 let full_sp = self.prev_span.to(self.span);
7300 let ident_sp = self.span;
7301 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7302 // possible public struct definition where `struct` was forgotten
7303 let ident = self.parse_ident().unwrap();
7304 let msg = format!("add `struct` here to parse `{}` as a public struct",
7306 let mut err = self.diagnostic()
7307 .struct_span_err(sp, "missing `struct` for struct definition");
7308 err.span_suggestion_short_with_applicability(
7309 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7312 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7313 let ident = self.parse_ident().unwrap();
7314 self.consume_block(token::Paren);
7315 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7316 self.check(&token::OpenDelim(token::Brace))
7318 ("fn", "method", false)
7319 } else if self.check(&token::Colon) {
7323 ("fn` or `struct", "method or struct", true)
7326 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7327 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7329 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7333 err.span_suggestion_short_with_applicability(
7334 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7337 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7338 err.span_suggestion_with_applicability(
7340 "if you meant to call a macro, try",
7341 format!("{}!", snippet),
7342 // this is the `ambiguous` conditional branch
7343 Applicability::MaybeIncorrect
7346 err.help("if you meant to call a macro, remove the `pub` \
7347 and add a trailing `!` after the identifier");
7353 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7356 /// Parse a foreign item.
7357 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7358 maybe_whole!(self, NtForeignItem, |ni| ni);
7360 let attrs = self.parse_outer_attributes()?;
7362 let visibility = self.parse_visibility(false)?;
7364 // FOREIGN STATIC ITEM
7365 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7366 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7367 if self.token.is_keyword(keywords::Const) {
7369 .struct_span_err(self.span, "extern items cannot be `const`")
7370 .span_suggestion_with_applicability(
7372 "try using a static value",
7373 "static".to_owned(),
7374 Applicability::MachineApplicable
7377 self.bump(); // `static` or `const`
7378 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7380 // FOREIGN FUNCTION ITEM
7381 if self.check_keyword(keywords::Fn) {
7382 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7384 // FOREIGN TYPE ITEM
7385 if self.check_keyword(keywords::Type) {
7386 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7389 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7393 ident: keywords::Invalid.ident(),
7394 span: lo.to(self.prev_span),
7395 id: ast::DUMMY_NODE_ID,
7398 node: ForeignItemKind::Macro(mac),
7403 if !attrs.is_empty() {
7404 self.expected_item_err(&attrs);
7412 /// This is the fall-through for parsing items.
7413 fn parse_macro_use_or_failure(
7415 attrs: Vec<Attribute> ,
7416 macros_allowed: bool,
7417 attributes_allowed: bool,
7419 visibility: Visibility
7420 ) -> PResult<'a, Option<P<Item>>> {
7421 if macros_allowed && self.token.is_path_start() {
7422 // MACRO INVOCATION ITEM
7424 let prev_span = self.prev_span;
7425 self.complain_if_pub_macro(&visibility.node, prev_span);
7427 let mac_lo = self.span;
7430 let pth = self.parse_path(PathStyle::Mod)?;
7431 self.expect(&token::Not)?;
7433 // a 'special' identifier (like what `macro_rules!` uses)
7434 // is optional. We should eventually unify invoc syntax
7436 let id = if self.token.is_ident() {
7439 keywords::Invalid.ident() // no special identifier
7441 // eat a matched-delimiter token tree:
7442 let (delim, tts) = self.expect_delimited_token_tree()?;
7443 if delim != MacDelimiter::Brace {
7444 if !self.eat(&token::Semi) {
7445 self.span_err(self.prev_span,
7446 "macros that expand to items must either \
7447 be surrounded with braces or followed by \
7452 let hi = self.prev_span;
7453 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7454 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7455 return Ok(Some(item));
7458 // FAILURE TO PARSE ITEM
7459 match visibility.node {
7460 VisibilityKind::Inherited => {}
7462 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7466 if !attributes_allowed && !attrs.is_empty() {
7467 self.expected_item_err(&attrs);
7472 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7473 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7474 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7476 if self.token.is_path_start() && !self.is_extern_non_path() {
7477 let prev_span = self.prev_span;
7479 let pth = self.parse_path(PathStyle::Mod)?;
7481 if pth.segments.len() == 1 {
7482 if !self.eat(&token::Not) {
7483 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7486 self.expect(&token::Not)?;
7489 if let Some(vis) = vis {
7490 self.complain_if_pub_macro(&vis.node, prev_span);
7495 // eat a matched-delimiter token tree:
7496 let (delim, tts) = self.expect_delimited_token_tree()?;
7497 if delim != MacDelimiter::Brace {
7498 self.expect(&token::Semi)?
7501 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7507 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7508 where F: FnOnce(&mut Self) -> PResult<'a, R>
7510 // Record all tokens we parse when parsing this item.
7511 let mut tokens = Vec::new();
7512 let prev_collecting = match self.token_cursor.frame.last_token {
7513 LastToken::Collecting(ref mut list) => {
7514 Some(mem::replace(list, Vec::new()))
7516 LastToken::Was(ref mut last) => {
7517 tokens.extend(last.take());
7521 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7522 let prev = self.token_cursor.stack.len();
7524 let last_token = if self.token_cursor.stack.len() == prev {
7525 &mut self.token_cursor.frame.last_token
7527 &mut self.token_cursor.stack[prev].last_token
7530 // Pull our the toekns that we've collected from the call to `f` above
7531 let mut collected_tokens = match *last_token {
7532 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7533 LastToken::Was(_) => panic!("our vector went away?"),
7536 // If we're not at EOF our current token wasn't actually consumed by
7537 // `f`, but it'll still be in our list that we pulled out. In that case
7539 let extra_token = if self.token != token::Eof {
7540 collected_tokens.pop()
7545 // If we were previously collecting tokens, then this was a recursive
7546 // call. In that case we need to record all the tokens we collected in
7547 // our parent list as well. To do that we push a clone of our stream
7548 // onto the previous list.
7549 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7550 match prev_collecting {
7552 list.push(stream.clone());
7553 list.extend(extra_token);
7554 *last_token = LastToken::Collecting(list);
7557 *last_token = LastToken::Was(extra_token);
7564 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7565 let attrs = self.parse_outer_attributes()?;
7566 self.parse_item_(attrs, true, false)
7570 fn is_import_coupler(&mut self) -> bool {
7571 self.check(&token::ModSep) &&
7572 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7573 *t == token::BinOp(token::Star))
7578 /// USE_TREE = [`::`] `*` |
7579 /// [`::`] `{` USE_TREE_LIST `}` |
7581 /// PATH `::` `{` USE_TREE_LIST `}` |
7582 /// PATH [`as` IDENT]
7583 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7586 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7587 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7588 self.check(&token::BinOp(token::Star)) ||
7589 self.is_import_coupler() {
7590 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7591 if self.eat(&token::ModSep) {
7592 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7595 if self.eat(&token::BinOp(token::Star)) {
7598 UseTreeKind::Nested(self.parse_use_tree_list()?)
7601 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7602 prefix = self.parse_path(PathStyle::Mod)?;
7604 if self.eat(&token::ModSep) {
7605 if self.eat(&token::BinOp(token::Star)) {
7608 UseTreeKind::Nested(self.parse_use_tree_list()?)
7611 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7615 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7618 /// Parse UseTreeKind::Nested(list)
7620 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7621 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7622 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7623 &token::CloseDelim(token::Brace),
7624 SeqSep::trailing_allowed(token::Comma), |this| {
7625 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7629 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7630 if self.eat_keyword(keywords::As) {
7632 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7634 Ok(Some(ident.gensym()))
7636 _ => self.parse_ident().map(Some),
7643 /// Parses a source module as a crate. This is the main
7644 /// entry point for the parser.
7645 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7648 attrs: self.parse_inner_attributes()?,
7649 module: self.parse_mod_items(&token::Eof, lo)?,
7650 span: lo.to(self.span),
7654 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7655 let ret = match self.token {
7656 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7657 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7664 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7665 match self.parse_optional_str() {
7666 Some((s, style, suf)) => {
7667 let sp = self.prev_span;
7668 self.expect_no_suffix(sp, "string literal", suf);
7672 let msg = "expected string literal";
7673 let mut err = self.fatal(msg);
7674 err.span_label(self.span, msg);