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",
614 token::DocComment(..) => "doc comment",
619 fn this_token_descr(&self) -> String {
620 if let Some(prefix) = self.token_descr() {
621 format!("{} `{}`", prefix, self.this_token_to_string())
623 format!("`{}`", self.this_token_to_string())
627 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
628 let token_str = pprust::token_to_string(t);
629 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
632 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
633 match self.expect_one_of(&[], &[]) {
635 Ok(_) => unreachable!(),
639 /// Expect and consume the token t. Signal an error if
640 /// the next token is not t.
641 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
642 if self.expected_tokens.is_empty() {
643 if self.token == *t {
647 let token_str = pprust::token_to_string(t);
648 let this_token_str = self.this_token_descr();
649 let mut err = self.fatal(&format!("expected `{}`, found {}",
653 let sp = if self.token == token::Token::Eof {
654 // EOF, don't want to point at the following char, but rather the last token
657 self.sess.source_map().next_point(self.prev_span)
659 let label_exp = format!("expected `{}`", token_str);
660 let cm = self.sess.source_map();
661 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
662 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
663 // When the spans are in the same line, it means that the only content
664 // between them is whitespace, point only at the found token.
665 err.span_label(self.span, label_exp);
668 err.span_label(sp, label_exp);
669 err.span_label(self.span, "unexpected token");
675 self.expect_one_of(slice::from_ref(t), &[])
679 /// Expect next token to be edible or inedible token. If edible,
680 /// then consume it; if inedible, then return without consuming
681 /// anything. Signal a fatal error if next token is unexpected.
682 pub fn expect_one_of(&mut self,
683 edible: &[token::Token],
684 inedible: &[token::Token]) -> PResult<'a, ()>{
685 fn tokens_to_string(tokens: &[TokenType]) -> String {
686 let mut i = tokens.iter();
687 // This might be a sign we need a connect method on Iterator.
689 .map_or(String::new(), |t| t.to_string());
690 i.enumerate().fold(b, |mut b, (i, a)| {
691 if tokens.len() > 2 && i == tokens.len() - 2 {
693 } else if tokens.len() == 2 && i == tokens.len() - 2 {
698 b.push_str(&a.to_string());
702 if edible.contains(&self.token) {
705 } else if inedible.contains(&self.token) {
706 // leave it in the input
709 let mut expected = edible.iter()
710 .map(|x| TokenType::Token(x.clone()))
711 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
712 .chain(self.expected_tokens.iter().cloned())
713 .collect::<Vec<_>>();
714 expected.sort_by_cached_key(|x| x.to_string());
716 let expect = tokens_to_string(&expected[..]);
717 let actual = self.this_token_to_string();
718 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
719 let short_expect = if expected.len() > 6 {
720 format!("{} possible tokens", expected.len())
724 (format!("expected one of {}, found `{}`", expect, actual),
725 (self.sess.source_map().next_point(self.prev_span),
726 format!("expected one of {} here", short_expect)))
727 } else if expected.is_empty() {
728 (format!("unexpected token: `{}`", actual),
729 (self.prev_span, "unexpected token after this".to_string()))
731 (format!("expected {}, found `{}`", expect, actual),
732 (self.sess.source_map().next_point(self.prev_span),
733 format!("expected {} here", expect)))
735 let mut err = self.fatal(&msg_exp);
736 if self.token.is_ident_named("and") {
737 err.span_suggestion_short_with_applicability(
739 "use `&&` instead of `and` for the boolean operator",
741 Applicability::MaybeIncorrect,
744 if self.token.is_ident_named("or") {
745 err.span_suggestion_short_with_applicability(
747 "use `||` instead of `or` for the boolean operator",
749 Applicability::MaybeIncorrect,
752 let sp = if self.token == token::Token::Eof {
753 // This is EOF, don't want to point at the following char, but rather the last token
759 let cm = self.sess.source_map();
760 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
761 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
762 // When the spans are in the same line, it means that the only content between
763 // them is whitespace, point at the found token in that case:
765 // X | () => { syntax error };
766 // | ^^^^^ expected one of 8 possible tokens here
768 // instead of having:
770 // X | () => { syntax error };
771 // | -^^^^^ unexpected token
773 // | expected one of 8 possible tokens here
774 err.span_label(self.span, label_exp);
776 _ if self.prev_span == syntax_pos::DUMMY_SP => {
777 // Account for macro context where the previous span might not be
778 // available to avoid incorrect output (#54841).
779 err.span_label(self.span, "unexpected token");
782 err.span_label(sp, label_exp);
783 err.span_label(self.span, "unexpected token");
790 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
791 fn interpolated_or_expr_span(&self,
792 expr: PResult<'a, P<Expr>>)
793 -> PResult<'a, (Span, P<Expr>)> {
795 if self.prev_token_kind == PrevTokenKind::Interpolated {
803 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
804 let mut err = self.struct_span_err(self.span,
805 &format!("expected identifier, found {}",
806 self.this_token_descr()));
807 if let Some(token_descr) = self.token_descr() {
808 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
810 err.span_label(self.span, "expected identifier");
811 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
812 err.span_suggestion_with_applicability(
816 Applicability::MachineApplicable,
823 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
824 self.parse_ident_common(true)
827 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
829 token::Ident(ident, _) => {
830 if self.token.is_reserved_ident() {
831 let mut err = self.expected_ident_found();
838 let span = self.span;
840 Ok(Ident::new(ident.name, span))
843 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
844 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
846 self.expected_ident_found()
852 /// Check if the next token is `tok`, and return `true` if so.
854 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
856 crate fn check(&mut self, tok: &token::Token) -> bool {
857 let is_present = self.token == *tok;
858 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
862 /// Consume token 'tok' if it exists. Returns true if the given
863 /// token was present, false otherwise.
864 pub fn eat(&mut self, tok: &token::Token) -> bool {
865 let is_present = self.check(tok);
866 if is_present { self.bump() }
870 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
871 self.expected_tokens.push(TokenType::Keyword(kw));
872 self.token.is_keyword(kw)
875 /// If the next token is the given keyword, eat it and return
876 /// true. Otherwise, return false.
877 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
878 if self.check_keyword(kw) {
886 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
887 if self.token.is_keyword(kw) {
895 /// If the given word is not a keyword, signal an error.
896 /// If the next token is not the given word, signal an error.
897 /// Otherwise, eat it.
898 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
899 if !self.eat_keyword(kw) {
906 fn check_ident(&mut self) -> bool {
907 if self.token.is_ident() {
910 self.expected_tokens.push(TokenType::Ident);
915 fn check_path(&mut self) -> bool {
916 if self.token.is_path_start() {
919 self.expected_tokens.push(TokenType::Path);
924 fn check_type(&mut self) -> bool {
925 if self.token.can_begin_type() {
928 self.expected_tokens.push(TokenType::Type);
933 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
934 /// and continue. If a `+` is not seen, return false.
936 /// This is using when token splitting += into +.
937 /// See issue 47856 for an example of when this may occur.
938 fn eat_plus(&mut self) -> bool {
939 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
941 token::BinOp(token::Plus) => {
945 token::BinOpEq(token::Plus) => {
946 let span = self.span.with_lo(self.span.lo() + BytePos(1));
947 self.bump_with(token::Eq, span);
955 /// Checks to see if the next token is either `+` or `+=`.
956 /// Otherwise returns false.
957 fn check_plus(&mut self) -> bool {
958 if self.token.is_like_plus() {
962 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
967 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
968 /// `&` and continue. If an `&` is not seen, signal an error.
969 fn expect_and(&mut self) -> PResult<'a, ()> {
970 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
972 token::BinOp(token::And) => {
977 let span = self.span.with_lo(self.span.lo() + BytePos(1));
978 Ok(self.bump_with(token::BinOp(token::And), span))
980 _ => self.unexpected()
984 /// Expect and consume an `|`. If `||` is seen, replace it with a single
985 /// `|` and continue. If an `|` is not seen, signal an error.
986 fn expect_or(&mut self) -> PResult<'a, ()> {
987 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
989 token::BinOp(token::Or) => {
994 let span = self.span.with_lo(self.span.lo() + BytePos(1));
995 Ok(self.bump_with(token::BinOp(token::Or), span))
997 _ => self.unexpected()
1001 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1003 None => {/* everything ok */}
1005 let text = suf.as_str();
1006 if text.is_empty() {
1007 self.span_bug(sp, "found empty literal suffix in Some")
1009 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
1014 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
1015 /// `<` and continue. If a `<` is not seen, return false.
1017 /// This is meant to be used when parsing generics on a path to get the
1019 fn eat_lt(&mut self) -> bool {
1020 self.expected_tokens.push(TokenType::Token(token::Lt));
1026 token::BinOp(token::Shl) => {
1027 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1028 self.bump_with(token::Lt, span);
1035 fn expect_lt(&mut self) -> PResult<'a, ()> {
1043 /// Expect and consume a GT. if a >> is seen, replace it
1044 /// with a single > and continue. If a GT is not seen,
1045 /// signal an error.
1046 fn expect_gt(&mut self) -> PResult<'a, ()> {
1047 self.expected_tokens.push(TokenType::Token(token::Gt));
1053 token::BinOp(token::Shr) => {
1054 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1055 Ok(self.bump_with(token::Gt, span))
1057 token::BinOpEq(token::Shr) => {
1058 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1059 Ok(self.bump_with(token::Ge, span))
1062 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1063 Ok(self.bump_with(token::Eq, span))
1065 _ => self.unexpected()
1069 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1070 /// passes through any errors encountered. Used for error recovery.
1071 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1072 let handler = self.diagnostic();
1074 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1076 TokenExpectType::Expect,
1077 |p| Ok(p.parse_token_tree())) {
1078 handler.cancel(err);
1082 /// Parse a sequence, including the closing delimiter. The function
1083 /// f must consume tokens until reaching the next separator or
1084 /// closing bracket.
1085 pub fn parse_seq_to_end<T, F>(&mut self,
1089 -> PResult<'a, Vec<T>> where
1090 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1092 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1097 /// Parse a sequence, not including the closing delimiter. The function
1098 /// f must consume tokens until reaching the next separator or
1099 /// closing bracket.
1100 pub fn parse_seq_to_before_end<T, F>(&mut self,
1104 -> PResult<'a, Vec<T>>
1105 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1107 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1110 fn parse_seq_to_before_tokens<T, F>(
1112 kets: &[&token::Token],
1114 expect: TokenExpectType,
1116 ) -> PResult<'a, Vec<T>>
1117 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1119 let mut first: bool = true;
1121 while !kets.iter().any(|k| {
1123 TokenExpectType::Expect => self.check(k),
1124 TokenExpectType::NoExpect => self.token == **k,
1128 token::CloseDelim(..) | token::Eof => break,
1131 if let Some(ref t) = sep.sep {
1135 if let Err(mut e) = self.expect(t) {
1136 // Attempt to keep parsing if it was a similar separator
1137 if let Some(ref tokens) = t.similar_tokens() {
1138 if tokens.contains(&self.token) {
1143 // Attempt to keep parsing if it was an omitted separator
1157 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1159 TokenExpectType::Expect => self.check(k),
1160 TokenExpectType::NoExpect => self.token == **k,
1173 /// Parse a sequence, including the closing delimiter. The function
1174 /// f must consume tokens until reaching the next separator or
1175 /// closing bracket.
1176 fn parse_unspanned_seq<T, F>(&mut self,
1181 -> PResult<'a, Vec<T>> where
1182 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1185 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1190 /// Advance the parser by one token
1191 pub fn bump(&mut self) {
1192 if self.prev_token_kind == PrevTokenKind::Eof {
1193 // Bumping after EOF is a bad sign, usually an infinite loop.
1194 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1197 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1199 // Record last token kind for possible error recovery.
1200 self.prev_token_kind = match self.token {
1201 token::DocComment(..) => PrevTokenKind::DocComment,
1202 token::Comma => PrevTokenKind::Comma,
1203 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1204 token::Interpolated(..) => PrevTokenKind::Interpolated,
1205 token::Eof => PrevTokenKind::Eof,
1206 token::Ident(..) => PrevTokenKind::Ident,
1207 _ => PrevTokenKind::Other,
1210 let next = self.next_tok();
1211 self.span = next.sp;
1212 self.token = next.tok;
1213 self.expected_tokens.clear();
1214 // check after each token
1215 self.process_potential_macro_variable();
1218 /// Advance the parser using provided token as a next one. Use this when
1219 /// consuming a part of a token. For example a single `<` from `<<`.
1220 fn bump_with(&mut self, next: token::Token, span: Span) {
1221 self.prev_span = self.span.with_hi(span.lo());
1222 // It would be incorrect to record the kind of the current token, but
1223 // fortunately for tokens currently using `bump_with`, the
1224 // prev_token_kind will be of no use anyway.
1225 self.prev_token_kind = PrevTokenKind::Other;
1228 self.expected_tokens.clear();
1231 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1232 F: FnOnce(&token::Token) -> R,
1235 return f(&self.token)
1238 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1239 Some(tree) => match tree {
1240 TokenTree::Token(_, tok) => tok,
1241 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1243 None => token::CloseDelim(self.token_cursor.frame.delim),
1247 fn look_ahead_span(&self, dist: usize) -> Span {
1252 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1253 Some(TokenTree::Token(span, _)) => span,
1254 Some(TokenTree::Delimited(span, _)) => span.entire(),
1255 None => self.look_ahead_span(dist - 1),
1258 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1259 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1261 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1262 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1264 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1265 err.span_err(sp, self.diagnostic())
1267 fn bug(&self, m: &str) -> ! {
1268 self.sess.span_diagnostic.span_bug(self.span, m)
1270 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1271 self.sess.span_diagnostic.span_err(sp, m)
1273 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1274 self.sess.span_diagnostic.struct_span_err(sp, m)
1276 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1277 self.sess.span_diagnostic.span_bug(sp, m)
1279 crate fn abort_if_errors(&self) {
1280 self.sess.span_diagnostic.abort_if_errors();
1283 fn cancel(&self, err: &mut DiagnosticBuilder) {
1284 self.sess.span_diagnostic.cancel(err)
1287 crate fn diagnostic(&self) -> &'a errors::Handler {
1288 &self.sess.span_diagnostic
1291 /// Is the current token one of the keywords that signals a bare function
1293 fn token_is_bare_fn_keyword(&mut self) -> bool {
1294 self.check_keyword(keywords::Fn) ||
1295 self.check_keyword(keywords::Unsafe) ||
1296 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1299 /// parse a `TyKind::BareFn` type:
1300 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1303 [unsafe] [extern "ABI"] fn (S) -> T
1313 let unsafety = self.parse_unsafety();
1314 let abi = if self.eat_keyword(keywords::Extern) {
1315 self.parse_opt_abi()?.unwrap_or(Abi::C)
1320 self.expect_keyword(keywords::Fn)?;
1321 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1322 let ret_ty = self.parse_ret_ty(false)?;
1323 let decl = P(FnDecl {
1328 Ok(TyKind::BareFn(P(BareFnTy {
1336 /// Parse asyncness: `async` or nothing
1337 fn parse_asyncness(&mut self) -> IsAsync {
1338 if self.eat_keyword(keywords::Async) {
1340 closure_id: ast::DUMMY_NODE_ID,
1341 return_impl_trait_id: ast::DUMMY_NODE_ID,
1348 /// Parse unsafety: `unsafe` or nothing.
1349 fn parse_unsafety(&mut self) -> Unsafety {
1350 if self.eat_keyword(keywords::Unsafe) {
1357 /// Parse the items in a trait declaration
1358 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1359 maybe_whole!(self, NtTraitItem, |x| x);
1360 let attrs = self.parse_outer_attributes()?;
1361 let (mut item, tokens) = self.collect_tokens(|this| {
1362 this.parse_trait_item_(at_end, attrs)
1364 // See `parse_item` for why this clause is here.
1365 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1366 item.tokens = Some(tokens);
1371 fn parse_trait_item_(&mut self,
1373 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1376 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1377 self.parse_trait_item_assoc_ty()?
1378 } else if self.is_const_item() {
1379 self.expect_keyword(keywords::Const)?;
1380 let ident = self.parse_ident()?;
1381 self.expect(&token::Colon)?;
1382 let ty = self.parse_ty()?;
1383 let default = if self.eat(&token::Eq) {
1384 let expr = self.parse_expr()?;
1385 self.expect(&token::Semi)?;
1388 self.expect(&token::Semi)?;
1391 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1392 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1393 // trait item macro.
1394 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1396 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1398 let ident = self.parse_ident()?;
1399 let mut generics = self.parse_generics()?;
1401 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1402 // This is somewhat dubious; We don't want to allow
1403 // argument names to be left off if there is a
1406 // We don't allow argument names to be left off in edition 2018.
1407 if p.span.edition() >= Edition::Edition2018 {
1408 p.parse_arg_general(true)
1410 p.parse_arg_general(false)
1413 generics.where_clause = self.parse_where_clause()?;
1415 let sig = ast::MethodSig {
1425 let body = match self.token {
1429 debug!("parse_trait_methods(): parsing required method");
1432 token::OpenDelim(token::Brace) => {
1433 debug!("parse_trait_methods(): parsing provided method");
1435 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1436 attrs.extend(inner_attrs.iter().cloned());
1439 token::Interpolated(ref nt) => {
1441 token::NtBlock(..) => {
1443 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1444 attrs.extend(inner_attrs.iter().cloned());
1448 let token_str = self.this_token_descr();
1449 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1451 err.span_label(self.span, "expected `;` or `{`");
1457 let token_str = self.this_token_descr();
1458 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1460 err.span_label(self.span, "expected `;` or `{`");
1464 (ident, ast::TraitItemKind::Method(sig, body), generics)
1468 id: ast::DUMMY_NODE_ID,
1473 span: lo.to(self.prev_span),
1478 /// Parse optional return type [ -> TY ] in function decl
1479 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1480 if self.eat(&token::RArrow) {
1481 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1483 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1488 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1489 self.parse_ty_common(true, true)
1492 /// Parse a type in restricted contexts where `+` is not permitted.
1493 /// Example 1: `&'a TYPE`
1494 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1495 /// Example 2: `value1 as TYPE + value2`
1496 /// `+` is prohibited to avoid interactions with expression grammar.
1497 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1498 self.parse_ty_common(false, true)
1501 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1502 -> PResult<'a, P<Ty>> {
1503 maybe_whole!(self, NtTy, |x| x);
1506 let mut impl_dyn_multi = false;
1507 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1508 // `(TYPE)` is a parenthesized type.
1509 // `(TYPE,)` is a tuple with a single field of type TYPE.
1510 let mut ts = vec![];
1511 let mut last_comma = false;
1512 while self.token != token::CloseDelim(token::Paren) {
1513 ts.push(self.parse_ty()?);
1514 if self.eat(&token::Comma) {
1521 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1522 self.expect(&token::CloseDelim(token::Paren))?;
1524 if ts.len() == 1 && !last_comma {
1525 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1526 let maybe_bounds = allow_plus && self.token.is_like_plus();
1528 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1529 TyKind::Path(None, ref path) if maybe_bounds => {
1530 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1532 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1533 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1534 let path = match bounds[0] {
1535 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1536 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1538 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1541 _ => TyKind::Paren(P(ty))
1546 } else if self.eat(&token::Not) {
1549 } else if self.eat(&token::BinOp(token::Star)) {
1551 TyKind::Ptr(self.parse_ptr()?)
1552 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1554 let t = self.parse_ty()?;
1555 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1556 let t = match self.maybe_parse_fixed_length_of_vec()? {
1557 None => TyKind::Slice(t),
1558 Some(length) => TyKind::Array(t, AnonConst {
1559 id: ast::DUMMY_NODE_ID,
1563 self.expect(&token::CloseDelim(token::Bracket))?;
1565 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1568 self.parse_borrowed_pointee()?
1569 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1571 // In order to not be ambiguous, the type must be surrounded by parens.
1572 self.expect(&token::OpenDelim(token::Paren))?;
1574 id: ast::DUMMY_NODE_ID,
1575 value: self.parse_expr()?,
1577 self.expect(&token::CloseDelim(token::Paren))?;
1579 } else if self.eat_keyword(keywords::Underscore) {
1580 // A type to be inferred `_`
1582 } else if self.token_is_bare_fn_keyword() {
1583 // Function pointer type
1584 self.parse_ty_bare_fn(Vec::new())?
1585 } else if self.check_keyword(keywords::For) {
1586 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1587 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1588 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1590 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1591 if self.token_is_bare_fn_keyword() {
1592 self.parse_ty_bare_fn(lifetime_defs)?
1594 let path = self.parse_path(PathStyle::Type)?;
1595 let parse_plus = allow_plus && self.check_plus();
1596 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1598 } else if self.eat_keyword(keywords::Impl) {
1599 // Always parse bounds greedily for better error recovery.
1600 let bounds = self.parse_generic_bounds()?;
1601 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1602 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1603 } else if self.check_keyword(keywords::Dyn) &&
1604 (self.span.edition() == Edition::Edition2018 ||
1605 self.look_ahead(1, |t| t.can_begin_bound() &&
1606 !can_continue_type_after_non_fn_ident(t))) {
1607 self.bump(); // `dyn`
1608 // Always parse bounds greedily for better error recovery.
1609 let bounds = self.parse_generic_bounds()?;
1610 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1611 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1612 } else if self.check(&token::Question) ||
1613 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1614 // Bound list (trait object type)
1615 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1616 TraitObjectSyntax::None)
1617 } else if self.eat_lt() {
1619 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1620 TyKind::Path(Some(qself), path)
1621 } else if self.token.is_path_start() {
1623 let path = self.parse_path(PathStyle::Type)?;
1624 if self.eat(&token::Not) {
1625 // Macro invocation in type position
1626 let (delim, tts) = self.expect_delimited_token_tree()?;
1627 let node = Mac_ { path, tts, delim };
1628 TyKind::Mac(respan(lo.to(self.prev_span), node))
1630 // Just a type path or bound list (trait object type) starting with a trait.
1632 // `Trait1 + Trait2 + 'a`
1633 if allow_plus && self.check_plus() {
1634 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1636 TyKind::Path(None, path)
1640 let msg = format!("expected type, found {}", self.this_token_descr());
1641 return Err(self.fatal(&msg));
1644 let span = lo.to(self.prev_span);
1645 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1647 // Try to recover from use of `+` with incorrect priority.
1648 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1649 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1650 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1655 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1656 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1657 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1658 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1660 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1661 bounds.append(&mut self.parse_generic_bounds()?);
1663 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1666 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1667 if !allow_plus && impl_dyn_multi {
1668 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1669 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1670 .span_suggestion_with_applicability(
1672 "use parentheses to disambiguate",
1674 Applicability::MachineApplicable
1679 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1680 // Do not add `+` to expected tokens.
1681 if !allow_plus || !self.token.is_like_plus() {
1686 let bounds = self.parse_generic_bounds()?;
1687 let sum_span = ty.span.to(self.prev_span);
1689 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1690 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1693 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1694 let sum_with_parens = pprust::to_string(|s| {
1695 use print::pprust::PrintState;
1698 s.print_opt_lifetime(lifetime)?;
1699 s.print_mutability(mut_ty.mutbl)?;
1701 s.print_type(&mut_ty.ty)?;
1702 s.print_type_bounds(" +", &bounds)?;
1705 err.span_suggestion_with_applicability(
1707 "try adding parentheses",
1709 Applicability::MachineApplicable
1712 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1713 err.span_label(sum_span, "perhaps you forgot parentheses?");
1716 err.span_label(sum_span, "expected a path");
1723 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1724 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1726 // Do not add `::` to expected tokens.
1727 if !allow_recovery || self.token != token::ModSep {
1730 let ty = match base.to_ty() {
1732 None => return Ok(base),
1735 self.bump(); // `::`
1736 let mut segments = Vec::new();
1737 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1739 let span = ty.span.to(self.prev_span);
1740 let path_span = span.to(span); // use an empty path since `position` == 0
1741 let recovered = base.to_recovered(
1742 Some(QSelf { ty, path_span, position: 0 }),
1743 ast::Path { segments, span },
1747 .struct_span_err(span, "missing angle brackets in associated item path")
1748 .span_suggestion_with_applicability( // this is a best-effort recovery
1749 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1755 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1756 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1757 let mutbl = self.parse_mutability();
1758 let ty = self.parse_ty_no_plus()?;
1759 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1762 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1763 let mutbl = if self.eat_keyword(keywords::Mut) {
1765 } else if self.eat_keyword(keywords::Const) {
1766 Mutability::Immutable
1768 let span = self.prev_span;
1770 "expected mut or const in raw pointer type (use \
1771 `*mut T` or `*const T` as appropriate)");
1772 Mutability::Immutable
1774 let t = self.parse_ty_no_plus()?;
1775 Ok(MutTy { ty: t, mutbl: mutbl })
1778 fn is_named_argument(&mut self) -> bool {
1779 let offset = match self.token {
1780 token::Interpolated(ref nt) => match nt.0 {
1781 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1784 token::BinOp(token::And) | token::AndAnd => 1,
1785 _ if self.token.is_keyword(keywords::Mut) => 1,
1789 self.look_ahead(offset, |t| t.is_ident()) &&
1790 self.look_ahead(offset + 1, |t| t == &token::Colon)
1793 /// Skip unexpected attributes and doc comments in this position and emit an appropriate error.
1794 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1795 if let token::DocComment(_) = self.token {
1796 let mut err = self.diagnostic().struct_span_err(
1798 &format!("documentation comments cannot be applied to {}", applied_to),
1800 err.span_label(self.span, "doc comments are not allowed here");
1803 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1804 *t == token::OpenDelim(token::Bracket)
1807 // Skip every token until next possible arg.
1808 while self.token != token::CloseDelim(token::Bracket) {
1811 let sp = lo.to(self.span);
1813 let mut err = self.diagnostic().struct_span_err(
1815 &format!("attributes cannot be applied to {}", applied_to),
1817 err.span_label(sp, "attributes are not allowed here");
1822 /// This version of parse arg doesn't necessarily require
1823 /// identifier names.
1824 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1825 maybe_whole!(self, NtArg, |x| x);
1827 if let Ok(Some(_)) = self.parse_self_arg() {
1828 let mut err = self.struct_span_err(self.prev_span,
1829 "unexpected `self` argument in function");
1830 err.span_label(self.prev_span,
1831 "`self` is only valid as the first argument of an associated function");
1835 let (pat, ty) = if require_name || self.is_named_argument() {
1836 debug!("parse_arg_general parse_pat (require_name:{})",
1838 self.eat_incorrect_doc_comment("method arguments");
1839 let pat = self.parse_pat(Some("argument name"))?;
1841 if let Err(mut err) = self.expect(&token::Colon) {
1842 // If we find a pattern followed by an identifier, it could be an (incorrect)
1843 // C-style parameter declaration.
1844 if self.check_ident() && self.look_ahead(1, |t| {
1845 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1847 let ident = self.parse_ident().unwrap();
1848 let span = pat.span.with_hi(ident.span.hi());
1850 err.span_suggestion_with_applicability(
1852 "declare the type after the parameter binding",
1853 String::from("<identifier>: <type>"),
1854 Applicability::HasPlaceholders,
1861 self.eat_incorrect_doc_comment("a method argument's type");
1862 (pat, self.parse_ty()?)
1864 debug!("parse_arg_general ident_to_pat");
1865 let parser_snapshot_before_ty = self.clone();
1866 self.eat_incorrect_doc_comment("a method argument's type");
1867 let mut ty = self.parse_ty();
1868 if ty.is_ok() && self.token == token::Colon {
1869 // This wasn't actually a type, but a pattern looking like a type,
1870 // so we are going to rollback and re-parse for recovery.
1871 ty = self.unexpected();
1875 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1877 id: ast::DUMMY_NODE_ID,
1878 node: PatKind::Ident(
1879 BindingMode::ByValue(Mutability::Immutable), ident, None),
1885 // Recover from attempting to parse the argument as a type without pattern.
1887 mem::replace(self, parser_snapshot_before_ty);
1888 let pat = self.parse_pat(Some("argument name"))?;
1889 self.expect(&token::Colon)?;
1890 let ty = self.parse_ty()?;
1892 let mut err = self.diagnostic().struct_span_err_with_code(
1894 "patterns aren't allowed in methods without bodies",
1895 DiagnosticId::Error("E0642".into()),
1897 err.span_suggestion_short_with_applicability(
1899 "give this argument a name or use an underscore to ignore it",
1901 Applicability::MachineApplicable,
1905 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1907 node: PatKind::Wild,
1909 id: ast::DUMMY_NODE_ID
1916 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1919 /// Parse a single function argument
1920 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1921 self.parse_arg_general(true)
1924 /// Parse an argument in a lambda header e.g. |arg, arg|
1925 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1926 let pat = self.parse_pat(Some("argument name"))?;
1927 let t = if self.eat(&token::Colon) {
1931 id: ast::DUMMY_NODE_ID,
1932 node: TyKind::Infer,
1933 span: self.prev_span,
1939 id: ast::DUMMY_NODE_ID
1943 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1944 if self.eat(&token::Semi) {
1945 Ok(Some(self.parse_expr()?))
1951 /// Matches token_lit = LIT_INTEGER | ...
1952 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1953 let out = match self.token {
1954 token::Interpolated(ref nt) => match nt.0 {
1955 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1956 ExprKind::Lit(ref lit) => { lit.node.clone() }
1957 _ => { return self.unexpected_last(&self.token); }
1959 _ => { return self.unexpected_last(&self.token); }
1961 token::Literal(lit, suf) => {
1962 let diag = Some((self.span, &self.sess.span_diagnostic));
1963 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1967 self.expect_no_suffix(sp, lit.literal_name(), suf)
1972 _ => { return self.unexpected_last(&self.token); }
1979 /// Matches lit = true | false | token_lit
1980 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1982 let lit = if self.eat_keyword(keywords::True) {
1984 } else if self.eat_keyword(keywords::False) {
1985 LitKind::Bool(false)
1987 let lit = self.parse_lit_token()?;
1990 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
1993 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1994 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1995 maybe_whole_expr!(self);
1997 let minus_lo = self.span;
1998 let minus_present = self.eat(&token::BinOp(token::Minus));
2000 let literal = self.parse_lit()?;
2001 let hi = self.prev_span;
2002 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2005 let minus_hi = self.prev_span;
2006 let unary = self.mk_unary(UnOp::Neg, expr);
2007 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2013 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2015 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2016 let span = self.span;
2018 Ok(Ident::new(ident.name, span))
2020 _ => self.parse_ident(),
2024 /// Parses qualified path.
2025 /// Assumes that the leading `<` has been parsed already.
2027 /// `qualified_path = <type [as trait_ref]>::path`
2032 /// `<T as U>::F::a<S>` (without disambiguator)
2033 /// `<T as U>::F::a::<S>` (with disambiguator)
2034 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2035 let lo = self.prev_span;
2036 let ty = self.parse_ty()?;
2038 // `path` will contain the prefix of the path up to the `>`,
2039 // if any (e.g., `U` in the `<T as U>::*` examples
2040 // above). `path_span` has the span of that path, or an empty
2041 // span in the case of something like `<T>::Bar`.
2042 let (mut path, path_span);
2043 if self.eat_keyword(keywords::As) {
2044 let path_lo = self.span;
2045 path = self.parse_path(PathStyle::Type)?;
2046 path_span = path_lo.to(self.prev_span);
2048 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2049 path_span = self.span.to(self.span);
2052 self.expect(&token::Gt)?;
2053 self.expect(&token::ModSep)?;
2055 let qself = QSelf { ty, path_span, position: path.segments.len() };
2056 self.parse_path_segments(&mut path.segments, style, true)?;
2058 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2061 /// Parses simple paths.
2063 /// `path = [::] segment+`
2064 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2067 /// `a::b::C<D>` (without disambiguator)
2068 /// `a::b::C::<D>` (with disambiguator)
2069 /// `Fn(Args)` (without disambiguator)
2070 /// `Fn::(Args)` (with disambiguator)
2071 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2072 self.parse_path_common(style, true)
2075 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2076 -> PResult<'a, ast::Path> {
2077 maybe_whole!(self, NtPath, |path| {
2078 if style == PathStyle::Mod &&
2079 path.segments.iter().any(|segment| segment.args.is_some()) {
2080 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2085 let lo = self.meta_var_span.unwrap_or(self.span);
2086 let mut segments = Vec::new();
2087 if self.eat(&token::ModSep) {
2088 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
2090 self.parse_path_segments(&mut segments, style, enable_warning)?;
2092 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2095 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2096 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2097 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2098 let meta_ident = match self.token {
2099 token::Interpolated(ref nt) => match nt.0 {
2100 token::NtMeta(ref meta) => match meta.node {
2101 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2108 if let Some(path) = meta_ident {
2112 self.parse_path(style)
2115 fn parse_path_segments(&mut self,
2116 segments: &mut Vec<PathSegment>,
2118 enable_warning: bool)
2119 -> PResult<'a, ()> {
2121 segments.push(self.parse_path_segment(style, enable_warning)?);
2123 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2129 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2130 -> PResult<'a, PathSegment> {
2131 let ident = self.parse_path_segment_ident()?;
2133 let is_args_start = |token: &token::Token| match *token {
2134 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2137 let check_args_start = |this: &mut Self| {
2138 this.expected_tokens.extend_from_slice(
2139 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2141 is_args_start(&this.token)
2144 Ok(if style == PathStyle::Type && check_args_start(self) ||
2145 style != PathStyle::Mod && self.check(&token::ModSep)
2146 && self.look_ahead(1, |t| is_args_start(t)) {
2147 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2149 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2150 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2151 .span_label(self.prev_span, "try removing `::`").emit();
2154 let args = if self.eat_lt() {
2156 let (args, bindings) = self.parse_generic_args()?;
2158 let span = lo.to(self.prev_span);
2159 AngleBracketedArgs { args, bindings, span }.into()
2163 let inputs = self.parse_seq_to_before_tokens(
2164 &[&token::CloseDelim(token::Paren)],
2165 SeqSep::trailing_allowed(token::Comma),
2166 TokenExpectType::Expect,
2169 let span = lo.to(self.prev_span);
2170 let output = if self.eat(&token::RArrow) {
2171 Some(self.parse_ty_common(false, false)?)
2175 ParenthesisedArgs { inputs, output, span }.into()
2178 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2180 // Generic arguments are not found.
2181 PathSegment::from_ident(ident)
2185 crate fn check_lifetime(&mut self) -> bool {
2186 self.expected_tokens.push(TokenType::Lifetime);
2187 self.token.is_lifetime()
2190 /// Parse single lifetime 'a or panic.
2191 crate fn expect_lifetime(&mut self) -> Lifetime {
2192 if let Some(ident) = self.token.lifetime() {
2193 let span = self.span;
2195 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2197 self.span_bug(self.span, "not a lifetime")
2201 fn eat_label(&mut self) -> Option<Label> {
2202 if let Some(ident) = self.token.lifetime() {
2203 let span = self.span;
2205 Some(Label { ident: Ident::new(ident.name, span) })
2211 /// Parse mutability (`mut` or nothing).
2212 fn parse_mutability(&mut self) -> Mutability {
2213 if self.eat_keyword(keywords::Mut) {
2216 Mutability::Immutable
2220 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2221 if let token::Literal(token::Integer(name), None) = self.token {
2223 Ok(Ident::new(name, self.prev_span))
2225 self.parse_ident_common(false)
2229 /// Parse ident (COLON expr)?
2230 fn parse_field(&mut self) -> PResult<'a, Field> {
2231 let attrs = self.parse_outer_attributes()?;
2234 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2235 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2236 let fieldname = self.parse_field_name()?;
2238 (fieldname, self.parse_expr()?, false)
2240 let fieldname = self.parse_ident_common(false)?;
2242 // Mimic `x: x` for the `x` field shorthand.
2243 let path = ast::Path::from_ident(fieldname);
2244 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2245 (fieldname, expr, true)
2249 span: lo.to(expr.span),
2252 attrs: attrs.into(),
2256 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2257 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2260 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2261 ExprKind::Unary(unop, expr)
2264 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2265 ExprKind::Binary(binop, lhs, rhs)
2268 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2269 ExprKind::Call(f, args)
2272 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2273 ExprKind::Index(expr, idx)
2276 fn mk_range(&mut self,
2277 start: Option<P<Expr>>,
2278 end: Option<P<Expr>>,
2279 limits: RangeLimits)
2280 -> PResult<'a, ast::ExprKind> {
2281 if end.is_none() && limits == RangeLimits::Closed {
2282 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2284 Ok(ExprKind::Range(start, end, limits))
2288 fn mk_assign_op(&mut self, binop: ast::BinOp,
2289 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2290 ExprKind::AssignOp(binop, lhs, rhs)
2293 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2295 id: ast::DUMMY_NODE_ID,
2296 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2302 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2303 let delim = match self.token {
2304 token::OpenDelim(delim) => delim,
2306 let msg = "expected open delimiter";
2307 let mut err = self.fatal(msg);
2308 err.span_label(self.span, msg);
2312 let delimited = match self.parse_token_tree() {
2313 TokenTree::Delimited(_, delimited) => delimited,
2314 _ => unreachable!(),
2316 let delim = match delim {
2317 token::Paren => MacDelimiter::Parenthesis,
2318 token::Bracket => MacDelimiter::Bracket,
2319 token::Brace => MacDelimiter::Brace,
2320 token::NoDelim => self.bug("unexpected no delimiter"),
2322 Ok((delim, delimited.stream().into()))
2325 /// At the bottom (top?) of the precedence hierarchy,
2326 /// parse things like parenthesized exprs,
2327 /// macros, return, etc.
2329 /// NB: This does not parse outer attributes,
2330 /// and is private because it only works
2331 /// correctly if called from parse_dot_or_call_expr().
2332 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2333 maybe_whole_expr!(self);
2335 // Outer attributes are already parsed and will be
2336 // added to the return value after the fact.
2338 // Therefore, prevent sub-parser from parsing
2339 // attributes by giving them a empty "already parsed" list.
2340 let mut attrs = ThinVec::new();
2343 let mut hi = self.span;
2347 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2349 token::OpenDelim(token::Paren) => {
2352 attrs.extend(self.parse_inner_attributes()?);
2354 // (e) is parenthesized e
2355 // (e,) is a tuple with only one field, e
2356 let mut es = vec![];
2357 let mut trailing_comma = false;
2358 while self.token != token::CloseDelim(token::Paren) {
2359 es.push(self.parse_expr()?);
2360 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2361 if self.eat(&token::Comma) {
2362 trailing_comma = true;
2364 trailing_comma = false;
2370 hi = self.prev_span;
2371 ex = if es.len() == 1 && !trailing_comma {
2372 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2377 token::OpenDelim(token::Brace) => {
2378 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2380 token::BinOp(token::Or) | token::OrOr => {
2381 return self.parse_lambda_expr(attrs);
2383 token::OpenDelim(token::Bracket) => {
2386 attrs.extend(self.parse_inner_attributes()?);
2388 if self.eat(&token::CloseDelim(token::Bracket)) {
2390 ex = ExprKind::Array(Vec::new());
2393 let first_expr = self.parse_expr()?;
2394 if self.eat(&token::Semi) {
2395 // Repeating array syntax: [ 0; 512 ]
2396 let count = AnonConst {
2397 id: ast::DUMMY_NODE_ID,
2398 value: self.parse_expr()?,
2400 self.expect(&token::CloseDelim(token::Bracket))?;
2401 ex = ExprKind::Repeat(first_expr, count);
2402 } else if self.eat(&token::Comma) {
2403 // Vector with two or more elements.
2404 let remaining_exprs = self.parse_seq_to_end(
2405 &token::CloseDelim(token::Bracket),
2406 SeqSep::trailing_allowed(token::Comma),
2407 |p| Ok(p.parse_expr()?)
2409 let mut exprs = vec![first_expr];
2410 exprs.extend(remaining_exprs);
2411 ex = ExprKind::Array(exprs);
2413 // Vector with one element.
2414 self.expect(&token::CloseDelim(token::Bracket))?;
2415 ex = ExprKind::Array(vec![first_expr]);
2418 hi = self.prev_span;
2422 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2424 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2426 if self.span.edition() >= Edition::Edition2018 &&
2427 self.check_keyword(keywords::Async)
2429 if self.is_async_block() { // check for `async {` and `async move {`
2430 return self.parse_async_block(attrs);
2432 return self.parse_lambda_expr(attrs);
2435 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2436 return self.parse_lambda_expr(attrs);
2438 if self.eat_keyword(keywords::If) {
2439 return self.parse_if_expr(attrs);
2441 if self.eat_keyword(keywords::For) {
2442 let lo = self.prev_span;
2443 return self.parse_for_expr(None, lo, attrs);
2445 if self.eat_keyword(keywords::While) {
2446 let lo = self.prev_span;
2447 return self.parse_while_expr(None, lo, attrs);
2449 if let Some(label) = self.eat_label() {
2450 let lo = label.ident.span;
2451 self.expect(&token::Colon)?;
2452 if self.eat_keyword(keywords::While) {
2453 return self.parse_while_expr(Some(label), lo, attrs)
2455 if self.eat_keyword(keywords::For) {
2456 return self.parse_for_expr(Some(label), lo, attrs)
2458 if self.eat_keyword(keywords::Loop) {
2459 return self.parse_loop_expr(Some(label), lo, attrs)
2461 if self.token == token::OpenDelim(token::Brace) {
2462 return self.parse_block_expr(Some(label),
2464 BlockCheckMode::Default,
2467 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2468 let mut err = self.fatal(msg);
2469 err.span_label(self.span, msg);
2472 if self.eat_keyword(keywords::Loop) {
2473 let lo = self.prev_span;
2474 return self.parse_loop_expr(None, lo, attrs);
2476 if self.eat_keyword(keywords::Continue) {
2477 let label = self.eat_label();
2478 let ex = ExprKind::Continue(label);
2479 let hi = self.prev_span;
2480 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2482 if self.eat_keyword(keywords::Match) {
2483 let match_sp = self.prev_span;
2484 return self.parse_match_expr(attrs).map_err(|mut err| {
2485 err.span_label(match_sp, "while parsing this match expression");
2489 if self.eat_keyword(keywords::Unsafe) {
2490 return self.parse_block_expr(
2493 BlockCheckMode::Unsafe(ast::UserProvided),
2496 if self.is_do_catch_block() {
2497 let mut db = self.fatal("found removed `do catch` syntax");
2498 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2501 if self.is_try_block() {
2503 assert!(self.eat_keyword(keywords::Try));
2504 return self.parse_try_block(lo, attrs);
2506 if self.eat_keyword(keywords::Return) {
2507 if self.token.can_begin_expr() {
2508 let e = self.parse_expr()?;
2510 ex = ExprKind::Ret(Some(e));
2512 ex = ExprKind::Ret(None);
2514 } else if self.eat_keyword(keywords::Break) {
2515 let label = self.eat_label();
2516 let e = if self.token.can_begin_expr()
2517 && !(self.token == token::OpenDelim(token::Brace)
2518 && self.restrictions.contains(
2519 Restrictions::NO_STRUCT_LITERAL)) {
2520 Some(self.parse_expr()?)
2524 ex = ExprKind::Break(label, e);
2525 hi = self.prev_span;
2526 } else if self.eat_keyword(keywords::Yield) {
2527 if self.token.can_begin_expr() {
2528 let e = self.parse_expr()?;
2530 ex = ExprKind::Yield(Some(e));
2532 ex = ExprKind::Yield(None);
2534 } else if self.token.is_keyword(keywords::Let) {
2535 // Catch this syntax error here, instead of in `parse_ident`, so
2536 // that we can explicitly mention that let is not to be used as an expression
2537 let mut db = self.fatal("expected expression, found statement (`let`)");
2538 db.span_label(self.span, "expected expression");
2539 db.note("variable declaration using `let` is a statement");
2541 } else if self.token.is_path_start() {
2542 let pth = self.parse_path(PathStyle::Expr)?;
2544 // `!`, as an operator, is prefix, so we know this isn't that
2545 if self.eat(&token::Not) {
2546 // MACRO INVOCATION expression
2547 let (delim, tts) = self.expect_delimited_token_tree()?;
2548 let hi = self.prev_span;
2549 let node = Mac_ { path: pth, tts, delim };
2550 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2552 if self.check(&token::OpenDelim(token::Brace)) {
2553 // This is a struct literal, unless we're prohibited
2554 // from parsing struct literals here.
2555 let prohibited = self.restrictions.contains(
2556 Restrictions::NO_STRUCT_LITERAL
2559 return self.parse_struct_expr(lo, pth, attrs);
2564 ex = ExprKind::Path(None, pth);
2566 match self.parse_literal_maybe_minus() {
2569 ex = expr.node.clone();
2572 self.cancel(&mut err);
2573 let msg = format!("expected expression, found {}",
2574 self.this_token_descr());
2575 let mut err = self.fatal(&msg);
2576 err.span_label(self.span, "expected expression");
2584 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2585 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2590 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2591 -> PResult<'a, P<Expr>> {
2592 let struct_sp = lo.to(self.prev_span);
2594 let mut fields = Vec::new();
2595 let mut base = None;
2597 attrs.extend(self.parse_inner_attributes()?);
2599 while self.token != token::CloseDelim(token::Brace) {
2600 if self.eat(&token::DotDot) {
2601 let exp_span = self.prev_span;
2602 match self.parse_expr() {
2608 self.recover_stmt();
2611 if self.token == token::Comma {
2612 let mut err = self.sess.span_diagnostic.mut_span_err(
2613 exp_span.to(self.prev_span),
2614 "cannot use a comma after the base struct",
2616 err.span_suggestion_short_with_applicability(
2618 "remove this comma",
2620 Applicability::MachineApplicable
2622 err.note("the base struct must always be the last field");
2624 self.recover_stmt();
2629 match self.parse_field() {
2630 Ok(f) => fields.push(f),
2632 e.span_label(struct_sp, "while parsing this struct");
2635 // If the next token is a comma, then try to parse
2636 // what comes next as additional fields, rather than
2637 // bailing out until next `}`.
2638 if self.token != token::Comma {
2639 self.recover_stmt();
2645 match self.expect_one_of(&[token::Comma],
2646 &[token::CloseDelim(token::Brace)]) {
2650 self.recover_stmt();
2656 let span = lo.to(self.span);
2657 self.expect(&token::CloseDelim(token::Brace))?;
2658 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2661 fn parse_or_use_outer_attributes(&mut self,
2662 already_parsed_attrs: Option<ThinVec<Attribute>>)
2663 -> PResult<'a, ThinVec<Attribute>> {
2664 if let Some(attrs) = already_parsed_attrs {
2667 self.parse_outer_attributes().map(|a| a.into())
2671 /// Parse a block or unsafe block
2672 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2673 lo: Span, blk_mode: BlockCheckMode,
2674 outer_attrs: ThinVec<Attribute>)
2675 -> PResult<'a, P<Expr>> {
2676 self.expect(&token::OpenDelim(token::Brace))?;
2678 let mut attrs = outer_attrs;
2679 attrs.extend(self.parse_inner_attributes()?);
2681 let blk = self.parse_block_tail(lo, blk_mode)?;
2682 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2685 /// parse a.b or a(13) or a[4] or just a
2686 fn parse_dot_or_call_expr(&mut self,
2687 already_parsed_attrs: Option<ThinVec<Attribute>>)
2688 -> PResult<'a, P<Expr>> {
2689 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2691 let b = self.parse_bottom_expr();
2692 let (span, b) = self.interpolated_or_expr_span(b)?;
2693 self.parse_dot_or_call_expr_with(b, span, attrs)
2696 fn parse_dot_or_call_expr_with(&mut self,
2699 mut attrs: ThinVec<Attribute>)
2700 -> PResult<'a, P<Expr>> {
2701 // Stitch the list of outer attributes onto the return value.
2702 // A little bit ugly, but the best way given the current code
2704 self.parse_dot_or_call_expr_with_(e0, lo)
2706 expr.map(|mut expr| {
2707 attrs.extend::<Vec<_>>(expr.attrs.into());
2710 ExprKind::If(..) | ExprKind::IfLet(..) => {
2711 if !expr.attrs.is_empty() {
2712 // Just point to the first attribute in there...
2713 let span = expr.attrs[0].span;
2716 "attributes are not yet allowed on `if` \
2727 // Assuming we have just parsed `.`, continue parsing into an expression.
2728 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2729 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2730 Ok(match self.token {
2731 token::OpenDelim(token::Paren) => {
2732 // Method call `expr.f()`
2733 let mut args = self.parse_unspanned_seq(
2734 &token::OpenDelim(token::Paren),
2735 &token::CloseDelim(token::Paren),
2736 SeqSep::trailing_allowed(token::Comma),
2737 |p| Ok(p.parse_expr()?)
2739 args.insert(0, self_arg);
2741 let span = lo.to(self.prev_span);
2742 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2745 // Field access `expr.f`
2746 if let Some(args) = segment.args {
2747 self.span_err(args.span(),
2748 "field expressions may not have generic arguments");
2751 let span = lo.to(self.prev_span);
2752 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2757 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2762 while self.eat(&token::Question) {
2763 let hi = self.prev_span;
2764 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2768 if self.eat(&token::Dot) {
2770 token::Ident(..) => {
2771 e = self.parse_dot_suffix(e, lo)?;
2773 token::Literal(token::Integer(name), _) => {
2774 let span = self.span;
2776 let field = ExprKind::Field(e, Ident::new(name, span));
2777 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2779 token::Literal(token::Float(n), _suf) => {
2781 let fstr = n.as_str();
2782 let mut err = self.diagnostic()
2783 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
2784 err.span_label(self.prev_span, "unexpected token");
2785 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2786 let float = match fstr.parse::<f64>().ok() {
2790 let sugg = pprust::to_string(|s| {
2791 use print::pprust::PrintState;
2795 s.print_usize(float.trunc() as usize)?;
2798 s.s.word(fstr.splitn(2, ".").last().unwrap())
2800 err.span_suggestion_with_applicability(
2801 lo.to(self.prev_span),
2802 "try parenthesizing the first index",
2804 Applicability::MachineApplicable
2811 // FIXME Could factor this out into non_fatal_unexpected or something.
2812 let actual = self.this_token_to_string();
2813 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2818 if self.expr_is_complete(&e) { break; }
2821 token::OpenDelim(token::Paren) => {
2822 let es = self.parse_unspanned_seq(
2823 &token::OpenDelim(token::Paren),
2824 &token::CloseDelim(token::Paren),
2825 SeqSep::trailing_allowed(token::Comma),
2826 |p| Ok(p.parse_expr()?)
2828 hi = self.prev_span;
2830 let nd = self.mk_call(e, es);
2831 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2835 // Could be either an index expression or a slicing expression.
2836 token::OpenDelim(token::Bracket) => {
2838 let ix = self.parse_expr()?;
2840 self.expect(&token::CloseDelim(token::Bracket))?;
2841 let index = self.mk_index(e, ix);
2842 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2850 crate fn process_potential_macro_variable(&mut self) {
2851 let (token, span) = match self.token {
2852 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2853 self.look_ahead(1, |t| t.is_ident()) => {
2855 let name = match self.token {
2856 token::Ident(ident, _) => ident,
2859 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2860 err.span_label(self.span, "unknown macro variable");
2864 token::Interpolated(ref nt) => {
2865 self.meta_var_span = Some(self.span);
2866 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2867 // and lifetime tokens, so the former are never encountered during normal parsing.
2869 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2870 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2880 /// parse a single token tree from the input.
2881 crate fn parse_token_tree(&mut self) -> TokenTree {
2883 token::OpenDelim(..) => {
2884 let frame = mem::replace(&mut self.token_cursor.frame,
2885 self.token_cursor.stack.pop().unwrap());
2886 self.span = frame.span.entire();
2888 TokenTree::Delimited(frame.span, Delimited {
2890 tts: frame.tree_cursor.original_stream().into(),
2893 token::CloseDelim(_) | token::Eof => unreachable!(),
2895 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2897 TokenTree::Token(span, token)
2902 // parse a stream of tokens into a list of TokenTree's,
2904 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2905 let mut tts = Vec::new();
2906 while self.token != token::Eof {
2907 tts.push(self.parse_token_tree());
2912 pub fn parse_tokens(&mut self) -> TokenStream {
2913 let mut result = Vec::new();
2916 token::Eof | token::CloseDelim(..) => break,
2917 _ => result.push(self.parse_token_tree().into()),
2920 TokenStream::concat(result)
2923 /// Parse a prefix-unary-operator expr
2924 fn parse_prefix_expr(&mut self,
2925 already_parsed_attrs: Option<ThinVec<Attribute>>)
2926 -> PResult<'a, P<Expr>> {
2927 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2929 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2930 let (hi, ex) = match self.token {
2933 let e = self.parse_prefix_expr(None);
2934 let (span, e) = self.interpolated_or_expr_span(e)?;
2935 (lo.to(span), self.mk_unary(UnOp::Not, e))
2937 // Suggest `!` for bitwise negation when encountering a `~`
2940 let e = self.parse_prefix_expr(None);
2941 let (span, e) = self.interpolated_or_expr_span(e)?;
2942 let span_of_tilde = lo;
2943 let mut err = self.diagnostic()
2944 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2945 err.span_suggestion_short_with_applicability(
2947 "use `!` to perform bitwise negation",
2949 Applicability::MachineApplicable
2952 (lo.to(span), self.mk_unary(UnOp::Not, e))
2954 token::BinOp(token::Minus) => {
2956 let e = self.parse_prefix_expr(None);
2957 let (span, e) = self.interpolated_or_expr_span(e)?;
2958 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2960 token::BinOp(token::Star) => {
2962 let e = self.parse_prefix_expr(None);
2963 let (span, e) = self.interpolated_or_expr_span(e)?;
2964 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2966 token::BinOp(token::And) | token::AndAnd => {
2968 let m = self.parse_mutability();
2969 let e = self.parse_prefix_expr(None);
2970 let (span, e) = self.interpolated_or_expr_span(e)?;
2971 (lo.to(span), ExprKind::AddrOf(m, e))
2973 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2975 let place = self.parse_expr_res(
2976 Restrictions::NO_STRUCT_LITERAL,
2979 let blk = self.parse_block()?;
2980 let span = blk.span;
2981 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2982 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2984 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2986 let e = self.parse_prefix_expr(None);
2987 let (span, e) = self.interpolated_or_expr_span(e)?;
2988 (lo.to(span), ExprKind::Box(e))
2990 token::Ident(..) if self.token.is_ident_named("not") => {
2991 // `not` is just an ordinary identifier in Rust-the-language,
2992 // but as `rustc`-the-compiler, we can issue clever diagnostics
2993 // for confused users who really want to say `!`
2994 let token_cannot_continue_expr = |t: &token::Token| match *t {
2995 // These tokens can start an expression after `!`, but
2996 // can't continue an expression after an ident
2997 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2998 token::Literal(..) | token::Pound => true,
2999 token::Interpolated(ref nt) => match nt.0 {
3000 token::NtIdent(..) | token::NtExpr(..) |
3001 token::NtBlock(..) | token::NtPath(..) => true,
3006 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3007 if cannot_continue_expr {
3009 // Emit the error ...
3010 let mut err = self.diagnostic()
3011 .struct_span_err(self.span,
3012 &format!("unexpected {} after identifier",
3013 self.this_token_descr()));
3014 // span the `not` plus trailing whitespace to avoid
3015 // trailing whitespace after the `!` in our suggestion
3016 let to_replace = self.sess.source_map()
3017 .span_until_non_whitespace(lo.to(self.span));
3018 err.span_suggestion_short_with_applicability(
3020 "use `!` to perform logical negation",
3022 Applicability::MachineApplicable
3025 // —and recover! (just as if we were in the block
3026 // for the `token::Not` arm)
3027 let e = self.parse_prefix_expr(None);
3028 let (span, e) = self.interpolated_or_expr_span(e)?;
3029 (lo.to(span), self.mk_unary(UnOp::Not, e))
3031 return self.parse_dot_or_call_expr(Some(attrs));
3034 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3036 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3039 /// Parse an associative expression
3041 /// This parses an expression accounting for associativity and precedence of the operators in
3043 fn parse_assoc_expr(&mut self,
3044 already_parsed_attrs: Option<ThinVec<Attribute>>)
3045 -> PResult<'a, P<Expr>> {
3046 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3049 /// Parse an associative expression with operators of at least `min_prec` precedence
3050 fn parse_assoc_expr_with(&mut self,
3053 -> PResult<'a, P<Expr>> {
3054 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3057 let attrs = match lhs {
3058 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3061 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3062 return self.parse_prefix_range_expr(attrs);
3064 self.parse_prefix_expr(attrs)?
3068 if self.expr_is_complete(&lhs) {
3069 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3072 self.expected_tokens.push(TokenType::Operator);
3073 while let Some(op) = AssocOp::from_token(&self.token) {
3075 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3076 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3077 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3078 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3079 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3080 (PrevTokenKind::Interpolated, _) => self.prev_span,
3081 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3082 if path.segments.len() == 1 => self.prev_span,
3086 let cur_op_span = self.span;
3087 let restrictions = if op.is_assign_like() {
3088 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3092 if op.precedence() < min_prec {
3095 // Check for deprecated `...` syntax
3096 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3097 self.err_dotdotdot_syntax(self.span);
3101 if op.is_comparison() {
3102 self.check_no_chained_comparison(&lhs, &op);
3105 if op == AssocOp::As {
3106 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3108 } else if op == AssocOp::Colon {
3109 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3112 err.span_label(self.span,
3113 "expecting a type here because of type ascription");
3114 let cm = self.sess.source_map();
3115 let cur_pos = cm.lookup_char_pos(self.span.lo());
3116 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3117 if cur_pos.line != op_pos.line {
3118 err.span_suggestion_with_applicability(
3120 "try using a semicolon",
3122 Applicability::MaybeIncorrect // speculative
3129 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3130 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3131 // generalise it to the Fixity::None code.
3133 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3134 // two variants are handled with `parse_prefix_range_expr` call above.
3135 let rhs = if self.is_at_start_of_range_notation_rhs() {
3136 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3137 LhsExpr::NotYetParsed)?)
3141 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3146 let limits = if op == AssocOp::DotDot {
3147 RangeLimits::HalfOpen
3152 let r = try!(self.mk_range(Some(lhs), rhs, limits));
3153 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3157 let rhs = match op.fixity() {
3158 Fixity::Right => self.with_res(
3159 restrictions - Restrictions::STMT_EXPR,
3161 this.parse_assoc_expr_with(op.precedence(),
3162 LhsExpr::NotYetParsed)
3164 Fixity::Left => self.with_res(
3165 restrictions - Restrictions::STMT_EXPR,
3167 this.parse_assoc_expr_with(op.precedence() + 1,
3168 LhsExpr::NotYetParsed)
3170 // We currently have no non-associative operators that are not handled above by
3171 // the special cases. The code is here only for future convenience.
3172 Fixity::None => self.with_res(
3173 restrictions - Restrictions::STMT_EXPR,
3175 this.parse_assoc_expr_with(op.precedence() + 1,
3176 LhsExpr::NotYetParsed)
3180 let span = lhs_span.to(rhs.span);
3182 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3183 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3184 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3185 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3186 AssocOp::Greater | AssocOp::GreaterEqual => {
3187 let ast_op = op.to_ast_binop().unwrap();
3188 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3189 self.mk_expr(span, binary, ThinVec::new())
3192 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3193 AssocOp::ObsoleteInPlace =>
3194 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3195 AssocOp::AssignOp(k) => {
3197 token::Plus => BinOpKind::Add,
3198 token::Minus => BinOpKind::Sub,
3199 token::Star => BinOpKind::Mul,
3200 token::Slash => BinOpKind::Div,
3201 token::Percent => BinOpKind::Rem,
3202 token::Caret => BinOpKind::BitXor,
3203 token::And => BinOpKind::BitAnd,
3204 token::Or => BinOpKind::BitOr,
3205 token::Shl => BinOpKind::Shl,
3206 token::Shr => BinOpKind::Shr,
3208 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3209 self.mk_expr(span, aopexpr, ThinVec::new())
3211 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3212 self.bug("AssocOp should have been handled by special case")
3216 if op.fixity() == Fixity::None { break }
3221 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3222 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3223 -> PResult<'a, P<Expr>> {
3224 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3225 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3228 // Save the state of the parser before parsing type normally, in case there is a
3229 // LessThan comparison after this cast.
3230 let parser_snapshot_before_type = self.clone();
3231 match self.parse_ty_no_plus() {
3233 Ok(mk_expr(self, rhs))
3235 Err(mut type_err) => {
3236 // Rewind to before attempting to parse the type with generics, to recover
3237 // from situations like `x as usize < y` in which we first tried to parse
3238 // `usize < y` as a type with generic arguments.
3239 let parser_snapshot_after_type = self.clone();
3240 mem::replace(self, parser_snapshot_before_type);
3242 match self.parse_path(PathStyle::Expr) {
3244 let (op_noun, op_verb) = match self.token {
3245 token::Lt => ("comparison", "comparing"),
3246 token::BinOp(token::Shl) => ("shift", "shifting"),
3248 // We can end up here even without `<` being the next token, for
3249 // example because `parse_ty_no_plus` returns `Err` on keywords,
3250 // but `parse_path` returns `Ok` on them due to error recovery.
3251 // Return original error and parser state.
3252 mem::replace(self, parser_snapshot_after_type);
3253 return Err(type_err);
3257 // Successfully parsed the type path leaving a `<` yet to parse.
3260 // Report non-fatal diagnostics, keep `x as usize` as an expression
3261 // in AST and continue parsing.
3262 let msg = format!("`<` is interpreted as a start of generic \
3263 arguments for `{}`, not a {}", path, op_noun);
3264 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3265 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3266 "interpreted as generic arguments");
3267 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3269 let expr = mk_expr(self, P(Ty {
3271 node: TyKind::Path(None, path),
3272 id: ast::DUMMY_NODE_ID
3275 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3276 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3277 err.span_suggestion_with_applicability(
3279 &format!("try {} the cast value", op_verb),
3280 format!("({})", expr_str),
3281 Applicability::MachineApplicable
3287 Err(mut path_err) => {
3288 // Couldn't parse as a path, return original error and parser state.
3290 mem::replace(self, parser_snapshot_after_type);
3298 /// Produce an error if comparison operators are chained (RFC #558).
3299 /// We only need to check lhs, not rhs, because all comparison ops
3300 /// have same precedence and are left-associative
3301 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3302 debug_assert!(outer_op.is_comparison(),
3303 "check_no_chained_comparison: {:?} is not comparison",
3306 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3307 // respan to include both operators
3308 let op_span = op.span.to(self.span);
3309 let mut err = self.diagnostic().struct_span_err(op_span,
3310 "chained comparison operators require parentheses");
3311 if op.node == BinOpKind::Lt &&
3312 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3313 *outer_op == AssocOp::Greater // even in a case like the following:
3314 { // Foo<Bar<Baz<Qux, ()>>>
3316 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3317 err.help("or use `(...)` if you meant to specify fn arguments");
3325 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3326 fn parse_prefix_range_expr(&mut self,
3327 already_parsed_attrs: Option<ThinVec<Attribute>>)
3328 -> PResult<'a, P<Expr>> {
3329 // Check for deprecated `...` syntax
3330 if self.token == token::DotDotDot {
3331 self.err_dotdotdot_syntax(self.span);
3334 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3335 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3337 let tok = self.token.clone();
3338 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3340 let mut hi = self.span;
3342 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3343 // RHS must be parsed with more associativity than the dots.
3344 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3345 Some(self.parse_assoc_expr_with(next_prec,
3346 LhsExpr::NotYetParsed)
3354 let limits = if tok == token::DotDot {
3355 RangeLimits::HalfOpen
3360 let r = try!(self.mk_range(None,
3363 Ok(self.mk_expr(lo.to(hi), r, attrs))
3366 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3367 if self.token.can_begin_expr() {
3368 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3369 if self.token == token::OpenDelim(token::Brace) {
3370 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3378 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3379 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3380 if self.check_keyword(keywords::Let) {
3381 return self.parse_if_let_expr(attrs);
3383 let lo = self.prev_span;
3384 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3386 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3387 // verify that the last statement is either an implicit return (no `;`) or an explicit
3388 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3389 // the dead code lint.
3390 if self.eat_keyword(keywords::Else) || !cond.returns() {
3391 let sp = self.sess.source_map().next_point(lo);
3392 let mut err = self.diagnostic()
3393 .struct_span_err(sp, "missing condition for `if` statemement");
3394 err.span_label(sp, "expected if condition here");
3397 let not_block = self.token != token::OpenDelim(token::Brace);
3398 let thn = self.parse_block().map_err(|mut err| {
3400 err.span_label(lo, "this `if` statement has a condition, but no block");
3404 let mut els: Option<P<Expr>> = None;
3405 let mut hi = thn.span;
3406 if self.eat_keyword(keywords::Else) {
3407 let elexpr = self.parse_else_expr()?;
3411 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3414 /// Parse an 'if let' expression ('if' token already eaten)
3415 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3416 -> PResult<'a, P<Expr>> {
3417 let lo = self.prev_span;
3418 self.expect_keyword(keywords::Let)?;
3419 let pats = self.parse_pats()?;
3420 self.expect(&token::Eq)?;
3421 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3422 let thn = self.parse_block()?;
3423 let (hi, els) = if self.eat_keyword(keywords::Else) {
3424 let expr = self.parse_else_expr()?;
3425 (expr.span, Some(expr))
3429 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3432 // `move |args| expr`
3433 fn parse_lambda_expr(&mut self,
3434 attrs: ThinVec<Attribute>)
3435 -> PResult<'a, P<Expr>>
3438 let movability = if self.eat_keyword(keywords::Static) {
3443 let asyncness = if self.span.edition() >= Edition::Edition2018 {
3444 self.parse_asyncness()
3448 let capture_clause = if self.eat_keyword(keywords::Move) {
3453 let decl = self.parse_fn_block_decl()?;
3454 let decl_hi = self.prev_span;
3455 let body = match decl.output {
3456 FunctionRetTy::Default(_) => {
3457 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3458 self.parse_expr_res(restrictions, None)?
3461 // If an explicit return type is given, require a
3462 // block to appear (RFC 968).
3463 let body_lo = self.span;
3464 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3470 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3474 // `else` token already eaten
3475 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3476 if self.eat_keyword(keywords::If) {
3477 return self.parse_if_expr(ThinVec::new());
3479 let blk = self.parse_block()?;
3480 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3484 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3485 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3487 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3488 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3490 let pat = self.parse_top_level_pat()?;
3491 if !self.eat_keyword(keywords::In) {
3492 let in_span = self.prev_span.between(self.span);
3493 let mut err = self.sess.span_diagnostic
3494 .struct_span_err(in_span, "missing `in` in `for` loop");
3495 err.span_suggestion_short_with_applicability(
3496 in_span, "try adding `in` here", " in ".into(),
3497 // has been misleading, at least in the past (closed Issue #48492)
3498 Applicability::MaybeIncorrect
3502 let in_span = self.prev_span;
3503 if self.eat_keyword(keywords::In) {
3504 // a common typo: `for _ in in bar {}`
3505 let mut err = self.sess.span_diagnostic.struct_span_err(
3507 "expected iterable, found keyword `in`",
3509 err.span_suggestion_short_with_applicability(
3510 in_span.until(self.prev_span),
3511 "remove the duplicated `in`",
3513 Applicability::MachineApplicable,
3515 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3516 err.note("for more information on the status of emplacement syntax, see <\
3517 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3520 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3521 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3522 attrs.extend(iattrs);
3524 let hi = self.prev_span;
3525 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3528 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3529 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3531 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3532 if self.token.is_keyword(keywords::Let) {
3533 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3535 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3536 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3537 attrs.extend(iattrs);
3538 let span = span_lo.to(body.span);
3539 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3542 /// Parse a 'while let' expression ('while' token already eaten)
3543 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3545 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3546 self.expect_keyword(keywords::Let)?;
3547 let pats = self.parse_pats()?;
3548 self.expect(&token::Eq)?;
3549 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3550 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3551 attrs.extend(iattrs);
3552 let span = span_lo.to(body.span);
3553 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3556 // parse `loop {...}`, `loop` token already eaten
3557 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3559 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3560 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3561 attrs.extend(iattrs);
3562 let span = span_lo.to(body.span);
3563 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3566 /// Parse an `async move {...}` expression
3567 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3568 -> PResult<'a, P<Expr>>
3570 let span_lo = self.span;
3571 self.expect_keyword(keywords::Async)?;
3572 let capture_clause = if self.eat_keyword(keywords::Move) {
3577 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3578 attrs.extend(iattrs);
3580 span_lo.to(body.span),
3581 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3584 /// Parse a `try {...}` expression (`try` token already eaten)
3585 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3586 -> PResult<'a, P<Expr>>
3588 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3589 attrs.extend(iattrs);
3590 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3593 // `match` token already eaten
3594 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3595 let match_span = self.prev_span;
3596 let lo = self.prev_span;
3597 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3599 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3600 if self.token == token::Token::Semi {
3601 e.span_suggestion_short_with_applicability(
3603 "try removing this `match`",
3605 Applicability::MaybeIncorrect // speculative
3610 attrs.extend(self.parse_inner_attributes()?);
3612 let mut arms: Vec<Arm> = Vec::new();
3613 while self.token != token::CloseDelim(token::Brace) {
3614 match self.parse_arm() {
3615 Ok(arm) => arms.push(arm),
3617 // Recover by skipping to the end of the block.
3619 self.recover_stmt();
3620 let span = lo.to(self.span);
3621 if self.token == token::CloseDelim(token::Brace) {
3624 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3630 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3633 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3634 maybe_whole!(self, NtArm, |x| x);
3636 let attrs = self.parse_outer_attributes()?;
3637 // Allow a '|' before the pats (RFC 1925)
3638 self.eat(&token::BinOp(token::Or));
3639 let pats = self.parse_pats()?;
3640 let guard = if self.eat_keyword(keywords::If) {
3641 Some(Guard::If(self.parse_expr()?))
3645 let arrow_span = self.span;
3646 self.expect(&token::FatArrow)?;
3647 let arm_start_span = self.span;
3649 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3650 .map_err(|mut err| {
3651 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3655 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3656 && self.token != token::CloseDelim(token::Brace);
3659 let cm = self.sess.source_map();
3660 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3661 .map_err(|mut err| {
3662 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3663 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3664 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3665 && expr_lines.lines.len() == 2
3666 && self.token == token::FatArrow => {
3667 // We check whether there's any trailing code in the parse span,
3668 // if there isn't, we very likely have the following:
3671 // | -- - missing comma
3677 // | parsed until here as `"y" & X`
3678 err.span_suggestion_short_with_applicability(
3679 cm.next_point(arm_start_span),
3680 "missing a comma here to end this `match` arm",
3682 Applicability::MachineApplicable
3686 err.span_label(arrow_span,
3687 "while parsing the `match` arm starting here");
3693 self.eat(&token::Comma);
3704 /// Parse an expression
3705 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3706 self.parse_expr_res(Restrictions::empty(), None)
3709 /// Evaluate the closure with restrictions in place.
3711 /// After the closure is evaluated, restrictions are reset.
3712 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3713 where F: FnOnce(&mut Self) -> T
3715 let old = self.restrictions;
3716 self.restrictions = r;
3718 self.restrictions = old;
3723 /// Parse an expression, subject to the given restrictions
3724 fn parse_expr_res(&mut self, r: Restrictions,
3725 already_parsed_attrs: Option<ThinVec<Attribute>>)
3726 -> PResult<'a, P<Expr>> {
3727 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3730 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3731 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3732 if self.eat(&token::Eq) {
3733 Ok(Some(self.parse_expr()?))
3735 Ok(Some(self.parse_expr()?))
3741 /// Parse patterns, separated by '|' s
3742 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3743 let mut pats = Vec::new();
3745 pats.push(self.parse_top_level_pat()?);
3747 if self.token == token::OrOr {
3748 let mut err = self.struct_span_err(self.span,
3749 "unexpected token `||` after pattern");
3750 err.span_suggestion_with_applicability(
3752 "use a single `|` to specify multiple patterns",
3754 Applicability::MachineApplicable
3758 } else if self.eat(&token::BinOp(token::Or)) {
3766 // Parses a parenthesized list of patterns like
3767 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3768 // - a vector of the patterns that were parsed
3769 // - an option indicating the index of the `..` element
3770 // - a boolean indicating whether a trailing comma was present.
3771 // Trailing commas are significant because (p) and (p,) are different patterns.
3772 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3773 self.expect(&token::OpenDelim(token::Paren))?;
3774 let result = self.parse_pat_list()?;
3775 self.expect(&token::CloseDelim(token::Paren))?;
3779 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3780 let mut fields = Vec::new();
3781 let mut ddpos = None;
3782 let mut trailing_comma = false;
3784 if self.eat(&token::DotDot) {
3785 if ddpos.is_none() {
3786 ddpos = Some(fields.len());
3788 // Emit a friendly error, ignore `..` and continue parsing
3789 self.span_err(self.prev_span,
3790 "`..` can only be used once per tuple or tuple struct pattern");
3792 } else if !self.check(&token::CloseDelim(token::Paren)) {
3793 fields.push(self.parse_pat(None)?);
3798 trailing_comma = self.eat(&token::Comma);
3799 if !trailing_comma {
3804 if ddpos == Some(fields.len()) && trailing_comma {
3805 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3806 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3809 Ok((fields, ddpos, trailing_comma))
3812 fn parse_pat_vec_elements(
3814 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3815 let mut before = Vec::new();
3816 let mut slice = None;
3817 let mut after = Vec::new();
3818 let mut first = true;
3819 let mut before_slice = true;
3821 while self.token != token::CloseDelim(token::Bracket) {
3825 self.expect(&token::Comma)?;
3827 if self.token == token::CloseDelim(token::Bracket)
3828 && (before_slice || !after.is_empty()) {
3834 if self.eat(&token::DotDot) {
3836 if self.check(&token::Comma) ||
3837 self.check(&token::CloseDelim(token::Bracket)) {
3838 slice = Some(P(Pat {
3839 id: ast::DUMMY_NODE_ID,
3840 node: PatKind::Wild,
3841 span: self.prev_span,
3843 before_slice = false;
3849 let subpat = self.parse_pat(None)?;
3850 if before_slice && self.eat(&token::DotDot) {
3851 slice = Some(subpat);
3852 before_slice = false;
3853 } else if before_slice {
3854 before.push(subpat);
3860 Ok((before, slice, after))
3866 attrs: Vec<Attribute>
3867 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3868 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3870 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3871 // Parsing a pattern of the form "fieldname: pat"
3872 let fieldname = self.parse_field_name()?;
3874 let pat = self.parse_pat(None)?;
3876 (pat, fieldname, false)
3878 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3879 let is_box = self.eat_keyword(keywords::Box);
3880 let boxed_span = self.span;
3881 let is_ref = self.eat_keyword(keywords::Ref);
3882 let is_mut = self.eat_keyword(keywords::Mut);
3883 let fieldname = self.parse_ident()?;
3884 hi = self.prev_span;
3886 let bind_type = match (is_ref, is_mut) {
3887 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3888 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3889 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3890 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3892 let fieldpat = P(Pat {
3893 id: ast::DUMMY_NODE_ID,
3894 node: PatKind::Ident(bind_type, fieldname, None),
3895 span: boxed_span.to(hi),
3898 let subpat = if is_box {
3900 id: ast::DUMMY_NODE_ID,
3901 node: PatKind::Box(fieldpat),
3907 (subpat, fieldname, true)
3910 Ok(source_map::Spanned {
3912 node: ast::FieldPat {
3916 attrs: attrs.into(),
3921 /// Parse the fields of a struct-like pattern
3922 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3923 let mut fields = Vec::new();
3924 let mut etc = false;
3925 let mut ate_comma = true;
3926 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3927 let mut etc_span = None;
3929 while self.token != token::CloseDelim(token::Brace) {
3930 let attrs = self.parse_outer_attributes()?;
3933 // check that a comma comes after every field
3935 let err = self.struct_span_err(self.prev_span, "expected `,`");
3936 if let Some(mut delayed) = delayed_err {
3943 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3945 let mut etc_sp = self.span;
3947 if self.token == token::DotDotDot { // Issue #46718
3948 // Accept `...` as if it were `..` to avoid further errors
3949 let mut err = self.struct_span_err(self.span,
3950 "expected field pattern, found `...`");
3951 err.span_suggestion_with_applicability(
3953 "to omit remaining fields, use one fewer `.`",
3955 Applicability::MachineApplicable
3959 self.bump(); // `..` || `...`:w
3961 if self.token == token::CloseDelim(token::Brace) {
3962 etc_span = Some(etc_sp);
3965 let token_str = self.this_token_descr();
3966 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3968 err.span_label(self.span, "expected `}`");
3969 let mut comma_sp = None;
3970 if self.token == token::Comma { // Issue #49257
3971 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3972 err.span_label(etc_sp,
3973 "`..` must be at the end and cannot have a trailing comma");
3974 comma_sp = Some(self.span);
3979 etc_span = Some(etc_sp);
3980 if self.token == token::CloseDelim(token::Brace) {
3981 // If the struct looks otherwise well formed, recover and continue.
3982 if let Some(sp) = comma_sp {
3983 err.span_suggestion_short_with_applicability(
3985 "remove this comma",
3987 Applicability::MachineApplicable,
3992 } else if self.token.is_ident() && ate_comma {
3993 // Accept fields coming after `..,`.
3994 // This way we avoid "pattern missing fields" errors afterwards.
3995 // We delay this error until the end in order to have a span for a
3997 if let Some(mut delayed_err) = delayed_err {
4001 delayed_err = Some(err);
4004 if let Some(mut err) = delayed_err {
4011 fields.push(match self.parse_pat_field(lo, attrs) {
4014 if let Some(mut delayed_err) = delayed_err {
4020 ate_comma = self.eat(&token::Comma);
4023 if let Some(mut err) = delayed_err {
4024 if let Some(etc_span) = etc_span {
4025 err.multipart_suggestion(
4026 "move the `..` to the end of the field list",
4028 (etc_span, String::new()),
4029 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4035 return Ok((fields, etc));
4038 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4039 if self.token.is_path_start() {
4041 let (qself, path) = if self.eat_lt() {
4042 // Parse a qualified path
4043 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4046 // Parse an unqualified path
4047 (None, self.parse_path(PathStyle::Expr)?)
4049 let hi = self.prev_span;
4050 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4052 self.parse_literal_maybe_minus()
4056 // helper function to decide whether to parse as ident binding or to try to do
4057 // something more complex like range patterns
4058 fn parse_as_ident(&mut self) -> bool {
4059 self.look_ahead(1, |t| match *t {
4060 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4061 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4062 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4063 // range pattern branch
4064 token::DotDot => None,
4066 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4067 token::Comma | token::CloseDelim(token::Bracket) => true,
4072 /// A wrapper around `parse_pat` with some special error handling for the
4073 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4074 /// to subpatterns within such).
4075 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4076 let pat = self.parse_pat(None)?;
4077 if self.token == token::Comma {
4078 // An unexpected comma after a top-level pattern is a clue that the
4079 // user (perhaps more accustomed to some other language) forgot the
4080 // parentheses in what should have been a tuple pattern; return a
4081 // suggestion-enhanced error here rather than choking on the comma
4083 let comma_span = self.span;
4085 if let Err(mut err) = self.parse_pat_list() {
4086 // We didn't expect this to work anyway; we just wanted
4087 // to advance to the end of the comma-sequence so we know
4088 // the span to suggest parenthesizing
4091 let seq_span = pat.span.to(self.prev_span);
4092 let mut err = self.struct_span_err(comma_span,
4093 "unexpected `,` in pattern");
4094 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4095 err.span_suggestion_with_applicability(
4097 "try adding parentheses",
4098 format!("({})", seq_snippet),
4099 Applicability::MachineApplicable
4107 /// Parse a pattern.
4108 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4109 self.parse_pat_with_range_pat(true, expected)
4112 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
4114 fn parse_pat_with_range_pat(
4116 allow_range_pat: bool,
4117 expected: Option<&'static str>,
4118 ) -> PResult<'a, P<Pat>> {
4119 maybe_whole!(self, NtPat, |x| x);
4124 token::BinOp(token::And) | token::AndAnd => {
4125 // Parse &pat / &mut pat
4127 let mutbl = self.parse_mutability();
4128 if let token::Lifetime(ident) = self.token {
4129 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4131 err.span_label(self.span, "unexpected lifetime");
4134 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4135 pat = PatKind::Ref(subpat, mutbl);
4137 token::OpenDelim(token::Paren) => {
4138 // Parse (pat,pat,pat,...) as tuple pattern
4139 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4140 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4141 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4143 PatKind::Tuple(fields, ddpos)
4146 token::OpenDelim(token::Bracket) => {
4147 // Parse [pat,pat,...] as slice pattern
4149 let (before, slice, after) = self.parse_pat_vec_elements()?;
4150 self.expect(&token::CloseDelim(token::Bracket))?;
4151 pat = PatKind::Slice(before, slice, after);
4153 // At this point, token != &, &&, (, [
4154 _ => if self.eat_keyword(keywords::Underscore) {
4156 pat = PatKind::Wild;
4157 } else if self.eat_keyword(keywords::Mut) {
4158 // Parse mut ident @ pat / mut ref ident @ pat
4159 let mutref_span = self.prev_span.to(self.span);
4160 let binding_mode = if self.eat_keyword(keywords::Ref) {
4162 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4163 .span_suggestion_with_applicability(
4165 "try switching the order",
4167 Applicability::MachineApplicable
4169 BindingMode::ByRef(Mutability::Mutable)
4171 BindingMode::ByValue(Mutability::Mutable)
4173 pat = self.parse_pat_ident(binding_mode)?;
4174 } else if self.eat_keyword(keywords::Ref) {
4175 // Parse ref ident @ pat / ref mut ident @ pat
4176 let mutbl = self.parse_mutability();
4177 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4178 } else if self.eat_keyword(keywords::Box) {
4180 let subpat = self.parse_pat_with_range_pat(false, None)?;
4181 pat = PatKind::Box(subpat);
4182 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4183 self.parse_as_ident() {
4184 // Parse ident @ pat
4185 // This can give false positives and parse nullary enums,
4186 // they are dealt with later in resolve
4187 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4188 pat = self.parse_pat_ident(binding_mode)?;
4189 } else if self.token.is_path_start() {
4190 // Parse pattern starting with a path
4191 let (qself, path) = if self.eat_lt() {
4192 // Parse a qualified path
4193 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4196 // Parse an unqualified path
4197 (None, self.parse_path(PathStyle::Expr)?)
4200 token::Not if qself.is_none() => {
4201 // Parse macro invocation
4203 let (delim, tts) = self.expect_delimited_token_tree()?;
4204 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4205 pat = PatKind::Mac(mac);
4207 token::DotDotDot | token::DotDotEq | token::DotDot => {
4208 let end_kind = match self.token {
4209 token::DotDot => RangeEnd::Excluded,
4210 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4211 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4212 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4215 let op_span = self.span;
4217 let span = lo.to(self.prev_span);
4218 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4220 let end = self.parse_pat_range_end()?;
4221 let op = Spanned { span: op_span, node: end_kind };
4222 pat = PatKind::Range(begin, end, op);
4224 token::OpenDelim(token::Brace) => {
4225 if qself.is_some() {
4226 let msg = "unexpected `{` after qualified path";
4227 let mut err = self.fatal(msg);
4228 err.span_label(self.span, msg);
4231 // Parse struct pattern
4233 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4235 self.recover_stmt();
4239 pat = PatKind::Struct(path, fields, etc);
4241 token::OpenDelim(token::Paren) => {
4242 if qself.is_some() {
4243 let msg = "unexpected `(` after qualified path";
4244 let mut err = self.fatal(msg);
4245 err.span_label(self.span, msg);
4248 // Parse tuple struct or enum pattern
4249 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4250 pat = PatKind::TupleStruct(path, fields, ddpos)
4252 _ => pat = PatKind::Path(qself, path),
4255 // Try to parse everything else as literal with optional minus
4256 match self.parse_literal_maybe_minus() {
4258 let op_span = self.span;
4259 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4260 self.check(&token::DotDotDot) {
4261 let end_kind = if self.eat(&token::DotDotDot) {
4262 RangeEnd::Included(RangeSyntax::DotDotDot)
4263 } else if self.eat(&token::DotDotEq) {
4264 RangeEnd::Included(RangeSyntax::DotDotEq)
4265 } else if self.eat(&token::DotDot) {
4268 panic!("impossible case: we already matched \
4269 on a range-operator token")
4271 let end = self.parse_pat_range_end()?;
4272 let op = Spanned { span: op_span, node: end_kind };
4273 pat = PatKind::Range(begin, end, op);
4275 pat = PatKind::Lit(begin);
4279 self.cancel(&mut err);
4280 let expected = expected.unwrap_or("pattern");
4282 "expected {}, found {}",
4284 self.this_token_descr(),
4286 let mut err = self.fatal(&msg);
4287 err.span_label(self.span, format!("expected {}", expected));
4294 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4295 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4297 if !allow_range_pat {
4300 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4302 PatKind::Range(..) => {
4303 let mut err = self.struct_span_err(
4305 "the range pattern here has ambiguous interpretation",
4307 err.span_suggestion_with_applicability(
4309 "add parentheses to clarify the precedence",
4310 format!("({})", pprust::pat_to_string(&pat)),
4311 // "ambiguous interpretation" implies that we have to be guessing
4312 Applicability::MaybeIncorrect
4323 /// Parse ident or ident @ pat
4324 /// used by the copy foo and ref foo patterns to give a good
4325 /// error message when parsing mistakes like ref foo(a,b)
4326 fn parse_pat_ident(&mut self,
4327 binding_mode: ast::BindingMode)
4328 -> PResult<'a, PatKind> {
4329 let ident = self.parse_ident()?;
4330 let sub = if self.eat(&token::At) {
4331 Some(self.parse_pat(Some("binding pattern"))?)
4336 // just to be friendly, if they write something like
4338 // we end up here with ( as the current token. This shortly
4339 // leads to a parse error. Note that if there is no explicit
4340 // binding mode then we do not end up here, because the lookahead
4341 // will direct us over to parse_enum_variant()
4342 if self.token == token::OpenDelim(token::Paren) {
4343 return Err(self.span_fatal(
4345 "expected identifier, found enum pattern"))
4348 Ok(PatKind::Ident(binding_mode, ident, sub))
4351 /// Parse a local variable declaration
4352 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4353 let lo = self.prev_span;
4354 let pat = self.parse_top_level_pat()?;
4356 let (err, ty) = if self.eat(&token::Colon) {
4357 // Save the state of the parser before parsing type normally, in case there is a `:`
4358 // instead of an `=` typo.
4359 let parser_snapshot_before_type = self.clone();
4360 let colon_sp = self.prev_span;
4361 match self.parse_ty() {
4362 Ok(ty) => (None, Some(ty)),
4364 // Rewind to before attempting to parse the type and continue parsing
4365 let parser_snapshot_after_type = self.clone();
4366 mem::replace(self, parser_snapshot_before_type);
4368 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4369 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4370 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4376 let init = match (self.parse_initializer(err.is_some()), err) {
4377 (Ok(init), None) => { // init parsed, ty parsed
4380 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4381 // Could parse the type as if it were the initializer, it is likely there was a
4382 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4383 err.span_suggestion_short_with_applicability(
4385 "use `=` if you meant to assign",
4387 Applicability::MachineApplicable
4390 // As this was parsed successfully, continue as if the code has been fixed for the
4391 // rest of the file. It will still fail due to the emitted error, but we avoid
4395 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4397 // Couldn't parse the type nor the initializer, only raise the type error and
4398 // return to the parser state before parsing the type as the initializer.
4399 // let x: <parse_error>;
4400 mem::replace(self, snapshot);
4403 (Err(err), None) => { // init error, ty parsed
4404 // Couldn't parse the initializer and we're not attempting to recover a failed
4405 // parse of the type, return the error.
4409 let hi = if self.token == token::Semi {
4418 id: ast::DUMMY_NODE_ID,
4424 /// Parse a structure field
4425 fn parse_name_and_ty(&mut self,
4428 attrs: Vec<Attribute>)
4429 -> PResult<'a, StructField> {
4430 let name = self.parse_ident()?;
4431 self.expect(&token::Colon)?;
4432 let ty = self.parse_ty()?;
4434 span: lo.to(self.prev_span),
4437 id: ast::DUMMY_NODE_ID,
4443 /// Emit an expected item after attributes error.
4444 fn expected_item_err(&self, attrs: &[Attribute]) {
4445 let message = match attrs.last() {
4446 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4447 _ => "expected item after attributes",
4450 self.span_err(self.prev_span, message);
4453 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4454 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4455 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4456 Ok(self.parse_stmt_(true))
4459 // Eat tokens until we can be relatively sure we reached the end of the
4460 // statement. This is something of a best-effort heuristic.
4462 // We terminate when we find an unmatched `}` (without consuming it).
4463 fn recover_stmt(&mut self) {
4464 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4467 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4468 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4469 // approximate - it can mean we break too early due to macros, but that
4470 // should only lead to sub-optimal recovery, not inaccurate parsing).
4472 // If `break_on_block` is `Break`, then we will stop consuming tokens
4473 // after finding (and consuming) a brace-delimited block.
4474 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4475 let mut brace_depth = 0;
4476 let mut bracket_depth = 0;
4477 let mut in_block = false;
4478 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4479 break_on_semi, break_on_block);
4481 debug!("recover_stmt_ loop {:?}", self.token);
4483 token::OpenDelim(token::DelimToken::Brace) => {
4486 if break_on_block == BlockMode::Break &&
4488 bracket_depth == 0 {
4492 token::OpenDelim(token::DelimToken::Bracket) => {
4496 token::CloseDelim(token::DelimToken::Brace) => {
4497 if brace_depth == 0 {
4498 debug!("recover_stmt_ return - close delim {:?}", self.token);
4503 if in_block && bracket_depth == 0 && brace_depth == 0 {
4504 debug!("recover_stmt_ return - block end {:?}", self.token);
4508 token::CloseDelim(token::DelimToken::Bracket) => {
4510 if bracket_depth < 0 {
4516 debug!("recover_stmt_ return - Eof");
4521 if break_on_semi == SemiColonMode::Break &&
4523 bracket_depth == 0 {
4524 debug!("recover_stmt_ return - Semi");
4535 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4536 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4538 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4543 fn is_async_block(&mut self) -> bool {
4544 self.token.is_keyword(keywords::Async) &&
4547 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4548 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4550 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4555 fn is_do_catch_block(&mut self) -> bool {
4556 self.token.is_keyword(keywords::Do) &&
4557 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4558 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4559 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4562 fn is_try_block(&mut self) -> bool {
4563 self.token.is_keyword(keywords::Try) &&
4564 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4566 self.span.edition() >= Edition::Edition2018 &&
4568 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4569 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4572 fn is_union_item(&self) -> bool {
4573 self.token.is_keyword(keywords::Union) &&
4574 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4577 fn is_crate_vis(&self) -> bool {
4578 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4581 fn is_extern_non_path(&self) -> bool {
4582 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4585 fn is_existential_type_decl(&self) -> bool {
4586 self.token.is_keyword(keywords::Existential) &&
4587 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4590 fn is_auto_trait_item(&mut self) -> bool {
4592 (self.token.is_keyword(keywords::Auto)
4593 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4594 || // unsafe auto trait
4595 (self.token.is_keyword(keywords::Unsafe) &&
4596 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4597 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4600 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4601 -> PResult<'a, Option<P<Item>>> {
4602 let token_lo = self.span;
4603 let (ident, def) = match self.token {
4604 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4606 let ident = self.parse_ident()?;
4607 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4608 match self.parse_token_tree() {
4609 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4610 _ => unreachable!(),
4612 } else if self.check(&token::OpenDelim(token::Paren)) {
4613 let args = self.parse_token_tree();
4614 let body = if self.check(&token::OpenDelim(token::Brace)) {
4615 self.parse_token_tree()
4620 TokenStream::concat(vec![
4622 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4630 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4632 token::Ident(ident, _) if ident.name == "macro_rules" &&
4633 self.look_ahead(1, |t| *t == token::Not) => {
4634 let prev_span = self.prev_span;
4635 self.complain_if_pub_macro(&vis.node, prev_span);
4639 let ident = self.parse_ident()?;
4640 let (delim, tokens) = self.expect_delimited_token_tree()?;
4641 if delim != MacDelimiter::Brace {
4642 if !self.eat(&token::Semi) {
4643 let msg = "macros that expand to items must either \
4644 be surrounded with braces or followed by a semicolon";
4645 self.span_err(self.prev_span, msg);
4649 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4651 _ => return Ok(None),
4654 let span = lo.to(self.prev_span);
4655 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4658 fn parse_stmt_without_recovery(&mut self,
4659 macro_legacy_warnings: bool)
4660 -> PResult<'a, Option<Stmt>> {
4661 maybe_whole!(self, NtStmt, |x| Some(x));
4663 let attrs = self.parse_outer_attributes()?;
4666 Ok(Some(if self.eat_keyword(keywords::Let) {
4668 id: ast::DUMMY_NODE_ID,
4669 node: StmtKind::Local(self.parse_local(attrs.into())?),
4670 span: lo.to(self.prev_span),
4672 } else if let Some(macro_def) = self.eat_macro_def(
4674 &source_map::respan(lo, VisibilityKind::Inherited),
4678 id: ast::DUMMY_NODE_ID,
4679 node: StmtKind::Item(macro_def),
4680 span: lo.to(self.prev_span),
4682 // Starts like a simple path, being careful to avoid contextual keywords
4683 // such as a union items, item with `crate` visibility or auto trait items.
4684 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4685 // like a path (1 token), but it fact not a path.
4686 // `union::b::c` - path, `union U { ... }` - not a path.
4687 // `crate::b::c` - path, `crate struct S;` - not a path.
4688 // `extern::b::c` - path, `extern crate c;` - not a path.
4689 } else if self.token.is_path_start() &&
4690 !self.token.is_qpath_start() &&
4691 !self.is_union_item() &&
4692 !self.is_crate_vis() &&
4693 !self.is_extern_non_path() &&
4694 !self.is_existential_type_decl() &&
4695 !self.is_auto_trait_item() {
4696 let pth = self.parse_path(PathStyle::Expr)?;
4698 if !self.eat(&token::Not) {
4699 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4700 self.parse_struct_expr(lo, pth, ThinVec::new())?
4702 let hi = self.prev_span;
4703 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4706 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4707 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4708 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4711 return Ok(Some(Stmt {
4712 id: ast::DUMMY_NODE_ID,
4713 node: StmtKind::Expr(expr),
4714 span: lo.to(self.prev_span),
4718 // it's a macro invocation
4719 let id = match self.token {
4720 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4721 _ => self.parse_ident()?,
4724 // check that we're pointing at delimiters (need to check
4725 // again after the `if`, because of `parse_ident`
4726 // consuming more tokens).
4728 token::OpenDelim(_) => {}
4730 // we only expect an ident if we didn't parse one
4732 let ident_str = if id.name == keywords::Invalid.name() {
4737 let tok_str = self.this_token_descr();
4738 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4741 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4746 let (delim, tts) = self.expect_delimited_token_tree()?;
4747 let hi = self.prev_span;
4749 let style = if delim == MacDelimiter::Brace {
4750 MacStmtStyle::Braces
4752 MacStmtStyle::NoBraces
4755 if id.name == keywords::Invalid.name() {
4756 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4757 let node = if delim == MacDelimiter::Brace ||
4758 self.token == token::Semi || self.token == token::Eof {
4759 StmtKind::Mac(P((mac, style, attrs.into())))
4761 // We used to incorrectly stop parsing macro-expanded statements here.
4762 // If the next token will be an error anyway but could have parsed with the
4763 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4764 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4765 // These can continue an expression, so we can't stop parsing and warn.
4766 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4767 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4768 token::BinOp(token::And) | token::BinOp(token::Or) |
4769 token::AndAnd | token::OrOr |
4770 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4773 self.warn_missing_semicolon();
4774 StmtKind::Mac(P((mac, style, attrs.into())))
4776 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4777 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4778 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4782 id: ast::DUMMY_NODE_ID,
4787 // if it has a special ident, it's definitely an item
4789 // Require a semicolon or braces.
4790 if style != MacStmtStyle::Braces {
4791 if !self.eat(&token::Semi) {
4792 self.span_err(self.prev_span,
4793 "macros that expand to items must \
4794 either be surrounded with braces or \
4795 followed by a semicolon");
4798 let span = lo.to(hi);
4800 id: ast::DUMMY_NODE_ID,
4802 node: StmtKind::Item({
4804 span, id /*id is good here*/,
4805 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4806 respan(lo, VisibilityKind::Inherited),
4812 // FIXME: Bad copy of attrs
4813 let old_directory_ownership =
4814 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4815 let item = self.parse_item_(attrs.clone(), false, true)?;
4816 self.directory.ownership = old_directory_ownership;
4820 id: ast::DUMMY_NODE_ID,
4821 span: lo.to(i.span),
4822 node: StmtKind::Item(i),
4825 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4826 if !attrs.is_empty() {
4827 if s.prev_token_kind == PrevTokenKind::DocComment {
4828 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4829 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4830 s.span_err(s.span, "expected statement after outer attribute");
4835 // Do not attempt to parse an expression if we're done here.
4836 if self.token == token::Semi {
4837 unused_attrs(&attrs, self);
4842 if self.token == token::CloseDelim(token::Brace) {
4843 unused_attrs(&attrs, self);
4847 // Remainder are line-expr stmts.
4848 let e = self.parse_expr_res(
4849 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4851 id: ast::DUMMY_NODE_ID,
4852 span: lo.to(e.span),
4853 node: StmtKind::Expr(e),
4860 /// Is this expression a successfully-parsed statement?
4861 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4862 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4863 !classify::expr_requires_semi_to_be_stmt(e)
4866 /// Parse a block. No inner attrs are allowed.
4867 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4868 maybe_whole!(self, NtBlock, |x| x);
4872 if !self.eat(&token::OpenDelim(token::Brace)) {
4874 let tok = self.this_token_descr();
4875 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4876 let do_not_suggest_help =
4877 self.token.is_keyword(keywords::In) || self.token == token::Colon;
4879 if self.token.is_ident_named("and") {
4880 e.span_suggestion_short_with_applicability(
4882 "use `&&` instead of `and` for the boolean operator",
4884 Applicability::MaybeIncorrect,
4887 if self.token.is_ident_named("or") {
4888 e.span_suggestion_short_with_applicability(
4890 "use `||` instead of `or` for the boolean operator",
4892 Applicability::MaybeIncorrect,
4896 // Check to see if the user has written something like
4901 // Which is valid in other languages, but not Rust.
4902 match self.parse_stmt_without_recovery(false) {
4904 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4905 || do_not_suggest_help {
4906 // if the next token is an open brace (e.g., `if a b {`), the place-
4907 // inside-a-block suggestion would be more likely wrong than right
4908 e.span_label(sp, "expected `{`");
4911 let mut stmt_span = stmt.span;
4912 // expand the span to include the semicolon, if it exists
4913 if self.eat(&token::Semi) {
4914 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4916 let sugg = pprust::to_string(|s| {
4917 use print::pprust::{PrintState, INDENT_UNIT};
4918 s.ibox(INDENT_UNIT)?;
4920 s.print_stmt(&stmt)?;
4921 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4923 e.span_suggestion_with_applicability(
4925 "try placing this code inside a block",
4927 // speculative, has been misleading in the past (closed Issue #46836)
4928 Applicability::MaybeIncorrect
4932 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4933 self.cancel(&mut e);
4937 e.span_label(sp, "expected `{`");
4941 self.parse_block_tail(lo, BlockCheckMode::Default)
4944 /// Parse a block. Inner attrs are allowed.
4945 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4946 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4949 self.expect(&token::OpenDelim(token::Brace))?;
4950 Ok((self.parse_inner_attributes()?,
4951 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4954 /// Parse the rest of a block expression or function body
4955 /// Precondition: already parsed the '{'.
4956 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4957 let mut stmts = vec![];
4958 let mut recovered = false;
4960 while !self.eat(&token::CloseDelim(token::Brace)) {
4961 let stmt = match self.parse_full_stmt(false) {
4964 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4965 self.eat(&token::CloseDelim(token::Brace));
4971 if let Some(stmt) = stmt {
4973 } else if self.token == token::Eof {
4976 // Found only `;` or `}`.
4982 id: ast::DUMMY_NODE_ID,
4984 span: lo.to(self.prev_span),
4989 /// Parse a statement, including the trailing semicolon.
4990 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4991 // skip looking for a trailing semicolon when we have an interpolated statement
4992 maybe_whole!(self, NtStmt, |x| Some(x));
4994 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4996 None => return Ok(None),
5000 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5001 // expression without semicolon
5002 if classify::expr_requires_semi_to_be_stmt(expr) {
5003 // Just check for errors and recover; do not eat semicolon yet.
5005 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5008 self.recover_stmt();
5012 StmtKind::Local(..) => {
5013 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5014 if macro_legacy_warnings && self.token != token::Semi {
5015 self.warn_missing_semicolon();
5017 self.expect_one_of(&[], &[token::Semi])?;
5023 if self.eat(&token::Semi) {
5024 stmt = stmt.add_trailing_semicolon();
5027 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5031 fn warn_missing_semicolon(&self) {
5032 self.diagnostic().struct_span_warn(self.span, {
5033 &format!("expected `;`, found {}", self.this_token_descr())
5035 "This was erroneously allowed and will become a hard error in a future release"
5039 fn err_dotdotdot_syntax(&self, span: Span) {
5040 self.diagnostic().struct_span_err(span, {
5041 "unexpected token: `...`"
5042 }).span_suggestion_with_applicability(
5043 span, "use `..` for an exclusive range", "..".to_owned(),
5044 Applicability::MaybeIncorrect
5045 ).span_suggestion_with_applicability(
5046 span, "or `..=` for an inclusive range", "..=".to_owned(),
5047 Applicability::MaybeIncorrect
5051 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5052 // BOUND = TY_BOUND | LT_BOUND
5053 // LT_BOUND = LIFETIME (e.g. `'a`)
5054 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5055 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
5056 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
5057 let mut bounds = Vec::new();
5059 // This needs to be synchronized with `Token::can_begin_bound`.
5060 let is_bound_start = self.check_path() || self.check_lifetime() ||
5061 self.check(&token::Question) ||
5062 self.check_keyword(keywords::For) ||
5063 self.check(&token::OpenDelim(token::Paren));
5066 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5067 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5068 if self.token.is_lifetime() {
5069 if let Some(question_span) = question {
5070 self.span_err(question_span,
5071 "`?` may only modify trait bounds, not lifetime bounds");
5073 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5075 self.expect(&token::CloseDelim(token::Paren))?;
5076 self.span_err(self.prev_span,
5077 "parenthesized lifetime bounds are not supported");
5080 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5081 let path = self.parse_path(PathStyle::Type)?;
5083 self.expect(&token::CloseDelim(token::Paren))?;
5085 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
5086 let modifier = if question.is_some() {
5087 TraitBoundModifier::Maybe
5089 TraitBoundModifier::None
5091 bounds.push(GenericBound::Trait(poly_trait, modifier));
5097 if !allow_plus || !self.eat_plus() {
5105 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
5106 self.parse_generic_bounds_common(true)
5109 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5110 // BOUND = LT_BOUND (e.g. `'a`)
5111 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5112 let mut lifetimes = Vec::new();
5113 while self.check_lifetime() {
5114 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5116 if !self.eat_plus() {
5123 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
5124 fn parse_ty_param(&mut self,
5125 preceding_attrs: Vec<Attribute>)
5126 -> PResult<'a, GenericParam> {
5127 let ident = self.parse_ident()?;
5129 // Parse optional colon and param bounds.
5130 let bounds = if self.eat(&token::Colon) {
5131 self.parse_generic_bounds()?
5136 let default = if self.eat(&token::Eq) {
5137 Some(self.parse_ty()?)
5144 id: ast::DUMMY_NODE_ID,
5145 attrs: preceding_attrs.into(),
5147 kind: GenericParamKind::Type {
5153 /// Parses the following grammar:
5154 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5155 fn parse_trait_item_assoc_ty(&mut self)
5156 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5157 let ident = self.parse_ident()?;
5158 let mut generics = self.parse_generics()?;
5160 // Parse optional colon and param bounds.
5161 let bounds = if self.eat(&token::Colon) {
5162 self.parse_generic_bounds()?
5166 generics.where_clause = self.parse_where_clause()?;
5168 let default = if self.eat(&token::Eq) {
5169 Some(self.parse_ty()?)
5173 self.expect(&token::Semi)?;
5175 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5178 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5179 /// trailing comma and erroneous trailing attributes.
5180 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5181 let mut params = Vec::new();
5182 let mut seen_ty_param = false;
5184 let attrs = self.parse_outer_attributes()?;
5185 if self.check_lifetime() {
5186 let lifetime = self.expect_lifetime();
5187 // Parse lifetime parameter.
5188 let bounds = if self.eat(&token::Colon) {
5189 self.parse_lt_param_bounds()
5193 params.push(ast::GenericParam {
5194 ident: lifetime.ident,
5196 attrs: attrs.into(),
5198 kind: ast::GenericParamKind::Lifetime,
5201 self.span_err(self.prev_span,
5202 "lifetime parameters must be declared prior to type parameters");
5204 } else if self.check_ident() {
5205 // Parse type parameter.
5206 params.push(self.parse_ty_param(attrs)?);
5207 seen_ty_param = true;
5209 // Check for trailing attributes and stop parsing.
5210 if !attrs.is_empty() {
5211 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
5212 self.span_err(attrs[0].span,
5213 &format!("trailing attribute after {} parameters", param_kind));
5218 if !self.eat(&token::Comma) {
5225 /// Parse a set of optional generic type parameter declarations. Where
5226 /// clauses are not parsed here, and must be added later via
5227 /// `parse_where_clause()`.
5229 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5230 /// | ( < lifetimes , typaramseq ( , )? > )
5231 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5232 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5233 maybe_whole!(self, NtGenerics, |x| x);
5235 let span_lo = self.span;
5237 let params = self.parse_generic_params()?;
5241 where_clause: WhereClause {
5242 id: ast::DUMMY_NODE_ID,
5243 predicates: Vec::new(),
5244 span: syntax_pos::DUMMY_SP,
5246 span: span_lo.to(self.prev_span),
5249 Ok(ast::Generics::default())
5253 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5254 /// possibly including trailing comma.
5255 fn parse_generic_args(&mut self)
5256 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5257 let mut args = Vec::new();
5258 let mut bindings = Vec::new();
5259 let mut seen_type = false;
5260 let mut seen_binding = false;
5262 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5263 // Parse lifetime argument.
5264 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5265 if seen_type || seen_binding {
5266 self.span_err(self.prev_span,
5267 "lifetime parameters must be declared prior to type parameters");
5269 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5270 // Parse associated type binding.
5272 let ident = self.parse_ident()?;
5274 let ty = self.parse_ty()?;
5275 bindings.push(TypeBinding {
5276 id: ast::DUMMY_NODE_ID,
5279 span: lo.to(self.prev_span),
5281 seen_binding = true;
5282 } else if self.check_type() {
5283 // Parse type argument.
5284 let ty_param = self.parse_ty()?;
5286 self.span_err(ty_param.span,
5287 "type parameters must be declared prior to associated type bindings");
5289 args.push(GenericArg::Type(ty_param));
5295 if !self.eat(&token::Comma) {
5299 Ok((args, bindings))
5302 /// Parses an optional `where` clause and places it in `generics`.
5304 /// ```ignore (only-for-syntax-highlight)
5305 /// where T : Trait<U, V> + 'b, 'a : 'b
5307 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5308 maybe_whole!(self, NtWhereClause, |x| x);
5310 let mut where_clause = WhereClause {
5311 id: ast::DUMMY_NODE_ID,
5312 predicates: Vec::new(),
5313 span: syntax_pos::DUMMY_SP,
5316 if !self.eat_keyword(keywords::Where) {
5317 return Ok(where_clause);
5319 let lo = self.prev_span;
5321 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5322 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5323 // change we parse those generics now, but report an error.
5324 if self.choose_generics_over_qpath() {
5325 let generics = self.parse_generics()?;
5326 self.span_err(generics.span,
5327 "generic parameters on `where` clauses are reserved for future use");
5332 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5333 let lifetime = self.expect_lifetime();
5334 // Bounds starting with a colon are mandatory, but possibly empty.
5335 self.expect(&token::Colon)?;
5336 let bounds = self.parse_lt_param_bounds();
5337 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5338 ast::WhereRegionPredicate {
5339 span: lo.to(self.prev_span),
5344 } else if self.check_type() {
5345 // Parse optional `for<'a, 'b>`.
5346 // This `for` is parsed greedily and applies to the whole predicate,
5347 // the bounded type can have its own `for` applying only to it.
5348 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5349 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5350 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5351 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5353 // Parse type with mandatory colon and (possibly empty) bounds,
5354 // or with mandatory equality sign and the second type.
5355 let ty = self.parse_ty()?;
5356 if self.eat(&token::Colon) {
5357 let bounds = self.parse_generic_bounds()?;
5358 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5359 ast::WhereBoundPredicate {
5360 span: lo.to(self.prev_span),
5361 bound_generic_params: lifetime_defs,
5366 // FIXME: Decide what should be used here, `=` or `==`.
5367 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5368 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5369 let rhs_ty = self.parse_ty()?;
5370 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5371 ast::WhereEqPredicate {
5372 span: lo.to(self.prev_span),
5375 id: ast::DUMMY_NODE_ID,
5379 return self.unexpected();
5385 if !self.eat(&token::Comma) {
5390 where_clause.span = lo.to(self.prev_span);
5394 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5395 -> PResult<'a, (Vec<Arg> , bool)> {
5396 self.expect(&token::OpenDelim(token::Paren))?;
5399 let mut variadic = false;
5400 let args: Vec<Option<Arg>> =
5401 self.parse_seq_to_before_end(
5402 &token::CloseDelim(token::Paren),
5403 SeqSep::trailing_allowed(token::Comma),
5405 if p.token == token::DotDotDot {
5409 if p.token != token::CloseDelim(token::Paren) {
5412 "`...` must be last in argument list for variadic function");
5416 let span = p.prev_span;
5417 if p.token == token::CloseDelim(token::Paren) {
5418 // continue parsing to present any further errors
5421 "only foreign functions are allowed to be variadic"
5423 Ok(Some(dummy_arg(span)))
5425 // this function definition looks beyond recovery, stop parsing
5427 "only foreign functions are allowed to be variadic");
5432 match p.parse_arg_general(named_args) {
5433 Ok(arg) => Ok(Some(arg)),
5436 let lo = p.prev_span;
5437 // Skip every token until next possible arg or end.
5438 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5439 // Create a placeholder argument for proper arg count (#34264).
5440 let span = lo.to(p.prev_span);
5441 Ok(Some(dummy_arg(span)))
5448 self.eat(&token::CloseDelim(token::Paren));
5450 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5452 if variadic && args.is_empty() {
5454 "variadic function must be declared with at least one named argument");
5457 Ok((args, variadic))
5460 /// Parse the argument list and result type of a function declaration
5461 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5463 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5464 let ret_ty = self.parse_ret_ty(true)?;
5473 /// Returns the parsed optional self argument and whether a self shortcut was used.
5474 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5475 let expect_ident = |this: &mut Self| match this.token {
5476 // Preserve hygienic context.
5477 token::Ident(ident, _) =>
5478 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5481 let isolated_self = |this: &mut Self, n| {
5482 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5483 this.look_ahead(n + 1, |t| t != &token::ModSep)
5486 // Parse optional self parameter of a method.
5487 // Only a limited set of initial token sequences is considered self parameters, anything
5488 // else is parsed as a normal function parameter list, so some lookahead is required.
5489 let eself_lo = self.span;
5490 let (eself, eself_ident, eself_hi) = match self.token {
5491 token::BinOp(token::And) => {
5497 (if isolated_self(self, 1) {
5499 SelfKind::Region(None, Mutability::Immutable)
5500 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5501 isolated_self(self, 2) {
5504 SelfKind::Region(None, Mutability::Mutable)
5505 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5506 isolated_self(self, 2) {
5508 let lt = self.expect_lifetime();
5509 SelfKind::Region(Some(lt), Mutability::Immutable)
5510 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5511 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5512 isolated_self(self, 3) {
5514 let lt = self.expect_lifetime();
5516 SelfKind::Region(Some(lt), Mutability::Mutable)
5519 }, expect_ident(self), self.prev_span)
5521 token::BinOp(token::Star) => {
5526 // Emit special error for `self` cases.
5527 (if isolated_self(self, 1) {
5529 self.span_err(self.span, "cannot pass `self` by raw pointer");
5530 SelfKind::Value(Mutability::Immutable)
5531 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5532 isolated_self(self, 2) {
5535 self.span_err(self.span, "cannot pass `self` by raw pointer");
5536 SelfKind::Value(Mutability::Immutable)
5539 }, expect_ident(self), self.prev_span)
5541 token::Ident(..) => {
5542 if isolated_self(self, 0) {
5545 let eself_ident = expect_ident(self);
5546 let eself_hi = self.prev_span;
5547 (if self.eat(&token::Colon) {
5548 let ty = self.parse_ty()?;
5549 SelfKind::Explicit(ty, Mutability::Immutable)
5551 SelfKind::Value(Mutability::Immutable)
5552 }, eself_ident, eself_hi)
5553 } else if self.token.is_keyword(keywords::Mut) &&
5554 isolated_self(self, 1) {
5558 let eself_ident = expect_ident(self);
5559 let eself_hi = self.prev_span;
5560 (if self.eat(&token::Colon) {
5561 let ty = self.parse_ty()?;
5562 SelfKind::Explicit(ty, Mutability::Mutable)
5564 SelfKind::Value(Mutability::Mutable)
5565 }, eself_ident, eself_hi)
5570 _ => return Ok(None),
5573 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5574 Ok(Some(Arg::from_self(eself, eself_ident)))
5577 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5578 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5579 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5581 self.expect(&token::OpenDelim(token::Paren))?;
5583 // Parse optional self argument
5584 let self_arg = self.parse_self_arg()?;
5586 // Parse the rest of the function parameter list.
5587 let sep = SeqSep::trailing_allowed(token::Comma);
5588 let fn_inputs = if let Some(self_arg) = self_arg {
5589 if self.check(&token::CloseDelim(token::Paren)) {
5591 } else if self.eat(&token::Comma) {
5592 let mut fn_inputs = vec![self_arg];
5593 fn_inputs.append(&mut self.parse_seq_to_before_end(
5594 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5598 return self.unexpected();
5601 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5604 // Parse closing paren and return type.
5605 self.expect(&token::CloseDelim(token::Paren))?;
5608 output: self.parse_ret_ty(true)?,
5613 // parse the |arg, arg| header on a lambda
5614 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5615 let inputs_captures = {
5616 if self.eat(&token::OrOr) {
5619 self.expect(&token::BinOp(token::Or))?;
5620 let args = self.parse_seq_to_before_tokens(
5621 &[&token::BinOp(token::Or), &token::OrOr],
5622 SeqSep::trailing_allowed(token::Comma),
5623 TokenExpectType::NoExpect,
5624 |p| p.parse_fn_block_arg()
5630 let output = self.parse_ret_ty(true)?;
5633 inputs: inputs_captures,
5639 /// Parse the name and optional generic types of a function header.
5640 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5641 let id = self.parse_ident()?;
5642 let generics = self.parse_generics()?;
5646 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5647 attrs: Vec<Attribute>) -> P<Item> {
5651 id: ast::DUMMY_NODE_ID,
5659 /// Parse an item-position function declaration.
5660 fn parse_item_fn(&mut self,
5663 constness: Spanned<Constness>,
5665 -> PResult<'a, ItemInfo> {
5666 let (ident, mut generics) = self.parse_fn_header()?;
5667 let decl = self.parse_fn_decl(false)?;
5668 generics.where_clause = self.parse_where_clause()?;
5669 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5670 let header = FnHeader { unsafety, asyncness, constness, abi };
5671 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5674 /// true if we are looking at `const ID`, false for things like `const fn` etc
5675 fn is_const_item(&mut self) -> bool {
5676 self.token.is_keyword(keywords::Const) &&
5677 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5678 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5681 /// parses all the "front matter" for a `fn` declaration, up to
5682 /// and including the `fn` keyword:
5686 /// - `const unsafe fn`
5689 fn parse_fn_front_matter(&mut self)
5697 let is_const_fn = self.eat_keyword(keywords::Const);
5698 let const_span = self.prev_span;
5699 let unsafety = self.parse_unsafety();
5700 let asyncness = self.parse_asyncness();
5701 let (constness, unsafety, abi) = if is_const_fn {
5702 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5704 let abi = if self.eat_keyword(keywords::Extern) {
5705 self.parse_opt_abi()?.unwrap_or(Abi::C)
5709 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5711 self.expect_keyword(keywords::Fn)?;
5712 Ok((constness, unsafety, asyncness, abi))
5715 /// Parse an impl item.
5716 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5717 maybe_whole!(self, NtImplItem, |x| x);
5718 let attrs = self.parse_outer_attributes()?;
5719 let (mut item, tokens) = self.collect_tokens(|this| {
5720 this.parse_impl_item_(at_end, attrs)
5723 // See `parse_item` for why this clause is here.
5724 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5725 item.tokens = Some(tokens);
5730 fn parse_impl_item_(&mut self,
5732 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5734 let vis = self.parse_visibility(false)?;
5735 let defaultness = self.parse_defaultness();
5736 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5737 let (name, alias, generics) = type_?;
5738 let kind = match alias {
5739 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5740 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5742 (name, kind, generics)
5743 } else if self.is_const_item() {
5744 // This parses the grammar:
5745 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5746 self.expect_keyword(keywords::Const)?;
5747 let name = self.parse_ident()?;
5748 self.expect(&token::Colon)?;
5749 let typ = self.parse_ty()?;
5750 self.expect(&token::Eq)?;
5751 let expr = self.parse_expr()?;
5752 self.expect(&token::Semi)?;
5753 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5755 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5756 attrs.extend(inner_attrs);
5757 (name, node, generics)
5761 id: ast::DUMMY_NODE_ID,
5762 span: lo.to(self.prev_span),
5773 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5774 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5779 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5781 VisibilityKind::Inherited => Ok(()),
5783 let is_macro_rules: bool = match self.token {
5784 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5788 let mut err = self.diagnostic()
5789 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5790 err.span_suggestion_with_applicability(
5792 "try exporting the macro",
5793 "#[macro_export]".to_owned(),
5794 Applicability::MaybeIncorrect // speculative
5798 let mut err = self.diagnostic()
5799 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5800 err.help("try adjusting the macro to put `pub` inside the invocation");
5807 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5808 -> DiagnosticBuilder<'a>
5810 let expected_kinds = if item_type == "extern" {
5811 "missing `fn`, `type`, or `static`"
5813 "missing `fn`, `type`, or `const`"
5816 // Given this code `path(`, it seems like this is not
5817 // setting the visibility of a macro invocation, but rather
5818 // a mistyped method declaration.
5819 // Create a diagnostic pointing out that `fn` is missing.
5821 // x | pub path(&self) {
5822 // | ^ missing `fn`, `type`, or `const`
5824 // ^^ `sp` below will point to this
5825 let sp = prev_span.between(self.prev_span);
5826 let mut err = self.diagnostic().struct_span_err(
5828 &format!("{} for {}-item declaration",
5829 expected_kinds, item_type));
5830 err.span_label(sp, expected_kinds);
5834 /// Parse a method or a macro invocation in a trait impl.
5835 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5836 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5837 ast::ImplItemKind)> {
5838 // code copied from parse_macro_use_or_failure... abstraction!
5839 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5841 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5842 ast::ImplItemKind::Macro(mac)))
5844 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5845 let ident = self.parse_ident()?;
5846 let mut generics = self.parse_generics()?;
5847 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5848 generics.where_clause = self.parse_where_clause()?;
5850 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5851 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5852 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5853 ast::MethodSig { header, decl },
5859 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5860 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5861 let ident = self.parse_ident()?;
5862 let mut tps = self.parse_generics()?;
5864 // Parse optional colon and supertrait bounds.
5865 let bounds = if self.eat(&token::Colon) {
5866 self.parse_generic_bounds()?
5871 if self.eat(&token::Eq) {
5872 // it's a trait alias
5873 let bounds = self.parse_generic_bounds()?;
5874 tps.where_clause = self.parse_where_clause()?;
5875 self.expect(&token::Semi)?;
5876 if unsafety != Unsafety::Normal {
5877 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5879 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5881 // it's a normal trait
5882 tps.where_clause = self.parse_where_clause()?;
5883 self.expect(&token::OpenDelim(token::Brace))?;
5884 let mut trait_items = vec![];
5885 while !self.eat(&token::CloseDelim(token::Brace)) {
5886 let mut at_end = false;
5887 match self.parse_trait_item(&mut at_end) {
5888 Ok(item) => trait_items.push(item),
5892 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5897 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5901 fn choose_generics_over_qpath(&self) -> bool {
5902 // There's an ambiguity between generic parameters and qualified paths in impls.
5903 // If we see `<` it may start both, so we have to inspect some following tokens.
5904 // The following combinations can only start generics,
5905 // but not qualified paths (with one exception):
5906 // `<` `>` - empty generic parameters
5907 // `<` `#` - generic parameters with attributes
5908 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5909 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5910 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5911 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5912 // The only truly ambiguous case is
5913 // `<` IDENT `>` `::` IDENT ...
5914 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5915 // because this is what almost always expected in practice, qualified paths in impls
5916 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5917 self.token == token::Lt &&
5918 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5919 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5920 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5921 t == &token::Colon || t == &token::Eq))
5924 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5925 self.expect(&token::OpenDelim(token::Brace))?;
5926 let attrs = self.parse_inner_attributes()?;
5928 let mut impl_items = Vec::new();
5929 while !self.eat(&token::CloseDelim(token::Brace)) {
5930 let mut at_end = false;
5931 match self.parse_impl_item(&mut at_end) {
5932 Ok(impl_item) => impl_items.push(impl_item),
5936 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5941 Ok((impl_items, attrs))
5944 /// Parses an implementation item, `impl` keyword is already parsed.
5945 /// impl<'a, T> TYPE { /* impl items */ }
5946 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5947 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5948 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5949 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5950 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5951 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5952 -> PResult<'a, ItemInfo> {
5953 // First, parse generic parameters if necessary.
5954 let mut generics = if self.choose_generics_over_qpath() {
5955 self.parse_generics()?
5957 ast::Generics::default()
5960 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5961 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5963 ast::ImplPolarity::Negative
5965 ast::ImplPolarity::Positive
5968 // Parse both types and traits as a type, then reinterpret if necessary.
5969 let ty_first = self.parse_ty()?;
5971 // If `for` is missing we try to recover.
5972 let has_for = self.eat_keyword(keywords::For);
5973 let missing_for_span = self.prev_span.between(self.span);
5975 let ty_second = if self.token == token::DotDot {
5976 // We need to report this error after `cfg` expansion for compatibility reasons
5977 self.bump(); // `..`, do not add it to expected tokens
5978 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5979 } else if has_for || self.token.can_begin_type() {
5980 Some(self.parse_ty()?)
5985 generics.where_clause = self.parse_where_clause()?;
5987 let (impl_items, attrs) = self.parse_impl_body()?;
5989 let item_kind = match ty_second {
5990 Some(ty_second) => {
5991 // impl Trait for Type
5993 self.span_err(missing_for_span, "missing `for` in a trait impl");
5996 let ty_first = ty_first.into_inner();
5997 let path = match ty_first.node {
5998 // This notably includes paths passed through `ty` macro fragments (#46438).
5999 TyKind::Path(None, path) => path,
6001 self.span_err(ty_first.span, "expected a trait, found type");
6002 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
6005 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6007 ItemKind::Impl(unsafety, polarity, defaultness,
6008 generics, Some(trait_ref), ty_second, impl_items)
6012 ItemKind::Impl(unsafety, polarity, defaultness,
6013 generics, None, ty_first, impl_items)
6017 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6020 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6021 if self.eat_keyword(keywords::For) {
6023 let params = self.parse_generic_params()?;
6025 // We rely on AST validation to rule out invalid cases: There must not be type
6026 // parameters, and the lifetime parameters must not have bounds.
6033 /// Parse struct Foo { ... }
6034 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6035 let class_name = self.parse_ident()?;
6037 let mut generics = self.parse_generics()?;
6039 // There is a special case worth noting here, as reported in issue #17904.
6040 // If we are parsing a tuple struct it is the case that the where clause
6041 // should follow the field list. Like so:
6043 // struct Foo<T>(T) where T: Copy;
6045 // If we are parsing a normal record-style struct it is the case
6046 // that the where clause comes before the body, and after the generics.
6047 // So if we look ahead and see a brace or a where-clause we begin
6048 // parsing a record style struct.
6050 // Otherwise if we look ahead and see a paren we parse a tuple-style
6053 let vdata = if self.token.is_keyword(keywords::Where) {
6054 generics.where_clause = self.parse_where_clause()?;
6055 if self.eat(&token::Semi) {
6056 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6057 VariantData::Unit(ast::DUMMY_NODE_ID)
6059 // If we see: `struct Foo<T> where T: Copy { ... }`
6060 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6062 // No `where` so: `struct Foo<T>;`
6063 } else if self.eat(&token::Semi) {
6064 VariantData::Unit(ast::DUMMY_NODE_ID)
6065 // Record-style struct definition
6066 } else if self.token == token::OpenDelim(token::Brace) {
6067 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6068 // Tuple-style struct definition with optional where-clause.
6069 } else if self.token == token::OpenDelim(token::Paren) {
6070 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6071 generics.where_clause = self.parse_where_clause()?;
6072 self.expect(&token::Semi)?;
6075 let token_str = self.this_token_descr();
6076 let mut err = self.fatal(&format!(
6077 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6080 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6084 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6087 /// Parse union Foo { ... }
6088 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6089 let class_name = self.parse_ident()?;
6091 let mut generics = self.parse_generics()?;
6093 let vdata = if self.token.is_keyword(keywords::Where) {
6094 generics.where_clause = self.parse_where_clause()?;
6095 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6096 } else if self.token == token::OpenDelim(token::Brace) {
6097 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6099 let token_str = self.this_token_descr();
6100 let mut err = self.fatal(&format!(
6101 "expected `where` or `{{` after union name, found {}", token_str));
6102 err.span_label(self.span, "expected `where` or `{` after union name");
6106 Ok((class_name, ItemKind::Union(vdata, generics), None))
6109 fn consume_block(&mut self, delim: token::DelimToken) {
6110 let mut brace_depth = 0;
6111 if !self.eat(&token::OpenDelim(delim)) {
6115 if self.eat(&token::OpenDelim(delim)) {
6117 } else if self.eat(&token::CloseDelim(delim)) {
6118 if brace_depth == 0 {
6124 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
6132 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6133 let mut fields = Vec::new();
6134 if self.eat(&token::OpenDelim(token::Brace)) {
6135 while self.token != token::CloseDelim(token::Brace) {
6136 let field = self.parse_struct_decl_field().map_err(|e| {
6137 self.recover_stmt();
6141 Ok(field) => fields.push(field),
6147 self.eat(&token::CloseDelim(token::Brace));
6149 let token_str = self.this_token_descr();
6150 let mut err = self.fatal(&format!(
6151 "expected `where`, or `{{` after struct name, found {}", token_str));
6152 err.span_label(self.span, "expected `where`, or `{` after struct name");
6159 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6160 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6161 // Unit like structs are handled in parse_item_struct function
6162 let fields = self.parse_unspanned_seq(
6163 &token::OpenDelim(token::Paren),
6164 &token::CloseDelim(token::Paren),
6165 SeqSep::trailing_allowed(token::Comma),
6167 let attrs = p.parse_outer_attributes()?;
6169 let vis = p.parse_visibility(true)?;
6170 let ty = p.parse_ty()?;
6172 span: lo.to(ty.span),
6175 id: ast::DUMMY_NODE_ID,
6184 /// Parse a structure field declaration
6185 fn parse_single_struct_field(&mut self,
6188 attrs: Vec<Attribute> )
6189 -> PResult<'a, StructField> {
6190 let mut seen_comma: bool = false;
6191 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6192 if self.token == token::Comma {
6199 token::CloseDelim(token::Brace) => {}
6200 token::DocComment(_) => {
6201 let previous_span = self.prev_span;
6202 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6203 self.bump(); // consume the doc comment
6204 let comma_after_doc_seen = self.eat(&token::Comma);
6205 // `seen_comma` is always false, because we are inside doc block
6206 // condition is here to make code more readable
6207 if seen_comma == false && comma_after_doc_seen == true {
6210 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6213 if seen_comma == false {
6214 let sp = self.sess.source_map().next_point(previous_span);
6215 err.span_suggestion_with_applicability(
6217 "missing comma here",
6219 Applicability::MachineApplicable
6226 let sp = self.sess.source_map().next_point(self.prev_span);
6227 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6228 self.this_token_descr()));
6229 if self.token.is_ident() {
6230 // This is likely another field; emit the diagnostic and keep going
6231 err.span_suggestion_with_applicability(
6233 "try adding a comma",
6235 Applicability::MachineApplicable,
6246 /// Parse an element of a struct definition
6247 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6248 let attrs = self.parse_outer_attributes()?;
6250 let vis = self.parse_visibility(false)?;
6251 self.parse_single_struct_field(lo, vis, attrs)
6254 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6255 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
6256 /// a function definition, it's not a tuple struct field) and the contents within the parens
6257 /// isn't valid, emit a proper diagnostic.
6258 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6259 maybe_whole!(self, NtVis, |x| x);
6261 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6262 if self.is_crate_vis() {
6263 self.bump(); // `crate`
6264 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6267 if !self.eat_keyword(keywords::Pub) {
6268 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6269 // keyword to grab a span from for inherited visibility; an empty span at the
6270 // beginning of the current token would seem to be the "Schelling span".
6271 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6273 let lo = self.prev_span;
6275 if self.check(&token::OpenDelim(token::Paren)) {
6276 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6277 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6278 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6279 // by the following tokens.
6280 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6283 self.bump(); // `crate`
6284 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6286 lo.to(self.prev_span),
6287 VisibilityKind::Crate(CrateSugar::PubCrate),
6290 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6293 self.bump(); // `in`
6294 let path = self.parse_path(PathStyle::Mod)?; // `path`
6295 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6296 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6298 id: ast::DUMMY_NODE_ID,
6301 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6302 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6303 t.is_keyword(keywords::SelfValue))
6305 // `pub(self)` or `pub(super)`
6307 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6308 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6309 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6311 id: ast::DUMMY_NODE_ID,
6314 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6315 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6317 let msg = "incorrect visibility restriction";
6318 let suggestion = r##"some possible visibility restrictions are:
6319 `pub(crate)`: visible only on the current crate
6320 `pub(super)`: visible only in the current module's parent
6321 `pub(in path::to::module)`: visible only on the specified path"##;
6322 let path = self.parse_path(PathStyle::Mod)?;
6323 let sp = self.prev_span;
6324 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6325 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6326 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6327 err.help(suggestion);
6328 err.span_suggestion_with_applicability(
6329 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6331 err.emit(); // emit diagnostic, but continue with public visibility
6335 Ok(respan(lo, VisibilityKind::Public))
6338 /// Parse defaultness: `default` or nothing.
6339 fn parse_defaultness(&mut self) -> Defaultness {
6340 // `pub` is included for better error messages
6341 if self.check_keyword(keywords::Default) &&
6342 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6343 t.is_keyword(keywords::Const) ||
6344 t.is_keyword(keywords::Fn) ||
6345 t.is_keyword(keywords::Unsafe) ||
6346 t.is_keyword(keywords::Extern) ||
6347 t.is_keyword(keywords::Type) ||
6348 t.is_keyword(keywords::Pub)) {
6349 self.bump(); // `default`
6350 Defaultness::Default
6356 /// Given a termination token, parse all of the items in a module
6357 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6358 let mut items = vec![];
6359 while let Some(item) = self.parse_item()? {
6363 if !self.eat(term) {
6364 let token_str = self.this_token_descr();
6365 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6366 if self.token == token::Semi {
6367 let msg = "consider removing this semicolon";
6368 err.span_suggestion_short_with_applicability(
6369 self.span, msg, String::new(), Applicability::MachineApplicable
6371 if !items.is_empty() { // Issue #51603
6372 let previous_item = &items[items.len()-1];
6373 let previous_item_kind_name = match previous_item.node {
6374 // say "braced struct" because tuple-structs and
6375 // braceless-empty-struct declarations do take a semicolon
6376 ItemKind::Struct(..) => Some("braced struct"),
6377 ItemKind::Enum(..) => Some("enum"),
6378 ItemKind::Trait(..) => Some("trait"),
6379 ItemKind::Union(..) => Some("union"),
6382 if let Some(name) = previous_item_kind_name {
6383 err.help(&format!("{} declarations are not followed by a semicolon",
6388 err.span_label(self.span, "expected item");
6393 let hi = if self.span.is_dummy() {
6400 inner: inner_lo.to(hi),
6406 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6407 let id = match self.token {
6408 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
6412 _ => self.parse_ident()?,
6414 self.expect(&token::Colon)?;
6415 let ty = self.parse_ty()?;
6416 self.expect(&token::Eq)?;
6417 let e = self.parse_expr()?;
6418 self.expect(&token::Semi)?;
6419 let item = match m {
6420 Some(m) => ItemKind::Static(ty, m, e),
6421 None => ItemKind::Const(ty, e),
6423 Ok((id, item, None))
6426 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6427 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6428 let (in_cfg, outer_attrs) = {
6429 let mut strip_unconfigured = ::config::StripUnconfigured {
6431 features: None, // don't perform gated feature checking
6433 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6434 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6437 let id_span = self.span;
6438 let id = self.parse_ident()?;
6439 if self.eat(&token::Semi) {
6440 if in_cfg && self.recurse_into_file_modules {
6441 // This mod is in an external file. Let's go get it!
6442 let ModulePathSuccess { path, directory_ownership, warn } =
6443 self.submod_path(id, &outer_attrs, id_span)?;
6444 let (module, mut attrs) =
6445 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6446 // Record that we fetched the mod from an external file
6448 let attr = Attribute {
6449 id: attr::mk_attr_id(),
6450 style: ast::AttrStyle::Outer,
6451 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6452 tokens: TokenStream::empty(),
6453 is_sugared_doc: false,
6454 span: syntax_pos::DUMMY_SP,
6456 attr::mark_known(&attr);
6459 Ok((id, ItemKind::Mod(module), Some(attrs)))
6461 let placeholder = ast::Mod {
6462 inner: syntax_pos::DUMMY_SP,
6466 Ok((id, ItemKind::Mod(placeholder), None))
6469 let old_directory = self.directory.clone();
6470 self.push_directory(id, &outer_attrs);
6472 self.expect(&token::OpenDelim(token::Brace))?;
6473 let mod_inner_lo = self.span;
6474 let attrs = self.parse_inner_attributes()?;
6475 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6477 self.directory = old_directory;
6478 Ok((id, ItemKind::Mod(module), Some(attrs)))
6482 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6483 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6484 self.directory.path.to_mut().push(&path.as_str());
6485 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6487 // We have to push on the current module name in the case of relative
6488 // paths in order to ensure that any additional module paths from inline
6489 // `mod x { ... }` come after the relative extension.
6491 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6492 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6493 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6494 if let Some(ident) = relative.take() { // remove the relative offset
6495 self.directory.path.to_mut().push(ident.as_str());
6498 self.directory.path.to_mut().push(&id.as_str());
6502 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6503 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6506 // On windows, the base path might have the form
6507 // `\\?\foo\bar` in which case it does not tolerate
6508 // mixed `/` and `\` separators, so canonicalize
6511 let s = s.replace("/", "\\");
6512 Some(dir_path.join(s))
6518 /// Returns either a path to a module, or .
6519 pub fn default_submod_path(
6521 relative: Option<ast::Ident>,
6523 source_map: &SourceMap) -> ModulePath
6525 // If we're in a foo.rs file instead of a mod.rs file,
6526 // we need to look for submodules in
6527 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6528 // `./<id>.rs` and `./<id>/mod.rs`.
6529 let relative_prefix_string;
6530 let relative_prefix = if let Some(ident) = relative {
6531 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6532 &relative_prefix_string
6537 let mod_name = id.to_string();
6538 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6539 let secondary_path_str = format!("{}{}{}mod.rs",
6540 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6541 let default_path = dir_path.join(&default_path_str);
6542 let secondary_path = dir_path.join(&secondary_path_str);
6543 let default_exists = source_map.file_exists(&default_path);
6544 let secondary_exists = source_map.file_exists(&secondary_path);
6546 let result = match (default_exists, secondary_exists) {
6547 (true, false) => Ok(ModulePathSuccess {
6549 directory_ownership: DirectoryOwnership::Owned {
6554 (false, true) => Ok(ModulePathSuccess {
6555 path: secondary_path,
6556 directory_ownership: DirectoryOwnership::Owned {
6561 (false, false) => Err(Error::FileNotFoundForModule {
6562 mod_name: mod_name.clone(),
6563 default_path: default_path_str,
6564 secondary_path: secondary_path_str,
6565 dir_path: dir_path.display().to_string(),
6567 (true, true) => Err(Error::DuplicatePaths {
6568 mod_name: mod_name.clone(),
6569 default_path: default_path_str,
6570 secondary_path: secondary_path_str,
6576 path_exists: default_exists || secondary_exists,
6581 fn submod_path(&mut self,
6583 outer_attrs: &[Attribute],
6585 -> PResult<'a, ModulePathSuccess> {
6586 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6587 return Ok(ModulePathSuccess {
6588 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6589 // All `#[path]` files are treated as though they are a `mod.rs` file.
6590 // This means that `mod foo;` declarations inside `#[path]`-included
6591 // files are siblings,
6593 // Note that this will produce weirdness when a file named `foo.rs` is
6594 // `#[path]` included and contains a `mod foo;` declaration.
6595 // If you encounter this, it's your own darn fault :P
6596 Some(_) => DirectoryOwnership::Owned { relative: None },
6597 _ => DirectoryOwnership::UnownedViaMod(true),
6604 let relative = match self.directory.ownership {
6605 DirectoryOwnership::Owned { relative } => relative,
6606 DirectoryOwnership::UnownedViaBlock |
6607 DirectoryOwnership::UnownedViaMod(_) => None,
6609 let paths = Parser::default_submod_path(
6610 id, relative, &self.directory.path, self.sess.source_map());
6612 match self.directory.ownership {
6613 DirectoryOwnership::Owned { .. } => {
6614 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6616 DirectoryOwnership::UnownedViaBlock => {
6618 "Cannot declare a non-inline module inside a block \
6619 unless it has a path attribute";
6620 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6621 if paths.path_exists {
6622 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6624 err.span_note(id_sp, &msg);
6628 DirectoryOwnership::UnownedViaMod(warn) => {
6630 if let Ok(result) = paths.result {
6631 return Ok(ModulePathSuccess { warn: true, ..result });
6634 let mut err = self.diagnostic().struct_span_err(id_sp,
6635 "cannot declare a new module at this location");
6636 if !id_sp.is_dummy() {
6637 let src_path = self.sess.source_map().span_to_filename(id_sp);
6638 if let FileName::Real(src_path) = src_path {
6639 if let Some(stem) = src_path.file_stem() {
6640 let mut dest_path = src_path.clone();
6641 dest_path.set_file_name(stem);
6642 dest_path.push("mod.rs");
6643 err.span_note(id_sp,
6644 &format!("maybe move this module `{}` to its own \
6645 directory via `{}`", src_path.display(),
6646 dest_path.display()));
6650 if paths.path_exists {
6651 err.span_note(id_sp,
6652 &format!("... or maybe `use` the module `{}` instead \
6653 of possibly redeclaring it",
6661 /// Read a module from a source file.
6662 fn eval_src_mod(&mut self,
6664 directory_ownership: DirectoryOwnership,
6667 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6668 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6669 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6670 let mut err = String::from("circular modules: ");
6671 let len = included_mod_stack.len();
6672 for p in &included_mod_stack[i.. len] {
6673 err.push_str(&p.to_string_lossy());
6674 err.push_str(" -> ");
6676 err.push_str(&path.to_string_lossy());
6677 return Err(self.span_fatal(id_sp, &err[..]));
6679 included_mod_stack.push(path.clone());
6680 drop(included_mod_stack);
6683 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6684 p0.cfg_mods = self.cfg_mods;
6685 let mod_inner_lo = p0.span;
6686 let mod_attrs = p0.parse_inner_attributes()?;
6687 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6689 self.sess.included_mod_stack.borrow_mut().pop();
6693 /// Parse a function declaration from a foreign module
6694 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6695 -> PResult<'a, ForeignItem> {
6696 self.expect_keyword(keywords::Fn)?;
6698 let (ident, mut generics) = self.parse_fn_header()?;
6699 let decl = self.parse_fn_decl(true)?;
6700 generics.where_clause = self.parse_where_clause()?;
6702 self.expect(&token::Semi)?;
6703 Ok(ast::ForeignItem {
6706 node: ForeignItemKind::Fn(decl, generics),
6707 id: ast::DUMMY_NODE_ID,
6713 /// Parse a static item from a foreign module.
6714 /// Assumes that the `static` keyword is already parsed.
6715 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6716 -> PResult<'a, ForeignItem> {
6717 let mutbl = self.eat_keyword(keywords::Mut);
6718 let ident = self.parse_ident()?;
6719 self.expect(&token::Colon)?;
6720 let ty = self.parse_ty()?;
6722 self.expect(&token::Semi)?;
6726 node: ForeignItemKind::Static(ty, mutbl),
6727 id: ast::DUMMY_NODE_ID,
6733 /// Parse a type from a foreign module
6734 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6735 -> PResult<'a, ForeignItem> {
6736 self.expect_keyword(keywords::Type)?;
6738 let ident = self.parse_ident()?;
6740 self.expect(&token::Semi)?;
6741 Ok(ast::ForeignItem {
6744 node: ForeignItemKind::Ty,
6745 id: ast::DUMMY_NODE_ID,
6751 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6752 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6753 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6755 let mut ident = self.parse_ident()?;
6756 let mut idents = vec![];
6757 let mut replacement = vec![];
6758 let mut fixed_crate_name = false;
6759 // Accept `extern crate name-like-this` for better diagnostics
6760 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6761 if self.token == dash { // Do not include `-` as part of the expected tokens list
6762 while self.eat(&dash) {
6763 fixed_crate_name = true;
6764 replacement.push((self.prev_span, "_".to_string()));
6765 idents.push(self.parse_ident()?);
6768 if fixed_crate_name {
6769 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6770 let mut fixed_name = format!("{}", ident.name);
6771 for part in idents {
6772 fixed_name.push_str(&format!("_{}", part.name));
6774 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6776 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6777 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6778 err.multipart_suggestion(suggestion_msg, replacement);
6784 /// Parse extern crate links
6788 /// extern crate foo;
6789 /// extern crate bar as foo;
6790 fn parse_item_extern_crate(&mut self,
6792 visibility: Visibility,
6793 attrs: Vec<Attribute>)
6794 -> PResult<'a, P<Item>> {
6795 // Accept `extern crate name-like-this` for better diagnostics
6796 let orig_name = self.parse_crate_name_with_dashes()?;
6797 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6798 (rename, Some(orig_name.name))
6802 self.expect(&token::Semi)?;
6804 let span = lo.to(self.prev_span);
6805 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6808 /// Parse `extern` for foreign ABIs
6811 /// `extern` is expected to have been
6812 /// consumed before calling this method
6818 fn parse_item_foreign_mod(&mut self,
6820 opt_abi: Option<Abi>,
6821 visibility: Visibility,
6822 mut attrs: Vec<Attribute>)
6823 -> PResult<'a, P<Item>> {
6824 self.expect(&token::OpenDelim(token::Brace))?;
6826 let abi = opt_abi.unwrap_or(Abi::C);
6828 attrs.extend(self.parse_inner_attributes()?);
6830 let mut foreign_items = vec![];
6831 while !self.eat(&token::CloseDelim(token::Brace)) {
6832 foreign_items.push(self.parse_foreign_item()?);
6835 let prev_span = self.prev_span;
6836 let m = ast::ForeignMod {
6838 items: foreign_items
6840 let invalid = keywords::Invalid.ident();
6841 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6844 /// Parse `type Foo = Bar;`
6846 /// `existential type Foo: Bar;`
6848 /// `return None` without modifying the parser state
6849 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6850 // This parses the grammar:
6851 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6852 if self.check_keyword(keywords::Type) ||
6853 self.check_keyword(keywords::Existential) &&
6854 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6855 let existential = self.eat_keyword(keywords::Existential);
6856 assert!(self.eat_keyword(keywords::Type));
6857 Some(self.parse_existential_or_alias(existential))
6863 /// Parse type alias or existential type
6864 fn parse_existential_or_alias(
6867 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6868 let ident = self.parse_ident()?;
6869 let mut tps = self.parse_generics()?;
6870 tps.where_clause = self.parse_where_clause()?;
6871 let alias = if existential {
6872 self.expect(&token::Colon)?;
6873 let bounds = self.parse_generic_bounds()?;
6874 AliasKind::Existential(bounds)
6876 self.expect(&token::Eq)?;
6877 let ty = self.parse_ty()?;
6880 self.expect(&token::Semi)?;
6881 Ok((ident, alias, tps))
6884 /// Parse the part of an "enum" decl following the '{'
6885 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6886 let mut variants = Vec::new();
6887 let mut all_nullary = true;
6888 let mut any_disr = None;
6889 while self.token != token::CloseDelim(token::Brace) {
6890 let variant_attrs = self.parse_outer_attributes()?;
6891 let vlo = self.span;
6894 let mut disr_expr = None;
6895 let ident = self.parse_ident()?;
6896 if self.check(&token::OpenDelim(token::Brace)) {
6897 // Parse a struct variant.
6898 all_nullary = false;
6899 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6900 ast::DUMMY_NODE_ID);
6901 } else if self.check(&token::OpenDelim(token::Paren)) {
6902 all_nullary = false;
6903 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6904 ast::DUMMY_NODE_ID);
6905 } else if self.eat(&token::Eq) {
6906 disr_expr = Some(AnonConst {
6907 id: ast::DUMMY_NODE_ID,
6908 value: self.parse_expr()?,
6910 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6911 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6913 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6916 let vr = ast::Variant_ {
6918 attrs: variant_attrs,
6922 variants.push(respan(vlo.to(self.prev_span), vr));
6924 if !self.eat(&token::Comma) { break; }
6926 self.expect(&token::CloseDelim(token::Brace))?;
6928 Some(disr_span) if !all_nullary =>
6929 self.span_err(disr_span,
6930 "discriminator values can only be used with a field-less enum"),
6934 Ok(ast::EnumDef { variants })
6937 /// Parse an "enum" declaration
6938 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6939 let id = self.parse_ident()?;
6940 let mut generics = self.parse_generics()?;
6941 generics.where_clause = self.parse_where_clause()?;
6942 self.expect(&token::OpenDelim(token::Brace))?;
6944 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6945 self.recover_stmt();
6946 self.eat(&token::CloseDelim(token::Brace));
6949 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6952 /// Parses a string as an ABI spec on an extern type or module. Consumes
6953 /// the `extern` keyword, if one is found.
6954 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6956 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6958 self.expect_no_suffix(sp, "ABI spec", suf);
6960 match abi::lookup(&s.as_str()) {
6961 Some(abi) => Ok(Some(abi)),
6963 let prev_span = self.prev_span;
6964 let mut err = struct_span_err!(
6965 self.sess.span_diagnostic,
6968 "invalid ABI: found `{}`",
6970 err.span_label(prev_span, "invalid ABI");
6971 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6982 fn is_static_global(&mut self) -> bool {
6983 if self.check_keyword(keywords::Static) {
6984 // Check if this could be a closure
6985 !self.look_ahead(1, |token| {
6986 if token.is_keyword(keywords::Move) {
6990 token::BinOp(token::Or) | token::OrOr => true,
7001 attrs: Vec<Attribute>,
7002 macros_allowed: bool,
7003 attributes_allowed: bool,
7004 ) -> PResult<'a, Option<P<Item>>> {
7005 let (ret, tokens) = self.collect_tokens(|this| {
7006 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
7009 // Once we've parsed an item and recorded the tokens we got while
7010 // parsing we may want to store `tokens` into the item we're about to
7011 // return. Note, though, that we specifically didn't capture tokens
7012 // related to outer attributes. The `tokens` field here may later be
7013 // used with procedural macros to convert this item back into a token
7014 // stream, but during expansion we may be removing attributes as we go
7017 // If we've got inner attributes then the `tokens` we've got above holds
7018 // these inner attributes. If an inner attribute is expanded we won't
7019 // actually remove it from the token stream, so we'll just keep yielding
7020 // it (bad!). To work around this case for now we just avoid recording
7021 // `tokens` if we detect any inner attributes. This should help keep
7022 // expansion correct, but we should fix this bug one day!
7025 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7026 i.tokens = Some(tokens);
7033 /// Parse one of the items allowed by the flags.
7034 fn parse_item_implementation(
7036 attrs: Vec<Attribute>,
7037 macros_allowed: bool,
7038 attributes_allowed: bool,
7039 ) -> PResult<'a, Option<P<Item>>> {
7040 maybe_whole!(self, NtItem, |item| {
7041 let mut item = item.into_inner();
7042 let mut attrs = attrs;
7043 mem::swap(&mut item.attrs, &mut attrs);
7044 item.attrs.extend(attrs);
7050 let visibility = self.parse_visibility(false)?;
7052 if self.eat_keyword(keywords::Use) {
7054 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7055 self.expect(&token::Semi)?;
7057 let span = lo.to(self.prev_span);
7058 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7059 return Ok(Some(item));
7062 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
7063 self.bump(); // `extern`
7064 if self.eat_keyword(keywords::Crate) {
7065 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7068 let opt_abi = self.parse_opt_abi()?;
7070 if self.eat_keyword(keywords::Fn) {
7071 // EXTERN FUNCTION ITEM
7072 let fn_span = self.prev_span;
7073 let abi = opt_abi.unwrap_or(Abi::C);
7074 let (ident, item_, extra_attrs) =
7075 self.parse_item_fn(Unsafety::Normal,
7077 respan(fn_span, Constness::NotConst),
7079 let prev_span = self.prev_span;
7080 let item = self.mk_item(lo.to(prev_span),
7084 maybe_append(attrs, extra_attrs));
7085 return Ok(Some(item));
7086 } else if self.check(&token::OpenDelim(token::Brace)) {
7087 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7093 if self.is_static_global() {
7096 let m = if self.eat_keyword(keywords::Mut) {
7099 Mutability::Immutable
7101 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7102 let prev_span = self.prev_span;
7103 let item = self.mk_item(lo.to(prev_span),
7107 maybe_append(attrs, extra_attrs));
7108 return Ok(Some(item));
7110 if self.eat_keyword(keywords::Const) {
7111 let const_span = self.prev_span;
7112 if self.check_keyword(keywords::Fn)
7113 || (self.check_keyword(keywords::Unsafe)
7114 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7115 // CONST FUNCTION ITEM
7116 let unsafety = self.parse_unsafety();
7118 let (ident, item_, extra_attrs) =
7119 self.parse_item_fn(unsafety,
7121 respan(const_span, Constness::Const),
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));
7133 if self.eat_keyword(keywords::Mut) {
7134 let prev_span = self.prev_span;
7135 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
7136 .help("did you mean to declare a static?")
7139 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7140 let prev_span = self.prev_span;
7141 let item = self.mk_item(lo.to(prev_span),
7145 maybe_append(attrs, extra_attrs));
7146 return Ok(Some(item));
7149 // `unsafe async fn` or `async fn`
7151 self.check_keyword(keywords::Unsafe) &&
7152 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7154 self.check_keyword(keywords::Async) &&
7155 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7158 // ASYNC FUNCTION ITEM
7159 let unsafety = self.parse_unsafety();
7160 self.expect_keyword(keywords::Async)?;
7161 self.expect_keyword(keywords::Fn)?;
7162 let fn_span = self.prev_span;
7163 let (ident, item_, extra_attrs) =
7164 self.parse_item_fn(unsafety,
7166 closure_id: ast::DUMMY_NODE_ID,
7167 return_impl_trait_id: ast::DUMMY_NODE_ID,
7169 respan(fn_span, Constness::NotConst),
7171 let prev_span = self.prev_span;
7172 let item = self.mk_item(lo.to(prev_span),
7176 maybe_append(attrs, extra_attrs));
7177 return Ok(Some(item));
7179 if self.check_keyword(keywords::Unsafe) &&
7180 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7181 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7183 // UNSAFE TRAIT ITEM
7184 self.bump(); // `unsafe`
7185 let is_auto = if self.eat_keyword(keywords::Trait) {
7188 self.expect_keyword(keywords::Auto)?;
7189 self.expect_keyword(keywords::Trait)?;
7192 let (ident, item_, extra_attrs) =
7193 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
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 self.check_keyword(keywords::Impl) ||
7203 self.check_keyword(keywords::Unsafe) &&
7204 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7205 self.check_keyword(keywords::Default) &&
7206 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7207 self.check_keyword(keywords::Default) &&
7208 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7210 let defaultness = self.parse_defaultness();
7211 let unsafety = self.parse_unsafety();
7212 self.expect_keyword(keywords::Impl)?;
7213 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7214 let span = lo.to(self.prev_span);
7215 return Ok(Some(self.mk_item(span, ident, item, visibility,
7216 maybe_append(attrs, extra_attrs))));
7218 if self.check_keyword(keywords::Fn) {
7221 let fn_span = self.prev_span;
7222 let (ident, item_, extra_attrs) =
7223 self.parse_item_fn(Unsafety::Normal,
7225 respan(fn_span, Constness::NotConst),
7227 let prev_span = self.prev_span;
7228 let item = self.mk_item(lo.to(prev_span),
7232 maybe_append(attrs, extra_attrs));
7233 return Ok(Some(item));
7235 if self.check_keyword(keywords::Unsafe)
7236 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7237 // UNSAFE FUNCTION ITEM
7238 self.bump(); // `unsafe`
7239 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7240 self.check(&token::OpenDelim(token::Brace));
7241 let abi = if self.eat_keyword(keywords::Extern) {
7242 self.parse_opt_abi()?.unwrap_or(Abi::C)
7246 self.expect_keyword(keywords::Fn)?;
7247 let fn_span = self.prev_span;
7248 let (ident, item_, extra_attrs) =
7249 self.parse_item_fn(Unsafety::Unsafe,
7251 respan(fn_span, Constness::NotConst),
7253 let prev_span = self.prev_span;
7254 let item = self.mk_item(lo.to(prev_span),
7258 maybe_append(attrs, extra_attrs));
7259 return Ok(Some(item));
7261 if self.eat_keyword(keywords::Mod) {
7263 let (ident, item_, extra_attrs) =
7264 self.parse_item_mod(&attrs[..])?;
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(type_) = self.eat_type() {
7274 let (ident, alias, generics) = type_?;
7276 let item_ = match alias {
7277 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7278 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7280 let prev_span = self.prev_span;
7281 let item = self.mk_item(lo.to(prev_span),
7286 return Ok(Some(item));
7288 if self.eat_keyword(keywords::Enum) {
7290 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7291 let prev_span = self.prev_span;
7292 let item = self.mk_item(lo.to(prev_span),
7296 maybe_append(attrs, extra_attrs));
7297 return Ok(Some(item));
7299 if self.check_keyword(keywords::Trait)
7300 || (self.check_keyword(keywords::Auto)
7301 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7303 let is_auto = if self.eat_keyword(keywords::Trait) {
7306 self.expect_keyword(keywords::Auto)?;
7307 self.expect_keyword(keywords::Trait)?;
7311 let (ident, item_, extra_attrs) =
7312 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7313 let prev_span = self.prev_span;
7314 let item = self.mk_item(lo.to(prev_span),
7318 maybe_append(attrs, extra_attrs));
7319 return Ok(Some(item));
7321 if self.eat_keyword(keywords::Struct) {
7323 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7324 let prev_span = self.prev_span;
7325 let item = self.mk_item(lo.to(prev_span),
7329 maybe_append(attrs, extra_attrs));
7330 return Ok(Some(item));
7332 if self.is_union_item() {
7335 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7336 let prev_span = self.prev_span;
7337 let item = self.mk_item(lo.to(prev_span),
7341 maybe_append(attrs, extra_attrs));
7342 return Ok(Some(item));
7344 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7345 return Ok(Some(macro_def));
7348 // Verify whether we have encountered a struct or method definition where the user forgot to
7349 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7350 if visibility.node.is_pub() &&
7351 self.check_ident() &&
7352 self.look_ahead(1, |t| *t != token::Not)
7354 // Space between `pub` keyword and the identifier
7357 // ^^^ `sp` points here
7358 let sp = self.prev_span.between(self.span);
7359 let full_sp = self.prev_span.to(self.span);
7360 let ident_sp = self.span;
7361 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7362 // possible public struct definition where `struct` was forgotten
7363 let ident = self.parse_ident().unwrap();
7364 let msg = format!("add `struct` here to parse `{}` as a public struct",
7366 let mut err = self.diagnostic()
7367 .struct_span_err(sp, "missing `struct` for struct definition");
7368 err.span_suggestion_short_with_applicability(
7369 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7372 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7373 let ident = self.parse_ident().unwrap();
7374 self.consume_block(token::Paren);
7375 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
7376 self.check(&token::OpenDelim(token::Brace))
7378 ("fn", "method", false)
7379 } else if self.check(&token::Colon) {
7383 ("fn` or `struct", "method or struct", true)
7386 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7387 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7389 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7393 err.span_suggestion_short_with_applicability(
7394 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7397 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7398 err.span_suggestion_with_applicability(
7400 "if you meant to call a macro, try",
7401 format!("{}!", snippet),
7402 // this is the `ambiguous` conditional branch
7403 Applicability::MaybeIncorrect
7406 err.help("if you meant to call a macro, remove the `pub` \
7407 and add a trailing `!` after the identifier");
7413 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7416 /// Parse a foreign item.
7417 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7418 maybe_whole!(self, NtForeignItem, |ni| ni);
7420 let attrs = self.parse_outer_attributes()?;
7422 let visibility = self.parse_visibility(false)?;
7424 // FOREIGN STATIC ITEM
7425 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7426 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7427 if self.token.is_keyword(keywords::Const) {
7429 .struct_span_err(self.span, "extern items cannot be `const`")
7430 .span_suggestion_with_applicability(
7432 "try using a static value",
7433 "static".to_owned(),
7434 Applicability::MachineApplicable
7437 self.bump(); // `static` or `const`
7438 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7440 // FOREIGN FUNCTION ITEM
7441 if self.check_keyword(keywords::Fn) {
7442 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7444 // FOREIGN TYPE ITEM
7445 if self.check_keyword(keywords::Type) {
7446 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7449 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7453 ident: keywords::Invalid.ident(),
7454 span: lo.to(self.prev_span),
7455 id: ast::DUMMY_NODE_ID,
7458 node: ForeignItemKind::Macro(mac),
7463 if !attrs.is_empty() {
7464 self.expected_item_err(&attrs);
7472 /// This is the fall-through for parsing items.
7473 fn parse_macro_use_or_failure(
7475 attrs: Vec<Attribute> ,
7476 macros_allowed: bool,
7477 attributes_allowed: bool,
7479 visibility: Visibility
7480 ) -> PResult<'a, Option<P<Item>>> {
7481 if macros_allowed && self.token.is_path_start() {
7482 // MACRO INVOCATION ITEM
7484 let prev_span = self.prev_span;
7485 self.complain_if_pub_macro(&visibility.node, prev_span);
7487 let mac_lo = self.span;
7490 let pth = self.parse_path(PathStyle::Mod)?;
7491 self.expect(&token::Not)?;
7493 // a 'special' identifier (like what `macro_rules!` uses)
7494 // is optional. We should eventually unify invoc syntax
7496 let id = if self.token.is_ident() {
7499 keywords::Invalid.ident() // no special identifier
7501 // eat a matched-delimiter token tree:
7502 let (delim, tts) = self.expect_delimited_token_tree()?;
7503 if delim != MacDelimiter::Brace {
7504 if !self.eat(&token::Semi) {
7505 self.span_err(self.prev_span,
7506 "macros that expand to items must either \
7507 be surrounded with braces or followed by \
7512 let hi = self.prev_span;
7513 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7514 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7515 return Ok(Some(item));
7518 // FAILURE TO PARSE ITEM
7519 match visibility.node {
7520 VisibilityKind::Inherited => {}
7522 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7526 if !attributes_allowed && !attrs.is_empty() {
7527 self.expected_item_err(&attrs);
7532 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7533 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7534 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7536 if self.token.is_path_start() && !self.is_extern_non_path() {
7537 let prev_span = self.prev_span;
7539 let pth = self.parse_path(PathStyle::Mod)?;
7541 if pth.segments.len() == 1 {
7542 if !self.eat(&token::Not) {
7543 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7546 self.expect(&token::Not)?;
7549 if let Some(vis) = vis {
7550 self.complain_if_pub_macro(&vis.node, prev_span);
7555 // eat a matched-delimiter token tree:
7556 let (delim, tts) = self.expect_delimited_token_tree()?;
7557 if delim != MacDelimiter::Brace {
7558 self.expect(&token::Semi)?
7561 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7567 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7568 where F: FnOnce(&mut Self) -> PResult<'a, R>
7570 // Record all tokens we parse when parsing this item.
7571 let mut tokens = Vec::new();
7572 let prev_collecting = match self.token_cursor.frame.last_token {
7573 LastToken::Collecting(ref mut list) => {
7574 Some(mem::replace(list, Vec::new()))
7576 LastToken::Was(ref mut last) => {
7577 tokens.extend(last.take());
7581 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7582 let prev = self.token_cursor.stack.len();
7584 let last_token = if self.token_cursor.stack.len() == prev {
7585 &mut self.token_cursor.frame.last_token
7587 &mut self.token_cursor.stack[prev].last_token
7590 // Pull our the toekns that we've collected from the call to `f` above
7591 let mut collected_tokens = match *last_token {
7592 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7593 LastToken::Was(_) => panic!("our vector went away?"),
7596 // If we're not at EOF our current token wasn't actually consumed by
7597 // `f`, but it'll still be in our list that we pulled out. In that case
7599 let extra_token = if self.token != token::Eof {
7600 collected_tokens.pop()
7605 // If we were previously collecting tokens, then this was a recursive
7606 // call. In that case we need to record all the tokens we collected in
7607 // our parent list as well. To do that we push a clone of our stream
7608 // onto the previous list.
7609 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7610 match prev_collecting {
7612 list.push(stream.clone());
7613 list.extend(extra_token);
7614 *last_token = LastToken::Collecting(list);
7617 *last_token = LastToken::Was(extra_token);
7624 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7625 let attrs = self.parse_outer_attributes()?;
7626 self.parse_item_(attrs, true, false)
7630 fn is_import_coupler(&mut self) -> bool {
7631 self.check(&token::ModSep) &&
7632 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7633 *t == token::BinOp(token::Star))
7638 /// USE_TREE = [`::`] `*` |
7639 /// [`::`] `{` USE_TREE_LIST `}` |
7641 /// PATH `::` `{` USE_TREE_LIST `}` |
7642 /// PATH [`as` IDENT]
7643 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7646 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7647 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7648 self.check(&token::BinOp(token::Star)) ||
7649 self.is_import_coupler() {
7650 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7651 if self.eat(&token::ModSep) {
7652 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7655 if self.eat(&token::BinOp(token::Star)) {
7658 UseTreeKind::Nested(self.parse_use_tree_list()?)
7661 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7662 prefix = self.parse_path(PathStyle::Mod)?;
7664 if self.eat(&token::ModSep) {
7665 if self.eat(&token::BinOp(token::Star)) {
7668 UseTreeKind::Nested(self.parse_use_tree_list()?)
7671 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7675 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7678 /// Parse UseTreeKind::Nested(list)
7680 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7681 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7682 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7683 &token::CloseDelim(token::Brace),
7684 SeqSep::trailing_allowed(token::Comma), |this| {
7685 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7689 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7690 if self.eat_keyword(keywords::As) {
7692 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7694 Ok(Some(ident.gensym()))
7696 _ => self.parse_ident().map(Some),
7703 /// Parses a source module as a crate. This is the main
7704 /// entry point for the parser.
7705 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7708 attrs: self.parse_inner_attributes()?,
7709 module: self.parse_mod_items(&token::Eof, lo)?,
7710 span: lo.to(self.span),
7714 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7715 let ret = match self.token {
7716 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7717 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7724 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7725 match self.parse_optional_str() {
7726 Some((s, style, suf)) => {
7727 let sp = self.prev_span;
7728 self.expect_no_suffix(sp, "string literal", suf);
7732 let msg = "expected string literal";
7733 let mut err = self.fatal(msg);
7734 err.span_label(self.span, msg);