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);
776 err.span_label(sp, label_exp);
777 err.span_label(self.span, "unexpected token");
784 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
785 fn interpolated_or_expr_span(&self,
786 expr: PResult<'a, P<Expr>>)
787 -> PResult<'a, (Span, P<Expr>)> {
789 if self.prev_token_kind == PrevTokenKind::Interpolated {
797 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
798 let mut err = self.struct_span_err(self.span,
799 &format!("expected identifier, found {}",
800 self.this_token_descr()));
801 if let Some(token_descr) = self.token_descr() {
802 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
804 err.span_label(self.span, "expected identifier");
805 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
806 err.span_suggestion_with_applicability(
810 Applicability::MachineApplicable,
817 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
818 self.parse_ident_common(true)
821 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
823 token::Ident(ident, _) => {
824 if self.token.is_reserved_ident() {
825 let mut err = self.expected_ident_found();
832 let span = self.span;
834 Ok(Ident::new(ident.name, span))
837 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
838 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
840 self.expected_ident_found()
846 /// Check if the next token is `tok`, and return `true` if so.
848 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
850 crate fn check(&mut self, tok: &token::Token) -> bool {
851 let is_present = self.token == *tok;
852 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
856 /// Consume token 'tok' if it exists. Returns true if the given
857 /// token was present, false otherwise.
858 pub fn eat(&mut self, tok: &token::Token) -> bool {
859 let is_present = self.check(tok);
860 if is_present { self.bump() }
864 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
865 self.expected_tokens.push(TokenType::Keyword(kw));
866 self.token.is_keyword(kw)
869 /// If the next token is the given keyword, eat it and return
870 /// true. Otherwise, return false.
871 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
872 if self.check_keyword(kw) {
880 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
881 if self.token.is_keyword(kw) {
889 /// If the given word is not a keyword, signal an error.
890 /// If the next token is not the given word, signal an error.
891 /// Otherwise, eat it.
892 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
893 if !self.eat_keyword(kw) {
900 fn check_ident(&mut self) -> bool {
901 if self.token.is_ident() {
904 self.expected_tokens.push(TokenType::Ident);
909 fn check_path(&mut self) -> bool {
910 if self.token.is_path_start() {
913 self.expected_tokens.push(TokenType::Path);
918 fn check_type(&mut self) -> bool {
919 if self.token.can_begin_type() {
922 self.expected_tokens.push(TokenType::Type);
927 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
928 /// and continue. If a `+` is not seen, return false.
930 /// This is using when token splitting += into +.
931 /// See issue 47856 for an example of when this may occur.
932 fn eat_plus(&mut self) -> bool {
933 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
935 token::BinOp(token::Plus) => {
939 token::BinOpEq(token::Plus) => {
940 let span = self.span.with_lo(self.span.lo() + BytePos(1));
941 self.bump_with(token::Eq, span);
949 /// Checks to see if the next token is either `+` or `+=`.
950 /// Otherwise returns false.
951 fn check_plus(&mut self) -> bool {
952 if self.token.is_like_plus() {
956 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
961 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
962 /// `&` and continue. If an `&` is not seen, signal an error.
963 fn expect_and(&mut self) -> PResult<'a, ()> {
964 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
966 token::BinOp(token::And) => {
971 let span = self.span.with_lo(self.span.lo() + BytePos(1));
972 Ok(self.bump_with(token::BinOp(token::And), span))
974 _ => self.unexpected()
978 /// Expect and consume an `|`. If `||` is seen, replace it with a single
979 /// `|` and continue. If an `|` is not seen, signal an error.
980 fn expect_or(&mut self) -> PResult<'a, ()> {
981 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
983 token::BinOp(token::Or) => {
988 let span = self.span.with_lo(self.span.lo() + BytePos(1));
989 Ok(self.bump_with(token::BinOp(token::Or), span))
991 _ => self.unexpected()
995 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
997 None => {/* everything ok */}
999 let text = suf.as_str();
1000 if text.is_empty() {
1001 self.span_bug(sp, "found empty literal suffix in Some")
1003 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
1008 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
1009 /// `<` and continue. If a `<` is not seen, return false.
1011 /// This is meant to be used when parsing generics on a path to get the
1013 fn eat_lt(&mut self) -> bool {
1014 self.expected_tokens.push(TokenType::Token(token::Lt));
1020 token::BinOp(token::Shl) => {
1021 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1022 self.bump_with(token::Lt, span);
1029 fn expect_lt(&mut self) -> PResult<'a, ()> {
1037 /// Expect and consume a GT. if a >> is seen, replace it
1038 /// with a single > and continue. If a GT is not seen,
1039 /// signal an error.
1040 fn expect_gt(&mut self) -> PResult<'a, ()> {
1041 self.expected_tokens.push(TokenType::Token(token::Gt));
1047 token::BinOp(token::Shr) => {
1048 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1049 Ok(self.bump_with(token::Gt, span))
1051 token::BinOpEq(token::Shr) => {
1052 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1053 Ok(self.bump_with(token::Ge, span))
1056 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1057 Ok(self.bump_with(token::Eq, span))
1059 _ => self.unexpected()
1063 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1064 /// passes through any errors encountered. Used for error recovery.
1065 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1066 let handler = self.diagnostic();
1068 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1070 TokenExpectType::Expect,
1071 |p| Ok(p.parse_token_tree())) {
1072 handler.cancel(err);
1076 /// Parse a sequence, including the closing delimiter. The function
1077 /// f must consume tokens until reaching the next separator or
1078 /// closing bracket.
1079 pub fn parse_seq_to_end<T, F>(&mut self,
1083 -> PResult<'a, Vec<T>> where
1084 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1086 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1091 /// Parse a sequence, not including the closing delimiter. The function
1092 /// f must consume tokens until reaching the next separator or
1093 /// closing bracket.
1094 pub fn parse_seq_to_before_end<T, F>(&mut self,
1098 -> PResult<'a, Vec<T>>
1099 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1101 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1104 fn parse_seq_to_before_tokens<T, F>(
1106 kets: &[&token::Token],
1108 expect: TokenExpectType,
1110 ) -> PResult<'a, Vec<T>>
1111 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1113 let mut first: bool = true;
1115 while !kets.iter().any(|k| {
1117 TokenExpectType::Expect => self.check(k),
1118 TokenExpectType::NoExpect => self.token == **k,
1122 token::CloseDelim(..) | token::Eof => break,
1125 if let Some(ref t) = sep.sep {
1129 if let Err(mut e) = self.expect(t) {
1130 // Attempt to keep parsing if it was a similar separator
1131 if let Some(ref tokens) = t.similar_tokens() {
1132 if tokens.contains(&self.token) {
1137 // Attempt to keep parsing if it was an omitted separator
1151 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1153 TokenExpectType::Expect => self.check(k),
1154 TokenExpectType::NoExpect => self.token == **k,
1167 /// Parse a sequence, including the closing delimiter. The function
1168 /// f must consume tokens until reaching the next separator or
1169 /// closing bracket.
1170 fn parse_unspanned_seq<T, F>(&mut self,
1175 -> PResult<'a, Vec<T>> where
1176 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1179 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1184 /// Advance the parser by one token
1185 pub fn bump(&mut self) {
1186 if self.prev_token_kind == PrevTokenKind::Eof {
1187 // Bumping after EOF is a bad sign, usually an infinite loop.
1188 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1191 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1193 // Record last token kind for possible error recovery.
1194 self.prev_token_kind = match self.token {
1195 token::DocComment(..) => PrevTokenKind::DocComment,
1196 token::Comma => PrevTokenKind::Comma,
1197 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1198 token::Interpolated(..) => PrevTokenKind::Interpolated,
1199 token::Eof => PrevTokenKind::Eof,
1200 token::Ident(..) => PrevTokenKind::Ident,
1201 _ => PrevTokenKind::Other,
1204 let next = self.next_tok();
1205 self.span = next.sp;
1206 self.token = next.tok;
1207 self.expected_tokens.clear();
1208 // check after each token
1209 self.process_potential_macro_variable();
1212 /// Advance the parser using provided token as a next one. Use this when
1213 /// consuming a part of a token. For example a single `<` from `<<`.
1214 fn bump_with(&mut self, next: token::Token, span: Span) {
1215 self.prev_span = self.span.with_hi(span.lo());
1216 // It would be incorrect to record the kind of the current token, but
1217 // fortunately for tokens currently using `bump_with`, the
1218 // prev_token_kind will be of no use anyway.
1219 self.prev_token_kind = PrevTokenKind::Other;
1222 self.expected_tokens.clear();
1225 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1226 F: FnOnce(&token::Token) -> R,
1229 return f(&self.token)
1232 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1233 Some(tree) => match tree {
1234 TokenTree::Token(_, tok) => tok,
1235 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1237 None => token::CloseDelim(self.token_cursor.frame.delim),
1241 fn look_ahead_span(&self, dist: usize) -> Span {
1246 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1247 Some(TokenTree::Token(span, _)) => span,
1248 Some(TokenTree::Delimited(span, _)) => span.entire(),
1249 None => self.look_ahead_span(dist - 1),
1252 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1253 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1255 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1256 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1258 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1259 err.span_err(sp, self.diagnostic())
1261 fn bug(&self, m: &str) -> ! {
1262 self.sess.span_diagnostic.span_bug(self.span, m)
1264 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1265 self.sess.span_diagnostic.span_err(sp, m)
1267 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1268 self.sess.span_diagnostic.struct_span_err(sp, m)
1270 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1271 self.sess.span_diagnostic.span_bug(sp, m)
1273 crate fn abort_if_errors(&self) {
1274 self.sess.span_diagnostic.abort_if_errors();
1277 fn cancel(&self, err: &mut DiagnosticBuilder) {
1278 self.sess.span_diagnostic.cancel(err)
1281 crate fn diagnostic(&self) -> &'a errors::Handler {
1282 &self.sess.span_diagnostic
1285 /// Is the current token one of the keywords that signals a bare function
1287 fn token_is_bare_fn_keyword(&mut self) -> bool {
1288 self.check_keyword(keywords::Fn) ||
1289 self.check_keyword(keywords::Unsafe) ||
1290 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1293 /// parse a TyKind::BareFn type:
1294 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1297 [unsafe] [extern "ABI"] fn (S) -> T
1307 let unsafety = self.parse_unsafety();
1308 let abi = if self.eat_keyword(keywords::Extern) {
1309 self.parse_opt_abi()?.unwrap_or(Abi::C)
1314 self.expect_keyword(keywords::Fn)?;
1315 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1316 let ret_ty = self.parse_ret_ty(false)?;
1317 let decl = P(FnDecl {
1322 Ok(TyKind::BareFn(P(BareFnTy {
1330 /// Parse asyncness: `async` or nothing
1331 fn parse_asyncness(&mut self) -> IsAsync {
1332 if self.eat_keyword(keywords::Async) {
1334 closure_id: ast::DUMMY_NODE_ID,
1335 return_impl_trait_id: ast::DUMMY_NODE_ID,
1342 /// Parse unsafety: `unsafe` or nothing.
1343 fn parse_unsafety(&mut self) -> Unsafety {
1344 if self.eat_keyword(keywords::Unsafe) {
1351 /// Parse the items in a trait declaration
1352 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1353 maybe_whole!(self, NtTraitItem, |x| x);
1354 let attrs = self.parse_outer_attributes()?;
1355 let (mut item, tokens) = self.collect_tokens(|this| {
1356 this.parse_trait_item_(at_end, attrs)
1358 // See `parse_item` for why this clause is here.
1359 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1360 item.tokens = Some(tokens);
1365 fn parse_trait_item_(&mut self,
1367 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1370 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1371 self.parse_trait_item_assoc_ty()?
1372 } else if self.is_const_item() {
1373 self.expect_keyword(keywords::Const)?;
1374 let ident = self.parse_ident()?;
1375 self.expect(&token::Colon)?;
1376 let ty = self.parse_ty()?;
1377 let default = if self.eat(&token::Eq) {
1378 let expr = self.parse_expr()?;
1379 self.expect(&token::Semi)?;
1382 self.expect(&token::Semi)?;
1385 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1386 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1387 // trait item macro.
1388 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1390 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1392 let ident = self.parse_ident()?;
1393 let mut generics = self.parse_generics()?;
1395 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1396 // This is somewhat dubious; We don't want to allow
1397 // argument names to be left off if there is a
1400 // We don't allow argument names to be left off in edition 2018.
1401 if p.span.edition() >= Edition::Edition2018 {
1402 p.parse_arg_general(true)
1404 p.parse_arg_general(false)
1407 generics.where_clause = self.parse_where_clause()?;
1409 let sig = ast::MethodSig {
1419 let body = match self.token {
1423 debug!("parse_trait_methods(): parsing required method");
1426 token::OpenDelim(token::Brace) => {
1427 debug!("parse_trait_methods(): parsing provided method");
1429 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1430 attrs.extend(inner_attrs.iter().cloned());
1433 token::Interpolated(ref nt) => {
1435 token::NtBlock(..) => {
1437 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1438 attrs.extend(inner_attrs.iter().cloned());
1442 let token_str = self.this_token_to_string();
1443 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1445 err.span_label(self.span, "expected `;` or `{`");
1451 let token_str = self.this_token_to_string();
1452 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1454 err.span_label(self.span, "expected `;` or `{`");
1458 (ident, ast::TraitItemKind::Method(sig, body), generics)
1462 id: ast::DUMMY_NODE_ID,
1467 span: lo.to(self.prev_span),
1472 /// Parse optional return type [ -> TY ] in function decl
1473 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1474 if self.eat(&token::RArrow) {
1475 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1477 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1482 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1483 self.parse_ty_common(true, true)
1486 /// Parse a type in restricted contexts where `+` is not permitted.
1487 /// Example 1: `&'a TYPE`
1488 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1489 /// Example 2: `value1 as TYPE + value2`
1490 /// `+` is prohibited to avoid interactions with expression grammar.
1491 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1492 self.parse_ty_common(false, true)
1495 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1496 -> PResult<'a, P<Ty>> {
1497 maybe_whole!(self, NtTy, |x| x);
1500 let mut impl_dyn_multi = false;
1501 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1502 // `(TYPE)` is a parenthesized type.
1503 // `(TYPE,)` is a tuple with a single field of type TYPE.
1504 let mut ts = vec![];
1505 let mut last_comma = false;
1506 while self.token != token::CloseDelim(token::Paren) {
1507 ts.push(self.parse_ty()?);
1508 if self.eat(&token::Comma) {
1515 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1516 self.expect(&token::CloseDelim(token::Paren))?;
1518 if ts.len() == 1 && !last_comma {
1519 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1520 let maybe_bounds = allow_plus && self.token.is_like_plus();
1522 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1523 TyKind::Path(None, ref path) if maybe_bounds => {
1524 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1526 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1527 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1528 let path = match bounds[0] {
1529 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1530 _ => self.bug("unexpected lifetime bound"),
1532 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1535 _ => TyKind::Paren(P(ty))
1540 } else if self.eat(&token::Not) {
1543 } else if self.eat(&token::BinOp(token::Star)) {
1545 TyKind::Ptr(self.parse_ptr()?)
1546 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1548 let t = self.parse_ty()?;
1549 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1550 let t = match self.maybe_parse_fixed_length_of_vec()? {
1551 None => TyKind::Slice(t),
1552 Some(length) => TyKind::Array(t, AnonConst {
1553 id: ast::DUMMY_NODE_ID,
1557 self.expect(&token::CloseDelim(token::Bracket))?;
1559 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1562 self.parse_borrowed_pointee()?
1563 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1565 // In order to not be ambiguous, the type must be surrounded by parens.
1566 self.expect(&token::OpenDelim(token::Paren))?;
1568 id: ast::DUMMY_NODE_ID,
1569 value: self.parse_expr()?,
1571 self.expect(&token::CloseDelim(token::Paren))?;
1573 } else if self.eat_keyword(keywords::Underscore) {
1574 // A type to be inferred `_`
1576 } else if self.token_is_bare_fn_keyword() {
1577 // Function pointer type
1578 self.parse_ty_bare_fn(Vec::new())?
1579 } else if self.check_keyword(keywords::For) {
1580 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1581 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1582 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1584 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1585 if self.token_is_bare_fn_keyword() {
1586 self.parse_ty_bare_fn(lifetime_defs)?
1588 let path = self.parse_path(PathStyle::Type)?;
1589 let parse_plus = allow_plus && self.check_plus();
1590 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1592 } else if self.eat_keyword(keywords::Impl) {
1593 // Always parse bounds greedily for better error recovery.
1594 let bounds = self.parse_generic_bounds()?;
1595 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1596 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1597 } else if self.check_keyword(keywords::Dyn) &&
1598 (self.span.edition() == Edition::Edition2018 ||
1599 self.look_ahead(1, |t| t.can_begin_bound() &&
1600 !can_continue_type_after_non_fn_ident(t))) {
1601 self.bump(); // `dyn`
1602 // Always parse bounds greedily for better error recovery.
1603 let bounds = self.parse_generic_bounds()?;
1604 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1605 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1606 } else if self.check(&token::Question) ||
1607 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1608 // Bound list (trait object type)
1609 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1610 TraitObjectSyntax::None)
1611 } else if self.eat_lt() {
1613 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1614 TyKind::Path(Some(qself), path)
1615 } else if self.token.is_path_start() {
1617 let path = self.parse_path(PathStyle::Type)?;
1618 if self.eat(&token::Not) {
1619 // Macro invocation in type position
1620 let (delim, tts) = self.expect_delimited_token_tree()?;
1621 let node = Mac_ { path, tts, delim };
1622 TyKind::Mac(respan(lo.to(self.prev_span), node))
1624 // Just a type path or bound list (trait object type) starting with a trait.
1626 // `Trait1 + Trait2 + 'a`
1627 if allow_plus && self.check_plus() {
1628 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1630 TyKind::Path(None, path)
1634 let msg = format!("expected type, found {}", self.this_token_descr());
1635 return Err(self.fatal(&msg));
1638 let span = lo.to(self.prev_span);
1639 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1641 // Try to recover from use of `+` with incorrect priority.
1642 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1643 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1644 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1649 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1650 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1651 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1652 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1654 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1655 bounds.append(&mut self.parse_generic_bounds()?);
1657 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1660 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1661 if !allow_plus && impl_dyn_multi {
1662 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1663 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1664 .span_suggestion_with_applicability(
1666 "use parentheses to disambiguate",
1668 Applicability::MachineApplicable
1673 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1674 // Do not add `+` to expected tokens.
1675 if !allow_plus || !self.token.is_like_plus() {
1680 let bounds = self.parse_generic_bounds()?;
1681 let sum_span = ty.span.to(self.prev_span);
1683 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1684 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1687 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1688 let sum_with_parens = pprust::to_string(|s| {
1689 use print::pprust::PrintState;
1692 s.print_opt_lifetime(lifetime)?;
1693 s.print_mutability(mut_ty.mutbl)?;
1695 s.print_type(&mut_ty.ty)?;
1696 s.print_type_bounds(" +", &bounds)?;
1699 err.span_suggestion_with_applicability(
1701 "try adding parentheses",
1703 Applicability::MachineApplicable
1706 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1707 err.span_label(sum_span, "perhaps you forgot parentheses?");
1710 err.span_label(sum_span, "expected a path");
1717 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1718 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1720 // Do not add `::` to expected tokens.
1721 if !allow_recovery || self.token != token::ModSep {
1724 let ty = match base.to_ty() {
1726 None => return Ok(base),
1729 self.bump(); // `::`
1730 let mut segments = Vec::new();
1731 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1733 let span = ty.span.to(self.prev_span);
1734 let path_span = span.to(span); // use an empty path since `position` == 0
1735 let recovered = base.to_recovered(
1736 Some(QSelf { ty, path_span, position: 0 }),
1737 ast::Path { segments, span },
1741 .struct_span_err(span, "missing angle brackets in associated item path")
1742 .span_suggestion_with_applicability( // this is a best-effort recovery
1743 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1749 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1750 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1751 let mutbl = self.parse_mutability();
1752 let ty = self.parse_ty_no_plus()?;
1753 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1756 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1757 let mutbl = if self.eat_keyword(keywords::Mut) {
1759 } else if self.eat_keyword(keywords::Const) {
1760 Mutability::Immutable
1762 let span = self.prev_span;
1764 "expected mut or const in raw pointer type (use \
1765 `*mut T` or `*const T` as appropriate)");
1766 Mutability::Immutable
1768 let t = self.parse_ty_no_plus()?;
1769 Ok(MutTy { ty: t, mutbl: mutbl })
1772 fn is_named_argument(&mut self) -> bool {
1773 let offset = match self.token {
1774 token::Interpolated(ref nt) => match nt.0 {
1775 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1778 token::BinOp(token::And) | token::AndAnd => 1,
1779 _ if self.token.is_keyword(keywords::Mut) => 1,
1783 self.look_ahead(offset, |t| t.is_ident()) &&
1784 self.look_ahead(offset + 1, |t| t == &token::Colon)
1787 /// This version of parse arg doesn't necessarily require
1788 /// identifier names.
1789 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1790 maybe_whole!(self, NtArg, |x| x);
1792 let (pat, ty) = if require_name || self.is_named_argument() {
1793 debug!("parse_arg_general parse_pat (require_name:{})",
1795 let pat = self.parse_pat()?;
1797 if let Err(mut err) = self.expect(&token::Colon) {
1798 // If we find a pattern followed by an identifier, it could be an (incorrect)
1799 // C-style parameter declaration.
1800 if self.check_ident() && self.look_ahead(1, |t| {
1801 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1803 let ident = self.parse_ident().unwrap();
1804 let span = pat.span.with_hi(ident.span.hi());
1806 err.span_suggestion_with_applicability(
1808 "declare the type after the parameter binding",
1809 String::from("<identifier>: <type>"),
1810 Applicability::HasPlaceholders,
1817 (pat, self.parse_ty()?)
1819 debug!("parse_arg_general ident_to_pat");
1820 let parser_snapshot_before_ty = self.clone();
1821 let mut ty = self.parse_ty();
1822 if ty.is_ok() && self.token == token::Colon {
1823 // This wasn't actually a type, but a pattern looking like a type,
1824 // so we are going to rollback and re-parse for recovery.
1825 ty = self.unexpected();
1829 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1831 id: ast::DUMMY_NODE_ID,
1832 node: PatKind::Ident(
1833 BindingMode::ByValue(Mutability::Immutable), ident, None),
1839 // Recover from attempting to parse the argument as a type without pattern.
1841 mem::replace(self, parser_snapshot_before_ty);
1842 let pat = self.parse_pat()?;
1843 self.expect(&token::Colon)?;
1844 let ty = self.parse_ty()?;
1846 let mut err = self.diagnostic().struct_span_err_with_code(
1848 "patterns aren't allowed in methods without bodies",
1849 DiagnosticId::Error("E0642".into()),
1851 err.span_suggestion_short_with_applicability(
1853 "give this argument a name or use an underscore to ignore it",
1855 Applicability::MachineApplicable,
1859 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1861 node: PatKind::Wild,
1863 id: ast::DUMMY_NODE_ID
1870 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1873 /// Parse a single function argument
1874 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1875 self.parse_arg_general(true)
1878 /// Parse an argument in a lambda header e.g. |arg, arg|
1879 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1880 let pat = self.parse_pat()?;
1881 let t = if self.eat(&token::Colon) {
1885 id: ast::DUMMY_NODE_ID,
1886 node: TyKind::Infer,
1887 span: self.prev_span,
1893 id: ast::DUMMY_NODE_ID
1897 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1898 if self.eat(&token::Semi) {
1899 Ok(Some(self.parse_expr()?))
1905 /// Matches token_lit = LIT_INTEGER | ...
1906 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1907 let out = match self.token {
1908 token::Interpolated(ref nt) => match nt.0 {
1909 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1910 ExprKind::Lit(ref lit) => { lit.node.clone() }
1911 _ => { return self.unexpected_last(&self.token); }
1913 _ => { return self.unexpected_last(&self.token); }
1915 token::Literal(lit, suf) => {
1916 let diag = Some((self.span, &self.sess.span_diagnostic));
1917 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1921 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1926 _ => { return self.unexpected_last(&self.token); }
1933 /// Matches lit = true | false | token_lit
1934 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1936 let lit = if self.eat_keyword(keywords::True) {
1938 } else if self.eat_keyword(keywords::False) {
1939 LitKind::Bool(false)
1941 let lit = self.parse_lit_token()?;
1944 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
1947 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1948 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1949 maybe_whole_expr!(self);
1951 let minus_lo = self.span;
1952 let minus_present = self.eat(&token::BinOp(token::Minus));
1954 let literal = P(self.parse_lit()?);
1955 let hi = self.prev_span;
1956 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1959 let minus_hi = self.prev_span;
1960 let unary = self.mk_unary(UnOp::Neg, expr);
1961 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1967 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1969 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1970 let span = self.span;
1972 Ok(Ident::new(ident.name, span))
1974 _ => self.parse_ident(),
1978 /// Parses qualified path.
1979 /// Assumes that the leading `<` has been parsed already.
1981 /// `qualified_path = <type [as trait_ref]>::path`
1986 /// `<T as U>::F::a<S>` (without disambiguator)
1987 /// `<T as U>::F::a::<S>` (with disambiguator)
1988 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1989 let lo = self.prev_span;
1990 let ty = self.parse_ty()?;
1992 // `path` will contain the prefix of the path up to the `>`,
1993 // if any (e.g., `U` in the `<T as U>::*` examples
1994 // above). `path_span` has the span of that path, or an empty
1995 // span in the case of something like `<T>::Bar`.
1996 let (mut path, path_span);
1997 if self.eat_keyword(keywords::As) {
1998 let path_lo = self.span;
1999 path = self.parse_path(PathStyle::Type)?;
2000 path_span = path_lo.to(self.prev_span);
2002 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2003 path_span = self.span.to(self.span);
2006 self.expect(&token::Gt)?;
2007 self.expect(&token::ModSep)?;
2009 let qself = QSelf { ty, path_span, position: path.segments.len() };
2010 self.parse_path_segments(&mut path.segments, style, true)?;
2012 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2015 /// Parses simple paths.
2017 /// `path = [::] segment+`
2018 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2021 /// `a::b::C<D>` (without disambiguator)
2022 /// `a::b::C::<D>` (with disambiguator)
2023 /// `Fn(Args)` (without disambiguator)
2024 /// `Fn::(Args)` (with disambiguator)
2025 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2026 self.parse_path_common(style, true)
2029 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2030 -> PResult<'a, ast::Path> {
2031 maybe_whole!(self, NtPath, |path| {
2032 if style == PathStyle::Mod &&
2033 path.segments.iter().any(|segment| segment.args.is_some()) {
2034 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2039 let lo = self.meta_var_span.unwrap_or(self.span);
2040 let mut segments = Vec::new();
2041 if self.eat(&token::ModSep) {
2042 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
2044 self.parse_path_segments(&mut segments, style, enable_warning)?;
2046 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2049 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2050 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2051 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2052 let meta_ident = match self.token {
2053 token::Interpolated(ref nt) => match nt.0 {
2054 token::NtMeta(ref meta) => match meta.node {
2055 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2062 if let Some(path) = meta_ident {
2066 self.parse_path(style)
2069 fn parse_path_segments(&mut self,
2070 segments: &mut Vec<PathSegment>,
2072 enable_warning: bool)
2073 -> PResult<'a, ()> {
2075 segments.push(self.parse_path_segment(style, enable_warning)?);
2077 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2083 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2084 -> PResult<'a, PathSegment> {
2085 let ident = self.parse_path_segment_ident()?;
2087 let is_args_start = |token: &token::Token| match *token {
2088 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2091 let check_args_start = |this: &mut Self| {
2092 this.expected_tokens.extend_from_slice(
2093 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2095 is_args_start(&this.token)
2098 Ok(if style == PathStyle::Type && check_args_start(self) ||
2099 style != PathStyle::Mod && self.check(&token::ModSep)
2100 && self.look_ahead(1, |t| is_args_start(t)) {
2101 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2103 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2104 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2105 .span_label(self.prev_span, "try removing `::`").emit();
2108 let args = if self.eat_lt() {
2110 let (args, bindings) = self.parse_generic_args()?;
2112 let span = lo.to(self.prev_span);
2113 AngleBracketedArgs { args, bindings, span }.into()
2117 let inputs = self.parse_seq_to_before_tokens(
2118 &[&token::CloseDelim(token::Paren)],
2119 SeqSep::trailing_allowed(token::Comma),
2120 TokenExpectType::Expect,
2123 let span = lo.to(self.prev_span);
2124 let output = if self.eat(&token::RArrow) {
2125 Some(self.parse_ty_common(false, false)?)
2129 ParenthesisedArgs { inputs, output, span }.into()
2132 PathSegment { ident, args }
2134 // Generic arguments are not found.
2135 PathSegment::from_ident(ident)
2139 crate fn check_lifetime(&mut self) -> bool {
2140 self.expected_tokens.push(TokenType::Lifetime);
2141 self.token.is_lifetime()
2144 /// Parse single lifetime 'a or panic.
2145 crate fn expect_lifetime(&mut self) -> Lifetime {
2146 if let Some(ident) = self.token.lifetime() {
2147 let span = self.span;
2149 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2151 self.span_bug(self.span, "not a lifetime")
2155 fn eat_label(&mut self) -> Option<Label> {
2156 if let Some(ident) = self.token.lifetime() {
2157 let span = self.span;
2159 Some(Label { ident: Ident::new(ident.name, span) })
2165 /// Parse mutability (`mut` or nothing).
2166 fn parse_mutability(&mut self) -> Mutability {
2167 if self.eat_keyword(keywords::Mut) {
2170 Mutability::Immutable
2174 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2175 if let token::Literal(token::Integer(name), None) = self.token {
2177 Ok(Ident::new(name, self.prev_span))
2179 self.parse_ident_common(false)
2183 /// Parse ident (COLON expr)?
2184 fn parse_field(&mut self) -> PResult<'a, Field> {
2185 let attrs = self.parse_outer_attributes()?;
2188 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2189 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2190 let fieldname = self.parse_field_name()?;
2192 (fieldname, self.parse_expr()?, false)
2194 let fieldname = self.parse_ident_common(false)?;
2196 // Mimic `x: x` for the `x` field shorthand.
2197 let path = ast::Path::from_ident(fieldname);
2198 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2199 (fieldname, expr, true)
2203 span: lo.to(expr.span),
2206 attrs: attrs.into(),
2210 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2211 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2214 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2215 ExprKind::Unary(unop, expr)
2218 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2219 ExprKind::Binary(binop, lhs, rhs)
2222 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2223 ExprKind::Call(f, args)
2226 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2227 ExprKind::Index(expr, idx)
2230 fn mk_range(&mut self,
2231 start: Option<P<Expr>>,
2232 end: Option<P<Expr>>,
2233 limits: RangeLimits)
2234 -> PResult<'a, ast::ExprKind> {
2235 if end.is_none() && limits == RangeLimits::Closed {
2236 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2238 Ok(ExprKind::Range(start, end, limits))
2242 fn mk_assign_op(&mut self, binop: ast::BinOp,
2243 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2244 ExprKind::AssignOp(binop, lhs, rhs)
2247 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2249 id: ast::DUMMY_NODE_ID,
2250 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2256 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2257 let delim = match self.token {
2258 token::OpenDelim(delim) => delim,
2260 let msg = "expected open delimiter";
2261 let mut err = self.fatal(msg);
2262 err.span_label(self.span, msg);
2266 let delimited = match self.parse_token_tree() {
2267 TokenTree::Delimited(_, delimited) => delimited,
2268 _ => unreachable!(),
2270 let delim = match delim {
2271 token::Paren => MacDelimiter::Parenthesis,
2272 token::Bracket => MacDelimiter::Bracket,
2273 token::Brace => MacDelimiter::Brace,
2274 token::NoDelim => self.bug("unexpected no delimiter"),
2276 Ok((delim, delimited.stream().into()))
2279 /// At the bottom (top?) of the precedence hierarchy,
2280 /// parse things like parenthesized exprs,
2281 /// macros, return, etc.
2283 /// NB: This does not parse outer attributes,
2284 /// and is private because it only works
2285 /// correctly if called from parse_dot_or_call_expr().
2286 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2287 maybe_whole_expr!(self);
2289 // Outer attributes are already parsed and will be
2290 // added to the return value after the fact.
2292 // Therefore, prevent sub-parser from parsing
2293 // attributes by giving them a empty "already parsed" list.
2294 let mut attrs = ThinVec::new();
2297 let mut hi = self.span;
2301 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2303 token::OpenDelim(token::Paren) => {
2306 attrs.extend(self.parse_inner_attributes()?);
2308 // (e) is parenthesized e
2309 // (e,) is a tuple with only one field, e
2310 let mut es = vec![];
2311 let mut trailing_comma = false;
2312 while self.token != token::CloseDelim(token::Paren) {
2313 es.push(self.parse_expr()?);
2314 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2315 if self.eat(&token::Comma) {
2316 trailing_comma = true;
2318 trailing_comma = false;
2324 hi = self.prev_span;
2325 ex = if es.len() == 1 && !trailing_comma {
2326 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2331 token::OpenDelim(token::Brace) => {
2332 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2334 token::BinOp(token::Or) | token::OrOr => {
2335 return self.parse_lambda_expr(attrs);
2337 token::OpenDelim(token::Bracket) => {
2340 attrs.extend(self.parse_inner_attributes()?);
2342 if self.eat(&token::CloseDelim(token::Bracket)) {
2344 ex = ExprKind::Array(Vec::new());
2347 let first_expr = self.parse_expr()?;
2348 if self.eat(&token::Semi) {
2349 // Repeating array syntax: [ 0; 512 ]
2350 let count = AnonConst {
2351 id: ast::DUMMY_NODE_ID,
2352 value: self.parse_expr()?,
2354 self.expect(&token::CloseDelim(token::Bracket))?;
2355 ex = ExprKind::Repeat(first_expr, count);
2356 } else if self.eat(&token::Comma) {
2357 // Vector with two or more elements.
2358 let remaining_exprs = self.parse_seq_to_end(
2359 &token::CloseDelim(token::Bracket),
2360 SeqSep::trailing_allowed(token::Comma),
2361 |p| Ok(p.parse_expr()?)
2363 let mut exprs = vec![first_expr];
2364 exprs.extend(remaining_exprs);
2365 ex = ExprKind::Array(exprs);
2367 // Vector with one element.
2368 self.expect(&token::CloseDelim(token::Bracket))?;
2369 ex = ExprKind::Array(vec![first_expr]);
2372 hi = self.prev_span;
2376 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2378 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2380 if self.span.edition() >= Edition::Edition2018 &&
2381 self.check_keyword(keywords::Async)
2383 if self.is_async_block() { // check for `async {` and `async move {`
2384 return self.parse_async_block(attrs);
2386 return self.parse_lambda_expr(attrs);
2389 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2390 return self.parse_lambda_expr(attrs);
2392 if self.eat_keyword(keywords::If) {
2393 return self.parse_if_expr(attrs);
2395 if self.eat_keyword(keywords::For) {
2396 let lo = self.prev_span;
2397 return self.parse_for_expr(None, lo, attrs);
2399 if self.eat_keyword(keywords::While) {
2400 let lo = self.prev_span;
2401 return self.parse_while_expr(None, lo, attrs);
2403 if let Some(label) = self.eat_label() {
2404 let lo = label.ident.span;
2405 self.expect(&token::Colon)?;
2406 if self.eat_keyword(keywords::While) {
2407 return self.parse_while_expr(Some(label), lo, attrs)
2409 if self.eat_keyword(keywords::For) {
2410 return self.parse_for_expr(Some(label), lo, attrs)
2412 if self.eat_keyword(keywords::Loop) {
2413 return self.parse_loop_expr(Some(label), lo, attrs)
2415 if self.token == token::OpenDelim(token::Brace) {
2416 return self.parse_block_expr(Some(label),
2418 BlockCheckMode::Default,
2421 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2422 let mut err = self.fatal(msg);
2423 err.span_label(self.span, msg);
2426 if self.eat_keyword(keywords::Loop) {
2427 let lo = self.prev_span;
2428 return self.parse_loop_expr(None, lo, attrs);
2430 if self.eat_keyword(keywords::Continue) {
2431 let label = self.eat_label();
2432 let ex = ExprKind::Continue(label);
2433 let hi = self.prev_span;
2434 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2436 if self.eat_keyword(keywords::Match) {
2437 return self.parse_match_expr(attrs);
2439 if self.eat_keyword(keywords::Unsafe) {
2440 return self.parse_block_expr(
2443 BlockCheckMode::Unsafe(ast::UserProvided),
2446 if self.is_do_catch_block() {
2447 let mut db = self.fatal("found removed `do catch` syntax");
2448 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2451 if self.is_try_block() {
2453 assert!(self.eat_keyword(keywords::Try));
2454 return self.parse_try_block(lo, attrs);
2456 if self.eat_keyword(keywords::Return) {
2457 if self.token.can_begin_expr() {
2458 let e = self.parse_expr()?;
2460 ex = ExprKind::Ret(Some(e));
2462 ex = ExprKind::Ret(None);
2464 } else if self.eat_keyword(keywords::Break) {
2465 let label = self.eat_label();
2466 let e = if self.token.can_begin_expr()
2467 && !(self.token == token::OpenDelim(token::Brace)
2468 && self.restrictions.contains(
2469 Restrictions::NO_STRUCT_LITERAL)) {
2470 Some(self.parse_expr()?)
2474 ex = ExprKind::Break(label, e);
2475 hi = self.prev_span;
2476 } else if self.eat_keyword(keywords::Yield) {
2477 if self.token.can_begin_expr() {
2478 let e = self.parse_expr()?;
2480 ex = ExprKind::Yield(Some(e));
2482 ex = ExprKind::Yield(None);
2484 } else if self.token.is_keyword(keywords::Let) {
2485 // Catch this syntax error here, instead of in `parse_ident`, so
2486 // that we can explicitly mention that let is not to be used as an expression
2487 let mut db = self.fatal("expected expression, found statement (`let`)");
2488 db.span_label(self.span, "expected expression");
2489 db.note("variable declaration using `let` is a statement");
2491 } else if self.token.is_path_start() {
2492 let pth = self.parse_path(PathStyle::Expr)?;
2494 // `!`, as an operator, is prefix, so we know this isn't that
2495 if self.eat(&token::Not) {
2496 // MACRO INVOCATION expression
2497 let (delim, tts) = self.expect_delimited_token_tree()?;
2498 let hi = self.prev_span;
2499 let node = Mac_ { path: pth, tts, delim };
2500 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2502 if self.check(&token::OpenDelim(token::Brace)) {
2503 // This is a struct literal, unless we're prohibited
2504 // from parsing struct literals here.
2505 let prohibited = self.restrictions.contains(
2506 Restrictions::NO_STRUCT_LITERAL
2509 return self.parse_struct_expr(lo, pth, attrs);
2514 ex = ExprKind::Path(None, pth);
2516 match self.parse_literal_maybe_minus() {
2519 ex = expr.node.clone();
2522 self.cancel(&mut err);
2523 let msg = format!("expected expression, found {}",
2524 self.this_token_descr());
2525 let mut err = self.fatal(&msg);
2526 err.span_label(self.span, "expected expression");
2534 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2535 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2540 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2541 -> PResult<'a, P<Expr>> {
2542 let struct_sp = lo.to(self.prev_span);
2544 let mut fields = Vec::new();
2545 let mut base = None;
2547 attrs.extend(self.parse_inner_attributes()?);
2549 while self.token != token::CloseDelim(token::Brace) {
2550 if self.eat(&token::DotDot) {
2551 let exp_span = self.prev_span;
2552 match self.parse_expr() {
2558 self.recover_stmt();
2561 if self.token == token::Comma {
2562 let mut err = self.sess.span_diagnostic.mut_span_err(
2563 exp_span.to(self.prev_span),
2564 "cannot use a comma after the base struct",
2566 err.span_suggestion_short_with_applicability(
2568 "remove this comma",
2570 Applicability::MachineApplicable
2572 err.note("the base struct must always be the last field");
2574 self.recover_stmt();
2579 match self.parse_field() {
2580 Ok(f) => fields.push(f),
2582 e.span_label(struct_sp, "while parsing this struct");
2585 // If the next token is a comma, then try to parse
2586 // what comes next as additional fields, rather than
2587 // bailing out until next `}`.
2588 if self.token != token::Comma {
2589 self.recover_stmt();
2595 match self.expect_one_of(&[token::Comma],
2596 &[token::CloseDelim(token::Brace)]) {
2600 self.recover_stmt();
2606 let span = lo.to(self.span);
2607 self.expect(&token::CloseDelim(token::Brace))?;
2608 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2611 fn parse_or_use_outer_attributes(&mut self,
2612 already_parsed_attrs: Option<ThinVec<Attribute>>)
2613 -> PResult<'a, ThinVec<Attribute>> {
2614 if let Some(attrs) = already_parsed_attrs {
2617 self.parse_outer_attributes().map(|a| a.into())
2621 /// Parse a block or unsafe block
2622 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2623 lo: Span, blk_mode: BlockCheckMode,
2624 outer_attrs: ThinVec<Attribute>)
2625 -> PResult<'a, P<Expr>> {
2626 self.expect(&token::OpenDelim(token::Brace))?;
2628 let mut attrs = outer_attrs;
2629 attrs.extend(self.parse_inner_attributes()?);
2631 let blk = self.parse_block_tail(lo, blk_mode)?;
2632 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2635 /// parse a.b or a(13) or a[4] or just a
2636 fn parse_dot_or_call_expr(&mut self,
2637 already_parsed_attrs: Option<ThinVec<Attribute>>)
2638 -> PResult<'a, P<Expr>> {
2639 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2641 let b = self.parse_bottom_expr();
2642 let (span, b) = self.interpolated_or_expr_span(b)?;
2643 self.parse_dot_or_call_expr_with(b, span, attrs)
2646 fn parse_dot_or_call_expr_with(&mut self,
2649 mut attrs: ThinVec<Attribute>)
2650 -> PResult<'a, P<Expr>> {
2651 // Stitch the list of outer attributes onto the return value.
2652 // A little bit ugly, but the best way given the current code
2654 self.parse_dot_or_call_expr_with_(e0, lo)
2656 expr.map(|mut expr| {
2657 attrs.extend::<Vec<_>>(expr.attrs.into());
2660 ExprKind::If(..) | ExprKind::IfLet(..) => {
2661 if !expr.attrs.is_empty() {
2662 // Just point to the first attribute in there...
2663 let span = expr.attrs[0].span;
2666 "attributes are not yet allowed on `if` \
2677 // Assuming we have just parsed `.`, continue parsing into an expression.
2678 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2679 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2680 Ok(match self.token {
2681 token::OpenDelim(token::Paren) => {
2682 // Method call `expr.f()`
2683 let mut args = self.parse_unspanned_seq(
2684 &token::OpenDelim(token::Paren),
2685 &token::CloseDelim(token::Paren),
2686 SeqSep::trailing_allowed(token::Comma),
2687 |p| Ok(p.parse_expr()?)
2689 args.insert(0, self_arg);
2691 let span = lo.to(self.prev_span);
2692 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2695 // Field access `expr.f`
2696 if let Some(args) = segment.args {
2697 self.span_err(args.span(),
2698 "field expressions may not have generic arguments");
2701 let span = lo.to(self.prev_span);
2702 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2707 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2712 while self.eat(&token::Question) {
2713 let hi = self.prev_span;
2714 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2718 if self.eat(&token::Dot) {
2720 token::Ident(..) => {
2721 e = self.parse_dot_suffix(e, lo)?;
2723 token::Literal(token::Integer(name), _) => {
2724 let span = self.span;
2726 let field = ExprKind::Field(e, Ident::new(name, span));
2727 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2729 token::Literal(token::Float(n), _suf) => {
2731 let fstr = n.as_str();
2732 let mut err = self.diagnostic()
2733 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
2734 err.span_label(self.prev_span, "unexpected token");
2735 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2736 let float = match fstr.parse::<f64>().ok() {
2740 let sugg = pprust::to_string(|s| {
2741 use print::pprust::PrintState;
2745 s.print_usize(float.trunc() as usize)?;
2748 s.s.word(fstr.splitn(2, ".").last().unwrap())
2750 err.span_suggestion_with_applicability(
2751 lo.to(self.prev_span),
2752 "try parenthesizing the first index",
2754 Applicability::MachineApplicable
2761 // FIXME Could factor this out into non_fatal_unexpected or something.
2762 let actual = self.this_token_to_string();
2763 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2768 if self.expr_is_complete(&e) { break; }
2771 token::OpenDelim(token::Paren) => {
2772 let es = self.parse_unspanned_seq(
2773 &token::OpenDelim(token::Paren),
2774 &token::CloseDelim(token::Paren),
2775 SeqSep::trailing_allowed(token::Comma),
2776 |p| Ok(p.parse_expr()?)
2778 hi = self.prev_span;
2780 let nd = self.mk_call(e, es);
2781 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2785 // Could be either an index expression or a slicing expression.
2786 token::OpenDelim(token::Bracket) => {
2788 let ix = self.parse_expr()?;
2790 self.expect(&token::CloseDelim(token::Bracket))?;
2791 let index = self.mk_index(e, ix);
2792 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2800 crate fn process_potential_macro_variable(&mut self) {
2801 let (token, span) = match self.token {
2802 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2803 self.look_ahead(1, |t| t.is_ident()) => {
2805 let name = match self.token {
2806 token::Ident(ident, _) => ident,
2809 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2810 err.span_label(self.span, "unknown macro variable");
2814 token::Interpolated(ref nt) => {
2815 self.meta_var_span = Some(self.span);
2816 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2817 // and lifetime tokens, so the former are never encountered during normal parsing.
2819 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2820 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2830 /// parse a single token tree from the input.
2831 crate fn parse_token_tree(&mut self) -> TokenTree {
2833 token::OpenDelim(..) => {
2834 let frame = mem::replace(&mut self.token_cursor.frame,
2835 self.token_cursor.stack.pop().unwrap());
2836 self.span = frame.span.entire();
2838 TokenTree::Delimited(frame.span, Delimited {
2840 tts: frame.tree_cursor.original_stream().into(),
2843 token::CloseDelim(_) | token::Eof => unreachable!(),
2845 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2847 TokenTree::Token(span, token)
2852 // parse a stream of tokens into a list of TokenTree's,
2854 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2855 let mut tts = Vec::new();
2856 while self.token != token::Eof {
2857 tts.push(self.parse_token_tree());
2862 pub fn parse_tokens(&mut self) -> TokenStream {
2863 let mut result = Vec::new();
2866 token::Eof | token::CloseDelim(..) => break,
2867 _ => result.push(self.parse_token_tree().into()),
2870 TokenStream::concat(result)
2873 /// Parse a prefix-unary-operator expr
2874 fn parse_prefix_expr(&mut self,
2875 already_parsed_attrs: Option<ThinVec<Attribute>>)
2876 -> PResult<'a, P<Expr>> {
2877 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2879 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2880 let (hi, ex) = match self.token {
2883 let e = self.parse_prefix_expr(None);
2884 let (span, e) = self.interpolated_or_expr_span(e)?;
2885 (lo.to(span), self.mk_unary(UnOp::Not, e))
2887 // Suggest `!` for bitwise negation when encountering a `~`
2890 let e = self.parse_prefix_expr(None);
2891 let (span, e) = self.interpolated_or_expr_span(e)?;
2892 let span_of_tilde = lo;
2893 let mut err = self.diagnostic()
2894 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2895 err.span_suggestion_short_with_applicability(
2897 "use `!` to perform bitwise negation",
2899 Applicability::MachineApplicable
2902 (lo.to(span), self.mk_unary(UnOp::Not, e))
2904 token::BinOp(token::Minus) => {
2906 let e = self.parse_prefix_expr(None);
2907 let (span, e) = self.interpolated_or_expr_span(e)?;
2908 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2910 token::BinOp(token::Star) => {
2912 let e = self.parse_prefix_expr(None);
2913 let (span, e) = self.interpolated_or_expr_span(e)?;
2914 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2916 token::BinOp(token::And) | token::AndAnd => {
2918 let m = self.parse_mutability();
2919 let e = self.parse_prefix_expr(None);
2920 let (span, e) = self.interpolated_or_expr_span(e)?;
2921 (lo.to(span), ExprKind::AddrOf(m, e))
2923 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2925 let place = self.parse_expr_res(
2926 Restrictions::NO_STRUCT_LITERAL,
2929 let blk = self.parse_block()?;
2930 let span = blk.span;
2931 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2932 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2934 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2936 let e = self.parse_prefix_expr(None);
2937 let (span, e) = self.interpolated_or_expr_span(e)?;
2938 (lo.to(span), ExprKind::Box(e))
2940 token::Ident(..) if self.token.is_ident_named("not") => {
2941 // `not` is just an ordinary identifier in Rust-the-language,
2942 // but as `rustc`-the-compiler, we can issue clever diagnostics
2943 // for confused users who really want to say `!`
2944 let token_cannot_continue_expr = |t: &token::Token| match *t {
2945 // These tokens can start an expression after `!`, but
2946 // can't continue an expression after an ident
2947 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2948 token::Literal(..) | token::Pound => true,
2949 token::Interpolated(ref nt) => match nt.0 {
2950 token::NtIdent(..) | token::NtExpr(..) |
2951 token::NtBlock(..) | token::NtPath(..) => true,
2956 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2957 if cannot_continue_expr {
2959 // Emit the error ...
2960 let mut err = self.diagnostic()
2961 .struct_span_err(self.span,
2962 &format!("unexpected {} after identifier",
2963 self.this_token_descr()));
2964 // span the `not` plus trailing whitespace to avoid
2965 // trailing whitespace after the `!` in our suggestion
2966 let to_replace = self.sess.source_map()
2967 .span_until_non_whitespace(lo.to(self.span));
2968 err.span_suggestion_short_with_applicability(
2970 "use `!` to perform logical negation",
2972 Applicability::MachineApplicable
2975 // —and recover! (just as if we were in the block
2976 // for the `token::Not` arm)
2977 let e = self.parse_prefix_expr(None);
2978 let (span, e) = self.interpolated_or_expr_span(e)?;
2979 (lo.to(span), self.mk_unary(UnOp::Not, e))
2981 return self.parse_dot_or_call_expr(Some(attrs));
2984 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2986 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2989 /// Parse an associative expression
2991 /// This parses an expression accounting for associativity and precedence of the operators in
2993 fn parse_assoc_expr(&mut self,
2994 already_parsed_attrs: Option<ThinVec<Attribute>>)
2995 -> PResult<'a, P<Expr>> {
2996 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2999 /// Parse an associative expression with operators of at least `min_prec` precedence
3000 fn parse_assoc_expr_with(&mut self,
3003 -> PResult<'a, P<Expr>> {
3004 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3007 let attrs = match lhs {
3008 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3011 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3012 return self.parse_prefix_range_expr(attrs);
3014 self.parse_prefix_expr(attrs)?
3018 if self.expr_is_complete(&lhs) {
3019 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3022 self.expected_tokens.push(TokenType::Operator);
3023 while let Some(op) = AssocOp::from_token(&self.token) {
3025 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3026 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3027 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3028 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3029 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3030 (PrevTokenKind::Interpolated, _) => self.prev_span,
3031 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3032 if path.segments.len() == 1 => self.prev_span,
3036 let cur_op_span = self.span;
3037 let restrictions = if op.is_assign_like() {
3038 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3042 if op.precedence() < min_prec {
3045 // Check for deprecated `...` syntax
3046 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3047 self.err_dotdotdot_syntax(self.span);
3051 if op.is_comparison() {
3052 self.check_no_chained_comparison(&lhs, &op);
3055 if op == AssocOp::As {
3056 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3058 } else if op == AssocOp::Colon {
3059 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3062 err.span_label(self.span,
3063 "expecting a type here because of type ascription");
3064 let cm = self.sess.source_map();
3065 let cur_pos = cm.lookup_char_pos(self.span.lo());
3066 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3067 if cur_pos.line != op_pos.line {
3068 err.span_suggestion_with_applicability(
3070 "try using a semicolon",
3072 Applicability::MaybeIncorrect // speculative
3079 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3080 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3081 // generalise it to the Fixity::None code.
3083 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3084 // two variants are handled with `parse_prefix_range_expr` call above.
3085 let rhs = if self.is_at_start_of_range_notation_rhs() {
3086 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3087 LhsExpr::NotYetParsed)?)
3091 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3096 let limits = if op == AssocOp::DotDot {
3097 RangeLimits::HalfOpen
3102 let r = try!(self.mk_range(Some(lhs), rhs, limits));
3103 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3107 let rhs = match op.fixity() {
3108 Fixity::Right => self.with_res(
3109 restrictions - Restrictions::STMT_EXPR,
3111 this.parse_assoc_expr_with(op.precedence(),
3112 LhsExpr::NotYetParsed)
3114 Fixity::Left => self.with_res(
3115 restrictions - Restrictions::STMT_EXPR,
3117 this.parse_assoc_expr_with(op.precedence() + 1,
3118 LhsExpr::NotYetParsed)
3120 // We currently have no non-associative operators that are not handled above by
3121 // the special cases. The code is here only for future convenience.
3122 Fixity::None => self.with_res(
3123 restrictions - Restrictions::STMT_EXPR,
3125 this.parse_assoc_expr_with(op.precedence() + 1,
3126 LhsExpr::NotYetParsed)
3130 let span = lhs_span.to(rhs.span);
3132 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3133 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3134 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3135 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3136 AssocOp::Greater | AssocOp::GreaterEqual => {
3137 let ast_op = op.to_ast_binop().unwrap();
3138 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3139 self.mk_expr(span, binary, ThinVec::new())
3142 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3143 AssocOp::ObsoleteInPlace =>
3144 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3145 AssocOp::AssignOp(k) => {
3147 token::Plus => BinOpKind::Add,
3148 token::Minus => BinOpKind::Sub,
3149 token::Star => BinOpKind::Mul,
3150 token::Slash => BinOpKind::Div,
3151 token::Percent => BinOpKind::Rem,
3152 token::Caret => BinOpKind::BitXor,
3153 token::And => BinOpKind::BitAnd,
3154 token::Or => BinOpKind::BitOr,
3155 token::Shl => BinOpKind::Shl,
3156 token::Shr => BinOpKind::Shr,
3158 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3159 self.mk_expr(span, aopexpr, ThinVec::new())
3161 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3162 self.bug("AssocOp should have been handled by special case")
3166 if op.fixity() == Fixity::None { break }
3171 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3172 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3173 -> PResult<'a, P<Expr>> {
3174 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3175 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3178 // Save the state of the parser before parsing type normally, in case there is a
3179 // LessThan comparison after this cast.
3180 let parser_snapshot_before_type = self.clone();
3181 match self.parse_ty_no_plus() {
3183 Ok(mk_expr(self, rhs))
3185 Err(mut type_err) => {
3186 // Rewind to before attempting to parse the type with generics, to recover
3187 // from situations like `x as usize < y` in which we first tried to parse
3188 // `usize < y` as a type with generic arguments.
3189 let parser_snapshot_after_type = self.clone();
3190 mem::replace(self, parser_snapshot_before_type);
3192 match self.parse_path(PathStyle::Expr) {
3194 let (op_noun, op_verb) = match self.token {
3195 token::Lt => ("comparison", "comparing"),
3196 token::BinOp(token::Shl) => ("shift", "shifting"),
3198 // We can end up here even without `<` being the next token, for
3199 // example because `parse_ty_no_plus` returns `Err` on keywords,
3200 // but `parse_path` returns `Ok` on them due to error recovery.
3201 // Return original error and parser state.
3202 mem::replace(self, parser_snapshot_after_type);
3203 return Err(type_err);
3207 // Successfully parsed the type path leaving a `<` yet to parse.
3210 // Report non-fatal diagnostics, keep `x as usize` as an expression
3211 // in AST and continue parsing.
3212 let msg = format!("`<` is interpreted as a start of generic \
3213 arguments for `{}`, not a {}", path, op_noun);
3214 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3215 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3216 "interpreted as generic arguments");
3217 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3219 let expr = mk_expr(self, P(Ty {
3221 node: TyKind::Path(None, path),
3222 id: ast::DUMMY_NODE_ID
3225 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3226 .unwrap_or(pprust::expr_to_string(&expr));
3227 err.span_suggestion_with_applicability(
3229 &format!("try {} the cast value", op_verb),
3230 format!("({})", expr_str),
3231 Applicability::MachineApplicable
3237 Err(mut path_err) => {
3238 // Couldn't parse as a path, return original error and parser state.
3240 mem::replace(self, parser_snapshot_after_type);
3248 /// Produce an error if comparison operators are chained (RFC #558).
3249 /// We only need to check lhs, not rhs, because all comparison ops
3250 /// have same precedence and are left-associative
3251 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3252 debug_assert!(outer_op.is_comparison(),
3253 "check_no_chained_comparison: {:?} is not comparison",
3256 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3257 // respan to include both operators
3258 let op_span = op.span.to(self.span);
3259 let mut err = self.diagnostic().struct_span_err(op_span,
3260 "chained comparison operators require parentheses");
3261 if op.node == BinOpKind::Lt &&
3262 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3263 *outer_op == AssocOp::Greater // even in a case like the following:
3264 { // Foo<Bar<Baz<Qux, ()>>>
3266 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3267 err.help("or use `(...)` if you meant to specify fn arguments");
3275 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3276 fn parse_prefix_range_expr(&mut self,
3277 already_parsed_attrs: Option<ThinVec<Attribute>>)
3278 -> PResult<'a, P<Expr>> {
3279 // Check for deprecated `...` syntax
3280 if self.token == token::DotDotDot {
3281 self.err_dotdotdot_syntax(self.span);
3284 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3285 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3287 let tok = self.token.clone();
3288 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3290 let mut hi = self.span;
3292 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3293 // RHS must be parsed with more associativity than the dots.
3294 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3295 Some(self.parse_assoc_expr_with(next_prec,
3296 LhsExpr::NotYetParsed)
3304 let limits = if tok == token::DotDot {
3305 RangeLimits::HalfOpen
3310 let r = try!(self.mk_range(None,
3313 Ok(self.mk_expr(lo.to(hi), r, attrs))
3316 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3317 if self.token.can_begin_expr() {
3318 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3319 if self.token == token::OpenDelim(token::Brace) {
3320 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3328 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3329 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3330 if self.check_keyword(keywords::Let) {
3331 return self.parse_if_let_expr(attrs);
3333 let lo = self.prev_span;
3334 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3336 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3337 // verify that the last statement is either an implicit return (no `;`) or an explicit
3338 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3339 // the dead code lint.
3340 if self.eat_keyword(keywords::Else) || !cond.returns() {
3341 let sp = self.sess.source_map().next_point(lo);
3342 let mut err = self.diagnostic()
3343 .struct_span_err(sp, "missing condition for `if` statemement");
3344 err.span_label(sp, "expected if condition here");
3347 let not_block = self.token != token::OpenDelim(token::Brace);
3348 let thn = self.parse_block().map_err(|mut err| {
3350 err.span_label(lo, "this `if` statement has a condition, but no block");
3354 let mut els: Option<P<Expr>> = None;
3355 let mut hi = thn.span;
3356 if self.eat_keyword(keywords::Else) {
3357 let elexpr = self.parse_else_expr()?;
3361 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3364 /// Parse an 'if let' expression ('if' token already eaten)
3365 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3366 -> PResult<'a, P<Expr>> {
3367 let lo = self.prev_span;
3368 self.expect_keyword(keywords::Let)?;
3369 let pats = self.parse_pats()?;
3370 self.expect(&token::Eq)?;
3371 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3372 let thn = self.parse_block()?;
3373 let (hi, els) = if self.eat_keyword(keywords::Else) {
3374 let expr = self.parse_else_expr()?;
3375 (expr.span, Some(expr))
3379 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3382 // `move |args| expr`
3383 fn parse_lambda_expr(&mut self,
3384 attrs: ThinVec<Attribute>)
3385 -> PResult<'a, P<Expr>>
3388 let movability = if self.eat_keyword(keywords::Static) {
3393 let asyncness = if self.span.edition() >= Edition::Edition2018 {
3394 self.parse_asyncness()
3398 let capture_clause = if self.eat_keyword(keywords::Move) {
3403 let decl = self.parse_fn_block_decl()?;
3404 let decl_hi = self.prev_span;
3405 let body = match decl.output {
3406 FunctionRetTy::Default(_) => {
3407 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3408 self.parse_expr_res(restrictions, None)?
3411 // If an explicit return type is given, require a
3412 // block to appear (RFC 968).
3413 let body_lo = self.span;
3414 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3420 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3424 // `else` token already eaten
3425 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3426 if self.eat_keyword(keywords::If) {
3427 return self.parse_if_expr(ThinVec::new());
3429 let blk = self.parse_block()?;
3430 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3434 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3435 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3437 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3438 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3440 let pat = self.parse_top_level_pat()?;
3441 if !self.eat_keyword(keywords::In) {
3442 let in_span = self.prev_span.between(self.span);
3443 let mut err = self.sess.span_diagnostic
3444 .struct_span_err(in_span, "missing `in` in `for` loop");
3445 err.span_suggestion_short_with_applicability(
3446 in_span, "try adding `in` here", " in ".into(),
3447 // has been misleading, at least in the past (closed Issue #48492)
3448 Applicability::MaybeIncorrect
3452 let in_span = self.prev_span;
3453 if self.eat_keyword(keywords::In) {
3454 // a common typo: `for _ in in bar {}`
3455 let mut err = self.sess.span_diagnostic.struct_span_err(
3457 "expected iterable, found keyword `in`",
3459 err.span_suggestion_short_with_applicability(
3460 in_span.until(self.prev_span),
3461 "remove the duplicated `in`",
3463 Applicability::MachineApplicable,
3465 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3466 err.note("for more information on the status of emplacement syntax, see <\
3467 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3470 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3471 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3472 attrs.extend(iattrs);
3474 let hi = self.prev_span;
3475 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3478 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3479 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3481 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3482 if self.token.is_keyword(keywords::Let) {
3483 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3485 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3486 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3487 attrs.extend(iattrs);
3488 let span = span_lo.to(body.span);
3489 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3492 /// Parse a 'while let' expression ('while' token already eaten)
3493 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3495 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3496 self.expect_keyword(keywords::Let)?;
3497 let pats = self.parse_pats()?;
3498 self.expect(&token::Eq)?;
3499 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3500 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3501 attrs.extend(iattrs);
3502 let span = span_lo.to(body.span);
3503 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3506 // parse `loop {...}`, `loop` token already eaten
3507 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3509 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3510 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3511 attrs.extend(iattrs);
3512 let span = span_lo.to(body.span);
3513 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3516 /// Parse an `async move {...}` expression
3517 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3518 -> PResult<'a, P<Expr>>
3520 let span_lo = self.span;
3521 self.expect_keyword(keywords::Async)?;
3522 let capture_clause = if self.eat_keyword(keywords::Move) {
3527 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3528 attrs.extend(iattrs);
3530 span_lo.to(body.span),
3531 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3534 /// Parse a `try {...}` expression (`try` token already eaten)
3535 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3536 -> PResult<'a, P<Expr>>
3538 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3539 attrs.extend(iattrs);
3540 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3543 // `match` token already eaten
3544 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3545 let match_span = self.prev_span;
3546 let lo = self.prev_span;
3547 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3549 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3550 if self.token == token::Token::Semi {
3551 e.span_suggestion_short_with_applicability(
3553 "try removing this `match`",
3555 Applicability::MaybeIncorrect // speculative
3560 attrs.extend(self.parse_inner_attributes()?);
3562 let mut arms: Vec<Arm> = Vec::new();
3563 while self.token != token::CloseDelim(token::Brace) {
3564 match self.parse_arm() {
3565 Ok(arm) => arms.push(arm),
3567 // Recover by skipping to the end of the block.
3569 self.recover_stmt();
3570 let span = lo.to(self.span);
3571 if self.token == token::CloseDelim(token::Brace) {
3574 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3580 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3583 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3584 maybe_whole!(self, NtArm, |x| x);
3586 let attrs = self.parse_outer_attributes()?;
3587 // Allow a '|' before the pats (RFC 1925)
3588 self.eat(&token::BinOp(token::Or));
3589 let pats = self.parse_pats()?;
3590 let guard = if self.eat_keyword(keywords::If) {
3591 Some(Guard::If(self.parse_expr()?))
3595 let arrow_span = self.span;
3596 self.expect(&token::FatArrow)?;
3597 let arm_start_span = self.span;
3599 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3600 .map_err(|mut err| {
3601 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3605 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3606 && self.token != token::CloseDelim(token::Brace);
3609 let cm = self.sess.source_map();
3610 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3611 .map_err(|mut err| {
3612 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3613 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3614 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3615 && expr_lines.lines.len() == 2
3616 && self.token == token::FatArrow => {
3617 // We check whether there's any trailing code in the parse span,
3618 // if there isn't, we very likely have the following:
3621 // | -- - missing comma
3627 // | parsed until here as `"y" & X`
3628 err.span_suggestion_short_with_applicability(
3629 cm.next_point(arm_start_span),
3630 "missing a comma here to end this `match` arm",
3632 Applicability::MachineApplicable
3636 err.span_label(arrow_span,
3637 "while parsing the `match` arm starting here");
3643 self.eat(&token::Comma);
3654 /// Parse an expression
3655 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3656 self.parse_expr_res(Restrictions::empty(), None)
3659 /// Evaluate the closure with restrictions in place.
3661 /// After the closure is evaluated, restrictions are reset.
3662 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3663 where F: FnOnce(&mut Self) -> T
3665 let old = self.restrictions;
3666 self.restrictions = r;
3668 self.restrictions = old;
3673 /// Parse an expression, subject to the given restrictions
3674 fn parse_expr_res(&mut self, r: Restrictions,
3675 already_parsed_attrs: Option<ThinVec<Attribute>>)
3676 -> PResult<'a, P<Expr>> {
3677 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3680 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3681 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3682 if self.eat(&token::Eq) {
3683 Ok(Some(self.parse_expr()?))
3685 Ok(Some(self.parse_expr()?))
3691 /// Parse patterns, separated by '|' s
3692 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3693 let mut pats = Vec::new();
3695 pats.push(self.parse_top_level_pat()?);
3697 if self.token == token::OrOr {
3698 let mut err = self.struct_span_err(self.span,
3699 "unexpected token `||` after pattern");
3700 err.span_suggestion_with_applicability(
3702 "use a single `|` to specify multiple patterns",
3704 Applicability::MachineApplicable
3708 } else if self.eat(&token::BinOp(token::Or)) {
3716 // Parses a parenthesized list of patterns like
3717 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3718 // - a vector of the patterns that were parsed
3719 // - an option indicating the index of the `..` element
3720 // - a boolean indicating whether a trailing comma was present.
3721 // Trailing commas are significant because (p) and (p,) are different patterns.
3722 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3723 self.expect(&token::OpenDelim(token::Paren))?;
3724 let result = self.parse_pat_list()?;
3725 self.expect(&token::CloseDelim(token::Paren))?;
3729 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3730 let mut fields = Vec::new();
3731 let mut ddpos = None;
3732 let mut trailing_comma = false;
3734 if self.eat(&token::DotDot) {
3735 if ddpos.is_none() {
3736 ddpos = Some(fields.len());
3738 // Emit a friendly error, ignore `..` and continue parsing
3739 self.span_err(self.prev_span,
3740 "`..` can only be used once per tuple or tuple struct pattern");
3742 } else if !self.check(&token::CloseDelim(token::Paren)) {
3743 fields.push(self.parse_pat()?);
3748 trailing_comma = self.eat(&token::Comma);
3749 if !trailing_comma {
3754 if ddpos == Some(fields.len()) && trailing_comma {
3755 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3756 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3759 Ok((fields, ddpos, trailing_comma))
3762 fn parse_pat_vec_elements(
3764 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3765 let mut before = Vec::new();
3766 let mut slice = None;
3767 let mut after = Vec::new();
3768 let mut first = true;
3769 let mut before_slice = true;
3771 while self.token != token::CloseDelim(token::Bracket) {
3775 self.expect(&token::Comma)?;
3777 if self.token == token::CloseDelim(token::Bracket)
3778 && (before_slice || !after.is_empty()) {
3784 if self.eat(&token::DotDot) {
3786 if self.check(&token::Comma) ||
3787 self.check(&token::CloseDelim(token::Bracket)) {
3788 slice = Some(P(Pat {
3789 id: ast::DUMMY_NODE_ID,
3790 node: PatKind::Wild,
3791 span: self.prev_span,
3793 before_slice = false;
3799 let subpat = self.parse_pat()?;
3800 if before_slice && self.eat(&token::DotDot) {
3801 slice = Some(subpat);
3802 before_slice = false;
3803 } else if before_slice {
3804 before.push(subpat);
3810 Ok((before, slice, after))
3816 attrs: Vec<Attribute>
3817 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3818 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3820 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3821 // Parsing a pattern of the form "fieldname: pat"
3822 let fieldname = self.parse_field_name()?;
3824 let pat = self.parse_pat()?;
3826 (pat, fieldname, false)
3828 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3829 let is_box = self.eat_keyword(keywords::Box);
3830 let boxed_span = self.span;
3831 let is_ref = self.eat_keyword(keywords::Ref);
3832 let is_mut = self.eat_keyword(keywords::Mut);
3833 let fieldname = self.parse_ident()?;
3834 hi = self.prev_span;
3836 let bind_type = match (is_ref, is_mut) {
3837 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3838 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3839 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3840 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3842 let fieldpat = P(Pat {
3843 id: ast::DUMMY_NODE_ID,
3844 node: PatKind::Ident(bind_type, fieldname, None),
3845 span: boxed_span.to(hi),
3848 let subpat = if is_box {
3850 id: ast::DUMMY_NODE_ID,
3851 node: PatKind::Box(fieldpat),
3857 (subpat, fieldname, true)
3860 Ok(source_map::Spanned {
3862 node: ast::FieldPat {
3866 attrs: attrs.into(),
3871 /// Parse the fields of a struct-like pattern
3872 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3873 let mut fields = Vec::new();
3874 let mut etc = false;
3875 let mut ate_comma = true;
3876 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3877 let mut etc_span = None;
3879 while self.token != token::CloseDelim(token::Brace) {
3880 let attrs = self.parse_outer_attributes()?;
3883 // check that a comma comes after every field
3885 let err = self.struct_span_err(self.prev_span, "expected `,`");
3886 if let Some(mut delayed) = delayed_err {
3893 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3895 let mut etc_sp = self.span;
3897 if self.token == token::DotDotDot { // Issue #46718
3898 // Accept `...` as if it were `..` to avoid further errors
3899 let mut err = self.struct_span_err(self.span,
3900 "expected field pattern, found `...`");
3901 err.span_suggestion_with_applicability(
3903 "to omit remaining fields, use one fewer `.`",
3905 Applicability::MachineApplicable
3909 self.bump(); // `..` || `...`:w
3911 if self.token == token::CloseDelim(token::Brace) {
3912 etc_span = Some(etc_sp);
3915 let token_str = self.this_token_to_string();
3916 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3918 err.span_label(self.span, "expected `}`");
3919 let mut comma_sp = None;
3920 if self.token == token::Comma { // Issue #49257
3921 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3922 err.span_label(etc_sp,
3923 "`..` must be at the end and cannot have a trailing comma");
3924 comma_sp = Some(self.span);
3929 etc_span = Some(etc_sp);
3930 if self.token == token::CloseDelim(token::Brace) {
3931 // If the struct looks otherwise well formed, recover and continue.
3932 if let Some(sp) = comma_sp {
3933 err.span_suggestion_short_with_applicability(
3935 "remove this comma",
3937 Applicability::MachineApplicable,
3942 } else if self.token.is_ident() && ate_comma {
3943 // Accept fields coming after `..,`.
3944 // This way we avoid "pattern missing fields" errors afterwards.
3945 // We delay this error until the end in order to have a span for a
3947 if let Some(mut delayed_err) = delayed_err {
3951 delayed_err = Some(err);
3954 if let Some(mut err) = delayed_err {
3961 fields.push(match self.parse_pat_field(lo, attrs) {
3964 if let Some(mut delayed_err) = delayed_err {
3970 ate_comma = self.eat(&token::Comma);
3973 if let Some(mut err) = delayed_err {
3974 if let Some(etc_span) = etc_span {
3975 err.multipart_suggestion(
3976 "move the `..` to the end of the field list",
3978 (etc_span, String::new()),
3979 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3985 return Ok((fields, etc));
3988 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3989 if self.token.is_path_start() {
3991 let (qself, path) = if self.eat_lt() {
3992 // Parse a qualified path
3993 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3996 // Parse an unqualified path
3997 (None, self.parse_path(PathStyle::Expr)?)
3999 let hi = self.prev_span;
4000 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4002 self.parse_literal_maybe_minus()
4006 // helper function to decide whether to parse as ident binding or to try to do
4007 // something more complex like range patterns
4008 fn parse_as_ident(&mut self) -> bool {
4009 self.look_ahead(1, |t| match *t {
4010 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4011 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4012 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4013 // range pattern branch
4014 token::DotDot => None,
4016 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4017 token::Comma | token::CloseDelim(token::Bracket) => true,
4022 /// A wrapper around `parse_pat` with some special error handling for the
4023 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4024 /// to subpatterns within such).
4025 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4026 let pat = self.parse_pat()?;
4027 if self.token == token::Comma {
4028 // An unexpected comma after a top-level pattern is a clue that the
4029 // user (perhaps more accustomed to some other language) forgot the
4030 // parentheses in what should have been a tuple pattern; return a
4031 // suggestion-enhanced error here rather than choking on the comma
4033 let comma_span = self.span;
4035 if let Err(mut err) = self.parse_pat_list() {
4036 // We didn't expect this to work anyway; we just wanted
4037 // to advance to the end of the comma-sequence so we know
4038 // the span to suggest parenthesizing
4041 let seq_span = pat.span.to(self.prev_span);
4042 let mut err = self.struct_span_err(comma_span,
4043 "unexpected `,` in pattern");
4044 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4045 err.span_suggestion_with_applicability(
4047 "try adding parentheses",
4048 format!("({})", seq_snippet),
4049 Applicability::MachineApplicable
4057 /// Parse a pattern.
4058 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
4059 self.parse_pat_with_range_pat(true)
4062 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
4064 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
4065 maybe_whole!(self, NtPat, |x| x);
4070 token::BinOp(token::And) | token::AndAnd => {
4071 // Parse &pat / &mut pat
4073 let mutbl = self.parse_mutability();
4074 if let token::Lifetime(ident) = self.token {
4075 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4077 err.span_label(self.span, "unexpected lifetime");
4080 let subpat = self.parse_pat_with_range_pat(false)?;
4081 pat = PatKind::Ref(subpat, mutbl);
4083 token::OpenDelim(token::Paren) => {
4084 // Parse (pat,pat,pat,...) as tuple pattern
4085 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4086 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4087 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4089 PatKind::Tuple(fields, ddpos)
4092 token::OpenDelim(token::Bracket) => {
4093 // Parse [pat,pat,...] as slice pattern
4095 let (before, slice, after) = self.parse_pat_vec_elements()?;
4096 self.expect(&token::CloseDelim(token::Bracket))?;
4097 pat = PatKind::Slice(before, slice, after);
4099 // At this point, token != &, &&, (, [
4100 _ => if self.eat_keyword(keywords::Underscore) {
4102 pat = PatKind::Wild;
4103 } else if self.eat_keyword(keywords::Mut) {
4104 // Parse mut ident @ pat / mut ref ident @ pat
4105 let mutref_span = self.prev_span.to(self.span);
4106 let binding_mode = if self.eat_keyword(keywords::Ref) {
4108 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4109 .span_suggestion_with_applicability(
4111 "try switching the order",
4113 Applicability::MachineApplicable
4115 BindingMode::ByRef(Mutability::Mutable)
4117 BindingMode::ByValue(Mutability::Mutable)
4119 pat = self.parse_pat_ident(binding_mode)?;
4120 } else if self.eat_keyword(keywords::Ref) {
4121 // Parse ref ident @ pat / ref mut ident @ pat
4122 let mutbl = self.parse_mutability();
4123 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4124 } else if self.eat_keyword(keywords::Box) {
4126 let subpat = self.parse_pat_with_range_pat(false)?;
4127 pat = PatKind::Box(subpat);
4128 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4129 self.parse_as_ident() {
4130 // Parse ident @ pat
4131 // This can give false positives and parse nullary enums,
4132 // they are dealt with later in resolve
4133 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4134 pat = self.parse_pat_ident(binding_mode)?;
4135 } else if self.token.is_path_start() {
4136 // Parse pattern starting with a path
4137 let (qself, path) = if self.eat_lt() {
4138 // Parse a qualified path
4139 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4142 // Parse an unqualified path
4143 (None, self.parse_path(PathStyle::Expr)?)
4146 token::Not if qself.is_none() => {
4147 // Parse macro invocation
4149 let (delim, tts) = self.expect_delimited_token_tree()?;
4150 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4151 pat = PatKind::Mac(mac);
4153 token::DotDotDot | token::DotDotEq | token::DotDot => {
4154 let end_kind = match self.token {
4155 token::DotDot => RangeEnd::Excluded,
4156 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4157 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4158 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4161 let op_span = self.span;
4163 let span = lo.to(self.prev_span);
4164 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4166 let end = self.parse_pat_range_end()?;
4167 let op = Spanned { span: op_span, node: end_kind };
4168 pat = PatKind::Range(begin, end, op);
4170 token::OpenDelim(token::Brace) => {
4171 if qself.is_some() {
4172 let msg = "unexpected `{` after qualified path";
4173 let mut err = self.fatal(msg);
4174 err.span_label(self.span, msg);
4177 // Parse struct pattern
4179 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4181 self.recover_stmt();
4185 pat = PatKind::Struct(path, fields, etc);
4187 token::OpenDelim(token::Paren) => {
4188 if qself.is_some() {
4189 let msg = "unexpected `(` after qualified path";
4190 let mut err = self.fatal(msg);
4191 err.span_label(self.span, msg);
4194 // Parse tuple struct or enum pattern
4195 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4196 pat = PatKind::TupleStruct(path, fields, ddpos)
4198 _ => pat = PatKind::Path(qself, path),
4201 // Try to parse everything else as literal with optional minus
4202 match self.parse_literal_maybe_minus() {
4204 let op_span = self.span;
4205 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4206 self.check(&token::DotDotDot) {
4207 let end_kind = if self.eat(&token::DotDotDot) {
4208 RangeEnd::Included(RangeSyntax::DotDotDot)
4209 } else if self.eat(&token::DotDotEq) {
4210 RangeEnd::Included(RangeSyntax::DotDotEq)
4211 } else if self.eat(&token::DotDot) {
4214 panic!("impossible case: we already matched \
4215 on a range-operator token")
4217 let end = self.parse_pat_range_end()?;
4218 let op = Spanned { span: op_span, node: end_kind };
4219 pat = PatKind::Range(begin, end, op);
4221 pat = PatKind::Lit(begin);
4225 self.cancel(&mut err);
4226 let msg = format!("expected pattern, found {}", self.this_token_descr());
4227 let mut err = self.fatal(&msg);
4228 err.span_label(self.span, "expected pattern");
4235 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4236 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4238 if !allow_range_pat {
4241 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4243 PatKind::Range(..) => {
4244 let mut err = self.struct_span_err(
4246 "the range pattern here has ambiguous interpretation",
4248 err.span_suggestion_with_applicability(
4250 "add parentheses to clarify the precedence",
4251 format!("({})", pprust::pat_to_string(&pat)),
4252 // "ambiguous interpretation" implies that we have to be guessing
4253 Applicability::MaybeIncorrect
4264 /// Parse ident or ident @ pat
4265 /// used by the copy foo and ref foo patterns to give a good
4266 /// error message when parsing mistakes like ref foo(a,b)
4267 fn parse_pat_ident(&mut self,
4268 binding_mode: ast::BindingMode)
4269 -> PResult<'a, PatKind> {
4270 let ident = self.parse_ident()?;
4271 let sub = if self.eat(&token::At) {
4272 Some(self.parse_pat()?)
4277 // just to be friendly, if they write something like
4279 // we end up here with ( as the current token. This shortly
4280 // leads to a parse error. Note that if there is no explicit
4281 // binding mode then we do not end up here, because the lookahead
4282 // will direct us over to parse_enum_variant()
4283 if self.token == token::OpenDelim(token::Paren) {
4284 return Err(self.span_fatal(
4286 "expected identifier, found enum pattern"))
4289 Ok(PatKind::Ident(binding_mode, ident, sub))
4292 /// Parse a local variable declaration
4293 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4294 let lo = self.prev_span;
4295 let pat = self.parse_top_level_pat()?;
4297 let (err, ty) = if self.eat(&token::Colon) {
4298 // Save the state of the parser before parsing type normally, in case there is a `:`
4299 // instead of an `=` typo.
4300 let parser_snapshot_before_type = self.clone();
4301 let colon_sp = self.prev_span;
4302 match self.parse_ty() {
4303 Ok(ty) => (None, Some(ty)),
4305 // Rewind to before attempting to parse the type and continue parsing
4306 let parser_snapshot_after_type = self.clone();
4307 mem::replace(self, parser_snapshot_before_type);
4309 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4310 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4311 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4317 let init = match (self.parse_initializer(err.is_some()), err) {
4318 (Ok(init), None) => { // init parsed, ty parsed
4321 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4322 // Could parse the type as if it were the initializer, it is likely there was a
4323 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4324 err.span_suggestion_short_with_applicability(
4326 "use `=` if you meant to assign",
4328 Applicability::MachineApplicable
4331 // As this was parsed successfully, continue as if the code has been fixed for the
4332 // rest of the file. It will still fail due to the emitted error, but we avoid
4336 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4338 // Couldn't parse the type nor the initializer, only raise the type error and
4339 // return to the parser state before parsing the type as the initializer.
4340 // let x: <parse_error>;
4341 mem::replace(self, snapshot);
4344 (Err(err), None) => { // init error, ty parsed
4345 // Couldn't parse the initializer and we're not attempting to recover a failed
4346 // parse of the type, return the error.
4350 let hi = if self.token == token::Semi {
4359 id: ast::DUMMY_NODE_ID,
4365 /// Parse a structure field
4366 fn parse_name_and_ty(&mut self,
4369 attrs: Vec<Attribute>)
4370 -> PResult<'a, StructField> {
4371 let name = self.parse_ident()?;
4372 self.expect(&token::Colon)?;
4373 let ty = self.parse_ty()?;
4375 span: lo.to(self.prev_span),
4378 id: ast::DUMMY_NODE_ID,
4384 /// Emit an expected item after attributes error.
4385 fn expected_item_err(&self, attrs: &[Attribute]) {
4386 let message = match attrs.last() {
4387 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4388 _ => "expected item after attributes",
4391 self.span_err(self.prev_span, message);
4394 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4395 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4396 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4397 Ok(self.parse_stmt_(true))
4400 // Eat tokens until we can be relatively sure we reached the end of the
4401 // statement. This is something of a best-effort heuristic.
4403 // We terminate when we find an unmatched `}` (without consuming it).
4404 fn recover_stmt(&mut self) {
4405 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4408 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4409 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4410 // approximate - it can mean we break too early due to macros, but that
4411 // should only lead to sub-optimal recovery, not inaccurate parsing).
4413 // If `break_on_block` is `Break`, then we will stop consuming tokens
4414 // after finding (and consuming) a brace-delimited block.
4415 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4416 let mut brace_depth = 0;
4417 let mut bracket_depth = 0;
4418 let mut in_block = false;
4419 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4420 break_on_semi, break_on_block);
4422 debug!("recover_stmt_ loop {:?}", self.token);
4424 token::OpenDelim(token::DelimToken::Brace) => {
4427 if break_on_block == BlockMode::Break &&
4429 bracket_depth == 0 {
4433 token::OpenDelim(token::DelimToken::Bracket) => {
4437 token::CloseDelim(token::DelimToken::Brace) => {
4438 if brace_depth == 0 {
4439 debug!("recover_stmt_ return - close delim {:?}", self.token);
4444 if in_block && bracket_depth == 0 && brace_depth == 0 {
4445 debug!("recover_stmt_ return - block end {:?}", self.token);
4449 token::CloseDelim(token::DelimToken::Bracket) => {
4451 if bracket_depth < 0 {
4457 debug!("recover_stmt_ return - Eof");
4462 if break_on_semi == SemiColonMode::Break &&
4464 bracket_depth == 0 {
4465 debug!("recover_stmt_ return - Semi");
4476 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4477 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4479 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4484 fn is_async_block(&mut self) -> bool {
4485 self.token.is_keyword(keywords::Async) &&
4488 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4489 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4491 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4496 fn is_do_catch_block(&mut self) -> bool {
4497 self.token.is_keyword(keywords::Do) &&
4498 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4499 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4500 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4503 fn is_try_block(&mut self) -> bool {
4504 self.token.is_keyword(keywords::Try) &&
4505 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4507 self.span.edition() >= Edition::Edition2018 &&
4509 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4510 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4513 fn is_union_item(&self) -> bool {
4514 self.token.is_keyword(keywords::Union) &&
4515 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4518 fn is_crate_vis(&self) -> bool {
4519 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4522 fn is_extern_non_path(&self) -> bool {
4523 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4526 fn is_existential_type_decl(&self) -> bool {
4527 self.token.is_keyword(keywords::Existential) &&
4528 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4531 fn is_auto_trait_item(&mut self) -> bool {
4533 (self.token.is_keyword(keywords::Auto)
4534 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4535 || // unsafe auto trait
4536 (self.token.is_keyword(keywords::Unsafe) &&
4537 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4538 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4541 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4542 -> PResult<'a, Option<P<Item>>> {
4543 let token_lo = self.span;
4544 let (ident, def) = match self.token {
4545 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4547 let ident = self.parse_ident()?;
4548 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4549 match self.parse_token_tree() {
4550 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4551 _ => unreachable!(),
4553 } else if self.check(&token::OpenDelim(token::Paren)) {
4554 let args = self.parse_token_tree();
4555 let body = if self.check(&token::OpenDelim(token::Brace)) {
4556 self.parse_token_tree()
4561 TokenStream::concat(vec![
4563 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4571 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4573 token::Ident(ident, _) if ident.name == "macro_rules" &&
4574 self.look_ahead(1, |t| *t == token::Not) => {
4575 let prev_span = self.prev_span;
4576 self.complain_if_pub_macro(&vis.node, prev_span);
4580 let ident = self.parse_ident()?;
4581 let (delim, tokens) = self.expect_delimited_token_tree()?;
4582 if delim != MacDelimiter::Brace {
4583 if !self.eat(&token::Semi) {
4584 let msg = "macros that expand to items must either \
4585 be surrounded with braces or followed by a semicolon";
4586 self.span_err(self.prev_span, msg);
4590 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4592 _ => return Ok(None),
4595 let span = lo.to(self.prev_span);
4596 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4599 fn parse_stmt_without_recovery(&mut self,
4600 macro_legacy_warnings: bool)
4601 -> PResult<'a, Option<Stmt>> {
4602 maybe_whole!(self, NtStmt, |x| Some(x));
4604 let attrs = self.parse_outer_attributes()?;
4607 Ok(Some(if self.eat_keyword(keywords::Let) {
4609 id: ast::DUMMY_NODE_ID,
4610 node: StmtKind::Local(self.parse_local(attrs.into())?),
4611 span: lo.to(self.prev_span),
4613 } else if let Some(macro_def) = self.eat_macro_def(
4615 &source_map::respan(lo, VisibilityKind::Inherited),
4619 id: ast::DUMMY_NODE_ID,
4620 node: StmtKind::Item(macro_def),
4621 span: lo.to(self.prev_span),
4623 // Starts like a simple path, being careful to avoid contextual keywords
4624 // such as a union items, item with `crate` visibility or auto trait items.
4625 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4626 // like a path (1 token), but it fact not a path.
4627 // `union::b::c` - path, `union U { ... }` - not a path.
4628 // `crate::b::c` - path, `crate struct S;` - not a path.
4629 // `extern::b::c` - path, `extern crate c;` - not a path.
4630 } else if self.token.is_path_start() &&
4631 !self.token.is_qpath_start() &&
4632 !self.is_union_item() &&
4633 !self.is_crate_vis() &&
4634 !self.is_extern_non_path() &&
4635 !self.is_existential_type_decl() &&
4636 !self.is_auto_trait_item() {
4637 let pth = self.parse_path(PathStyle::Expr)?;
4639 if !self.eat(&token::Not) {
4640 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4641 self.parse_struct_expr(lo, pth, ThinVec::new())?
4643 let hi = self.prev_span;
4644 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4647 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4648 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4649 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4652 return Ok(Some(Stmt {
4653 id: ast::DUMMY_NODE_ID,
4654 node: StmtKind::Expr(expr),
4655 span: lo.to(self.prev_span),
4659 // it's a macro invocation
4660 let id = match self.token {
4661 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4662 _ => self.parse_ident()?,
4665 // check that we're pointing at delimiters (need to check
4666 // again after the `if`, because of `parse_ident`
4667 // consuming more tokens).
4669 token::OpenDelim(_) => {}
4671 // we only expect an ident if we didn't parse one
4673 let ident_str = if id.name == keywords::Invalid.name() {
4678 let tok_str = self.this_token_to_string();
4679 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4682 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4687 let (delim, tts) = self.expect_delimited_token_tree()?;
4688 let hi = self.prev_span;
4690 let style = if delim == MacDelimiter::Brace {
4691 MacStmtStyle::Braces
4693 MacStmtStyle::NoBraces
4696 if id.name == keywords::Invalid.name() {
4697 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4698 let node = if delim == MacDelimiter::Brace ||
4699 self.token == token::Semi || self.token == token::Eof {
4700 StmtKind::Mac(P((mac, style, attrs.into())))
4702 // We used to incorrectly stop parsing macro-expanded statements here.
4703 // If the next token will be an error anyway but could have parsed with the
4704 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4705 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4706 // These can continue an expression, so we can't stop parsing and warn.
4707 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4708 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4709 token::BinOp(token::And) | token::BinOp(token::Or) |
4710 token::AndAnd | token::OrOr |
4711 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4714 self.warn_missing_semicolon();
4715 StmtKind::Mac(P((mac, style, attrs.into())))
4717 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4718 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4719 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4723 id: ast::DUMMY_NODE_ID,
4728 // if it has a special ident, it's definitely an item
4730 // Require a semicolon or braces.
4731 if style != MacStmtStyle::Braces {
4732 if !self.eat(&token::Semi) {
4733 self.span_err(self.prev_span,
4734 "macros that expand to items must \
4735 either be surrounded with braces or \
4736 followed by a semicolon");
4739 let span = lo.to(hi);
4741 id: ast::DUMMY_NODE_ID,
4743 node: StmtKind::Item({
4745 span, id /*id is good here*/,
4746 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4747 respan(lo, VisibilityKind::Inherited),
4753 // FIXME: Bad copy of attrs
4754 let old_directory_ownership =
4755 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4756 let item = self.parse_item_(attrs.clone(), false, true)?;
4757 self.directory.ownership = old_directory_ownership;
4761 id: ast::DUMMY_NODE_ID,
4762 span: lo.to(i.span),
4763 node: StmtKind::Item(i),
4766 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4767 if !attrs.is_empty() {
4768 if s.prev_token_kind == PrevTokenKind::DocComment {
4769 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4770 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4771 s.span_err(s.span, "expected statement after outer attribute");
4776 // Do not attempt to parse an expression if we're done here.
4777 if self.token == token::Semi {
4778 unused_attrs(&attrs, self);
4783 if self.token == token::CloseDelim(token::Brace) {
4784 unused_attrs(&attrs, self);
4788 // Remainder are line-expr stmts.
4789 let e = self.parse_expr_res(
4790 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4792 id: ast::DUMMY_NODE_ID,
4793 span: lo.to(e.span),
4794 node: StmtKind::Expr(e),
4801 /// Is this expression a successfully-parsed statement?
4802 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4803 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4804 !classify::expr_requires_semi_to_be_stmt(e)
4807 /// Parse a block. No inner attrs are allowed.
4808 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4809 maybe_whole!(self, NtBlock, |x| x);
4813 if !self.eat(&token::OpenDelim(token::Brace)) {
4815 let tok = self.this_token_to_string();
4816 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4817 let do_not_suggest_help =
4818 self.token.is_keyword(keywords::In) || self.token == token::Colon;
4820 if self.token.is_ident_named("and") {
4821 e.span_suggestion_short_with_applicability(
4823 "use `&&` instead of `and` for the boolean operator",
4825 Applicability::MaybeIncorrect,
4828 if self.token.is_ident_named("or") {
4829 e.span_suggestion_short_with_applicability(
4831 "use `||` instead of `or` for the boolean operator",
4833 Applicability::MaybeIncorrect,
4837 // Check to see if the user has written something like
4842 // Which is valid in other languages, but not Rust.
4843 match self.parse_stmt_without_recovery(false) {
4845 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4846 || do_not_suggest_help {
4847 // if the next token is an open brace (e.g., `if a b {`), the place-
4848 // inside-a-block suggestion would be more likely wrong than right
4849 e.span_label(sp, "expected `{`");
4852 let mut stmt_span = stmt.span;
4853 // expand the span to include the semicolon, if it exists
4854 if self.eat(&token::Semi) {
4855 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4857 let sugg = pprust::to_string(|s| {
4858 use print::pprust::{PrintState, INDENT_UNIT};
4859 s.ibox(INDENT_UNIT)?;
4861 s.print_stmt(&stmt)?;
4862 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4864 e.span_suggestion_with_applicability(
4866 "try placing this code inside a block",
4868 // speculative, has been misleading in the past (closed Issue #46836)
4869 Applicability::MaybeIncorrect
4873 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4874 self.cancel(&mut e);
4881 self.parse_block_tail(lo, BlockCheckMode::Default)
4884 /// Parse a block. Inner attrs are allowed.
4885 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4886 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4889 self.expect(&token::OpenDelim(token::Brace))?;
4890 Ok((self.parse_inner_attributes()?,
4891 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4894 /// Parse the rest of a block expression or function body
4895 /// Precondition: already parsed the '{'.
4896 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4897 let mut stmts = vec![];
4898 let mut recovered = false;
4900 while !self.eat(&token::CloseDelim(token::Brace)) {
4901 let stmt = match self.parse_full_stmt(false) {
4904 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4905 self.eat(&token::CloseDelim(token::Brace));
4911 if let Some(stmt) = stmt {
4913 } else if self.token == token::Eof {
4916 // Found only `;` or `}`.
4922 id: ast::DUMMY_NODE_ID,
4924 span: lo.to(self.prev_span),
4929 /// Parse a statement, including the trailing semicolon.
4930 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4931 // skip looking for a trailing semicolon when we have an interpolated statement
4932 maybe_whole!(self, NtStmt, |x| Some(x));
4934 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4936 None => return Ok(None),
4940 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4941 // expression without semicolon
4942 if classify::expr_requires_semi_to_be_stmt(expr) {
4943 // Just check for errors and recover; do not eat semicolon yet.
4945 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4948 self.recover_stmt();
4952 StmtKind::Local(..) => {
4953 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4954 if macro_legacy_warnings && self.token != token::Semi {
4955 self.warn_missing_semicolon();
4957 self.expect_one_of(&[], &[token::Semi])?;
4963 if self.eat(&token::Semi) {
4964 stmt = stmt.add_trailing_semicolon();
4967 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4971 fn warn_missing_semicolon(&self) {
4972 self.diagnostic().struct_span_warn(self.span, {
4973 &format!("expected `;`, found `{}`", self.this_token_to_string())
4975 "This was erroneously allowed and will become a hard error in a future release"
4979 fn err_dotdotdot_syntax(&self, span: Span) {
4980 self.diagnostic().struct_span_err(span, {
4981 "unexpected token: `...`"
4982 }).span_suggestion_with_applicability(
4983 span, "use `..` for an exclusive range", "..".to_owned(),
4984 Applicability::MaybeIncorrect
4985 ).span_suggestion_with_applicability(
4986 span, "or `..=` for an inclusive range", "..=".to_owned(),
4987 Applicability::MaybeIncorrect
4991 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4992 // BOUND = TY_BOUND | LT_BOUND
4993 // LT_BOUND = LIFETIME (e.g. `'a`)
4994 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4995 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4996 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4997 let mut bounds = Vec::new();
4999 // This needs to be synchronized with `Token::can_begin_bound`.
5000 let is_bound_start = self.check_path() || self.check_lifetime() ||
5001 self.check(&token::Question) ||
5002 self.check_keyword(keywords::For) ||
5003 self.check(&token::OpenDelim(token::Paren));
5006 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5007 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5008 if self.token.is_lifetime() {
5009 if let Some(question_span) = question {
5010 self.span_err(question_span,
5011 "`?` may only modify trait bounds, not lifetime bounds");
5013 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5015 self.expect(&token::CloseDelim(token::Paren))?;
5016 self.span_err(self.prev_span,
5017 "parenthesized lifetime bounds are not supported");
5020 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5021 let path = self.parse_path(PathStyle::Type)?;
5023 self.expect(&token::CloseDelim(token::Paren))?;
5025 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
5026 let modifier = if question.is_some() {
5027 TraitBoundModifier::Maybe
5029 TraitBoundModifier::None
5031 bounds.push(GenericBound::Trait(poly_trait, modifier));
5037 if !allow_plus || !self.eat_plus() {
5045 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
5046 self.parse_generic_bounds_common(true)
5049 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5050 // BOUND = LT_BOUND (e.g. `'a`)
5051 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5052 let mut lifetimes = Vec::new();
5053 while self.check_lifetime() {
5054 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5056 if !self.eat_plus() {
5063 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
5064 fn parse_ty_param(&mut self,
5065 preceding_attrs: Vec<Attribute>)
5066 -> PResult<'a, GenericParam> {
5067 let ident = self.parse_ident()?;
5069 // Parse optional colon and param bounds.
5070 let bounds = if self.eat(&token::Colon) {
5071 self.parse_generic_bounds()?
5076 let default = if self.eat(&token::Eq) {
5077 Some(self.parse_ty()?)
5084 id: ast::DUMMY_NODE_ID,
5085 attrs: preceding_attrs.into(),
5087 kind: GenericParamKind::Type {
5093 /// Parses the following grammar:
5094 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5095 fn parse_trait_item_assoc_ty(&mut self)
5096 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5097 let ident = self.parse_ident()?;
5098 let mut generics = self.parse_generics()?;
5100 // Parse optional colon and param bounds.
5101 let bounds = if self.eat(&token::Colon) {
5102 self.parse_generic_bounds()?
5106 generics.where_clause = self.parse_where_clause()?;
5108 let default = if self.eat(&token::Eq) {
5109 Some(self.parse_ty()?)
5113 self.expect(&token::Semi)?;
5115 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5118 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5119 /// trailing comma and erroneous trailing attributes.
5120 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5121 let mut params = Vec::new();
5122 let mut seen_ty_param = false;
5124 let attrs = self.parse_outer_attributes()?;
5125 if self.check_lifetime() {
5126 let lifetime = self.expect_lifetime();
5127 // Parse lifetime parameter.
5128 let bounds = if self.eat(&token::Colon) {
5129 self.parse_lt_param_bounds()
5133 params.push(ast::GenericParam {
5134 ident: lifetime.ident,
5136 attrs: attrs.into(),
5138 kind: ast::GenericParamKind::Lifetime,
5141 self.span_err(self.prev_span,
5142 "lifetime parameters must be declared prior to type parameters");
5144 } else if self.check_ident() {
5145 // Parse type parameter.
5146 params.push(self.parse_ty_param(attrs)?);
5147 seen_ty_param = true;
5149 // Check for trailing attributes and stop parsing.
5150 if !attrs.is_empty() {
5151 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
5152 self.span_err(attrs[0].span,
5153 &format!("trailing attribute after {} parameters", param_kind));
5158 if !self.eat(&token::Comma) {
5165 /// Parse a set of optional generic type parameter declarations. Where
5166 /// clauses are not parsed here, and must be added later via
5167 /// `parse_where_clause()`.
5169 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5170 /// | ( < lifetimes , typaramseq ( , )? > )
5171 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5172 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5173 maybe_whole!(self, NtGenerics, |x| x);
5175 let span_lo = self.span;
5177 let params = self.parse_generic_params()?;
5181 where_clause: WhereClause {
5182 id: ast::DUMMY_NODE_ID,
5183 predicates: Vec::new(),
5184 span: syntax_pos::DUMMY_SP,
5186 span: span_lo.to(self.prev_span),
5189 Ok(ast::Generics::default())
5193 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5194 /// possibly including trailing comma.
5195 fn parse_generic_args(&mut self)
5196 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5197 let mut args = Vec::new();
5198 let mut bindings = Vec::new();
5199 let mut seen_type = false;
5200 let mut seen_binding = false;
5202 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5203 // Parse lifetime argument.
5204 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5205 if seen_type || seen_binding {
5206 self.span_err(self.prev_span,
5207 "lifetime parameters must be declared prior to type parameters");
5209 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5210 // Parse associated type binding.
5212 let ident = self.parse_ident()?;
5214 let ty = self.parse_ty()?;
5215 bindings.push(TypeBinding {
5216 id: ast::DUMMY_NODE_ID,
5219 span: lo.to(self.prev_span),
5221 seen_binding = true;
5222 } else if self.check_type() {
5223 // Parse type argument.
5224 let ty_param = self.parse_ty()?;
5226 self.span_err(ty_param.span,
5227 "type parameters must be declared prior to associated type bindings");
5229 args.push(GenericArg::Type(ty_param));
5235 if !self.eat(&token::Comma) {
5239 Ok((args, bindings))
5242 /// Parses an optional `where` clause and places it in `generics`.
5244 /// ```ignore (only-for-syntax-highlight)
5245 /// where T : Trait<U, V> + 'b, 'a : 'b
5247 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5248 maybe_whole!(self, NtWhereClause, |x| x);
5250 let mut where_clause = WhereClause {
5251 id: ast::DUMMY_NODE_ID,
5252 predicates: Vec::new(),
5253 span: syntax_pos::DUMMY_SP,
5256 if !self.eat_keyword(keywords::Where) {
5257 return Ok(where_clause);
5259 let lo = self.prev_span;
5261 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5262 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5263 // change we parse those generics now, but report an error.
5264 if self.choose_generics_over_qpath() {
5265 let generics = self.parse_generics()?;
5266 self.span_err(generics.span,
5267 "generic parameters on `where` clauses are reserved for future use");
5272 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5273 let lifetime = self.expect_lifetime();
5274 // Bounds starting with a colon are mandatory, but possibly empty.
5275 self.expect(&token::Colon)?;
5276 let bounds = self.parse_lt_param_bounds();
5277 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5278 ast::WhereRegionPredicate {
5279 span: lo.to(self.prev_span),
5284 } else if self.check_type() {
5285 // Parse optional `for<'a, 'b>`.
5286 // This `for` is parsed greedily and applies to the whole predicate,
5287 // the bounded type can have its own `for` applying only to it.
5288 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5289 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5290 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5291 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5293 // Parse type with mandatory colon and (possibly empty) bounds,
5294 // or with mandatory equality sign and the second type.
5295 let ty = self.parse_ty()?;
5296 if self.eat(&token::Colon) {
5297 let bounds = self.parse_generic_bounds()?;
5298 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5299 ast::WhereBoundPredicate {
5300 span: lo.to(self.prev_span),
5301 bound_generic_params: lifetime_defs,
5306 // FIXME: Decide what should be used here, `=` or `==`.
5307 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5308 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5309 let rhs_ty = self.parse_ty()?;
5310 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5311 ast::WhereEqPredicate {
5312 span: lo.to(self.prev_span),
5315 id: ast::DUMMY_NODE_ID,
5319 return self.unexpected();
5325 if !self.eat(&token::Comma) {
5330 where_clause.span = lo.to(self.prev_span);
5334 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5335 -> PResult<'a, (Vec<Arg> , bool)> {
5337 let mut variadic = false;
5338 let args: Vec<Option<Arg>> =
5339 self.parse_unspanned_seq(
5340 &token::OpenDelim(token::Paren),
5341 &token::CloseDelim(token::Paren),
5342 SeqSep::trailing_allowed(token::Comma),
5344 if p.token == token::DotDotDot {
5348 if p.token != token::CloseDelim(token::Paren) {
5351 "`...` must be last in argument list for variadic function");
5355 let span = p.prev_span;
5356 if p.token == token::CloseDelim(token::Paren) {
5357 // continue parsing to present any further errors
5360 "only foreign functions are allowed to be variadic"
5362 Ok(Some(dummy_arg(span)))
5364 // this function definition looks beyond recovery, stop parsing
5366 "only foreign functions are allowed to be variadic");
5371 match p.parse_arg_general(named_args) {
5372 Ok(arg) => Ok(Some(arg)),
5375 let lo = p.prev_span;
5376 // Skip every token until next possible arg or end.
5377 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5378 // Create a placeholder argument for proper arg count (#34264).
5379 let span = lo.to(p.prev_span);
5380 Ok(Some(dummy_arg(span)))
5387 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5389 if variadic && args.is_empty() {
5391 "variadic function must be declared with at least one named argument");
5394 Ok((args, variadic))
5397 /// Parse the argument list and result type of a function declaration
5398 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5400 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5401 let ret_ty = self.parse_ret_ty(true)?;
5410 /// Returns the parsed optional self argument and whether a self shortcut was used.
5411 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5412 let expect_ident = |this: &mut Self| match this.token {
5413 // Preserve hygienic context.
5414 token::Ident(ident, _) =>
5415 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5418 let isolated_self = |this: &mut Self, n| {
5419 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5420 this.look_ahead(n + 1, |t| t != &token::ModSep)
5423 // Parse optional self parameter of a method.
5424 // Only a limited set of initial token sequences is considered self parameters, anything
5425 // else is parsed as a normal function parameter list, so some lookahead is required.
5426 let eself_lo = self.span;
5427 let (eself, eself_ident, eself_hi) = match self.token {
5428 token::BinOp(token::And) => {
5434 (if isolated_self(self, 1) {
5436 SelfKind::Region(None, Mutability::Immutable)
5437 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5438 isolated_self(self, 2) {
5441 SelfKind::Region(None, Mutability::Mutable)
5442 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5443 isolated_self(self, 2) {
5445 let lt = self.expect_lifetime();
5446 SelfKind::Region(Some(lt), Mutability::Immutable)
5447 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5448 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5449 isolated_self(self, 3) {
5451 let lt = self.expect_lifetime();
5453 SelfKind::Region(Some(lt), Mutability::Mutable)
5456 }, expect_ident(self), self.prev_span)
5458 token::BinOp(token::Star) => {
5463 // Emit special error for `self` cases.
5464 (if isolated_self(self, 1) {
5466 self.span_err(self.span, "cannot pass `self` by raw pointer");
5467 SelfKind::Value(Mutability::Immutable)
5468 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5469 isolated_self(self, 2) {
5472 self.span_err(self.span, "cannot pass `self` by raw pointer");
5473 SelfKind::Value(Mutability::Immutable)
5476 }, expect_ident(self), self.prev_span)
5478 token::Ident(..) => {
5479 if isolated_self(self, 0) {
5482 let eself_ident = expect_ident(self);
5483 let eself_hi = self.prev_span;
5484 (if self.eat(&token::Colon) {
5485 let ty = self.parse_ty()?;
5486 SelfKind::Explicit(ty, Mutability::Immutable)
5488 SelfKind::Value(Mutability::Immutable)
5489 }, eself_ident, eself_hi)
5490 } else if self.token.is_keyword(keywords::Mut) &&
5491 isolated_self(self, 1) {
5495 let eself_ident = expect_ident(self);
5496 let eself_hi = self.prev_span;
5497 (if self.eat(&token::Colon) {
5498 let ty = self.parse_ty()?;
5499 SelfKind::Explicit(ty, Mutability::Mutable)
5501 SelfKind::Value(Mutability::Mutable)
5502 }, eself_ident, eself_hi)
5507 _ => return Ok(None),
5510 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5511 Ok(Some(Arg::from_self(eself, eself_ident)))
5514 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5515 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5516 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5518 self.expect(&token::OpenDelim(token::Paren))?;
5520 // Parse optional self argument
5521 let self_arg = self.parse_self_arg()?;
5523 // Parse the rest of the function parameter list.
5524 let sep = SeqSep::trailing_allowed(token::Comma);
5525 let fn_inputs = if let Some(self_arg) = self_arg {
5526 if self.check(&token::CloseDelim(token::Paren)) {
5528 } else if self.eat(&token::Comma) {
5529 let mut fn_inputs = vec![self_arg];
5530 fn_inputs.append(&mut self.parse_seq_to_before_end(
5531 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5535 return self.unexpected();
5538 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5541 // Parse closing paren and return type.
5542 self.expect(&token::CloseDelim(token::Paren))?;
5545 output: self.parse_ret_ty(true)?,
5550 // parse the |arg, arg| header on a lambda
5551 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5552 let inputs_captures = {
5553 if self.eat(&token::OrOr) {
5556 self.expect(&token::BinOp(token::Or))?;
5557 let args = self.parse_seq_to_before_tokens(
5558 &[&token::BinOp(token::Or), &token::OrOr],
5559 SeqSep::trailing_allowed(token::Comma),
5560 TokenExpectType::NoExpect,
5561 |p| p.parse_fn_block_arg()
5567 let output = self.parse_ret_ty(true)?;
5570 inputs: inputs_captures,
5576 /// Parse the name and optional generic types of a function header.
5577 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5578 let id = self.parse_ident()?;
5579 let generics = self.parse_generics()?;
5583 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5584 attrs: Vec<Attribute>) -> P<Item> {
5588 id: ast::DUMMY_NODE_ID,
5596 /// Parse an item-position function declaration.
5597 fn parse_item_fn(&mut self,
5600 constness: Spanned<Constness>,
5602 -> PResult<'a, ItemInfo> {
5603 let (ident, mut generics) = self.parse_fn_header()?;
5604 let decl = self.parse_fn_decl(false)?;
5605 generics.where_clause = self.parse_where_clause()?;
5606 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5607 let header = FnHeader { unsafety, asyncness, constness, abi };
5608 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5611 /// true if we are looking at `const ID`, false for things like `const fn` etc
5612 fn is_const_item(&mut self) -> bool {
5613 self.token.is_keyword(keywords::Const) &&
5614 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5615 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5618 /// parses all the "front matter" for a `fn` declaration, up to
5619 /// and including the `fn` keyword:
5623 /// - `const unsafe fn`
5626 fn parse_fn_front_matter(&mut self)
5634 let is_const_fn = self.eat_keyword(keywords::Const);
5635 let const_span = self.prev_span;
5636 let unsafety = self.parse_unsafety();
5637 let asyncness = self.parse_asyncness();
5638 let (constness, unsafety, abi) = if is_const_fn {
5639 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5641 let abi = if self.eat_keyword(keywords::Extern) {
5642 self.parse_opt_abi()?.unwrap_or(Abi::C)
5646 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5648 self.expect_keyword(keywords::Fn)?;
5649 Ok((constness, unsafety, asyncness, abi))
5652 /// Parse an impl item.
5653 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5654 maybe_whole!(self, NtImplItem, |x| x);
5655 let attrs = self.parse_outer_attributes()?;
5656 let (mut item, tokens) = self.collect_tokens(|this| {
5657 this.parse_impl_item_(at_end, attrs)
5660 // See `parse_item` for why this clause is here.
5661 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5662 item.tokens = Some(tokens);
5667 fn parse_impl_item_(&mut self,
5669 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5671 let vis = self.parse_visibility(false)?;
5672 let defaultness = self.parse_defaultness();
5673 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5674 let (name, alias, generics) = type_?;
5675 let kind = match alias {
5676 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5677 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5679 (name, kind, generics)
5680 } else if self.is_const_item() {
5681 // This parses the grammar:
5682 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5683 self.expect_keyword(keywords::Const)?;
5684 let name = self.parse_ident()?;
5685 self.expect(&token::Colon)?;
5686 let typ = self.parse_ty()?;
5687 self.expect(&token::Eq)?;
5688 let expr = self.parse_expr()?;
5689 self.expect(&token::Semi)?;
5690 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5692 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5693 attrs.extend(inner_attrs);
5694 (name, node, generics)
5698 id: ast::DUMMY_NODE_ID,
5699 span: lo.to(self.prev_span),
5710 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5711 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5716 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5718 VisibilityKind::Inherited => Ok(()),
5720 let is_macro_rules: bool = match self.token {
5721 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5725 let mut err = self.diagnostic()
5726 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5727 err.span_suggestion_with_applicability(
5729 "try exporting the macro",
5730 "#[macro_export]".to_owned(),
5731 Applicability::MaybeIncorrect // speculative
5735 let mut err = self.diagnostic()
5736 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5737 err.help("try adjusting the macro to put `pub` inside the invocation");
5744 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5745 -> DiagnosticBuilder<'a>
5747 let expected_kinds = if item_type == "extern" {
5748 "missing `fn`, `type`, or `static`"
5750 "missing `fn`, `type`, or `const`"
5753 // Given this code `path(`, it seems like this is not
5754 // setting the visibility of a macro invocation, but rather
5755 // a mistyped method declaration.
5756 // Create a diagnostic pointing out that `fn` is missing.
5758 // x | pub path(&self) {
5759 // | ^ missing `fn`, `type`, or `const`
5761 // ^^ `sp` below will point to this
5762 let sp = prev_span.between(self.prev_span);
5763 let mut err = self.diagnostic().struct_span_err(
5765 &format!("{} for {}-item declaration",
5766 expected_kinds, item_type));
5767 err.span_label(sp, expected_kinds);
5771 /// Parse a method or a macro invocation in a trait impl.
5772 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5773 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5774 ast::ImplItemKind)> {
5775 // code copied from parse_macro_use_or_failure... abstraction!
5776 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5778 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5779 ast::ImplItemKind::Macro(mac)))
5781 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5782 let ident = self.parse_ident()?;
5783 let mut generics = self.parse_generics()?;
5784 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5785 generics.where_clause = self.parse_where_clause()?;
5787 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5788 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5789 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5790 ast::MethodSig { header, decl },
5796 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5797 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5798 let ident = self.parse_ident()?;
5799 let mut tps = self.parse_generics()?;
5801 // Parse optional colon and supertrait bounds.
5802 let bounds = if self.eat(&token::Colon) {
5803 self.parse_generic_bounds()?
5808 if self.eat(&token::Eq) {
5809 // it's a trait alias
5810 let bounds = self.parse_generic_bounds()?;
5811 tps.where_clause = self.parse_where_clause()?;
5812 self.expect(&token::Semi)?;
5813 if unsafety != Unsafety::Normal {
5814 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5816 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5818 // it's a normal trait
5819 tps.where_clause = self.parse_where_clause()?;
5820 self.expect(&token::OpenDelim(token::Brace))?;
5821 let mut trait_items = vec![];
5822 while !self.eat(&token::CloseDelim(token::Brace)) {
5823 let mut at_end = false;
5824 match self.parse_trait_item(&mut at_end) {
5825 Ok(item) => trait_items.push(item),
5829 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5834 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5838 fn choose_generics_over_qpath(&self) -> bool {
5839 // There's an ambiguity between generic parameters and qualified paths in impls.
5840 // If we see `<` it may start both, so we have to inspect some following tokens.
5841 // The following combinations can only start generics,
5842 // but not qualified paths (with one exception):
5843 // `<` `>` - empty generic parameters
5844 // `<` `#` - generic parameters with attributes
5845 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5846 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5847 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5848 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5849 // The only truly ambiguous case is
5850 // `<` IDENT `>` `::` IDENT ...
5851 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5852 // because this is what almost always expected in practice, qualified paths in impls
5853 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5854 self.token == token::Lt &&
5855 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5856 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5857 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5858 t == &token::Colon || t == &token::Eq))
5861 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5862 self.expect(&token::OpenDelim(token::Brace))?;
5863 let attrs = self.parse_inner_attributes()?;
5865 let mut impl_items = Vec::new();
5866 while !self.eat(&token::CloseDelim(token::Brace)) {
5867 let mut at_end = false;
5868 match self.parse_impl_item(&mut at_end) {
5869 Ok(impl_item) => impl_items.push(impl_item),
5873 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5878 Ok((impl_items, attrs))
5881 /// Parses an implementation item, `impl` keyword is already parsed.
5882 /// impl<'a, T> TYPE { /* impl items */ }
5883 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5884 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5885 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5886 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5887 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5888 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5889 -> PResult<'a, ItemInfo> {
5890 // First, parse generic parameters if necessary.
5891 let mut generics = if self.choose_generics_over_qpath() {
5892 self.parse_generics()?
5894 ast::Generics::default()
5897 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5898 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5900 ast::ImplPolarity::Negative
5902 ast::ImplPolarity::Positive
5905 // Parse both types and traits as a type, then reinterpret if necessary.
5906 let ty_first = self.parse_ty()?;
5908 // If `for` is missing we try to recover.
5909 let has_for = self.eat_keyword(keywords::For);
5910 let missing_for_span = self.prev_span.between(self.span);
5912 let ty_second = if self.token == token::DotDot {
5913 // We need to report this error after `cfg` expansion for compatibility reasons
5914 self.bump(); // `..`, do not add it to expected tokens
5915 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5916 } else if has_for || self.token.can_begin_type() {
5917 Some(self.parse_ty()?)
5922 generics.where_clause = self.parse_where_clause()?;
5924 let (impl_items, attrs) = self.parse_impl_body()?;
5926 let item_kind = match ty_second {
5927 Some(ty_second) => {
5928 // impl Trait for Type
5930 self.span_err(missing_for_span, "missing `for` in a trait impl");
5933 let ty_first = ty_first.into_inner();
5934 let path = match ty_first.node {
5935 // This notably includes paths passed through `ty` macro fragments (#46438).
5936 TyKind::Path(None, path) => path,
5938 self.span_err(ty_first.span, "expected a trait, found type");
5939 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5942 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5944 ItemKind::Impl(unsafety, polarity, defaultness,
5945 generics, Some(trait_ref), ty_second, impl_items)
5949 ItemKind::Impl(unsafety, polarity, defaultness,
5950 generics, None, ty_first, impl_items)
5954 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5957 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5958 if self.eat_keyword(keywords::For) {
5960 let params = self.parse_generic_params()?;
5962 // We rely on AST validation to rule out invalid cases: There must not be type
5963 // parameters, and the lifetime parameters must not have bounds.
5970 /// Parse struct Foo { ... }
5971 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5972 let class_name = self.parse_ident()?;
5974 let mut generics = self.parse_generics()?;
5976 // There is a special case worth noting here, as reported in issue #17904.
5977 // If we are parsing a tuple struct it is the case that the where clause
5978 // should follow the field list. Like so:
5980 // struct Foo<T>(T) where T: Copy;
5982 // If we are parsing a normal record-style struct it is the case
5983 // that the where clause comes before the body, and after the generics.
5984 // So if we look ahead and see a brace or a where-clause we begin
5985 // parsing a record style struct.
5987 // Otherwise if we look ahead and see a paren we parse a tuple-style
5990 let vdata = if self.token.is_keyword(keywords::Where) {
5991 generics.where_clause = self.parse_where_clause()?;
5992 if self.eat(&token::Semi) {
5993 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5994 VariantData::Unit(ast::DUMMY_NODE_ID)
5996 // If we see: `struct Foo<T> where T: Copy { ... }`
5997 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5999 // No `where` so: `struct Foo<T>;`
6000 } else if self.eat(&token::Semi) {
6001 VariantData::Unit(ast::DUMMY_NODE_ID)
6002 // Record-style struct definition
6003 } else if self.token == token::OpenDelim(token::Brace) {
6004 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6005 // Tuple-style struct definition with optional where-clause.
6006 } else if self.token == token::OpenDelim(token::Paren) {
6007 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6008 generics.where_clause = self.parse_where_clause()?;
6009 self.expect(&token::Semi)?;
6012 let token_str = self.this_token_to_string();
6013 let mut err = self.fatal(&format!(
6014 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
6017 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6021 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6024 /// Parse union Foo { ... }
6025 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6026 let class_name = self.parse_ident()?;
6028 let mut generics = self.parse_generics()?;
6030 let vdata = if self.token.is_keyword(keywords::Where) {
6031 generics.where_clause = self.parse_where_clause()?;
6032 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6033 } else if self.token == token::OpenDelim(token::Brace) {
6034 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6036 let token_str = self.this_token_to_string();
6037 let mut err = self.fatal(&format!(
6038 "expected `where` or `{{` after union name, found `{}`", token_str));
6039 err.span_label(self.span, "expected `where` or `{` after union name");
6043 Ok((class_name, ItemKind::Union(vdata, generics), None))
6046 fn consume_block(&mut self, delim: token::DelimToken) {
6047 let mut brace_depth = 0;
6048 if !self.eat(&token::OpenDelim(delim)) {
6052 if self.eat(&token::OpenDelim(delim)) {
6054 } else if self.eat(&token::CloseDelim(delim)) {
6055 if brace_depth == 0 {
6061 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
6069 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6070 let mut fields = Vec::new();
6071 if self.eat(&token::OpenDelim(token::Brace)) {
6072 while self.token != token::CloseDelim(token::Brace) {
6073 let field = self.parse_struct_decl_field().map_err(|e| {
6074 self.recover_stmt();
6078 Ok(field) => fields.push(field),
6084 self.eat(&token::CloseDelim(token::Brace));
6086 let token_str = self.this_token_to_string();
6087 let mut err = self.fatal(&format!(
6088 "expected `where`, or `{{` after struct name, found `{}`", token_str));
6089 err.span_label(self.span, "expected `where`, or `{` after struct name");
6096 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6097 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6098 // Unit like structs are handled in parse_item_struct function
6099 let fields = self.parse_unspanned_seq(
6100 &token::OpenDelim(token::Paren),
6101 &token::CloseDelim(token::Paren),
6102 SeqSep::trailing_allowed(token::Comma),
6104 let attrs = p.parse_outer_attributes()?;
6106 let vis = p.parse_visibility(true)?;
6107 let ty = p.parse_ty()?;
6109 span: lo.to(ty.span),
6112 id: ast::DUMMY_NODE_ID,
6121 /// Parse a structure field declaration
6122 fn parse_single_struct_field(&mut self,
6125 attrs: Vec<Attribute> )
6126 -> PResult<'a, StructField> {
6127 let mut seen_comma: bool = false;
6128 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6129 if self.token == token::Comma {
6136 token::CloseDelim(token::Brace) => {}
6137 token::DocComment(_) => {
6138 let previous_span = self.prev_span;
6139 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6140 self.bump(); // consume the doc comment
6141 let comma_after_doc_seen = self.eat(&token::Comma);
6142 // `seen_comma` is always false, because we are inside doc block
6143 // condition is here to make code more readable
6144 if seen_comma == false && comma_after_doc_seen == true {
6147 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6150 if seen_comma == false {
6151 let sp = self.sess.source_map().next_point(previous_span);
6152 err.span_suggestion_with_applicability(
6154 "missing comma here",
6156 Applicability::MachineApplicable
6163 let sp = self.sess.source_map().next_point(self.prev_span);
6164 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
6165 self.this_token_to_string()));
6166 if self.token.is_ident() {
6167 // This is likely another field; emit the diagnostic and keep going
6168 err.span_suggestion_with_applicability(
6170 "try adding a comma",
6172 Applicability::MachineApplicable,
6183 /// Parse an element of a struct definition
6184 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6185 let attrs = self.parse_outer_attributes()?;
6187 let vis = self.parse_visibility(false)?;
6188 self.parse_single_struct_field(lo, vis, attrs)
6191 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6192 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6193 /// a function definition, it's not a tuple struct field) and the contents within the parens
6194 /// isn't valid, emit a proper diagnostic.
6195 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6196 maybe_whole!(self, NtVis, |x| x);
6198 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6199 if self.is_crate_vis() {
6200 self.bump(); // `crate`
6201 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6204 if !self.eat_keyword(keywords::Pub) {
6205 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6206 // keyword to grab a span from for inherited visibility; an empty span at the
6207 // beginning of the current token would seem to be the "Schelling span".
6208 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6210 let lo = self.prev_span;
6212 if self.check(&token::OpenDelim(token::Paren)) {
6213 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6214 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6215 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6216 // by the following tokens.
6217 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6220 self.bump(); // `crate`
6221 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6223 lo.to(self.prev_span),
6224 VisibilityKind::Crate(CrateSugar::PubCrate),
6227 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6230 self.bump(); // `in`
6231 let path = self.parse_path(PathStyle::Mod)?; // `path`
6232 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6233 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6235 id: ast::DUMMY_NODE_ID,
6238 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6239 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6240 t.is_keyword(keywords::SelfValue))
6242 // `pub(self)` or `pub(super)`
6244 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6245 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6246 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6248 id: ast::DUMMY_NODE_ID,
6251 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6252 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6254 let msg = "incorrect visibility restriction";
6255 let suggestion = r##"some possible visibility restrictions are:
6256 `pub(crate)`: visible only on the current crate
6257 `pub(super)`: visible only in the current module's parent
6258 `pub(in path::to::module)`: visible only on the specified path"##;
6259 let path = self.parse_path(PathStyle::Mod)?;
6260 let sp = self.prev_span;
6261 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6262 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6263 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6264 err.help(suggestion);
6265 err.span_suggestion_with_applicability(
6266 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6268 err.emit(); // emit diagnostic, but continue with public visibility
6272 Ok(respan(lo, VisibilityKind::Public))
6275 /// Parse defaultness: `default` or nothing.
6276 fn parse_defaultness(&mut self) -> Defaultness {
6277 // `pub` is included for better error messages
6278 if self.check_keyword(keywords::Default) &&
6279 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6280 t.is_keyword(keywords::Const) ||
6281 t.is_keyword(keywords::Fn) ||
6282 t.is_keyword(keywords::Unsafe) ||
6283 t.is_keyword(keywords::Extern) ||
6284 t.is_keyword(keywords::Type) ||
6285 t.is_keyword(keywords::Pub)) {
6286 self.bump(); // `default`
6287 Defaultness::Default
6293 /// Given a termination token, parse all of the items in a module
6294 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6295 let mut items = vec![];
6296 while let Some(item) = self.parse_item()? {
6300 if !self.eat(term) {
6301 let token_str = self.this_token_to_string();
6302 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6303 if token_str == ";" {
6304 let msg = "consider removing this semicolon";
6305 err.span_suggestion_short_with_applicability(
6306 self.span, msg, String::new(), Applicability::MachineApplicable
6308 if !items.is_empty() { // Issue #51603
6309 let previous_item = &items[items.len()-1];
6310 let previous_item_kind_name = match previous_item.node {
6311 // say "braced struct" because tuple-structs and
6312 // braceless-empty-struct declarations do take a semicolon
6313 ItemKind::Struct(..) => Some("braced struct"),
6314 ItemKind::Enum(..) => Some("enum"),
6315 ItemKind::Trait(..) => Some("trait"),
6316 ItemKind::Union(..) => Some("union"),
6319 if let Some(name) = previous_item_kind_name {
6320 err.help(&format!("{} declarations are not followed by a semicolon",
6325 err.span_label(self.span, "expected item");
6330 let hi = if self.span.is_dummy() {
6337 inner: inner_lo.to(hi),
6343 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6344 let id = self.parse_ident()?;
6345 self.expect(&token::Colon)?;
6346 let ty = self.parse_ty()?;
6347 self.expect(&token::Eq)?;
6348 let e = self.parse_expr()?;
6349 self.expect(&token::Semi)?;
6350 let item = match m {
6351 Some(m) => ItemKind::Static(ty, m, e),
6352 None => ItemKind::Const(ty, e),
6354 Ok((id, item, None))
6357 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6358 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6359 let (in_cfg, outer_attrs) = {
6360 let mut strip_unconfigured = ::config::StripUnconfigured {
6362 features: None, // don't perform gated feature checking
6364 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6365 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6368 let id_span = self.span;
6369 let id = self.parse_ident()?;
6370 if self.eat(&token::Semi) {
6371 if in_cfg && self.recurse_into_file_modules {
6372 // This mod is in an external file. Let's go get it!
6373 let ModulePathSuccess { path, directory_ownership, warn } =
6374 self.submod_path(id, &outer_attrs, id_span)?;
6375 let (module, mut attrs) =
6376 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6377 // Record that we fetched the mod from an external file
6379 let attr = Attribute {
6380 id: attr::mk_attr_id(),
6381 style: ast::AttrStyle::Outer,
6382 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6383 tokens: TokenStream::empty(),
6384 is_sugared_doc: false,
6385 span: syntax_pos::DUMMY_SP,
6387 attr::mark_known(&attr);
6390 Ok((id, ItemKind::Mod(module), Some(attrs)))
6392 let placeholder = ast::Mod {
6393 inner: syntax_pos::DUMMY_SP,
6397 Ok((id, ItemKind::Mod(placeholder), None))
6400 let old_directory = self.directory.clone();
6401 self.push_directory(id, &outer_attrs);
6403 self.expect(&token::OpenDelim(token::Brace))?;
6404 let mod_inner_lo = self.span;
6405 let attrs = self.parse_inner_attributes()?;
6406 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6408 self.directory = old_directory;
6409 Ok((id, ItemKind::Mod(module), Some(attrs)))
6413 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6414 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6415 self.directory.path.to_mut().push(&path.as_str());
6416 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6418 self.directory.path.to_mut().push(&id.as_str());
6422 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6423 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6426 // On windows, the base path might have the form
6427 // `\\?\foo\bar` in which case it does not tolerate
6428 // mixed `/` and `\` separators, so canonicalize
6431 let s = s.replace("/", "\\");
6432 Some(dir_path.join(s))
6438 /// Returns either a path to a module, or .
6439 pub fn default_submod_path(
6441 relative: Option<ast::Ident>,
6443 source_map: &SourceMap) -> ModulePath
6445 // If we're in a foo.rs file instead of a mod.rs file,
6446 // we need to look for submodules in
6447 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6448 // `./<id>.rs` and `./<id>/mod.rs`.
6449 let relative_prefix_string;
6450 let relative_prefix = if let Some(ident) = relative {
6451 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6452 &relative_prefix_string
6457 let mod_name = id.to_string();
6458 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6459 let secondary_path_str = format!("{}{}{}mod.rs",
6460 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6461 let default_path = dir_path.join(&default_path_str);
6462 let secondary_path = dir_path.join(&secondary_path_str);
6463 let default_exists = source_map.file_exists(&default_path);
6464 let secondary_exists = source_map.file_exists(&secondary_path);
6466 let result = match (default_exists, secondary_exists) {
6467 (true, false) => Ok(ModulePathSuccess {
6469 directory_ownership: DirectoryOwnership::Owned {
6474 (false, true) => Ok(ModulePathSuccess {
6475 path: secondary_path,
6476 directory_ownership: DirectoryOwnership::Owned {
6481 (false, false) => Err(Error::FileNotFoundForModule {
6482 mod_name: mod_name.clone(),
6483 default_path: default_path_str,
6484 secondary_path: secondary_path_str,
6485 dir_path: dir_path.display().to_string(),
6487 (true, true) => Err(Error::DuplicatePaths {
6488 mod_name: mod_name.clone(),
6489 default_path: default_path_str,
6490 secondary_path: secondary_path_str,
6496 path_exists: default_exists || secondary_exists,
6501 fn submod_path(&mut self,
6503 outer_attrs: &[Attribute],
6505 -> PResult<'a, ModulePathSuccess> {
6506 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6507 return Ok(ModulePathSuccess {
6508 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6509 // All `#[path]` files are treated as though they are a `mod.rs` file.
6510 // This means that `mod foo;` declarations inside `#[path]`-included
6511 // files are siblings,
6513 // Note that this will produce weirdness when a file named `foo.rs` is
6514 // `#[path]` included and contains a `mod foo;` declaration.
6515 // If you encounter this, it's your own darn fault :P
6516 Some(_) => DirectoryOwnership::Owned { relative: None },
6517 _ => DirectoryOwnership::UnownedViaMod(true),
6524 let relative = match self.directory.ownership {
6525 DirectoryOwnership::Owned { relative } => {
6526 // Push the usage onto the list of non-mod.rs mod uses.
6527 // This is used later for feature-gate error reporting.
6528 if let Some(cur_file_ident) = relative {
6530 .non_modrs_mods.borrow_mut()
6531 .push((cur_file_ident, id_sp));
6535 DirectoryOwnership::UnownedViaBlock |
6536 DirectoryOwnership::UnownedViaMod(_) => None,
6538 let paths = Parser::default_submod_path(
6539 id, relative, &self.directory.path, self.sess.source_map());
6541 match self.directory.ownership {
6542 DirectoryOwnership::Owned { .. } => {
6543 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6545 DirectoryOwnership::UnownedViaBlock => {
6547 "Cannot declare a non-inline module inside a block \
6548 unless it has a path attribute";
6549 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6550 if paths.path_exists {
6551 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6553 err.span_note(id_sp, &msg);
6557 DirectoryOwnership::UnownedViaMod(warn) => {
6559 if let Ok(result) = paths.result {
6560 return Ok(ModulePathSuccess { warn: true, ..result });
6563 let mut err = self.diagnostic().struct_span_err(id_sp,
6564 "cannot declare a new module at this location");
6565 if !id_sp.is_dummy() {
6566 let src_path = self.sess.source_map().span_to_filename(id_sp);
6567 if let FileName::Real(src_path) = src_path {
6568 if let Some(stem) = src_path.file_stem() {
6569 let mut dest_path = src_path.clone();
6570 dest_path.set_file_name(stem);
6571 dest_path.push("mod.rs");
6572 err.span_note(id_sp,
6573 &format!("maybe move this module `{}` to its own \
6574 directory via `{}`", src_path.display(),
6575 dest_path.display()));
6579 if paths.path_exists {
6580 err.span_note(id_sp,
6581 &format!("... or maybe `use` the module `{}` instead \
6582 of possibly redeclaring it",
6590 /// Read a module from a source file.
6591 fn eval_src_mod(&mut self,
6593 directory_ownership: DirectoryOwnership,
6596 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6597 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6598 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6599 let mut err = String::from("circular modules: ");
6600 let len = included_mod_stack.len();
6601 for p in &included_mod_stack[i.. len] {
6602 err.push_str(&p.to_string_lossy());
6603 err.push_str(" -> ");
6605 err.push_str(&path.to_string_lossy());
6606 return Err(self.span_fatal(id_sp, &err[..]));
6608 included_mod_stack.push(path.clone());
6609 drop(included_mod_stack);
6612 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6613 p0.cfg_mods = self.cfg_mods;
6614 let mod_inner_lo = p0.span;
6615 let mod_attrs = p0.parse_inner_attributes()?;
6616 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6618 self.sess.included_mod_stack.borrow_mut().pop();
6622 /// Parse a function declaration from a foreign module
6623 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6624 -> PResult<'a, ForeignItem> {
6625 self.expect_keyword(keywords::Fn)?;
6627 let (ident, mut generics) = self.parse_fn_header()?;
6628 let decl = self.parse_fn_decl(true)?;
6629 generics.where_clause = self.parse_where_clause()?;
6631 self.expect(&token::Semi)?;
6632 Ok(ast::ForeignItem {
6635 node: ForeignItemKind::Fn(decl, generics),
6636 id: ast::DUMMY_NODE_ID,
6642 /// Parse a static item from a foreign module.
6643 /// Assumes that the `static` keyword is already parsed.
6644 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6645 -> PResult<'a, ForeignItem> {
6646 let mutbl = self.eat_keyword(keywords::Mut);
6647 let ident = self.parse_ident()?;
6648 self.expect(&token::Colon)?;
6649 let ty = self.parse_ty()?;
6651 self.expect(&token::Semi)?;
6655 node: ForeignItemKind::Static(ty, mutbl),
6656 id: ast::DUMMY_NODE_ID,
6662 /// Parse a type from a foreign module
6663 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6664 -> PResult<'a, ForeignItem> {
6665 self.expect_keyword(keywords::Type)?;
6667 let ident = self.parse_ident()?;
6669 self.expect(&token::Semi)?;
6670 Ok(ast::ForeignItem {
6673 node: ForeignItemKind::Ty,
6674 id: ast::DUMMY_NODE_ID,
6680 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6681 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6682 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6684 let mut ident = self.parse_ident()?;
6685 let mut idents = vec![];
6686 let mut replacement = vec![];
6687 let mut fixed_crate_name = false;
6688 // Accept `extern crate name-like-this` for better diagnostics
6689 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6690 if self.token == dash { // Do not include `-` as part of the expected tokens list
6691 while self.eat(&dash) {
6692 fixed_crate_name = true;
6693 replacement.push((self.prev_span, "_".to_string()));
6694 idents.push(self.parse_ident()?);
6697 if fixed_crate_name {
6698 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6699 let mut fixed_name = format!("{}", ident.name);
6700 for part in idents {
6701 fixed_name.push_str(&format!("_{}", part.name));
6703 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6705 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6706 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6707 err.multipart_suggestion(suggestion_msg, replacement);
6713 /// Parse extern crate links
6717 /// extern crate foo;
6718 /// extern crate bar as foo;
6719 fn parse_item_extern_crate(&mut self,
6721 visibility: Visibility,
6722 attrs: Vec<Attribute>)
6723 -> PResult<'a, P<Item>> {
6724 // Accept `extern crate name-like-this` for better diagnostics
6725 let orig_name = self.parse_crate_name_with_dashes()?;
6726 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6727 (rename, Some(orig_name.name))
6731 self.expect(&token::Semi)?;
6733 let span = lo.to(self.prev_span);
6734 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6737 /// Parse `extern` for foreign ABIs
6740 /// `extern` is expected to have been
6741 /// consumed before calling this method
6747 fn parse_item_foreign_mod(&mut self,
6749 opt_abi: Option<Abi>,
6750 visibility: Visibility,
6751 mut attrs: Vec<Attribute>)
6752 -> PResult<'a, P<Item>> {
6753 self.expect(&token::OpenDelim(token::Brace))?;
6755 let abi = opt_abi.unwrap_or(Abi::C);
6757 attrs.extend(self.parse_inner_attributes()?);
6759 let mut foreign_items = vec![];
6760 while !self.eat(&token::CloseDelim(token::Brace)) {
6761 foreign_items.push(self.parse_foreign_item()?);
6764 let prev_span = self.prev_span;
6765 let m = ast::ForeignMod {
6767 items: foreign_items
6769 let invalid = keywords::Invalid.ident();
6770 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6773 /// Parse type Foo = Bar;
6775 /// existential type Foo: Bar;
6777 /// return None without modifying the parser state
6778 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6779 // This parses the grammar:
6780 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6781 if self.check_keyword(keywords::Type) ||
6782 self.check_keyword(keywords::Existential) &&
6783 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6784 let existential = self.eat_keyword(keywords::Existential);
6785 assert!(self.eat_keyword(keywords::Type));
6786 Some(self.parse_existential_or_alias(existential))
6792 /// Parse type alias or existential type
6793 fn parse_existential_or_alias(
6796 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6797 let ident = self.parse_ident()?;
6798 let mut tps = self.parse_generics()?;
6799 tps.where_clause = self.parse_where_clause()?;
6800 let alias = if existential {
6801 self.expect(&token::Colon)?;
6802 let bounds = self.parse_generic_bounds()?;
6803 AliasKind::Existential(bounds)
6805 self.expect(&token::Eq)?;
6806 let ty = self.parse_ty()?;
6809 self.expect(&token::Semi)?;
6810 Ok((ident, alias, tps))
6813 /// Parse the part of an "enum" decl following the '{'
6814 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6815 let mut variants = Vec::new();
6816 let mut all_nullary = true;
6817 let mut any_disr = None;
6818 while self.token != token::CloseDelim(token::Brace) {
6819 let variant_attrs = self.parse_outer_attributes()?;
6820 let vlo = self.span;
6823 let mut disr_expr = None;
6824 let ident = self.parse_ident()?;
6825 if self.check(&token::OpenDelim(token::Brace)) {
6826 // Parse a struct variant.
6827 all_nullary = false;
6828 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6829 ast::DUMMY_NODE_ID);
6830 } else if self.check(&token::OpenDelim(token::Paren)) {
6831 all_nullary = false;
6832 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6833 ast::DUMMY_NODE_ID);
6834 } else if self.eat(&token::Eq) {
6835 disr_expr = Some(AnonConst {
6836 id: ast::DUMMY_NODE_ID,
6837 value: self.parse_expr()?,
6839 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6840 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6842 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6845 let vr = ast::Variant_ {
6847 attrs: variant_attrs,
6851 variants.push(respan(vlo.to(self.prev_span), vr));
6853 if !self.eat(&token::Comma) { break; }
6855 self.expect(&token::CloseDelim(token::Brace))?;
6857 Some(disr_span) if !all_nullary =>
6858 self.span_err(disr_span,
6859 "discriminator values can only be used with a field-less enum"),
6863 Ok(ast::EnumDef { variants: variants })
6866 /// Parse an "enum" declaration
6867 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6868 let id = self.parse_ident()?;
6869 let mut generics = self.parse_generics()?;
6870 generics.where_clause = self.parse_where_clause()?;
6871 self.expect(&token::OpenDelim(token::Brace))?;
6873 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6874 self.recover_stmt();
6875 self.eat(&token::CloseDelim(token::Brace));
6878 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6881 /// Parses a string as an ABI spec on an extern type or module. Consumes
6882 /// the `extern` keyword, if one is found.
6883 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6885 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6887 self.expect_no_suffix(sp, "ABI spec", suf);
6889 match abi::lookup(&s.as_str()) {
6890 Some(abi) => Ok(Some(abi)),
6892 let prev_span = self.prev_span;
6893 let mut err = struct_span_err!(
6894 self.sess.span_diagnostic,
6897 "invalid ABI: found `{}`",
6899 err.span_label(prev_span, "invalid ABI");
6900 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6911 fn is_static_global(&mut self) -> bool {
6912 if self.check_keyword(keywords::Static) {
6913 // Check if this could be a closure
6914 !self.look_ahead(1, |token| {
6915 if token.is_keyword(keywords::Move) {
6919 token::BinOp(token::Or) | token::OrOr => true,
6930 attrs: Vec<Attribute>,
6931 macros_allowed: bool,
6932 attributes_allowed: bool,
6933 ) -> PResult<'a, Option<P<Item>>> {
6934 let (ret, tokens) = self.collect_tokens(|this| {
6935 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
6938 // Once we've parsed an item and recorded the tokens we got while
6939 // parsing we may want to store `tokens` into the item we're about to
6940 // return. Note, though, that we specifically didn't capture tokens
6941 // related to outer attributes. The `tokens` field here may later be
6942 // used with procedural macros to convert this item back into a token
6943 // stream, but during expansion we may be removing attributes as we go
6946 // If we've got inner attributes then the `tokens` we've got above holds
6947 // these inner attributes. If an inner attribute is expanded we won't
6948 // actually remove it from the token stream, so we'll just keep yielding
6949 // it (bad!). To work around this case for now we just avoid recording
6950 // `tokens` if we detect any inner attributes. This should help keep
6951 // expansion correct, but we should fix this bug one day!
6954 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6955 i.tokens = Some(tokens);
6962 /// Parse one of the items allowed by the flags.
6963 fn parse_item_implementation(
6965 attrs: Vec<Attribute>,
6966 macros_allowed: bool,
6967 attributes_allowed: bool,
6968 ) -> PResult<'a, Option<P<Item>>> {
6969 maybe_whole!(self, NtItem, |item| {
6970 let mut item = item.into_inner();
6971 let mut attrs = attrs;
6972 mem::swap(&mut item.attrs, &mut attrs);
6973 item.attrs.extend(attrs);
6979 let visibility = self.parse_visibility(false)?;
6981 if self.eat_keyword(keywords::Use) {
6983 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6984 self.expect(&token::Semi)?;
6986 let span = lo.to(self.prev_span);
6987 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6988 return Ok(Some(item));
6991 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6992 self.bump(); // `extern`
6993 if self.eat_keyword(keywords::Crate) {
6994 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6997 let opt_abi = self.parse_opt_abi()?;
6999 if self.eat_keyword(keywords::Fn) {
7000 // EXTERN FUNCTION ITEM
7001 let fn_span = self.prev_span;
7002 let abi = opt_abi.unwrap_or(Abi::C);
7003 let (ident, item_, extra_attrs) =
7004 self.parse_item_fn(Unsafety::Normal,
7006 respan(fn_span, Constness::NotConst),
7008 let prev_span = self.prev_span;
7009 let item = self.mk_item(lo.to(prev_span),
7013 maybe_append(attrs, extra_attrs));
7014 return Ok(Some(item));
7015 } else if self.check(&token::OpenDelim(token::Brace)) {
7016 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7022 if self.is_static_global() {
7025 let m = if self.eat_keyword(keywords::Mut) {
7028 Mutability::Immutable
7030 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7031 let prev_span = self.prev_span;
7032 let item = self.mk_item(lo.to(prev_span),
7036 maybe_append(attrs, extra_attrs));
7037 return Ok(Some(item));
7039 if self.eat_keyword(keywords::Const) {
7040 let const_span = self.prev_span;
7041 if self.check_keyword(keywords::Fn)
7042 || (self.check_keyword(keywords::Unsafe)
7043 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7044 // CONST FUNCTION ITEM
7045 let unsafety = self.parse_unsafety();
7047 let (ident, item_, extra_attrs) =
7048 self.parse_item_fn(unsafety,
7050 respan(const_span, Constness::Const),
7052 let prev_span = self.prev_span;
7053 let item = self.mk_item(lo.to(prev_span),
7057 maybe_append(attrs, extra_attrs));
7058 return Ok(Some(item));
7062 if self.eat_keyword(keywords::Mut) {
7063 let prev_span = self.prev_span;
7064 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
7065 .help("did you mean to declare a static?")
7068 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7069 let prev_span = self.prev_span;
7070 let item = self.mk_item(lo.to(prev_span),
7074 maybe_append(attrs, extra_attrs));
7075 return Ok(Some(item));
7078 // `unsafe async fn` or `async fn`
7080 self.check_keyword(keywords::Unsafe) &&
7081 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7083 self.check_keyword(keywords::Async) &&
7084 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7087 // ASYNC FUNCTION ITEM
7088 let unsafety = self.parse_unsafety();
7089 self.expect_keyword(keywords::Async)?;
7090 self.expect_keyword(keywords::Fn)?;
7091 let fn_span = self.prev_span;
7092 let (ident, item_, extra_attrs) =
7093 self.parse_item_fn(unsafety,
7095 closure_id: ast::DUMMY_NODE_ID,
7096 return_impl_trait_id: ast::DUMMY_NODE_ID,
7098 respan(fn_span, Constness::NotConst),
7100 let prev_span = self.prev_span;
7101 let item = self.mk_item(lo.to(prev_span),
7105 maybe_append(attrs, extra_attrs));
7106 return Ok(Some(item));
7108 if self.check_keyword(keywords::Unsafe) &&
7109 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7110 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7112 // UNSAFE TRAIT ITEM
7113 self.bump(); // `unsafe`
7114 let is_auto = if self.eat_keyword(keywords::Trait) {
7117 self.expect_keyword(keywords::Auto)?;
7118 self.expect_keyword(keywords::Trait)?;
7121 let (ident, item_, extra_attrs) =
7122 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7123 let prev_span = self.prev_span;
7124 let item = self.mk_item(lo.to(prev_span),
7128 maybe_append(attrs, extra_attrs));
7129 return Ok(Some(item));
7131 if self.check_keyword(keywords::Impl) ||
7132 self.check_keyword(keywords::Unsafe) &&
7133 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7134 self.check_keyword(keywords::Default) &&
7135 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7136 self.check_keyword(keywords::Default) &&
7137 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7139 let defaultness = self.parse_defaultness();
7140 let unsafety = self.parse_unsafety();
7141 self.expect_keyword(keywords::Impl)?;
7142 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7143 let span = lo.to(self.prev_span);
7144 return Ok(Some(self.mk_item(span, ident, item, visibility,
7145 maybe_append(attrs, extra_attrs))));
7147 if self.check_keyword(keywords::Fn) {
7150 let fn_span = self.prev_span;
7151 let (ident, item_, extra_attrs) =
7152 self.parse_item_fn(Unsafety::Normal,
7154 respan(fn_span, Constness::NotConst),
7156 let prev_span = self.prev_span;
7157 let item = self.mk_item(lo.to(prev_span),
7161 maybe_append(attrs, extra_attrs));
7162 return Ok(Some(item));
7164 if self.check_keyword(keywords::Unsafe)
7165 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7166 // UNSAFE FUNCTION ITEM
7167 self.bump(); // `unsafe`
7168 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7169 self.check(&token::OpenDelim(token::Brace));
7170 let abi = if self.eat_keyword(keywords::Extern) {
7171 self.parse_opt_abi()?.unwrap_or(Abi::C)
7175 self.expect_keyword(keywords::Fn)?;
7176 let fn_span = self.prev_span;
7177 let (ident, item_, extra_attrs) =
7178 self.parse_item_fn(Unsafety::Unsafe,
7180 respan(fn_span, Constness::NotConst),
7182 let prev_span = self.prev_span;
7183 let item = self.mk_item(lo.to(prev_span),
7187 maybe_append(attrs, extra_attrs));
7188 return Ok(Some(item));
7190 if self.eat_keyword(keywords::Mod) {
7192 let (ident, item_, extra_attrs) =
7193 self.parse_item_mod(&attrs[..])?;
7194 let prev_span = self.prev_span;
7195 let item = self.mk_item(lo.to(prev_span),
7199 maybe_append(attrs, extra_attrs));
7200 return Ok(Some(item));
7202 if let Some(type_) = self.eat_type() {
7203 let (ident, alias, generics) = type_?;
7205 let item_ = match alias {
7206 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7207 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7209 let prev_span = self.prev_span;
7210 let item = self.mk_item(lo.to(prev_span),
7215 return Ok(Some(item));
7217 if self.eat_keyword(keywords::Enum) {
7219 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7220 let prev_span = self.prev_span;
7221 let item = self.mk_item(lo.to(prev_span),
7225 maybe_append(attrs, extra_attrs));
7226 return Ok(Some(item));
7228 if self.check_keyword(keywords::Trait)
7229 || (self.check_keyword(keywords::Auto)
7230 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7232 let is_auto = if self.eat_keyword(keywords::Trait) {
7235 self.expect_keyword(keywords::Auto)?;
7236 self.expect_keyword(keywords::Trait)?;
7240 let (ident, item_, extra_attrs) =
7241 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7242 let prev_span = self.prev_span;
7243 let item = self.mk_item(lo.to(prev_span),
7247 maybe_append(attrs, extra_attrs));
7248 return Ok(Some(item));
7250 if self.eat_keyword(keywords::Struct) {
7252 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
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.is_union_item() {
7264 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7265 let prev_span = self.prev_span;
7266 let item = self.mk_item(lo.to(prev_span),
7270 maybe_append(attrs, extra_attrs));
7271 return Ok(Some(item));
7273 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7274 return Ok(Some(macro_def));
7277 // Verify whether we have encountered a struct or method definition where the user forgot to
7278 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7279 if visibility.node.is_pub() &&
7280 self.check_ident() &&
7281 self.look_ahead(1, |t| *t != token::Not)
7283 // Space between `pub` keyword and the identifier
7286 // ^^^ `sp` points here
7287 let sp = self.prev_span.between(self.span);
7288 let full_sp = self.prev_span.to(self.span);
7289 let ident_sp = self.span;
7290 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7291 // possible public struct definition where `struct` was forgotten
7292 let ident = self.parse_ident().unwrap();
7293 let msg = format!("add `struct` here to parse `{}` as a public struct",
7295 let mut err = self.diagnostic()
7296 .struct_span_err(sp, "missing `struct` for struct definition");
7297 err.span_suggestion_short_with_applicability(
7298 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7301 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7302 let ident = self.parse_ident().unwrap();
7303 self.consume_block(token::Paren);
7304 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7305 self.check(&token::OpenDelim(token::Brace))
7307 ("fn", "method", false)
7308 } else if self.check(&token::Colon) {
7312 ("fn` or `struct", "method or struct", true)
7315 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7316 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7318 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7322 err.span_suggestion_short_with_applicability(
7323 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7326 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7327 err.span_suggestion_with_applicability(
7329 "if you meant to call a macro, try",
7330 format!("{}!", snippet),
7331 // this is the `ambiguous` conditional branch
7332 Applicability::MaybeIncorrect
7335 err.help("if you meant to call a macro, remove the `pub` \
7336 and add a trailing `!` after the identifier");
7342 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7345 /// Parse a foreign item.
7346 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7347 maybe_whole!(self, NtForeignItem, |ni| ni);
7349 let attrs = self.parse_outer_attributes()?;
7351 let visibility = self.parse_visibility(false)?;
7353 // FOREIGN STATIC ITEM
7354 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7355 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7356 if self.token.is_keyword(keywords::Const) {
7358 .struct_span_err(self.span, "extern items cannot be `const`")
7359 .span_suggestion_with_applicability(
7361 "try using a static value",
7362 "static".to_owned(),
7363 Applicability::MachineApplicable
7366 self.bump(); // `static` or `const`
7367 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7369 // FOREIGN FUNCTION ITEM
7370 if self.check_keyword(keywords::Fn) {
7371 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7373 // FOREIGN TYPE ITEM
7374 if self.check_keyword(keywords::Type) {
7375 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7378 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7382 ident: keywords::Invalid.ident(),
7383 span: lo.to(self.prev_span),
7384 id: ast::DUMMY_NODE_ID,
7387 node: ForeignItemKind::Macro(mac),
7392 if !attrs.is_empty() {
7393 self.expected_item_err(&attrs);
7401 /// This is the fall-through for parsing items.
7402 fn parse_macro_use_or_failure(
7404 attrs: Vec<Attribute> ,
7405 macros_allowed: bool,
7406 attributes_allowed: bool,
7408 visibility: Visibility
7409 ) -> PResult<'a, Option<P<Item>>> {
7410 if macros_allowed && self.token.is_path_start() {
7411 // MACRO INVOCATION ITEM
7413 let prev_span = self.prev_span;
7414 self.complain_if_pub_macro(&visibility.node, prev_span);
7416 let mac_lo = self.span;
7419 let pth = self.parse_path(PathStyle::Mod)?;
7420 self.expect(&token::Not)?;
7422 // a 'special' identifier (like what `macro_rules!` uses)
7423 // is optional. We should eventually unify invoc syntax
7425 let id = if self.token.is_ident() {
7428 keywords::Invalid.ident() // no special identifier
7430 // eat a matched-delimiter token tree:
7431 let (delim, tts) = self.expect_delimited_token_tree()?;
7432 if delim != MacDelimiter::Brace {
7433 if !self.eat(&token::Semi) {
7434 self.span_err(self.prev_span,
7435 "macros that expand to items must either \
7436 be surrounded with braces or followed by \
7441 let hi = self.prev_span;
7442 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7443 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7444 return Ok(Some(item));
7447 // FAILURE TO PARSE ITEM
7448 match visibility.node {
7449 VisibilityKind::Inherited => {}
7451 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7455 if !attributes_allowed && !attrs.is_empty() {
7456 self.expected_item_err(&attrs);
7461 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7462 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7463 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7465 if self.token.is_path_start() && !self.is_extern_non_path() {
7466 let prev_span = self.prev_span;
7468 let pth = self.parse_path(PathStyle::Mod)?;
7470 if pth.segments.len() == 1 {
7471 if !self.eat(&token::Not) {
7472 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7475 self.expect(&token::Not)?;
7478 if let Some(vis) = vis {
7479 self.complain_if_pub_macro(&vis.node, prev_span);
7484 // eat a matched-delimiter token tree:
7485 let (delim, tts) = self.expect_delimited_token_tree()?;
7486 if delim != MacDelimiter::Brace {
7487 self.expect(&token::Semi)?
7490 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7496 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7497 where F: FnOnce(&mut Self) -> PResult<'a, R>
7499 // Record all tokens we parse when parsing this item.
7500 let mut tokens = Vec::new();
7501 let prev_collecting = match self.token_cursor.frame.last_token {
7502 LastToken::Collecting(ref mut list) => {
7503 Some(mem::replace(list, Vec::new()))
7505 LastToken::Was(ref mut last) => {
7506 tokens.extend(last.take());
7510 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7511 let prev = self.token_cursor.stack.len();
7513 let last_token = if self.token_cursor.stack.len() == prev {
7514 &mut self.token_cursor.frame.last_token
7516 &mut self.token_cursor.stack[prev].last_token
7519 // Pull our the toekns that we've collected from the call to `f` above
7520 let mut collected_tokens = match *last_token {
7521 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7522 LastToken::Was(_) => panic!("our vector went away?"),
7525 // If we're not at EOF our current token wasn't actually consumed by
7526 // `f`, but it'll still be in our list that we pulled out. In that case
7528 let extra_token = if self.token != token::Eof {
7529 collected_tokens.pop()
7534 // If we were previously collecting tokens, then this was a recursive
7535 // call. In that case we need to record all the tokens we collected in
7536 // our parent list as well. To do that we push a clone of our stream
7537 // onto the previous list.
7538 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7539 match prev_collecting {
7541 list.push(stream.clone());
7542 list.extend(extra_token);
7543 *last_token = LastToken::Collecting(list);
7546 *last_token = LastToken::Was(extra_token);
7553 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7554 let attrs = self.parse_outer_attributes()?;
7555 self.parse_item_(attrs, true, false)
7559 fn is_import_coupler(&mut self) -> bool {
7560 self.check(&token::ModSep) &&
7561 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7562 *t == token::BinOp(token::Star))
7567 /// USE_TREE = [`::`] `*` |
7568 /// [`::`] `{` USE_TREE_LIST `}` |
7570 /// PATH `::` `{` USE_TREE_LIST `}` |
7571 /// PATH [`as` IDENT]
7572 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7575 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7576 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7577 self.check(&token::BinOp(token::Star)) ||
7578 self.is_import_coupler() {
7579 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7580 if self.eat(&token::ModSep) {
7581 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7584 if self.eat(&token::BinOp(token::Star)) {
7587 UseTreeKind::Nested(self.parse_use_tree_list()?)
7590 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7591 prefix = self.parse_path(PathStyle::Mod)?;
7593 if self.eat(&token::ModSep) {
7594 if self.eat(&token::BinOp(token::Star)) {
7597 UseTreeKind::Nested(self.parse_use_tree_list()?)
7600 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7604 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7607 /// Parse UseTreeKind::Nested(list)
7609 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7610 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7611 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7612 &token::CloseDelim(token::Brace),
7613 SeqSep::trailing_allowed(token::Comma), |this| {
7614 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7618 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7619 if self.eat_keyword(keywords::As) {
7621 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7623 Ok(Some(ident.gensym()))
7625 _ => self.parse_ident().map(Some),
7632 /// Parses a source module as a crate. This is the main
7633 /// entry point for the parser.
7634 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7637 attrs: self.parse_inner_attributes()?,
7638 module: self.parse_mod_items(&token::Eof, lo)?,
7639 span: lo.to(self.span),
7643 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7644 let ret = match self.token {
7645 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7646 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7653 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7654 match self.parse_optional_str() {
7655 Some((s, style, suf)) => {
7656 let sp = self.prev_span;
7657 self.expect_no_suffix(sp, "string literal", suf);
7661 let msg = "expected string literal";
7662 let mut err = self.fatal(msg);
7663 err.span_label(self.span, msg);