1 use rustc_target::spec::abi::{self, Abi};
2 use ast::{AngleBracketedArgs, ParenthesisedArgs, AttrStyle, BareFnTy};
3 use ast::{GenericBound, TraitBoundModifier};
5 use ast::{Mod, AnonConst, Arg, Arm, Guard, Attribute, BindingMode, TraitItemKind};
7 use ast::{BlockCheckMode, CaptureBy, Movability};
8 use ast::{Constness, Crate};
11 use ast::{Expr, ExprKind, RangeLimits};
12 use ast::{Field, FnDecl, FnHeader};
13 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
14 use ast::{GenericParam, GenericParamKind};
16 use ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
17 use ast::{Label, Lifetime, Lit, LitKind};
19 use ast::MacStmtStyle;
20 use ast::{Mac, Mac_, MacDelimiter};
21 use ast::{MutTy, Mutability};
22 use ast::{Pat, PatKind, PathSegment};
23 use ast::{PolyTraitRef, QSelf};
24 use ast::{Stmt, StmtKind};
25 use ast::{VariantData, StructField};
28 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
29 use ast::{Ty, TyKind, TypeBinding, GenericBounds};
30 use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
31 use ast::{UseTree, UseTreeKind};
32 use ast::{BinOpKind, UnOp};
33 use ast::{RangeEnd, RangeSyntax};
35 use ext::base::DummyResult;
36 use source_map::{self, SourceMap, Spanned, respan};
37 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName};
38 use errors::{self, Applicability, DiagnosticBuilder, DiagnosticId};
39 use parse::{self, SeqSep, classify, token};
40 use parse::lexer::TokenAndSpan;
41 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
42 use parse::token::DelimToken;
43 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
44 use util::parser::{AssocOp, Fixity};
49 use tokenstream::{self, DelimSpan, ThinTokenStream, TokenTree, TokenStream};
50 use symbol::{Symbol, keywords};
55 use std::path::{self, Path, PathBuf};
59 /// Whether the type alias or associated type is a concrete type or an existential type
61 /// Just a new name for the same type
63 /// Only trait impls of the type will be usable, not the actual type itself
64 Existential(GenericBounds),
68 struct Restrictions: u8 {
69 const STMT_EXPR = 1 << 0;
70 const NO_STRUCT_LITERAL = 1 << 1;
74 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
76 /// How to parse a path.
77 #[derive(Copy, Clone, PartialEq)]
79 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
80 /// with something else. For example, in expressions `segment < ....` can be interpreted
81 /// as a comparison and `segment ( ....` can be interpreted as a function call.
82 /// In all such contexts the non-path interpretation is preferred by default for practical
83 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
84 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
86 /// In other contexts, notably in types, no ambiguity exists and paths can be written
87 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
88 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
90 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
91 /// visibilities or attributes.
92 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
93 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
94 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
95 /// tokens when something goes wrong.
99 #[derive(Clone, Copy, PartialEq, Debug)]
105 #[derive(Clone, Copy, PartialEq, Debug)]
111 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
112 /// dropped into the token stream, which happens while parsing the result of
113 /// macro expansion). Placement of these is not as complex as I feared it would
114 /// be. The important thing is to make sure that lookahead doesn't balk at
115 /// `token::Interpolated` tokens.
116 macro_rules! maybe_whole_expr {
118 if let token::Interpolated(nt) = $p.token.clone() {
120 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
122 return Ok((*e).clone());
124 token::NtPath(ref path) => {
127 let kind = ExprKind::Path(None, (*path).clone());
128 return Ok($p.mk_expr(span, kind, ThinVec::new()));
130 token::NtBlock(ref block) => {
133 let kind = ExprKind::Block((*block).clone(), None);
134 return Ok($p.mk_expr(span, kind, ThinVec::new()));
142 /// As maybe_whole_expr, but for things other than expressions
143 macro_rules! maybe_whole {
144 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
145 if let token::Interpolated(nt) = $p.token.clone() {
146 if let token::$constructor($x) = nt.0.clone() {
154 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
155 if let Some(ref mut rhs) = rhs {
161 #[derive(Debug, Clone, Copy, PartialEq)]
172 trait RecoverQPath: Sized {
173 const PATH_STYLE: PathStyle = PathStyle::Expr;
174 fn to_ty(&self) -> Option<P<Ty>>;
175 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
176 fn to_string(&self) -> String;
179 impl RecoverQPath for Ty {
180 const PATH_STYLE: PathStyle = PathStyle::Type;
181 fn to_ty(&self) -> Option<P<Ty>> {
182 Some(P(self.clone()))
184 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
185 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
187 fn to_string(&self) -> String {
188 pprust::ty_to_string(self)
192 impl RecoverQPath for Pat {
193 fn to_ty(&self) -> Option<P<Ty>> {
196 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
197 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
199 fn to_string(&self) -> String {
200 pprust::pat_to_string(self)
204 impl RecoverQPath for Expr {
205 fn to_ty(&self) -> Option<P<Ty>> {
208 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
209 Self { span: path.span, node: ExprKind::Path(qself, path),
210 id: self.id, attrs: self.attrs.clone() }
212 fn to_string(&self) -> String {
213 pprust::expr_to_string(self)
217 /* ident is handled by common.rs */
220 pub struct Parser<'a> {
221 pub sess: &'a ParseSess,
222 /// the current token:
223 pub token: token::Token,
224 /// the span of the current token:
226 /// the span of the previous token:
227 meta_var_span: Option<Span>,
229 /// the previous token kind
230 prev_token_kind: PrevTokenKind,
231 restrictions: Restrictions,
232 /// Used to determine the path to externally loaded source files
233 crate directory: Directory<'a>,
234 /// Whether to parse sub-modules in other files.
235 pub recurse_into_file_modules: bool,
236 /// Name of the root module this parser originated from. If `None`, then the
237 /// name is not known. This does not change while the parser is descending
238 /// into modules, and sub-parsers have new values for this name.
239 pub root_module_name: Option<String>,
240 crate expected_tokens: Vec<TokenType>,
241 token_cursor: TokenCursor,
242 desugar_doc_comments: bool,
243 /// Whether we should configure out of line modules as we parse.
250 frame: TokenCursorFrame,
251 stack: Vec<TokenCursorFrame>,
255 struct TokenCursorFrame {
256 delim: token::DelimToken,
259 tree_cursor: tokenstream::Cursor,
261 last_token: LastToken,
264 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
265 /// by the parser, and then that's transitively used to record the tokens that
266 /// each parse AST item is created with.
268 /// Right now this has two states, either collecting tokens or not collecting
269 /// tokens. If we're collecting tokens we just save everything off into a local
270 /// `Vec`. This should eventually though likely save tokens from the original
271 /// token stream and just use slicing of token streams to avoid creation of a
272 /// whole new vector.
274 /// The second state is where we're passively not recording tokens, but the last
275 /// token is still tracked for when we want to start recording tokens. This
276 /// "last token" means that when we start recording tokens we'll want to ensure
277 /// that this, the first token, is included in the output.
279 /// You can find some more example usage of this in the `collect_tokens` method
283 Collecting(Vec<TokenStream>),
284 Was(Option<TokenStream>),
287 impl TokenCursorFrame {
288 fn new(sp: DelimSpan, delim: DelimToken, tts: &ThinTokenStream) -> Self {
292 open_delim: delim == token::NoDelim,
293 tree_cursor: tts.stream().into_trees(),
294 close_delim: delim == token::NoDelim,
295 last_token: LastToken::Was(None),
301 fn next(&mut self) -> TokenAndSpan {
303 let tree = if !self.frame.open_delim {
304 self.frame.open_delim = true;
305 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
306 } else if let Some(tree) = self.frame.tree_cursor.next() {
308 } else if !self.frame.close_delim {
309 self.frame.close_delim = true;
310 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
311 } else if let Some(frame) = self.stack.pop() {
315 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
318 match self.frame.last_token {
319 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
320 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
324 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
325 TokenTree::Delimited(sp, delim, tts) => {
326 let frame = TokenCursorFrame::new(sp, delim, &tts);
327 self.stack.push(mem::replace(&mut self.frame, frame));
333 fn next_desugared(&mut self) -> TokenAndSpan {
334 let (sp, name) = match self.next() {
335 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
339 let stripped = strip_doc_comment_decoration(&name.as_str());
341 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
342 // required to wrap the text.
343 let mut num_of_hashes = 0;
345 for ch in stripped.chars() {
348 '#' if count > 0 => count + 1,
351 num_of_hashes = cmp::max(num_of_hashes, count);
354 let delim_span = DelimSpan::from_single(sp);
355 let body = TokenTree::Delimited(
358 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
359 TokenTree::Token(sp, token::Eq),
360 TokenTree::Token(sp, token::Literal(
361 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
363 .iter().cloned().collect::<TokenStream>().into(),
366 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
369 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
370 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
371 .iter().cloned().collect::<TokenStream>().into()
373 [TokenTree::Token(sp, token::Pound), body]
374 .iter().cloned().collect::<TokenStream>().into()
382 #[derive(Clone, PartialEq)]
383 crate enum TokenType {
385 Keyword(keywords::Keyword),
394 fn to_string(&self) -> String {
396 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
397 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
398 TokenType::Operator => "an operator".to_string(),
399 TokenType::Lifetime => "lifetime".to_string(),
400 TokenType::Ident => "identifier".to_string(),
401 TokenType::Path => "path".to_string(),
402 TokenType::Type => "type".to_string(),
407 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
408 /// `IDENT<<u8 as Trait>::AssocTy>`.
410 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
411 /// that IDENT is not the ident of a fn trait
412 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
413 t == &token::ModSep || t == &token::Lt ||
414 t == &token::BinOp(token::Shl)
417 /// Information about the path to a module.
418 pub struct ModulePath {
421 pub result: Result<ModulePathSuccess, Error>,
424 pub struct ModulePathSuccess {
426 pub directory_ownership: DirectoryOwnership,
431 FileNotFoundForModule {
433 default_path: String,
434 secondary_path: String,
439 default_path: String,
440 secondary_path: String,
443 InclusiveRangeWithNoEnd,
447 fn span_err<S: Into<MultiSpan>>(self,
449 handler: &errors::Handler) -> DiagnosticBuilder {
451 Error::FileNotFoundForModule { ref mod_name,
455 let mut err = struct_span_err!(handler, sp, E0583,
456 "file not found for module `{}`", mod_name);
457 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
463 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
464 let mut err = struct_span_err!(handler, sp, E0584,
465 "file for module `{}` found at both {} and {}",
469 err.help("delete or rename one of them to remove the ambiguity");
472 Error::UselessDocComment => {
473 let mut err = struct_span_err!(handler, sp, E0585,
474 "found a documentation comment that doesn't document anything");
475 err.help("doc comments must come before what they document, maybe a comment was \
476 intended with `//`?");
479 Error::InclusiveRangeWithNoEnd => {
480 let mut err = struct_span_err!(handler, sp, E0586,
481 "inclusive range with no end");
482 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
492 AttributesParsed(ThinVec<Attribute>),
493 AlreadyParsed(P<Expr>),
496 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
497 fn from(o: Option<ThinVec<Attribute>>) -> Self {
498 if let Some(attrs) = o {
499 LhsExpr::AttributesParsed(attrs)
501 LhsExpr::NotYetParsed
506 impl From<P<Expr>> for LhsExpr {
507 fn from(expr: P<Expr>) -> Self {
508 LhsExpr::AlreadyParsed(expr)
512 /// Create a placeholder argument.
513 fn dummy_arg(span: Span) -> Arg {
514 let ident = Ident::new(keywords::Invalid.name(), span);
516 id: ast::DUMMY_NODE_ID,
517 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
523 id: ast::DUMMY_NODE_ID
525 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
528 #[derive(Copy, Clone, Debug)]
529 enum TokenExpectType {
534 impl<'a> Parser<'a> {
535 pub fn new(sess: &'a ParseSess,
537 directory: Option<Directory<'a>>,
538 recurse_into_file_modules: bool,
539 desugar_doc_comments: bool)
541 let mut parser = Parser {
543 token: token::Whitespace,
544 span: syntax_pos::DUMMY_SP,
545 prev_span: syntax_pos::DUMMY_SP,
547 prev_token_kind: PrevTokenKind::Other,
548 restrictions: Restrictions::empty(),
549 recurse_into_file_modules,
550 directory: Directory {
551 path: Cow::from(PathBuf::new()),
552 ownership: DirectoryOwnership::Owned { relative: None }
554 root_module_name: None,
555 expected_tokens: Vec::new(),
556 token_cursor: TokenCursor {
557 frame: TokenCursorFrame::new(
564 desugar_doc_comments,
568 let tok = parser.next_tok();
569 parser.token = tok.tok;
570 parser.span = tok.sp;
572 if let Some(directory) = directory {
573 parser.directory = directory;
574 } else if !parser.span.is_dummy() {
575 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
577 parser.directory.path = Cow::from(path);
581 parser.process_potential_macro_variable();
585 fn next_tok(&mut self) -> TokenAndSpan {
586 let mut next = if self.desugar_doc_comments {
587 self.token_cursor.next_desugared()
589 self.token_cursor.next()
591 if next.sp.is_dummy() {
592 // Tweak the location for better diagnostics, but keep syntactic context intact.
593 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
598 /// Convert the current token to a string using self's reader
599 pub fn this_token_to_string(&self) -> String {
600 pprust::token_to_string(&self.token)
603 fn token_descr(&self) -> Option<&'static str> {
604 Some(match &self.token {
605 t if t.is_special_ident() => "reserved identifier",
606 t if t.is_used_keyword() => "keyword",
607 t if t.is_unused_keyword() => "reserved keyword",
608 token::DocComment(..) => "doc comment",
613 fn this_token_descr(&self) -> String {
614 if let Some(prefix) = self.token_descr() {
615 format!("{} `{}`", prefix, self.this_token_to_string())
617 format!("`{}`", self.this_token_to_string())
621 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
622 let token_str = pprust::token_to_string(t);
623 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
626 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
627 match self.expect_one_of(&[], &[]) {
629 Ok(_) => unreachable!(),
633 /// Expect and consume the token t. Signal an error if
634 /// the next token is not t.
635 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
636 if self.expected_tokens.is_empty() {
637 if self.token == *t {
641 let token_str = pprust::token_to_string(t);
642 let this_token_str = self.this_token_descr();
643 let mut err = self.fatal(&format!("expected `{}`, found {}",
647 let sp = if self.token == token::Token::Eof {
648 // EOF, don't want to point at the following char, but rather the last token
651 self.sess.source_map().next_point(self.prev_span)
653 let label_exp = format!("expected `{}`", token_str);
654 let cm = self.sess.source_map();
655 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
656 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
657 // When the spans are in the same line, it means that the only content
658 // between them is whitespace, point only at the found token.
659 err.span_label(self.span, label_exp);
662 err.span_label(sp, label_exp);
663 err.span_label(self.span, "unexpected token");
669 self.expect_one_of(slice::from_ref(t), &[])
673 /// Expect next token to be edible or inedible token. If edible,
674 /// then consume it; if inedible, then return without consuming
675 /// anything. Signal a fatal error if next token is unexpected.
676 pub fn expect_one_of(&mut self,
677 edible: &[token::Token],
678 inedible: &[token::Token]) -> PResult<'a, ()>{
679 fn tokens_to_string(tokens: &[TokenType]) -> String {
680 let mut i = tokens.iter();
681 // This might be a sign we need a connect method on Iterator.
683 .map_or(String::new(), |t| t.to_string());
684 i.enumerate().fold(b, |mut b, (i, a)| {
685 if tokens.len() > 2 && i == tokens.len() - 2 {
687 } else if tokens.len() == 2 && i == tokens.len() - 2 {
692 b.push_str(&a.to_string());
696 if edible.contains(&self.token) {
699 } else if inedible.contains(&self.token) {
700 // leave it in the input
703 let mut expected = edible.iter()
704 .map(|x| TokenType::Token(x.clone()))
705 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
706 .chain(self.expected_tokens.iter().cloned())
707 .collect::<Vec<_>>();
708 expected.sort_by_cached_key(|x| x.to_string());
710 let expect = tokens_to_string(&expected[..]);
711 let actual = self.this_token_to_string();
712 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
713 let short_expect = if expected.len() > 6 {
714 format!("{} possible tokens", expected.len())
718 (format!("expected one of {}, found `{}`", expect, actual),
719 (self.sess.source_map().next_point(self.prev_span),
720 format!("expected one of {} here", short_expect)))
721 } else if expected.is_empty() {
722 (format!("unexpected token: `{}`", actual),
723 (self.prev_span, "unexpected token after this".to_string()))
725 (format!("expected {}, found `{}`", expect, actual),
726 (self.sess.source_map().next_point(self.prev_span),
727 format!("expected {} here", expect)))
729 let mut err = self.fatal(&msg_exp);
730 if self.token.is_ident_named("and") {
731 err.span_suggestion_short_with_applicability(
733 "use `&&` instead of `and` for the boolean operator",
735 Applicability::MaybeIncorrect,
738 if self.token.is_ident_named("or") {
739 err.span_suggestion_short_with_applicability(
741 "use `||` instead of `or` for the boolean operator",
743 Applicability::MaybeIncorrect,
746 let sp = if self.token == token::Token::Eof {
747 // This is EOF, don't want to point at the following char, but rather the last token
753 let cm = self.sess.source_map();
754 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
755 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
756 // When the spans are in the same line, it means that the only content between
757 // them is whitespace, point at the found token in that case:
759 // X | () => { syntax error };
760 // | ^^^^^ expected one of 8 possible tokens here
762 // instead of having:
764 // X | () => { syntax error };
765 // | -^^^^^ unexpected token
767 // | expected one of 8 possible tokens here
768 err.span_label(self.span, label_exp);
770 _ if self.prev_span == syntax_pos::DUMMY_SP => {
771 // Account for macro context where the previous span might not be
772 // available to avoid incorrect output (#54841).
773 err.span_label(self.span, "unexpected token");
776 err.span_label(sp, label_exp);
777 err.span_label(self.span, "unexpected token");
784 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
785 fn interpolated_or_expr_span(&self,
786 expr: PResult<'a, P<Expr>>)
787 -> PResult<'a, (Span, P<Expr>)> {
789 if self.prev_token_kind == PrevTokenKind::Interpolated {
797 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
798 let mut err = self.struct_span_err(self.span,
799 &format!("expected identifier, found {}",
800 self.this_token_descr()));
801 if let token::Ident(ident, false) = &self.token {
802 if ident.is_reserved() && !ident.is_path_segment_keyword() &&
803 ident.name != keywords::Underscore.name()
805 err.span_suggestion_with_applicability(
807 "you can escape reserved keywords to use them as identifiers",
808 format!("r#{}", ident),
809 Applicability::MaybeIncorrect,
813 if let Some(token_descr) = self.token_descr() {
814 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
816 err.span_label(self.span, "expected identifier");
817 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
818 err.span_suggestion_with_applicability(
822 Applicability::MachineApplicable,
829 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
830 self.parse_ident_common(true)
833 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
835 token::Ident(ident, _) => {
836 if self.token.is_reserved_ident() {
837 let mut err = self.expected_ident_found();
844 let span = self.span;
846 Ok(Ident::new(ident.name, span))
849 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
850 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
852 self.expected_ident_found()
858 /// Check if the next token is `tok`, and return `true` if so.
860 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
862 crate fn check(&mut self, tok: &token::Token) -> bool {
863 let is_present = self.token == *tok;
864 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
868 /// Consume token 'tok' if it exists. Returns true if the given
869 /// token was present, false otherwise.
870 pub fn eat(&mut self, tok: &token::Token) -> bool {
871 let is_present = self.check(tok);
872 if is_present { self.bump() }
876 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
877 self.expected_tokens.push(TokenType::Keyword(kw));
878 self.token.is_keyword(kw)
881 /// If the next token is the given keyword, eat it and return
882 /// true. Otherwise, return false.
883 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
884 if self.check_keyword(kw) {
892 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
893 if self.token.is_keyword(kw) {
901 /// If the given word is not a keyword, signal an error.
902 /// If the next token is not the given word, signal an error.
903 /// Otherwise, eat it.
904 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
905 if !self.eat_keyword(kw) {
912 fn check_ident(&mut self) -> bool {
913 if self.token.is_ident() {
916 self.expected_tokens.push(TokenType::Ident);
921 fn check_path(&mut self) -> bool {
922 if self.token.is_path_start() {
925 self.expected_tokens.push(TokenType::Path);
930 fn check_type(&mut self) -> bool {
931 if self.token.can_begin_type() {
934 self.expected_tokens.push(TokenType::Type);
939 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
940 /// and continue. If a `+` is not seen, return false.
942 /// This is using when token splitting += into +.
943 /// See issue 47856 for an example of when this may occur.
944 fn eat_plus(&mut self) -> bool {
945 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
947 token::BinOp(token::Plus) => {
951 token::BinOpEq(token::Plus) => {
952 let span = self.span.with_lo(self.span.lo() + BytePos(1));
953 self.bump_with(token::Eq, span);
961 /// Checks to see if the next token is either `+` or `+=`.
962 /// Otherwise returns false.
963 fn check_plus(&mut self) -> bool {
964 if self.token.is_like_plus() {
968 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
973 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
974 /// `&` and continue. If an `&` is not seen, signal an error.
975 fn expect_and(&mut self) -> PResult<'a, ()> {
976 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
978 token::BinOp(token::And) => {
983 let span = self.span.with_lo(self.span.lo() + BytePos(1));
984 Ok(self.bump_with(token::BinOp(token::And), span))
986 _ => self.unexpected()
990 /// Expect and consume an `|`. If `||` is seen, replace it with a single
991 /// `|` and continue. If an `|` is not seen, signal an error.
992 fn expect_or(&mut self) -> PResult<'a, ()> {
993 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
995 token::BinOp(token::Or) => {
1000 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1001 Ok(self.bump_with(token::BinOp(token::Or), span))
1003 _ => self.unexpected()
1007 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1009 None => {/* everything ok */}
1011 let text = suf.as_str();
1012 if text.is_empty() {
1013 self.span_bug(sp, "found empty literal suffix in Some")
1015 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
1020 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
1021 /// `<` and continue. If a `<` is not seen, return false.
1023 /// This is meant to be used when parsing generics on a path to get the
1025 fn eat_lt(&mut self) -> bool {
1026 self.expected_tokens.push(TokenType::Token(token::Lt));
1032 token::BinOp(token::Shl) => {
1033 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1034 self.bump_with(token::Lt, span);
1041 fn expect_lt(&mut self) -> PResult<'a, ()> {
1049 /// Expect and consume a GT. if a >> is seen, replace it
1050 /// with a single > and continue. If a GT is not seen,
1051 /// signal an error.
1052 fn expect_gt(&mut self) -> PResult<'a, ()> {
1053 self.expected_tokens.push(TokenType::Token(token::Gt));
1059 token::BinOp(token::Shr) => {
1060 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1061 Ok(self.bump_with(token::Gt, span))
1063 token::BinOpEq(token::Shr) => {
1064 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1065 Ok(self.bump_with(token::Ge, span))
1068 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1069 Ok(self.bump_with(token::Eq, span))
1071 _ => self.unexpected()
1075 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1076 /// passes through any errors encountered. Used for error recovery.
1077 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1078 let handler = self.diagnostic();
1080 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1082 TokenExpectType::Expect,
1083 |p| Ok(p.parse_token_tree())) {
1084 handler.cancel(err);
1088 /// Parse a sequence, including the closing delimiter. The function
1089 /// f must consume tokens until reaching the next separator or
1090 /// closing bracket.
1091 pub fn parse_seq_to_end<T, F>(&mut self,
1095 -> PResult<'a, Vec<T>> where
1096 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1098 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1103 /// Parse a sequence, not including the closing delimiter. The function
1104 /// f must consume tokens until reaching the next separator or
1105 /// closing bracket.
1106 pub fn parse_seq_to_before_end<T, F>(&mut self,
1110 -> PResult<'a, Vec<T>>
1111 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1113 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1116 fn parse_seq_to_before_tokens<T, F>(
1118 kets: &[&token::Token],
1120 expect: TokenExpectType,
1122 ) -> PResult<'a, Vec<T>>
1123 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1125 let mut first: bool = true;
1127 while !kets.iter().any(|k| {
1129 TokenExpectType::Expect => self.check(k),
1130 TokenExpectType::NoExpect => self.token == **k,
1134 token::CloseDelim(..) | token::Eof => break,
1137 if let Some(ref t) = sep.sep {
1141 if let Err(mut e) = self.expect(t) {
1142 // Attempt to keep parsing if it was a similar separator
1143 if let Some(ref tokens) = t.similar_tokens() {
1144 if tokens.contains(&self.token) {
1149 // Attempt to keep parsing if it was an omitted separator
1163 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1165 TokenExpectType::Expect => self.check(k),
1166 TokenExpectType::NoExpect => self.token == **k,
1179 /// Parse a sequence, including the closing delimiter. The function
1180 /// f must consume tokens until reaching the next separator or
1181 /// closing bracket.
1182 fn parse_unspanned_seq<T, F>(&mut self,
1187 -> PResult<'a, Vec<T>> where
1188 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1191 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1196 /// Advance the parser by one token
1197 pub fn bump(&mut self) {
1198 if self.prev_token_kind == PrevTokenKind::Eof {
1199 // Bumping after EOF is a bad sign, usually an infinite loop.
1200 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1203 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1205 // Record last token kind for possible error recovery.
1206 self.prev_token_kind = match self.token {
1207 token::DocComment(..) => PrevTokenKind::DocComment,
1208 token::Comma => PrevTokenKind::Comma,
1209 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1210 token::Interpolated(..) => PrevTokenKind::Interpolated,
1211 token::Eof => PrevTokenKind::Eof,
1212 token::Ident(..) => PrevTokenKind::Ident,
1213 _ => PrevTokenKind::Other,
1216 let next = self.next_tok();
1217 self.span = next.sp;
1218 self.token = next.tok;
1219 self.expected_tokens.clear();
1220 // check after each token
1221 self.process_potential_macro_variable();
1224 /// Advance the parser using provided token as a next one. Use this when
1225 /// consuming a part of a token. For example a single `<` from `<<`.
1226 fn bump_with(&mut self, next: token::Token, span: Span) {
1227 self.prev_span = self.span.with_hi(span.lo());
1228 // It would be incorrect to record the kind of the current token, but
1229 // fortunately for tokens currently using `bump_with`, the
1230 // prev_token_kind will be of no use anyway.
1231 self.prev_token_kind = PrevTokenKind::Other;
1234 self.expected_tokens.clear();
1237 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1238 F: FnOnce(&token::Token) -> R,
1241 return f(&self.token)
1244 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1245 Some(tree) => match tree {
1246 TokenTree::Token(_, tok) => tok,
1247 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1249 None => token::CloseDelim(self.token_cursor.frame.delim),
1253 fn look_ahead_span(&self, dist: usize) -> Span {
1258 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1259 Some(TokenTree::Token(span, _)) => span,
1260 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1261 None => self.look_ahead_span(dist - 1),
1264 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1265 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1267 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1268 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1270 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1271 err.span_err(sp, self.diagnostic())
1273 fn bug(&self, m: &str) -> ! {
1274 self.sess.span_diagnostic.span_bug(self.span, m)
1276 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1277 self.sess.span_diagnostic.span_err(sp, m)
1279 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1280 self.sess.span_diagnostic.struct_span_err(sp, m)
1282 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1283 self.sess.span_diagnostic.span_bug(sp, m)
1285 crate fn abort_if_errors(&self) {
1286 self.sess.span_diagnostic.abort_if_errors();
1289 fn cancel(&self, err: &mut DiagnosticBuilder) {
1290 self.sess.span_diagnostic.cancel(err)
1293 crate fn diagnostic(&self) -> &'a errors::Handler {
1294 &self.sess.span_diagnostic
1297 /// Is the current token one of the keywords that signals a bare function
1299 fn token_is_bare_fn_keyword(&mut self) -> bool {
1300 self.check_keyword(keywords::Fn) ||
1301 self.check_keyword(keywords::Unsafe) ||
1302 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1305 /// parse a `TyKind::BareFn` type:
1306 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1309 [unsafe] [extern "ABI"] fn (S) -> T
1319 let unsafety = self.parse_unsafety();
1320 let abi = if self.eat_keyword(keywords::Extern) {
1321 self.parse_opt_abi()?.unwrap_or(Abi::C)
1326 self.expect_keyword(keywords::Fn)?;
1327 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1328 let ret_ty = self.parse_ret_ty(false)?;
1329 let decl = P(FnDecl {
1334 Ok(TyKind::BareFn(P(BareFnTy {
1342 /// Parse asyncness: `async` or nothing
1343 fn parse_asyncness(&mut self) -> IsAsync {
1344 if self.eat_keyword(keywords::Async) {
1346 closure_id: ast::DUMMY_NODE_ID,
1347 return_impl_trait_id: ast::DUMMY_NODE_ID,
1354 /// Parse unsafety: `unsafe` or nothing.
1355 fn parse_unsafety(&mut self) -> Unsafety {
1356 if self.eat_keyword(keywords::Unsafe) {
1363 /// Parse the items in a trait declaration
1364 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1365 maybe_whole!(self, NtTraitItem, |x| x);
1366 let attrs = self.parse_outer_attributes()?;
1367 let (mut item, tokens) = self.collect_tokens(|this| {
1368 this.parse_trait_item_(at_end, attrs)
1370 // See `parse_item` for why this clause is here.
1371 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1372 item.tokens = Some(tokens);
1377 fn parse_trait_item_(&mut self,
1379 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1382 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1383 self.parse_trait_item_assoc_ty()?
1384 } else if self.is_const_item() {
1385 self.expect_keyword(keywords::Const)?;
1386 let ident = self.parse_ident()?;
1387 self.expect(&token::Colon)?;
1388 let ty = self.parse_ty()?;
1389 let default = if self.eat(&token::Eq) {
1390 let expr = self.parse_expr()?;
1391 self.expect(&token::Semi)?;
1394 self.expect(&token::Semi)?;
1397 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1398 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1399 // trait item macro.
1400 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1402 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1404 let ident = self.parse_ident()?;
1405 let mut generics = self.parse_generics()?;
1407 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1408 // This is somewhat dubious; We don't want to allow
1409 // argument names to be left off if there is a
1412 // We don't allow argument names to be left off in edition 2018.
1413 p.parse_arg_general(p.span.rust_2018(), true)
1415 generics.where_clause = self.parse_where_clause()?;
1417 let sig = ast::MethodSig {
1427 let body = match self.token {
1431 debug!("parse_trait_methods(): parsing required method");
1434 token::OpenDelim(token::Brace) => {
1435 debug!("parse_trait_methods(): parsing provided method");
1437 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1438 attrs.extend(inner_attrs.iter().cloned());
1441 token::Interpolated(ref nt) => {
1443 token::NtBlock(..) => {
1445 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1446 attrs.extend(inner_attrs.iter().cloned());
1450 let token_str = self.this_token_descr();
1451 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1453 err.span_label(self.span, "expected `;` or `{`");
1459 let token_str = self.this_token_descr();
1460 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1462 err.span_label(self.span, "expected `;` or `{`");
1466 (ident, ast::TraitItemKind::Method(sig, body), generics)
1470 id: ast::DUMMY_NODE_ID,
1475 span: lo.to(self.prev_span),
1480 /// Parse optional return type [ -> TY ] in function decl
1481 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1482 if self.eat(&token::RArrow) {
1483 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1485 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1490 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1491 self.parse_ty_common(true, true)
1494 /// Parse a type in restricted contexts where `+` is not permitted.
1495 /// Example 1: `&'a TYPE`
1496 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1497 /// Example 2: `value1 as TYPE + value2`
1498 /// `+` is prohibited to avoid interactions with expression grammar.
1499 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1500 self.parse_ty_common(false, true)
1503 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1504 -> PResult<'a, P<Ty>> {
1505 maybe_whole!(self, NtTy, |x| x);
1508 let mut impl_dyn_multi = false;
1509 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1510 // `(TYPE)` is a parenthesized type.
1511 // `(TYPE,)` is a tuple with a single field of type TYPE.
1512 let mut ts = vec![];
1513 let mut last_comma = false;
1514 while self.token != token::CloseDelim(token::Paren) {
1515 ts.push(self.parse_ty()?);
1516 if self.eat(&token::Comma) {
1523 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1524 self.expect(&token::CloseDelim(token::Paren))?;
1526 if ts.len() == 1 && !last_comma {
1527 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1528 let maybe_bounds = allow_plus && self.token.is_like_plus();
1530 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1531 TyKind::Path(None, ref path) if maybe_bounds => {
1532 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1534 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1535 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1536 let path = match bounds[0] {
1537 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1538 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1540 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1543 _ => TyKind::Paren(P(ty))
1548 } else if self.eat(&token::Not) {
1551 } else if self.eat(&token::BinOp(token::Star)) {
1553 TyKind::Ptr(self.parse_ptr()?)
1554 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1556 let t = self.parse_ty()?;
1557 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1558 let t = match self.maybe_parse_fixed_length_of_vec()? {
1559 None => TyKind::Slice(t),
1560 Some(length) => TyKind::Array(t, AnonConst {
1561 id: ast::DUMMY_NODE_ID,
1565 self.expect(&token::CloseDelim(token::Bracket))?;
1567 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1570 self.parse_borrowed_pointee()?
1571 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1573 // In order to not be ambiguous, the type must be surrounded by parens.
1574 self.expect(&token::OpenDelim(token::Paren))?;
1576 id: ast::DUMMY_NODE_ID,
1577 value: self.parse_expr()?,
1579 self.expect(&token::CloseDelim(token::Paren))?;
1581 } else if self.eat_keyword(keywords::Underscore) {
1582 // A type to be inferred `_`
1584 } else if self.token_is_bare_fn_keyword() {
1585 // Function pointer type
1586 self.parse_ty_bare_fn(Vec::new())?
1587 } else if self.check_keyword(keywords::For) {
1588 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1589 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1590 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1592 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1593 if self.token_is_bare_fn_keyword() {
1594 self.parse_ty_bare_fn(lifetime_defs)?
1596 let path = self.parse_path(PathStyle::Type)?;
1597 let parse_plus = allow_plus && self.check_plus();
1598 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1600 } else if self.eat_keyword(keywords::Impl) {
1601 // Always parse bounds greedily for better error recovery.
1602 let bounds = self.parse_generic_bounds()?;
1603 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1604 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1605 } else if self.check_keyword(keywords::Dyn) &&
1606 (self.span.rust_2018() ||
1607 self.look_ahead(1, |t| t.can_begin_bound() &&
1608 !can_continue_type_after_non_fn_ident(t))) {
1609 self.bump(); // `dyn`
1610 // Always parse bounds greedily for better error recovery.
1611 let bounds = self.parse_generic_bounds()?;
1612 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1613 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1614 } else if self.check(&token::Question) ||
1615 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1616 // Bound list (trait object type)
1617 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1618 TraitObjectSyntax::None)
1619 } else if self.eat_lt() {
1621 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1622 TyKind::Path(Some(qself), path)
1623 } else if self.token.is_path_start() {
1625 let path = self.parse_path(PathStyle::Type)?;
1626 if self.eat(&token::Not) {
1627 // Macro invocation in type position
1628 let (delim, tts) = self.expect_delimited_token_tree()?;
1629 let node = Mac_ { path, tts, delim };
1630 TyKind::Mac(respan(lo.to(self.prev_span), node))
1632 // Just a type path or bound list (trait object type) starting with a trait.
1634 // `Trait1 + Trait2 + 'a`
1635 if allow_plus && self.check_plus() {
1636 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1638 TyKind::Path(None, path)
1642 let msg = format!("expected type, found {}", self.this_token_descr());
1643 return Err(self.fatal(&msg));
1646 let span = lo.to(self.prev_span);
1647 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1649 // Try to recover from use of `+` with incorrect priority.
1650 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1651 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1652 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1657 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1658 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1659 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1660 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1662 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1663 bounds.append(&mut self.parse_generic_bounds()?);
1665 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1668 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1669 if !allow_plus && impl_dyn_multi {
1670 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1671 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1672 .span_suggestion_with_applicability(
1674 "use parentheses to disambiguate",
1676 Applicability::MachineApplicable
1681 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1682 // Do not add `+` to expected tokens.
1683 if !allow_plus || !self.token.is_like_plus() {
1688 let bounds = self.parse_generic_bounds()?;
1689 let sum_span = ty.span.to(self.prev_span);
1691 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1692 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1695 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1696 let sum_with_parens = pprust::to_string(|s| {
1697 use print::pprust::PrintState;
1700 s.print_opt_lifetime(lifetime)?;
1701 s.print_mutability(mut_ty.mutbl)?;
1703 s.print_type(&mut_ty.ty)?;
1704 s.print_type_bounds(" +", &bounds)?;
1707 err.span_suggestion_with_applicability(
1709 "try adding parentheses",
1711 Applicability::MachineApplicable
1714 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1715 err.span_label(sum_span, "perhaps you forgot parentheses?");
1718 err.span_label(sum_span, "expected a path");
1725 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1726 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1728 // Do not add `::` to expected tokens.
1729 if !allow_recovery || self.token != token::ModSep {
1732 let ty = match base.to_ty() {
1734 None => return Ok(base),
1737 self.bump(); // `::`
1738 let mut segments = Vec::new();
1739 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1741 let span = ty.span.to(self.prev_span);
1742 let path_span = span.to(span); // use an empty path since `position` == 0
1743 let recovered = base.to_recovered(
1744 Some(QSelf { ty, path_span, position: 0 }),
1745 ast::Path { segments, span },
1749 .struct_span_err(span, "missing angle brackets in associated item path")
1750 .span_suggestion_with_applicability( // this is a best-effort recovery
1751 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1757 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1758 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1759 let mutbl = self.parse_mutability();
1760 let ty = self.parse_ty_no_plus()?;
1761 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1764 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1765 let mutbl = if self.eat_keyword(keywords::Mut) {
1767 } else if self.eat_keyword(keywords::Const) {
1768 Mutability::Immutable
1770 let span = self.prev_span;
1772 "expected mut or const in raw pointer type (use \
1773 `*mut T` or `*const T` as appropriate)");
1774 Mutability::Immutable
1776 let t = self.parse_ty_no_plus()?;
1777 Ok(MutTy { ty: t, mutbl: mutbl })
1780 fn is_named_argument(&mut self) -> bool {
1781 let offset = match self.token {
1782 token::Interpolated(ref nt) => match nt.0 {
1783 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1786 token::BinOp(token::And) | token::AndAnd => 1,
1787 _ if self.token.is_keyword(keywords::Mut) => 1,
1791 self.look_ahead(offset, |t| t.is_ident()) &&
1792 self.look_ahead(offset + 1, |t| t == &token::Colon)
1795 /// Skip unexpected attributes and doc comments in this position and emit an appropriate error.
1796 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1797 if let token::DocComment(_) = self.token {
1798 let mut err = self.diagnostic().struct_span_err(
1800 &format!("documentation comments cannot be applied to {}", applied_to),
1802 err.span_label(self.span, "doc comments are not allowed here");
1805 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1806 *t == token::OpenDelim(token::Bracket)
1809 // Skip every token until next possible arg.
1810 while self.token != token::CloseDelim(token::Bracket) {
1813 let sp = lo.to(self.span);
1815 let mut err = self.diagnostic().struct_span_err(
1817 &format!("attributes cannot be applied to {}", applied_to),
1819 err.span_label(sp, "attributes are not allowed here");
1824 /// This version of parse arg doesn't necessarily require
1825 /// identifier names.
1826 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool) -> PResult<'a, Arg> {
1827 maybe_whole!(self, NtArg, |x| x);
1829 if let Ok(Some(_)) = self.parse_self_arg() {
1830 let mut err = self.struct_span_err(self.prev_span,
1831 "unexpected `self` argument in function");
1832 err.span_label(self.prev_span,
1833 "`self` is only valid as the first argument of an associated function");
1837 let (pat, ty) = if require_name || self.is_named_argument() {
1838 debug!("parse_arg_general parse_pat (require_name:{})",
1840 self.eat_incorrect_doc_comment("method arguments");
1841 let pat = self.parse_pat(Some("argument name"))?;
1843 if let Err(mut err) = self.expect(&token::Colon) {
1844 // If we find a pattern followed by an identifier, it could be an (incorrect)
1845 // C-style parameter declaration.
1846 if self.check_ident() && self.look_ahead(1, |t| {
1847 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1849 let ident = self.parse_ident().unwrap();
1850 let span = pat.span.with_hi(ident.span.hi());
1852 err.span_suggestion_with_applicability(
1854 "declare the type after the parameter binding",
1855 String::from("<identifier>: <type>"),
1856 Applicability::HasPlaceholders,
1858 } else if require_name && is_trait_item {
1859 if let PatKind::Ident(_, ident, _) = pat.node {
1860 err.span_suggestion_with_applicability(
1862 "explicitly ignore parameter",
1863 format!("_: {}", ident),
1864 Applicability::MachineApplicable,
1868 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1874 self.eat_incorrect_doc_comment("a method argument's type");
1875 (pat, self.parse_ty()?)
1877 debug!("parse_arg_general ident_to_pat");
1878 let parser_snapshot_before_ty = self.clone();
1879 self.eat_incorrect_doc_comment("a method argument's type");
1880 let mut ty = self.parse_ty();
1881 if ty.is_ok() && self.token != token::Comma &&
1882 self.token != token::CloseDelim(token::Paren) {
1883 // This wasn't actually a type, but a pattern looking like a type,
1884 // so we are going to rollback and re-parse for recovery.
1885 ty = self.unexpected();
1889 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1891 id: ast::DUMMY_NODE_ID,
1892 node: PatKind::Ident(
1893 BindingMode::ByValue(Mutability::Immutable), ident, None),
1899 // Recover from attempting to parse the argument as a type without pattern.
1901 mem::replace(self, parser_snapshot_before_ty);
1902 let pat = self.parse_pat(Some("argument name"))?;
1903 self.expect(&token::Colon)?;
1904 let ty = self.parse_ty()?;
1906 let mut err = self.diagnostic().struct_span_err_with_code(
1908 "patterns aren't allowed in methods without bodies",
1909 DiagnosticId::Error("E0642".into()),
1911 err.span_suggestion_short_with_applicability(
1913 "give this argument a name or use an underscore to ignore it",
1915 Applicability::MachineApplicable,
1919 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1921 node: PatKind::Wild,
1923 id: ast::DUMMY_NODE_ID
1930 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1933 /// Parse a single function argument
1934 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1935 self.parse_arg_general(true, false)
1938 /// Parse an argument in a lambda header e.g., |arg, arg|
1939 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1940 let pat = self.parse_pat(Some("argument name"))?;
1941 let t = if self.eat(&token::Colon) {
1945 id: ast::DUMMY_NODE_ID,
1946 node: TyKind::Infer,
1947 span: self.prev_span,
1953 id: ast::DUMMY_NODE_ID
1957 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1958 if self.eat(&token::Semi) {
1959 Ok(Some(self.parse_expr()?))
1965 /// Matches token_lit = LIT_INTEGER | ...
1966 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1967 let out = match self.token {
1968 token::Interpolated(ref nt) => match nt.0 {
1969 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1970 ExprKind::Lit(ref lit) => { lit.node.clone() }
1971 _ => { return self.unexpected_last(&self.token); }
1973 _ => { return self.unexpected_last(&self.token); }
1975 token::Literal(lit, suf) => {
1976 let diag = Some((self.span, &self.sess.span_diagnostic));
1977 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1981 self.expect_no_suffix(sp, lit.literal_name(), suf)
1986 _ => { return self.unexpected_last(&self.token); }
1993 /// Matches lit = true | false | token_lit
1994 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1996 let lit = if self.eat_keyword(keywords::True) {
1998 } else if self.eat_keyword(keywords::False) {
1999 LitKind::Bool(false)
2001 let lit = self.parse_lit_token()?;
2004 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2007 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
2008 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2009 maybe_whole_expr!(self);
2011 let minus_lo = self.span;
2012 let minus_present = self.eat(&token::BinOp(token::Minus));
2014 let literal = self.parse_lit()?;
2015 let hi = self.prev_span;
2016 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2019 let minus_hi = self.prev_span;
2020 let unary = self.mk_unary(UnOp::Neg, expr);
2021 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2027 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2029 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2030 let span = self.span;
2032 Ok(Ident::new(ident.name, span))
2034 _ => self.parse_ident(),
2038 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2040 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2041 let span = self.span;
2043 Ok(Ident::new(ident.name, span))
2045 _ => self.parse_ident(),
2049 /// Parses qualified path.
2050 /// Assumes that the leading `<` has been parsed already.
2052 /// `qualified_path = <type [as trait_ref]>::path`
2057 /// `<T as U>::F::a<S>` (without disambiguator)
2058 /// `<T as U>::F::a::<S>` (with disambiguator)
2059 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2060 let lo = self.prev_span;
2061 let ty = self.parse_ty()?;
2063 // `path` will contain the prefix of the path up to the `>`,
2064 // if any (e.g., `U` in the `<T as U>::*` examples
2065 // above). `path_span` has the span of that path, or an empty
2066 // span in the case of something like `<T>::Bar`.
2067 let (mut path, path_span);
2068 if self.eat_keyword(keywords::As) {
2069 let path_lo = self.span;
2070 path = self.parse_path(PathStyle::Type)?;
2071 path_span = path_lo.to(self.prev_span);
2073 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2074 path_span = self.span.to(self.span);
2077 self.expect(&token::Gt)?;
2078 self.expect(&token::ModSep)?;
2080 let qself = QSelf { ty, path_span, position: path.segments.len() };
2081 self.parse_path_segments(&mut path.segments, style, true)?;
2083 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2086 /// Parses simple paths.
2088 /// `path = [::] segment+`
2089 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2092 /// `a::b::C<D>` (without disambiguator)
2093 /// `a::b::C::<D>` (with disambiguator)
2094 /// `Fn(Args)` (without disambiguator)
2095 /// `Fn::(Args)` (with disambiguator)
2096 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2097 self.parse_path_common(style, true)
2100 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2101 -> PResult<'a, ast::Path> {
2102 maybe_whole!(self, NtPath, |path| {
2103 if style == PathStyle::Mod &&
2104 path.segments.iter().any(|segment| segment.args.is_some()) {
2105 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2110 let lo = self.meta_var_span.unwrap_or(self.span);
2111 let mut segments = Vec::new();
2112 let mod_sep_ctxt = self.span.ctxt();
2113 if self.eat(&token::ModSep) {
2114 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2116 self.parse_path_segments(&mut segments, style, enable_warning)?;
2118 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2121 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2122 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2123 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2124 let meta_ident = match self.token {
2125 token::Interpolated(ref nt) => match nt.0 {
2126 token::NtMeta(ref meta) => match meta.node {
2127 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2134 if let Some(path) = meta_ident {
2138 self.parse_path(style)
2141 fn parse_path_segments(&mut self,
2142 segments: &mut Vec<PathSegment>,
2144 enable_warning: bool)
2145 -> PResult<'a, ()> {
2147 segments.push(self.parse_path_segment(style, enable_warning)?);
2149 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2155 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2156 -> PResult<'a, PathSegment> {
2157 let ident = self.parse_path_segment_ident()?;
2159 let is_args_start = |token: &token::Token| match *token {
2160 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2163 let check_args_start = |this: &mut Self| {
2164 this.expected_tokens.extend_from_slice(
2165 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2167 is_args_start(&this.token)
2170 Ok(if style == PathStyle::Type && check_args_start(self) ||
2171 style != PathStyle::Mod && self.check(&token::ModSep)
2172 && self.look_ahead(1, |t| is_args_start(t)) {
2173 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2175 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2176 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2177 .span_label(self.prev_span, "try removing `::`").emit();
2180 let args = if self.eat_lt() {
2182 let (args, bindings) = self.parse_generic_args()?;
2184 let span = lo.to(self.prev_span);
2185 AngleBracketedArgs { args, bindings, span }.into()
2189 let inputs = self.parse_seq_to_before_tokens(
2190 &[&token::CloseDelim(token::Paren)],
2191 SeqSep::trailing_allowed(token::Comma),
2192 TokenExpectType::Expect,
2195 let span = lo.to(self.prev_span);
2196 let output = if self.eat(&token::RArrow) {
2197 Some(self.parse_ty_common(false, false)?)
2201 ParenthesisedArgs { inputs, output, span }.into()
2204 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2206 // Generic arguments are not found.
2207 PathSegment::from_ident(ident)
2211 crate fn check_lifetime(&mut self) -> bool {
2212 self.expected_tokens.push(TokenType::Lifetime);
2213 self.token.is_lifetime()
2216 /// Parse single lifetime 'a or panic.
2217 crate fn expect_lifetime(&mut self) -> Lifetime {
2218 if let Some(ident) = self.token.lifetime() {
2219 let span = self.span;
2221 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2223 self.span_bug(self.span, "not a lifetime")
2227 fn eat_label(&mut self) -> Option<Label> {
2228 if let Some(ident) = self.token.lifetime() {
2229 let span = self.span;
2231 Some(Label { ident: Ident::new(ident.name, span) })
2237 /// Parse mutability (`mut` or nothing).
2238 fn parse_mutability(&mut self) -> Mutability {
2239 if self.eat_keyword(keywords::Mut) {
2242 Mutability::Immutable
2246 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2247 if let token::Literal(token::Integer(name), None) = self.token {
2249 Ok(Ident::new(name, self.prev_span))
2251 self.parse_ident_common(false)
2255 /// Parse ident (COLON expr)?
2256 fn parse_field(&mut self) -> PResult<'a, Field> {
2257 let attrs = self.parse_outer_attributes()?;
2260 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2261 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2262 let fieldname = self.parse_field_name()?;
2264 (fieldname, self.parse_expr()?, false)
2266 let fieldname = self.parse_ident_common(false)?;
2268 // Mimic `x: x` for the `x` field shorthand.
2269 let path = ast::Path::from_ident(fieldname);
2270 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2271 (fieldname, expr, true)
2275 span: lo.to(expr.span),
2278 attrs: attrs.into(),
2282 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2283 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2286 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2287 ExprKind::Unary(unop, expr)
2290 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2291 ExprKind::Binary(binop, lhs, rhs)
2294 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2295 ExprKind::Call(f, args)
2298 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2299 ExprKind::Index(expr, idx)
2302 fn mk_range(&mut self,
2303 start: Option<P<Expr>>,
2304 end: Option<P<Expr>>,
2305 limits: RangeLimits)
2306 -> PResult<'a, ast::ExprKind> {
2307 if end.is_none() && limits == RangeLimits::Closed {
2308 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2310 Ok(ExprKind::Range(start, end, limits))
2314 fn mk_assign_op(&mut self, binop: ast::BinOp,
2315 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2316 ExprKind::AssignOp(binop, lhs, rhs)
2319 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2321 id: ast::DUMMY_NODE_ID,
2322 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2328 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2329 let delim = match self.token {
2330 token::OpenDelim(delim) => delim,
2332 let msg = "expected open delimiter";
2333 let mut err = self.fatal(msg);
2334 err.span_label(self.span, msg);
2338 let tts = match self.parse_token_tree() {
2339 TokenTree::Delimited(_, _, tts) => tts,
2340 _ => unreachable!(),
2342 let delim = match delim {
2343 token::Paren => MacDelimiter::Parenthesis,
2344 token::Bracket => MacDelimiter::Bracket,
2345 token::Brace => MacDelimiter::Brace,
2346 token::NoDelim => self.bug("unexpected no delimiter"),
2348 Ok((delim, tts.stream().into()))
2351 /// At the bottom (top?) of the precedence hierarchy,
2352 /// parse things like parenthesized exprs,
2353 /// macros, return, etc.
2355 /// N.B., this does not parse outer attributes,
2356 /// and is private because it only works
2357 /// correctly if called from parse_dot_or_call_expr().
2358 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2359 maybe_whole_expr!(self);
2361 // Outer attributes are already parsed and will be
2362 // added to the return value after the fact.
2364 // Therefore, prevent sub-parser from parsing
2365 // attributes by giving them a empty "already parsed" list.
2366 let mut attrs = ThinVec::new();
2369 let mut hi = self.span;
2373 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2375 token::OpenDelim(token::Paren) => {
2378 attrs.extend(self.parse_inner_attributes()?);
2380 // (e) is parenthesized e
2381 // (e,) is a tuple with only one field, e
2382 let mut es = vec![];
2383 let mut trailing_comma = false;
2384 while self.token != token::CloseDelim(token::Paren) {
2385 es.push(self.parse_expr()?);
2386 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2387 if self.eat(&token::Comma) {
2388 trailing_comma = true;
2390 trailing_comma = false;
2396 hi = self.prev_span;
2397 ex = if es.len() == 1 && !trailing_comma {
2398 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2403 token::OpenDelim(token::Brace) => {
2404 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2406 token::BinOp(token::Or) | token::OrOr => {
2407 return self.parse_lambda_expr(attrs);
2409 token::OpenDelim(token::Bracket) => {
2412 attrs.extend(self.parse_inner_attributes()?);
2414 if self.eat(&token::CloseDelim(token::Bracket)) {
2416 ex = ExprKind::Array(Vec::new());
2419 let first_expr = self.parse_expr()?;
2420 if self.eat(&token::Semi) {
2421 // Repeating array syntax: [ 0; 512 ]
2422 let count = AnonConst {
2423 id: ast::DUMMY_NODE_ID,
2424 value: self.parse_expr()?,
2426 self.expect(&token::CloseDelim(token::Bracket))?;
2427 ex = ExprKind::Repeat(first_expr, count);
2428 } else if self.eat(&token::Comma) {
2429 // Vector with two or more elements.
2430 let remaining_exprs = self.parse_seq_to_end(
2431 &token::CloseDelim(token::Bracket),
2432 SeqSep::trailing_allowed(token::Comma),
2433 |p| Ok(p.parse_expr()?)
2435 let mut exprs = vec![first_expr];
2436 exprs.extend(remaining_exprs);
2437 ex = ExprKind::Array(exprs);
2439 // Vector with one element.
2440 self.expect(&token::CloseDelim(token::Bracket))?;
2441 ex = ExprKind::Array(vec![first_expr]);
2444 hi = self.prev_span;
2448 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2450 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2452 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2454 if self.is_async_block() { // check for `async {` and `async move {`
2455 return self.parse_async_block(attrs);
2457 return self.parse_lambda_expr(attrs);
2460 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2461 return self.parse_lambda_expr(attrs);
2463 if self.eat_keyword(keywords::If) {
2464 return self.parse_if_expr(attrs);
2466 if self.eat_keyword(keywords::For) {
2467 let lo = self.prev_span;
2468 return self.parse_for_expr(None, lo, attrs);
2470 if self.eat_keyword(keywords::While) {
2471 let lo = self.prev_span;
2472 return self.parse_while_expr(None, lo, attrs);
2474 if let Some(label) = self.eat_label() {
2475 let lo = label.ident.span;
2476 self.expect(&token::Colon)?;
2477 if self.eat_keyword(keywords::While) {
2478 return self.parse_while_expr(Some(label), lo, attrs)
2480 if self.eat_keyword(keywords::For) {
2481 return self.parse_for_expr(Some(label), lo, attrs)
2483 if self.eat_keyword(keywords::Loop) {
2484 return self.parse_loop_expr(Some(label), lo, attrs)
2486 if self.token == token::OpenDelim(token::Brace) {
2487 return self.parse_block_expr(Some(label),
2489 BlockCheckMode::Default,
2492 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2493 let mut err = self.fatal(msg);
2494 err.span_label(self.span, msg);
2497 if self.eat_keyword(keywords::Loop) {
2498 let lo = self.prev_span;
2499 return self.parse_loop_expr(None, lo, attrs);
2501 if self.eat_keyword(keywords::Continue) {
2502 let label = self.eat_label();
2503 let ex = ExprKind::Continue(label);
2504 let hi = self.prev_span;
2505 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2507 if self.eat_keyword(keywords::Match) {
2508 let match_sp = self.prev_span;
2509 return self.parse_match_expr(attrs).map_err(|mut err| {
2510 err.span_label(match_sp, "while parsing this match expression");
2514 if self.eat_keyword(keywords::Unsafe) {
2515 return self.parse_block_expr(
2518 BlockCheckMode::Unsafe(ast::UserProvided),
2521 if self.is_do_catch_block() {
2522 let mut db = self.fatal("found removed `do catch` syntax");
2523 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2526 if self.is_try_block() {
2528 assert!(self.eat_keyword(keywords::Try));
2529 return self.parse_try_block(lo, attrs);
2531 if self.eat_keyword(keywords::Return) {
2532 if self.token.can_begin_expr() {
2533 let e = self.parse_expr()?;
2535 ex = ExprKind::Ret(Some(e));
2537 ex = ExprKind::Ret(None);
2539 } else if self.eat_keyword(keywords::Break) {
2540 let label = self.eat_label();
2541 let e = if self.token.can_begin_expr()
2542 && !(self.token == token::OpenDelim(token::Brace)
2543 && self.restrictions.contains(
2544 Restrictions::NO_STRUCT_LITERAL)) {
2545 Some(self.parse_expr()?)
2549 ex = ExprKind::Break(label, e);
2550 hi = self.prev_span;
2551 } else if self.eat_keyword(keywords::Yield) {
2552 if self.token.can_begin_expr() {
2553 let e = self.parse_expr()?;
2555 ex = ExprKind::Yield(Some(e));
2557 ex = ExprKind::Yield(None);
2559 } else if self.token.is_keyword(keywords::Let) {
2560 // Catch this syntax error here, instead of in `parse_ident`, so
2561 // that we can explicitly mention that let is not to be used as an expression
2562 let mut db = self.fatal("expected expression, found statement (`let`)");
2563 db.span_label(self.span, "expected expression");
2564 db.note("variable declaration using `let` is a statement");
2566 } else if self.token.is_path_start() {
2567 let pth = self.parse_path(PathStyle::Expr)?;
2569 // `!`, as an operator, is prefix, so we know this isn't that
2570 if self.eat(&token::Not) {
2571 // MACRO INVOCATION expression
2572 let (delim, tts) = self.expect_delimited_token_tree()?;
2573 let hi = self.prev_span;
2574 let node = Mac_ { path: pth, tts, delim };
2575 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2577 if self.check(&token::OpenDelim(token::Brace)) {
2578 // This is a struct literal, unless we're prohibited
2579 // from parsing struct literals here.
2580 let prohibited = self.restrictions.contains(
2581 Restrictions::NO_STRUCT_LITERAL
2584 return self.parse_struct_expr(lo, pth, attrs);
2589 ex = ExprKind::Path(None, pth);
2591 match self.parse_literal_maybe_minus() {
2594 ex = expr.node.clone();
2597 self.cancel(&mut err);
2598 let msg = format!("expected expression, found {}",
2599 self.this_token_descr());
2600 let mut err = self.fatal(&msg);
2601 err.span_label(self.span, "expected expression");
2609 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2610 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2615 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2616 -> PResult<'a, P<Expr>> {
2617 let struct_sp = lo.to(self.prev_span);
2619 let mut fields = Vec::new();
2620 let mut base = None;
2622 attrs.extend(self.parse_inner_attributes()?);
2624 while self.token != token::CloseDelim(token::Brace) {
2625 if self.eat(&token::DotDot) {
2626 let exp_span = self.prev_span;
2627 match self.parse_expr() {
2633 self.recover_stmt();
2636 if self.token == token::Comma {
2637 let mut err = self.sess.span_diagnostic.mut_span_err(
2638 exp_span.to(self.prev_span),
2639 "cannot use a comma after the base struct",
2641 err.span_suggestion_short_with_applicability(
2643 "remove this comma",
2645 Applicability::MachineApplicable
2647 err.note("the base struct must always be the last field");
2649 self.recover_stmt();
2654 match self.parse_field() {
2655 Ok(f) => fields.push(f),
2657 e.span_label(struct_sp, "while parsing this struct");
2660 // If the next token is a comma, then try to parse
2661 // what comes next as additional fields, rather than
2662 // bailing out until next `}`.
2663 if self.token != token::Comma {
2664 self.recover_stmt();
2670 match self.expect_one_of(&[token::Comma],
2671 &[token::CloseDelim(token::Brace)]) {
2675 self.recover_stmt();
2681 let span = lo.to(self.span);
2682 self.expect(&token::CloseDelim(token::Brace))?;
2683 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2686 fn parse_or_use_outer_attributes(&mut self,
2687 already_parsed_attrs: Option<ThinVec<Attribute>>)
2688 -> PResult<'a, ThinVec<Attribute>> {
2689 if let Some(attrs) = already_parsed_attrs {
2692 self.parse_outer_attributes().map(|a| a.into())
2696 /// Parse a block or unsafe block
2697 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2698 lo: Span, blk_mode: BlockCheckMode,
2699 outer_attrs: ThinVec<Attribute>)
2700 -> PResult<'a, P<Expr>> {
2701 self.expect(&token::OpenDelim(token::Brace))?;
2703 let mut attrs = outer_attrs;
2704 attrs.extend(self.parse_inner_attributes()?);
2706 let blk = self.parse_block_tail(lo, blk_mode)?;
2707 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2710 /// parse a.b or a(13) or a[4] or just a
2711 fn parse_dot_or_call_expr(&mut self,
2712 already_parsed_attrs: Option<ThinVec<Attribute>>)
2713 -> PResult<'a, P<Expr>> {
2714 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2716 let b = self.parse_bottom_expr();
2717 let (span, b) = self.interpolated_or_expr_span(b)?;
2718 self.parse_dot_or_call_expr_with(b, span, attrs)
2721 fn parse_dot_or_call_expr_with(&mut self,
2724 mut attrs: ThinVec<Attribute>)
2725 -> PResult<'a, P<Expr>> {
2726 // Stitch the list of outer attributes onto the return value.
2727 // A little bit ugly, but the best way given the current code
2729 self.parse_dot_or_call_expr_with_(e0, lo)
2731 expr.map(|mut expr| {
2732 attrs.extend::<Vec<_>>(expr.attrs.into());
2735 ExprKind::If(..) | ExprKind::IfLet(..) => {
2736 if !expr.attrs.is_empty() {
2737 // Just point to the first attribute in there...
2738 let span = expr.attrs[0].span;
2741 "attributes are not yet allowed on `if` \
2752 // Assuming we have just parsed `.`, continue parsing into an expression.
2753 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2754 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2755 Ok(match self.token {
2756 token::OpenDelim(token::Paren) => {
2757 // Method call `expr.f()`
2758 let mut args = self.parse_unspanned_seq(
2759 &token::OpenDelim(token::Paren),
2760 &token::CloseDelim(token::Paren),
2761 SeqSep::trailing_allowed(token::Comma),
2762 |p| Ok(p.parse_expr()?)
2764 args.insert(0, self_arg);
2766 let span = lo.to(self.prev_span);
2767 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2770 // Field access `expr.f`
2771 if let Some(args) = segment.args {
2772 self.span_err(args.span(),
2773 "field expressions may not have generic arguments");
2776 let span = lo.to(self.prev_span);
2777 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2782 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2787 while self.eat(&token::Question) {
2788 let hi = self.prev_span;
2789 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2793 if self.eat(&token::Dot) {
2795 token::Ident(..) => {
2796 e = self.parse_dot_suffix(e, lo)?;
2798 token::Literal(token::Integer(name), _) => {
2799 let span = self.span;
2801 let field = ExprKind::Field(e, Ident::new(name, span));
2802 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2804 token::Literal(token::Float(n), _suf) => {
2806 let fstr = n.as_str();
2807 let mut err = self.diagnostic()
2808 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
2809 err.span_label(self.prev_span, "unexpected token");
2810 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2811 let float = match fstr.parse::<f64>().ok() {
2815 let sugg = pprust::to_string(|s| {
2816 use print::pprust::PrintState;
2820 s.print_usize(float.trunc() as usize)?;
2823 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2825 err.span_suggestion_with_applicability(
2826 lo.to(self.prev_span),
2827 "try parenthesizing the first index",
2829 Applicability::MachineApplicable
2836 // FIXME Could factor this out into non_fatal_unexpected or something.
2837 let actual = self.this_token_to_string();
2838 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2843 if self.expr_is_complete(&e) { break; }
2846 token::OpenDelim(token::Paren) => {
2847 let es = self.parse_unspanned_seq(
2848 &token::OpenDelim(token::Paren),
2849 &token::CloseDelim(token::Paren),
2850 SeqSep::trailing_allowed(token::Comma),
2851 |p| Ok(p.parse_expr()?)
2853 hi = self.prev_span;
2855 let nd = self.mk_call(e, es);
2856 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2860 // Could be either an index expression or a slicing expression.
2861 token::OpenDelim(token::Bracket) => {
2863 let ix = self.parse_expr()?;
2865 self.expect(&token::CloseDelim(token::Bracket))?;
2866 let index = self.mk_index(e, ix);
2867 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2875 crate fn process_potential_macro_variable(&mut self) {
2876 let (token, span) = match self.token {
2877 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2878 self.look_ahead(1, |t| t.is_ident()) => {
2880 let name = match self.token {
2881 token::Ident(ident, _) => ident,
2884 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2885 err.span_label(self.span, "unknown macro variable");
2890 token::Interpolated(ref nt) => {
2891 self.meta_var_span = Some(self.span);
2892 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2893 // and lifetime tokens, so the former are never encountered during normal parsing.
2895 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2896 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2906 /// parse a single token tree from the input.
2907 crate fn parse_token_tree(&mut self) -> TokenTree {
2909 token::OpenDelim(..) => {
2910 let frame = mem::replace(&mut self.token_cursor.frame,
2911 self.token_cursor.stack.pop().unwrap());
2912 self.span = frame.span.entire();
2914 TokenTree::Delimited(
2917 frame.tree_cursor.original_stream().into(),
2920 token::CloseDelim(_) | token::Eof => unreachable!(),
2922 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2924 TokenTree::Token(span, token)
2929 // parse a stream of tokens into a list of TokenTree's,
2931 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2932 let mut tts = Vec::new();
2933 while self.token != token::Eof {
2934 tts.push(self.parse_token_tree());
2939 pub fn parse_tokens(&mut self) -> TokenStream {
2940 let mut result = Vec::new();
2943 token::Eof | token::CloseDelim(..) => break,
2944 _ => result.push(self.parse_token_tree().into()),
2947 TokenStream::new(result)
2950 /// Parse a prefix-unary-operator expr
2951 fn parse_prefix_expr(&mut self,
2952 already_parsed_attrs: Option<ThinVec<Attribute>>)
2953 -> PResult<'a, P<Expr>> {
2954 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2956 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2957 let (hi, ex) = match self.token {
2960 let e = self.parse_prefix_expr(None);
2961 let (span, e) = self.interpolated_or_expr_span(e)?;
2962 (lo.to(span), self.mk_unary(UnOp::Not, e))
2964 // Suggest `!` for bitwise negation when encountering a `~`
2967 let e = self.parse_prefix_expr(None);
2968 let (span, e) = self.interpolated_or_expr_span(e)?;
2969 let span_of_tilde = lo;
2970 let mut err = self.diagnostic()
2971 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2972 err.span_suggestion_short_with_applicability(
2974 "use `!` to perform bitwise negation",
2976 Applicability::MachineApplicable
2979 (lo.to(span), self.mk_unary(UnOp::Not, e))
2981 token::BinOp(token::Minus) => {
2983 let e = self.parse_prefix_expr(None);
2984 let (span, e) = self.interpolated_or_expr_span(e)?;
2985 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2987 token::BinOp(token::Star) => {
2989 let e = self.parse_prefix_expr(None);
2990 let (span, e) = self.interpolated_or_expr_span(e)?;
2991 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2993 token::BinOp(token::And) | token::AndAnd => {
2995 let m = self.parse_mutability();
2996 let e = self.parse_prefix_expr(None);
2997 let (span, e) = self.interpolated_or_expr_span(e)?;
2998 (lo.to(span), ExprKind::AddrOf(m, e))
3000 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3002 let place = self.parse_expr_res(
3003 Restrictions::NO_STRUCT_LITERAL,
3006 let blk = self.parse_block()?;
3007 let span = blk.span;
3008 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3009 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3011 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3013 let e = self.parse_prefix_expr(None);
3014 let (span, e) = self.interpolated_or_expr_span(e)?;
3015 (lo.to(span), ExprKind::Box(e))
3017 token::Ident(..) if self.token.is_ident_named("not") => {
3018 // `not` is just an ordinary identifier in Rust-the-language,
3019 // but as `rustc`-the-compiler, we can issue clever diagnostics
3020 // for confused users who really want to say `!`
3021 let token_cannot_continue_expr = |t: &token::Token| match *t {
3022 // These tokens can start an expression after `!`, but
3023 // can't continue an expression after an ident
3024 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3025 token::Literal(..) | token::Pound => true,
3026 token::Interpolated(ref nt) => match nt.0 {
3027 token::NtIdent(..) | token::NtExpr(..) |
3028 token::NtBlock(..) | token::NtPath(..) => true,
3033 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3034 if cannot_continue_expr {
3036 // Emit the error ...
3037 let mut err = self.diagnostic()
3038 .struct_span_err(self.span,
3039 &format!("unexpected {} after identifier",
3040 self.this_token_descr()));
3041 // span the `not` plus trailing whitespace to avoid
3042 // trailing whitespace after the `!` in our suggestion
3043 let to_replace = self.sess.source_map()
3044 .span_until_non_whitespace(lo.to(self.span));
3045 err.span_suggestion_short_with_applicability(
3047 "use `!` to perform logical negation",
3049 Applicability::MachineApplicable
3052 // —and recover! (just as if we were in the block
3053 // for the `token::Not` arm)
3054 let e = self.parse_prefix_expr(None);
3055 let (span, e) = self.interpolated_or_expr_span(e)?;
3056 (lo.to(span), self.mk_unary(UnOp::Not, e))
3058 return self.parse_dot_or_call_expr(Some(attrs));
3061 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3063 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3066 /// Parse an associative expression
3068 /// This parses an expression accounting for associativity and precedence of the operators in
3071 fn parse_assoc_expr(&mut self,
3072 already_parsed_attrs: Option<ThinVec<Attribute>>)
3073 -> PResult<'a, P<Expr>> {
3074 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3077 /// Parse an associative expression with operators of at least `min_prec` precedence
3078 fn parse_assoc_expr_with(&mut self,
3081 -> PResult<'a, P<Expr>> {
3082 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3085 let attrs = match lhs {
3086 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3089 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3090 return self.parse_prefix_range_expr(attrs);
3092 self.parse_prefix_expr(attrs)?
3096 if self.expr_is_complete(&lhs) {
3097 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3100 self.expected_tokens.push(TokenType::Operator);
3101 while let Some(op) = AssocOp::from_token(&self.token) {
3103 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3104 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3105 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3106 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3107 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3108 (PrevTokenKind::Interpolated, _) => self.prev_span,
3109 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3110 if path.segments.len() == 1 => self.prev_span,
3114 let cur_op_span = self.span;
3115 let restrictions = if op.is_assign_like() {
3116 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3120 if op.precedence() < min_prec {
3123 // Check for deprecated `...` syntax
3124 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3125 self.err_dotdotdot_syntax(self.span);
3129 if op.is_comparison() {
3130 self.check_no_chained_comparison(&lhs, &op);
3133 if op == AssocOp::As {
3134 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3136 } else if op == AssocOp::Colon {
3137 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3140 err.span_label(self.span,
3141 "expecting a type here because of type ascription");
3142 let cm = self.sess.source_map();
3143 let cur_pos = cm.lookup_char_pos(self.span.lo());
3144 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3145 if cur_pos.line != op_pos.line {
3146 err.span_suggestion_with_applicability(
3148 "try using a semicolon",
3150 Applicability::MaybeIncorrect // speculative
3157 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3158 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3159 // generalise it to the Fixity::None code.
3161 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3162 // two variants are handled with `parse_prefix_range_expr` call above.
3163 let rhs = if self.is_at_start_of_range_notation_rhs() {
3164 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3165 LhsExpr::NotYetParsed)?)
3169 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3174 let limits = if op == AssocOp::DotDot {
3175 RangeLimits::HalfOpen
3180 let r = self.mk_range(Some(lhs), rhs, limits)?;
3181 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3185 let rhs = match op.fixity() {
3186 Fixity::Right => self.with_res(
3187 restrictions - Restrictions::STMT_EXPR,
3189 this.parse_assoc_expr_with(op.precedence(),
3190 LhsExpr::NotYetParsed)
3192 Fixity::Left => self.with_res(
3193 restrictions - Restrictions::STMT_EXPR,
3195 this.parse_assoc_expr_with(op.precedence() + 1,
3196 LhsExpr::NotYetParsed)
3198 // We currently have no non-associative operators that are not handled above by
3199 // the special cases. The code is here only for future convenience.
3200 Fixity::None => self.with_res(
3201 restrictions - Restrictions::STMT_EXPR,
3203 this.parse_assoc_expr_with(op.precedence() + 1,
3204 LhsExpr::NotYetParsed)
3208 let span = lhs_span.to(rhs.span);
3210 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3211 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3212 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3213 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3214 AssocOp::Greater | AssocOp::GreaterEqual => {
3215 let ast_op = op.to_ast_binop().unwrap();
3216 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3217 self.mk_expr(span, binary, ThinVec::new())
3220 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3221 AssocOp::ObsoleteInPlace =>
3222 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3223 AssocOp::AssignOp(k) => {
3225 token::Plus => BinOpKind::Add,
3226 token::Minus => BinOpKind::Sub,
3227 token::Star => BinOpKind::Mul,
3228 token::Slash => BinOpKind::Div,
3229 token::Percent => BinOpKind::Rem,
3230 token::Caret => BinOpKind::BitXor,
3231 token::And => BinOpKind::BitAnd,
3232 token::Or => BinOpKind::BitOr,
3233 token::Shl => BinOpKind::Shl,
3234 token::Shr => BinOpKind::Shr,
3236 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3237 self.mk_expr(span, aopexpr, ThinVec::new())
3239 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3240 self.bug("AssocOp should have been handled by special case")
3244 if op.fixity() == Fixity::None { break }
3249 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3250 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3251 -> PResult<'a, P<Expr>> {
3252 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3253 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3256 // Save the state of the parser before parsing type normally, in case there is a
3257 // LessThan comparison after this cast.
3258 let parser_snapshot_before_type = self.clone();
3259 match self.parse_ty_no_plus() {
3261 Ok(mk_expr(self, rhs))
3263 Err(mut type_err) => {
3264 // Rewind to before attempting to parse the type with generics, to recover
3265 // from situations like `x as usize < y` in which we first tried to parse
3266 // `usize < y` as a type with generic arguments.
3267 let parser_snapshot_after_type = self.clone();
3268 mem::replace(self, parser_snapshot_before_type);
3270 match self.parse_path(PathStyle::Expr) {
3272 let (op_noun, op_verb) = match self.token {
3273 token::Lt => ("comparison", "comparing"),
3274 token::BinOp(token::Shl) => ("shift", "shifting"),
3276 // We can end up here even without `<` being the next token, for
3277 // example because `parse_ty_no_plus` returns `Err` on keywords,
3278 // but `parse_path` returns `Ok` on them due to error recovery.
3279 // Return original error and parser state.
3280 mem::replace(self, parser_snapshot_after_type);
3281 return Err(type_err);
3285 // Successfully parsed the type path leaving a `<` yet to parse.
3288 // Report non-fatal diagnostics, keep `x as usize` as an expression
3289 // in AST and continue parsing.
3290 let msg = format!("`<` is interpreted as a start of generic \
3291 arguments for `{}`, not a {}", path, op_noun);
3292 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3293 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3294 "interpreted as generic arguments");
3295 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3297 let expr = mk_expr(self, P(Ty {
3299 node: TyKind::Path(None, path),
3300 id: ast::DUMMY_NODE_ID
3303 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3304 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3305 err.span_suggestion_with_applicability(
3307 &format!("try {} the cast value", op_verb),
3308 format!("({})", expr_str),
3309 Applicability::MachineApplicable
3315 Err(mut path_err) => {
3316 // Couldn't parse as a path, return original error and parser state.
3318 mem::replace(self, parser_snapshot_after_type);
3326 /// Produce an error if comparison operators are chained (RFC #558).
3327 /// We only need to check lhs, not rhs, because all comparison ops
3328 /// have same precedence and are left-associative
3329 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3330 debug_assert!(outer_op.is_comparison(),
3331 "check_no_chained_comparison: {:?} is not comparison",
3334 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3335 // respan to include both operators
3336 let op_span = op.span.to(self.span);
3337 let mut err = self.diagnostic().struct_span_err(op_span,
3338 "chained comparison operators require parentheses");
3339 if op.node == BinOpKind::Lt &&
3340 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3341 *outer_op == AssocOp::Greater // even in a case like the following:
3342 { // Foo<Bar<Baz<Qux, ()>>>
3344 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3345 err.help("or use `(...)` if you meant to specify fn arguments");
3353 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3354 fn parse_prefix_range_expr(&mut self,
3355 already_parsed_attrs: Option<ThinVec<Attribute>>)
3356 -> PResult<'a, P<Expr>> {
3357 // Check for deprecated `...` syntax
3358 if self.token == token::DotDotDot {
3359 self.err_dotdotdot_syntax(self.span);
3362 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3363 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3365 let tok = self.token.clone();
3366 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3368 let mut hi = self.span;
3370 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3371 // RHS must be parsed with more associativity than the dots.
3372 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3373 Some(self.parse_assoc_expr_with(next_prec,
3374 LhsExpr::NotYetParsed)
3382 let limits = if tok == token::DotDot {
3383 RangeLimits::HalfOpen
3388 let r = self.mk_range(None, opt_end, limits)?;
3389 Ok(self.mk_expr(lo.to(hi), r, attrs))
3392 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3393 if self.token.can_begin_expr() {
3394 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3395 if self.token == token::OpenDelim(token::Brace) {
3396 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3404 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3405 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3406 if self.check_keyword(keywords::Let) {
3407 return self.parse_if_let_expr(attrs);
3409 let lo = self.prev_span;
3410 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3412 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3413 // verify that the last statement is either an implicit return (no `;`) or an explicit
3414 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3415 // the dead code lint.
3416 if self.eat_keyword(keywords::Else) || !cond.returns() {
3417 let sp = self.sess.source_map().next_point(lo);
3418 let mut err = self.diagnostic()
3419 .struct_span_err(sp, "missing condition for `if` statemement");
3420 err.span_label(sp, "expected if condition here");
3423 let not_block = self.token != token::OpenDelim(token::Brace);
3424 let thn = self.parse_block().map_err(|mut err| {
3426 err.span_label(lo, "this `if` statement has a condition, but no block");
3430 let mut els: Option<P<Expr>> = None;
3431 let mut hi = thn.span;
3432 if self.eat_keyword(keywords::Else) {
3433 let elexpr = self.parse_else_expr()?;
3437 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3440 /// Parse an 'if let' expression ('if' token already eaten)
3441 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3442 -> PResult<'a, P<Expr>> {
3443 let lo = self.prev_span;
3444 self.expect_keyword(keywords::Let)?;
3445 let pats = self.parse_pats()?;
3446 self.expect(&token::Eq)?;
3447 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3448 let thn = self.parse_block()?;
3449 let (hi, els) = if self.eat_keyword(keywords::Else) {
3450 let expr = self.parse_else_expr()?;
3451 (expr.span, Some(expr))
3455 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3458 // `move |args| expr`
3459 fn parse_lambda_expr(&mut self,
3460 attrs: ThinVec<Attribute>)
3461 -> PResult<'a, P<Expr>>
3464 let movability = if self.eat_keyword(keywords::Static) {
3469 let asyncness = if self.span.rust_2018() {
3470 self.parse_asyncness()
3474 let capture_clause = if self.eat_keyword(keywords::Move) {
3479 let decl = self.parse_fn_block_decl()?;
3480 let decl_hi = self.prev_span;
3481 let body = match decl.output {
3482 FunctionRetTy::Default(_) => {
3483 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3484 self.parse_expr_res(restrictions, None)?
3487 // If an explicit return type is given, require a
3488 // block to appear (RFC 968).
3489 let body_lo = self.span;
3490 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3496 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3500 // `else` token already eaten
3501 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3502 if self.eat_keyword(keywords::If) {
3503 return self.parse_if_expr(ThinVec::new());
3505 let blk = self.parse_block()?;
3506 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3510 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3511 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3513 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3514 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3516 let pat = self.parse_top_level_pat()?;
3517 if !self.eat_keyword(keywords::In) {
3518 let in_span = self.prev_span.between(self.span);
3519 let mut err = self.sess.span_diagnostic
3520 .struct_span_err(in_span, "missing `in` in `for` loop");
3521 err.span_suggestion_short_with_applicability(
3522 in_span, "try adding `in` here", " in ".into(),
3523 // has been misleading, at least in the past (closed Issue #48492)
3524 Applicability::MaybeIncorrect
3528 let in_span = self.prev_span;
3529 if self.eat_keyword(keywords::In) {
3530 // a common typo: `for _ in in bar {}`
3531 let mut err = self.sess.span_diagnostic.struct_span_err(
3533 "expected iterable, found keyword `in`",
3535 err.span_suggestion_short_with_applicability(
3536 in_span.until(self.prev_span),
3537 "remove the duplicated `in`",
3539 Applicability::MachineApplicable,
3541 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3542 err.note("for more information on the status of emplacement syntax, see <\
3543 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3546 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3547 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3548 attrs.extend(iattrs);
3550 let hi = self.prev_span;
3551 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3554 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3555 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3557 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3558 if self.token.is_keyword(keywords::Let) {
3559 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3561 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3562 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3563 attrs.extend(iattrs);
3564 let span = span_lo.to(body.span);
3565 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3568 /// Parse a 'while let' expression ('while' token already eaten)
3569 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3571 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3572 self.expect_keyword(keywords::Let)?;
3573 let pats = self.parse_pats()?;
3574 self.expect(&token::Eq)?;
3575 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3576 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3577 attrs.extend(iattrs);
3578 let span = span_lo.to(body.span);
3579 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3582 // parse `loop {...}`, `loop` token already eaten
3583 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3585 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3586 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3587 attrs.extend(iattrs);
3588 let span = span_lo.to(body.span);
3589 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3592 /// Parse an `async move {...}` expression
3593 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3594 -> PResult<'a, P<Expr>>
3596 let span_lo = self.span;
3597 self.expect_keyword(keywords::Async)?;
3598 let capture_clause = if self.eat_keyword(keywords::Move) {
3603 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3604 attrs.extend(iattrs);
3606 span_lo.to(body.span),
3607 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3610 /// Parse a `try {...}` expression (`try` token already eaten)
3611 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3612 -> PResult<'a, P<Expr>>
3614 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3615 attrs.extend(iattrs);
3616 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3619 // `match` token already eaten
3620 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3621 let match_span = self.prev_span;
3622 let lo = self.prev_span;
3623 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3625 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3626 if self.token == token::Token::Semi {
3627 e.span_suggestion_short_with_applicability(
3629 "try removing this `match`",
3631 Applicability::MaybeIncorrect // speculative
3636 attrs.extend(self.parse_inner_attributes()?);
3638 let mut arms: Vec<Arm> = Vec::new();
3639 while self.token != token::CloseDelim(token::Brace) {
3640 match self.parse_arm() {
3641 Ok(arm) => arms.push(arm),
3643 // Recover by skipping to the end of the block.
3645 self.recover_stmt();
3646 let span = lo.to(self.span);
3647 if self.token == token::CloseDelim(token::Brace) {
3650 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3656 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3659 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3660 maybe_whole!(self, NtArm, |x| x);
3662 let attrs = self.parse_outer_attributes()?;
3663 // Allow a '|' before the pats (RFC 1925)
3664 self.eat(&token::BinOp(token::Or));
3665 let pats = self.parse_pats()?;
3666 let guard = if self.eat_keyword(keywords::If) {
3667 Some(Guard::If(self.parse_expr()?))
3671 let arrow_span = self.span;
3672 self.expect(&token::FatArrow)?;
3673 let arm_start_span = self.span;
3675 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3676 .map_err(|mut err| {
3677 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3681 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3682 && self.token != token::CloseDelim(token::Brace);
3685 let cm = self.sess.source_map();
3686 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3687 .map_err(|mut err| {
3688 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3689 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3690 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3691 && expr_lines.lines.len() == 2
3692 && self.token == token::FatArrow => {
3693 // We check whether there's any trailing code in the parse span,
3694 // if there isn't, we very likely have the following:
3697 // | -- - missing comma
3703 // | parsed until here as `"y" & X`
3704 err.span_suggestion_short_with_applicability(
3705 cm.next_point(arm_start_span),
3706 "missing a comma here to end this `match` arm",
3708 Applicability::MachineApplicable
3712 err.span_label(arrow_span,
3713 "while parsing the `match` arm starting here");
3719 self.eat(&token::Comma);
3730 /// Parse an expression
3732 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3733 self.parse_expr_res(Restrictions::empty(), None)
3736 /// Evaluate the closure with restrictions in place.
3738 /// After the closure is evaluated, restrictions are reset.
3739 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3740 where F: FnOnce(&mut Self) -> T
3742 let old = self.restrictions;
3743 self.restrictions = r;
3745 self.restrictions = old;
3750 /// Parse an expression, subject to the given restrictions
3752 fn parse_expr_res(&mut self, r: Restrictions,
3753 already_parsed_attrs: Option<ThinVec<Attribute>>)
3754 -> PResult<'a, P<Expr>> {
3755 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3758 /// Parse the RHS of a local variable declaration (e.g., '= 14;')
3759 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3760 if self.eat(&token::Eq) {
3761 Ok(Some(self.parse_expr()?))
3763 Ok(Some(self.parse_expr()?))
3769 /// Parse patterns, separated by '|' s
3770 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3771 let mut pats = Vec::new();
3773 pats.push(self.parse_top_level_pat()?);
3775 if self.token == token::OrOr {
3776 let mut err = self.struct_span_err(self.span,
3777 "unexpected token `||` after pattern");
3778 err.span_suggestion_with_applicability(
3780 "use a single `|` to specify multiple patterns",
3782 Applicability::MachineApplicable
3786 } else if self.eat(&token::BinOp(token::Or)) {
3794 // Parses a parenthesized list of patterns like
3795 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3796 // - a vector of the patterns that were parsed
3797 // - an option indicating the index of the `..` element
3798 // - a boolean indicating whether a trailing comma was present.
3799 // Trailing commas are significant because (p) and (p,) are different patterns.
3800 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3801 self.expect(&token::OpenDelim(token::Paren))?;
3802 let result = self.parse_pat_list()?;
3803 self.expect(&token::CloseDelim(token::Paren))?;
3807 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3808 let mut fields = Vec::new();
3809 let mut ddpos = None;
3810 let mut trailing_comma = false;
3812 if self.eat(&token::DotDot) {
3813 if ddpos.is_none() {
3814 ddpos = Some(fields.len());
3816 // Emit a friendly error, ignore `..` and continue parsing
3817 self.span_err(self.prev_span,
3818 "`..` can only be used once per tuple or tuple struct pattern");
3820 } else if !self.check(&token::CloseDelim(token::Paren)) {
3821 fields.push(self.parse_pat(None)?);
3826 trailing_comma = self.eat(&token::Comma);
3827 if !trailing_comma {
3832 if ddpos == Some(fields.len()) && trailing_comma {
3833 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3834 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3837 Ok((fields, ddpos, trailing_comma))
3840 fn parse_pat_vec_elements(
3842 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3843 let mut before = Vec::new();
3844 let mut slice = None;
3845 let mut after = Vec::new();
3846 let mut first = true;
3847 let mut before_slice = true;
3849 while self.token != token::CloseDelim(token::Bracket) {
3853 self.expect(&token::Comma)?;
3855 if self.token == token::CloseDelim(token::Bracket)
3856 && (before_slice || !after.is_empty()) {
3862 if self.eat(&token::DotDot) {
3864 if self.check(&token::Comma) ||
3865 self.check(&token::CloseDelim(token::Bracket)) {
3866 slice = Some(P(Pat {
3867 id: ast::DUMMY_NODE_ID,
3868 node: PatKind::Wild,
3869 span: self.prev_span,
3871 before_slice = false;
3877 let subpat = self.parse_pat(None)?;
3878 if before_slice && self.eat(&token::DotDot) {
3879 slice = Some(subpat);
3880 before_slice = false;
3881 } else if before_slice {
3882 before.push(subpat);
3888 Ok((before, slice, after))
3894 attrs: Vec<Attribute>
3895 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3896 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3898 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3899 // Parsing a pattern of the form "fieldname: pat"
3900 let fieldname = self.parse_field_name()?;
3902 let pat = self.parse_pat(None)?;
3904 (pat, fieldname, false)
3906 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3907 let is_box = self.eat_keyword(keywords::Box);
3908 let boxed_span = self.span;
3909 let is_ref = self.eat_keyword(keywords::Ref);
3910 let is_mut = self.eat_keyword(keywords::Mut);
3911 let fieldname = self.parse_ident()?;
3912 hi = self.prev_span;
3914 let bind_type = match (is_ref, is_mut) {
3915 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3916 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3917 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3918 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3920 let fieldpat = P(Pat {
3921 id: ast::DUMMY_NODE_ID,
3922 node: PatKind::Ident(bind_type, fieldname, None),
3923 span: boxed_span.to(hi),
3926 let subpat = if is_box {
3928 id: ast::DUMMY_NODE_ID,
3929 node: PatKind::Box(fieldpat),
3935 (subpat, fieldname, true)
3938 Ok(source_map::Spanned {
3940 node: ast::FieldPat {
3944 attrs: attrs.into(),
3949 /// Parse the fields of a struct-like pattern
3950 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3951 let mut fields = Vec::new();
3952 let mut etc = false;
3953 let mut ate_comma = true;
3954 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3955 let mut etc_span = None;
3957 while self.token != token::CloseDelim(token::Brace) {
3958 let attrs = self.parse_outer_attributes()?;
3961 // check that a comma comes after every field
3963 let err = self.struct_span_err(self.prev_span, "expected `,`");
3964 if let Some(mut delayed) = delayed_err {
3971 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3973 let mut etc_sp = self.span;
3975 if self.token == token::DotDotDot { // Issue #46718
3976 // Accept `...` as if it were `..` to avoid further errors
3977 let mut err = self.struct_span_err(self.span,
3978 "expected field pattern, found `...`");
3979 err.span_suggestion_with_applicability(
3981 "to omit remaining fields, use one fewer `.`",
3983 Applicability::MachineApplicable
3987 self.bump(); // `..` || `...`
3989 if self.token == token::CloseDelim(token::Brace) {
3990 etc_span = Some(etc_sp);
3993 let token_str = self.this_token_descr();
3994 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3996 err.span_label(self.span, "expected `}`");
3997 let mut comma_sp = None;
3998 if self.token == token::Comma { // Issue #49257
3999 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4000 err.span_label(etc_sp,
4001 "`..` must be at the end and cannot have a trailing comma");
4002 comma_sp = Some(self.span);
4007 etc_span = Some(etc_sp.until(self.span));
4008 if self.token == token::CloseDelim(token::Brace) {
4009 // If the struct looks otherwise well formed, recover and continue.
4010 if let Some(sp) = comma_sp {
4011 err.span_suggestion_short_with_applicability(
4013 "remove this comma",
4015 Applicability::MachineApplicable,
4020 } else if self.token.is_ident() && ate_comma {
4021 // Accept fields coming after `..,`.
4022 // This way we avoid "pattern missing fields" errors afterwards.
4023 // We delay this error until the end in order to have a span for a
4025 if let Some(mut delayed_err) = delayed_err {
4029 delayed_err = Some(err);
4032 if let Some(mut err) = delayed_err {
4039 fields.push(match self.parse_pat_field(lo, attrs) {
4042 if let Some(mut delayed_err) = delayed_err {
4048 ate_comma = self.eat(&token::Comma);
4051 if let Some(mut err) = delayed_err {
4052 if let Some(etc_span) = etc_span {
4053 err.multipart_suggestion(
4054 "move the `..` to the end of the field list",
4056 (etc_span, String::new()),
4057 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4063 return Ok((fields, etc));
4066 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4067 if self.token.is_path_start() {
4069 let (qself, path) = if self.eat_lt() {
4070 // Parse a qualified path
4071 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4074 // Parse an unqualified path
4075 (None, self.parse_path(PathStyle::Expr)?)
4077 let hi = self.prev_span;
4078 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4080 self.parse_literal_maybe_minus()
4084 // helper function to decide whether to parse as ident binding or to try to do
4085 // something more complex like range patterns
4086 fn parse_as_ident(&mut self) -> bool {
4087 self.look_ahead(1, |t| match *t {
4088 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4089 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4090 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4091 // range pattern branch
4092 token::DotDot => None,
4094 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4095 token::Comma | token::CloseDelim(token::Bracket) => true,
4100 /// A wrapper around `parse_pat` with some special error handling for the
4101 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4102 /// to subpatterns within such).
4103 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4104 let pat = self.parse_pat(None)?;
4105 if self.token == token::Comma {
4106 // An unexpected comma after a top-level pattern is a clue that the
4107 // user (perhaps more accustomed to some other language) forgot the
4108 // parentheses in what should have been a tuple pattern; return a
4109 // suggestion-enhanced error here rather than choking on the comma
4111 let comma_span = self.span;
4113 if let Err(mut err) = self.parse_pat_list() {
4114 // We didn't expect this to work anyway; we just wanted
4115 // to advance to the end of the comma-sequence so we know
4116 // the span to suggest parenthesizing
4119 let seq_span = pat.span.to(self.prev_span);
4120 let mut err = self.struct_span_err(comma_span,
4121 "unexpected `,` in pattern");
4122 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4123 err.span_suggestion_with_applicability(
4125 "try adding parentheses",
4126 format!("({})", seq_snippet),
4127 Applicability::MachineApplicable
4135 /// Parse a pattern.
4136 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4137 self.parse_pat_with_range_pat(true, expected)
4140 /// Parse a pattern, with a setting whether modern range patterns e.g., `a..=b`, `a..b` are
4142 fn parse_pat_with_range_pat(
4144 allow_range_pat: bool,
4145 expected: Option<&'static str>,
4146 ) -> PResult<'a, P<Pat>> {
4147 maybe_whole!(self, NtPat, |x| x);
4152 token::BinOp(token::And) | token::AndAnd => {
4153 // Parse &pat / &mut pat
4155 let mutbl = self.parse_mutability();
4156 if let token::Lifetime(ident) = self.token {
4157 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4159 err.span_label(self.span, "unexpected lifetime");
4162 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4163 pat = PatKind::Ref(subpat, mutbl);
4165 token::OpenDelim(token::Paren) => {
4166 // Parse (pat,pat,pat,...) as tuple pattern
4167 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4168 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4169 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4171 PatKind::Tuple(fields, ddpos)
4174 token::OpenDelim(token::Bracket) => {
4175 // Parse [pat,pat,...] as slice pattern
4177 let (before, slice, after) = self.parse_pat_vec_elements()?;
4178 self.expect(&token::CloseDelim(token::Bracket))?;
4179 pat = PatKind::Slice(before, slice, after);
4181 // At this point, token != &, &&, (, [
4182 _ => if self.eat_keyword(keywords::Underscore) {
4184 pat = PatKind::Wild;
4185 } else if self.eat_keyword(keywords::Mut) {
4186 // Parse mut ident @ pat / mut ref ident @ pat
4187 let mutref_span = self.prev_span.to(self.span);
4188 let binding_mode = if self.eat_keyword(keywords::Ref) {
4190 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4191 .span_suggestion_with_applicability(
4193 "try switching the order",
4195 Applicability::MachineApplicable
4197 BindingMode::ByRef(Mutability::Mutable)
4199 BindingMode::ByValue(Mutability::Mutable)
4201 pat = self.parse_pat_ident(binding_mode)?;
4202 } else if self.eat_keyword(keywords::Ref) {
4203 // Parse ref ident @ pat / ref mut ident @ pat
4204 let mutbl = self.parse_mutability();
4205 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4206 } else if self.eat_keyword(keywords::Box) {
4208 let subpat = self.parse_pat_with_range_pat(false, None)?;
4209 pat = PatKind::Box(subpat);
4210 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4211 self.parse_as_ident() {
4212 // Parse ident @ pat
4213 // This can give false positives and parse nullary enums,
4214 // they are dealt with later in resolve
4215 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4216 pat = self.parse_pat_ident(binding_mode)?;
4217 } else if self.token.is_path_start() {
4218 // Parse pattern starting with a path
4219 let (qself, path) = if self.eat_lt() {
4220 // Parse a qualified path
4221 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4224 // Parse an unqualified path
4225 (None, self.parse_path(PathStyle::Expr)?)
4228 token::Not if qself.is_none() => {
4229 // Parse macro invocation
4231 let (delim, tts) = self.expect_delimited_token_tree()?;
4232 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4233 pat = PatKind::Mac(mac);
4235 token::DotDotDot | token::DotDotEq | token::DotDot => {
4236 let end_kind = match self.token {
4237 token::DotDot => RangeEnd::Excluded,
4238 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4239 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4240 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4243 let op_span = self.span;
4245 let span = lo.to(self.prev_span);
4246 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4248 let end = self.parse_pat_range_end()?;
4249 let op = Spanned { span: op_span, node: end_kind };
4250 pat = PatKind::Range(begin, end, op);
4252 token::OpenDelim(token::Brace) => {
4253 if qself.is_some() {
4254 let msg = "unexpected `{` after qualified path";
4255 let mut err = self.fatal(msg);
4256 err.span_label(self.span, msg);
4259 // Parse struct pattern
4261 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4263 self.recover_stmt();
4267 pat = PatKind::Struct(path, fields, etc);
4269 token::OpenDelim(token::Paren) => {
4270 if qself.is_some() {
4271 let msg = "unexpected `(` after qualified path";
4272 let mut err = self.fatal(msg);
4273 err.span_label(self.span, msg);
4276 // Parse tuple struct or enum pattern
4277 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4278 pat = PatKind::TupleStruct(path, fields, ddpos)
4280 _ => pat = PatKind::Path(qself, path),
4283 // Try to parse everything else as literal with optional minus
4284 match self.parse_literal_maybe_minus() {
4286 let op_span = self.span;
4287 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4288 self.check(&token::DotDotDot) {
4289 let end_kind = if self.eat(&token::DotDotDot) {
4290 RangeEnd::Included(RangeSyntax::DotDotDot)
4291 } else if self.eat(&token::DotDotEq) {
4292 RangeEnd::Included(RangeSyntax::DotDotEq)
4293 } else if self.eat(&token::DotDot) {
4296 panic!("impossible case: we already matched \
4297 on a range-operator token")
4299 let end = self.parse_pat_range_end()?;
4300 let op = Spanned { span: op_span, node: end_kind };
4301 pat = PatKind::Range(begin, end, op);
4303 pat = PatKind::Lit(begin);
4307 self.cancel(&mut err);
4308 let expected = expected.unwrap_or("pattern");
4310 "expected {}, found {}",
4312 self.this_token_descr(),
4314 let mut err = self.fatal(&msg);
4315 err.span_label(self.span, format!("expected {}", expected));
4322 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4323 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4325 if !allow_range_pat {
4328 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4330 PatKind::Range(..) => {
4331 let mut err = self.struct_span_err(
4333 "the range pattern here has ambiguous interpretation",
4335 err.span_suggestion_with_applicability(
4337 "add parentheses to clarify the precedence",
4338 format!("({})", pprust::pat_to_string(&pat)),
4339 // "ambiguous interpretation" implies that we have to be guessing
4340 Applicability::MaybeIncorrect
4351 /// Parse ident or ident @ pat
4352 /// used by the copy foo and ref foo patterns to give a good
4353 /// error message when parsing mistakes like ref foo(a,b)
4354 fn parse_pat_ident(&mut self,
4355 binding_mode: ast::BindingMode)
4356 -> PResult<'a, PatKind> {
4357 let ident = self.parse_ident()?;
4358 let sub = if self.eat(&token::At) {
4359 Some(self.parse_pat(Some("binding pattern"))?)
4364 // just to be friendly, if they write something like
4366 // we end up here with ( as the current token. This shortly
4367 // leads to a parse error. Note that if there is no explicit
4368 // binding mode then we do not end up here, because the lookahead
4369 // will direct us over to parse_enum_variant()
4370 if self.token == token::OpenDelim(token::Paren) {
4371 return Err(self.span_fatal(
4373 "expected identifier, found enum pattern"))
4376 Ok(PatKind::Ident(binding_mode, ident, sub))
4379 /// Parse a local variable declaration
4380 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4381 let lo = self.prev_span;
4382 let pat = self.parse_top_level_pat()?;
4384 let (err, ty) = if self.eat(&token::Colon) {
4385 // Save the state of the parser before parsing type normally, in case there is a `:`
4386 // instead of an `=` typo.
4387 let parser_snapshot_before_type = self.clone();
4388 let colon_sp = self.prev_span;
4389 match self.parse_ty() {
4390 Ok(ty) => (None, Some(ty)),
4392 // Rewind to before attempting to parse the type and continue parsing
4393 let parser_snapshot_after_type = self.clone();
4394 mem::replace(self, parser_snapshot_before_type);
4396 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4397 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4398 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4404 let init = match (self.parse_initializer(err.is_some()), err) {
4405 (Ok(init), None) => { // init parsed, ty parsed
4408 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4409 // Could parse the type as if it were the initializer, it is likely there was a
4410 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4411 err.span_suggestion_short_with_applicability(
4413 "use `=` if you meant to assign",
4415 Applicability::MachineApplicable
4418 // As this was parsed successfully, continue as if the code has been fixed for the
4419 // rest of the file. It will still fail due to the emitted error, but we avoid
4423 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4425 // Couldn't parse the type nor the initializer, only raise the type error and
4426 // return to the parser state before parsing the type as the initializer.
4427 // let x: <parse_error>;
4428 mem::replace(self, snapshot);
4431 (Err(err), None) => { // init error, ty parsed
4432 // Couldn't parse the initializer and we're not attempting to recover a failed
4433 // parse of the type, return the error.
4437 let hi = if self.token == token::Semi {
4446 id: ast::DUMMY_NODE_ID,
4452 /// Parse a structure field
4453 fn parse_name_and_ty(&mut self,
4456 attrs: Vec<Attribute>)
4457 -> PResult<'a, StructField> {
4458 let name = self.parse_ident()?;
4459 self.expect(&token::Colon)?;
4460 let ty = self.parse_ty()?;
4462 span: lo.to(self.prev_span),
4465 id: ast::DUMMY_NODE_ID,
4471 /// Emit an expected item after attributes error.
4472 fn expected_item_err(&self, attrs: &[Attribute]) {
4473 let message = match attrs.last() {
4474 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4475 _ => "expected item after attributes",
4478 self.span_err(self.prev_span, message);
4481 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4482 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4483 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4484 Ok(self.parse_stmt_(true))
4487 // Eat tokens until we can be relatively sure we reached the end of the
4488 // statement. This is something of a best-effort heuristic.
4490 // We terminate when we find an unmatched `}` (without consuming it).
4491 fn recover_stmt(&mut self) {
4492 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4495 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4496 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4497 // approximate - it can mean we break too early due to macros, but that
4498 // should only lead to sub-optimal recovery, not inaccurate parsing).
4500 // If `break_on_block` is `Break`, then we will stop consuming tokens
4501 // after finding (and consuming) a brace-delimited block.
4502 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4503 let mut brace_depth = 0;
4504 let mut bracket_depth = 0;
4505 let mut in_block = false;
4506 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4507 break_on_semi, break_on_block);
4509 debug!("recover_stmt_ loop {:?}", self.token);
4511 token::OpenDelim(token::DelimToken::Brace) => {
4514 if break_on_block == BlockMode::Break &&
4516 bracket_depth == 0 {
4520 token::OpenDelim(token::DelimToken::Bracket) => {
4524 token::CloseDelim(token::DelimToken::Brace) => {
4525 if brace_depth == 0 {
4526 debug!("recover_stmt_ return - close delim {:?}", self.token);
4531 if in_block && bracket_depth == 0 && brace_depth == 0 {
4532 debug!("recover_stmt_ return - block end {:?}", self.token);
4536 token::CloseDelim(token::DelimToken::Bracket) => {
4538 if bracket_depth < 0 {
4544 debug!("recover_stmt_ return - Eof");
4549 if break_on_semi == SemiColonMode::Break &&
4551 bracket_depth == 0 {
4552 debug!("recover_stmt_ return - Semi");
4563 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4564 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4566 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4571 fn is_async_block(&mut self) -> bool {
4572 self.token.is_keyword(keywords::Async) &&
4575 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4576 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4578 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4583 fn is_do_catch_block(&mut self) -> bool {
4584 self.token.is_keyword(keywords::Do) &&
4585 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4586 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4587 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4590 fn is_try_block(&mut self) -> bool {
4591 self.token.is_keyword(keywords::Try) &&
4592 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4593 self.span.rust_2018() &&
4594 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4595 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4598 fn is_union_item(&self) -> bool {
4599 self.token.is_keyword(keywords::Union) &&
4600 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4603 fn is_crate_vis(&self) -> bool {
4604 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4607 fn is_extern_non_path(&self) -> bool {
4608 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4611 fn is_existential_type_decl(&self) -> bool {
4612 self.token.is_keyword(keywords::Existential) &&
4613 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4616 fn is_auto_trait_item(&mut self) -> bool {
4618 (self.token.is_keyword(keywords::Auto)
4619 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4620 || // unsafe auto trait
4621 (self.token.is_keyword(keywords::Unsafe) &&
4622 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4623 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4626 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4627 -> PResult<'a, Option<P<Item>>> {
4628 let token_lo = self.span;
4629 let (ident, def) = match self.token {
4630 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4632 let ident = self.parse_ident()?;
4633 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4634 match self.parse_token_tree() {
4635 TokenTree::Delimited(_, _, tts) => tts.stream(),
4636 _ => unreachable!(),
4638 } else if self.check(&token::OpenDelim(token::Paren)) {
4639 let args = self.parse_token_tree();
4640 let body = if self.check(&token::OpenDelim(token::Brace)) {
4641 self.parse_token_tree()
4646 TokenStream::new(vec![
4648 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4656 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4658 token::Ident(ident, _) if ident.name == "macro_rules" &&
4659 self.look_ahead(1, |t| *t == token::Not) => {
4660 let prev_span = self.prev_span;
4661 self.complain_if_pub_macro(&vis.node, prev_span);
4665 let ident = self.parse_ident()?;
4666 let (delim, tokens) = self.expect_delimited_token_tree()?;
4667 if delim != MacDelimiter::Brace {
4668 if !self.eat(&token::Semi) {
4669 let msg = "macros that expand to items must either \
4670 be surrounded with braces or followed by a semicolon";
4671 self.span_err(self.prev_span, msg);
4675 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4677 _ => return Ok(None),
4680 let span = lo.to(self.prev_span);
4681 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4684 fn parse_stmt_without_recovery(&mut self,
4685 macro_legacy_warnings: bool)
4686 -> PResult<'a, Option<Stmt>> {
4687 maybe_whole!(self, NtStmt, |x| Some(x));
4689 let attrs = self.parse_outer_attributes()?;
4692 Ok(Some(if self.eat_keyword(keywords::Let) {
4694 id: ast::DUMMY_NODE_ID,
4695 node: StmtKind::Local(self.parse_local(attrs.into())?),
4696 span: lo.to(self.prev_span),
4698 } else if let Some(macro_def) = self.eat_macro_def(
4700 &source_map::respan(lo, VisibilityKind::Inherited),
4704 id: ast::DUMMY_NODE_ID,
4705 node: StmtKind::Item(macro_def),
4706 span: lo.to(self.prev_span),
4708 // Starts like a simple path, being careful to avoid contextual keywords
4709 // such as a union items, item with `crate` visibility or auto trait items.
4710 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4711 // like a path (1 token), but it fact not a path.
4712 // `union::b::c` - path, `union U { ... }` - not a path.
4713 // `crate::b::c` - path, `crate struct S;` - not a path.
4714 // `extern::b::c` - path, `extern crate c;` - not a path.
4715 } else if self.token.is_path_start() &&
4716 !self.token.is_qpath_start() &&
4717 !self.is_union_item() &&
4718 !self.is_crate_vis() &&
4719 !self.is_extern_non_path() &&
4720 !self.is_existential_type_decl() &&
4721 !self.is_auto_trait_item() {
4722 let pth = self.parse_path(PathStyle::Expr)?;
4724 if !self.eat(&token::Not) {
4725 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4726 self.parse_struct_expr(lo, pth, ThinVec::new())?
4728 let hi = self.prev_span;
4729 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4732 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4733 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4734 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4737 return Ok(Some(Stmt {
4738 id: ast::DUMMY_NODE_ID,
4739 node: StmtKind::Expr(expr),
4740 span: lo.to(self.prev_span),
4744 // it's a macro invocation
4745 let id = match self.token {
4746 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4747 _ => self.parse_ident()?,
4750 // check that we're pointing at delimiters (need to check
4751 // again after the `if`, because of `parse_ident`
4752 // consuming more tokens).
4754 token::OpenDelim(_) => {}
4756 // we only expect an ident if we didn't parse one
4758 let ident_str = if id.name == keywords::Invalid.name() {
4763 let tok_str = self.this_token_descr();
4764 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4767 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4772 let (delim, tts) = self.expect_delimited_token_tree()?;
4773 let hi = self.prev_span;
4775 let style = if delim == MacDelimiter::Brace {
4776 MacStmtStyle::Braces
4778 MacStmtStyle::NoBraces
4781 if id.name == keywords::Invalid.name() {
4782 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4783 let node = if delim == MacDelimiter::Brace ||
4784 self.token == token::Semi || self.token == token::Eof {
4785 StmtKind::Mac(P((mac, style, attrs.into())))
4787 // We used to incorrectly stop parsing macro-expanded statements here.
4788 // If the next token will be an error anyway but could have parsed with the
4789 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4790 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4791 // These can continue an expression, so we can't stop parsing and warn.
4792 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4793 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4794 token::BinOp(token::And) | token::BinOp(token::Or) |
4795 token::AndAnd | token::OrOr |
4796 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4799 self.warn_missing_semicolon();
4800 StmtKind::Mac(P((mac, style, attrs.into())))
4802 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4803 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4804 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4808 id: ast::DUMMY_NODE_ID,
4813 // if it has a special ident, it's definitely an item
4815 // Require a semicolon or braces.
4816 if style != MacStmtStyle::Braces {
4817 if !self.eat(&token::Semi) {
4818 self.span_err(self.prev_span,
4819 "macros that expand to items must \
4820 either be surrounded with braces or \
4821 followed by a semicolon");
4824 let span = lo.to(hi);
4826 id: ast::DUMMY_NODE_ID,
4828 node: StmtKind::Item({
4830 span, id /*id is good here*/,
4831 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4832 respan(lo, VisibilityKind::Inherited),
4838 // FIXME: Bad copy of attrs
4839 let old_directory_ownership =
4840 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4841 let item = self.parse_item_(attrs.clone(), false, true)?;
4842 self.directory.ownership = old_directory_ownership;
4846 id: ast::DUMMY_NODE_ID,
4847 span: lo.to(i.span),
4848 node: StmtKind::Item(i),
4851 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4852 if !attrs.is_empty() {
4853 if s.prev_token_kind == PrevTokenKind::DocComment {
4854 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4855 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4856 s.span_err(s.span, "expected statement after outer attribute");
4861 // Do not attempt to parse an expression if we're done here.
4862 if self.token == token::Semi {
4863 unused_attrs(&attrs, self);
4868 if self.token == token::CloseDelim(token::Brace) {
4869 unused_attrs(&attrs, self);
4873 // Remainder are line-expr stmts.
4874 let e = self.parse_expr_res(
4875 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4877 id: ast::DUMMY_NODE_ID,
4878 span: lo.to(e.span),
4879 node: StmtKind::Expr(e),
4886 /// Is this expression a successfully-parsed statement?
4887 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4888 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4889 !classify::expr_requires_semi_to_be_stmt(e)
4892 /// Parse a block. No inner attrs are allowed.
4893 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4894 maybe_whole!(self, NtBlock, |x| x);
4898 if !self.eat(&token::OpenDelim(token::Brace)) {
4900 let tok = self.this_token_descr();
4901 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4902 let do_not_suggest_help =
4903 self.token.is_keyword(keywords::In) || self.token == token::Colon;
4905 if self.token.is_ident_named("and") {
4906 e.span_suggestion_short_with_applicability(
4908 "use `&&` instead of `and` for the boolean operator",
4910 Applicability::MaybeIncorrect,
4913 if self.token.is_ident_named("or") {
4914 e.span_suggestion_short_with_applicability(
4916 "use `||` instead of `or` for the boolean operator",
4918 Applicability::MaybeIncorrect,
4922 // Check to see if the user has written something like
4927 // Which is valid in other languages, but not Rust.
4928 match self.parse_stmt_without_recovery(false) {
4930 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4931 || do_not_suggest_help {
4932 // if the next token is an open brace (e.g., `if a b {`), the place-
4933 // inside-a-block suggestion would be more likely wrong than right
4934 e.span_label(sp, "expected `{`");
4937 let mut stmt_span = stmt.span;
4938 // expand the span to include the semicolon, if it exists
4939 if self.eat(&token::Semi) {
4940 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4942 let sugg = pprust::to_string(|s| {
4943 use print::pprust::{PrintState, INDENT_UNIT};
4944 s.ibox(INDENT_UNIT)?;
4946 s.print_stmt(&stmt)?;
4947 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4949 e.span_suggestion_with_applicability(
4951 "try placing this code inside a block",
4953 // speculative, has been misleading in the past (closed Issue #46836)
4954 Applicability::MaybeIncorrect
4958 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4959 self.cancel(&mut e);
4963 e.span_label(sp, "expected `{`");
4967 self.parse_block_tail(lo, BlockCheckMode::Default)
4970 /// Parse a block. Inner attrs are allowed.
4971 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4972 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4975 self.expect(&token::OpenDelim(token::Brace))?;
4976 Ok((self.parse_inner_attributes()?,
4977 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4980 /// Parse the rest of a block expression or function body
4981 /// Precondition: already parsed the '{'.
4982 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4983 let mut stmts = vec![];
4984 while !self.eat(&token::CloseDelim(token::Brace)) {
4985 let stmt = match self.parse_full_stmt(false) {
4988 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4990 id: ast::DUMMY_NODE_ID,
4991 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
4997 if let Some(stmt) = stmt {
4999 } else if self.token == token::Eof {
5002 // Found only `;` or `}`.
5008 id: ast::DUMMY_NODE_ID,
5010 span: lo.to(self.prev_span),
5014 /// Parse a statement, including the trailing semicolon.
5015 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5016 // skip looking for a trailing semicolon when we have an interpolated statement
5017 maybe_whole!(self, NtStmt, |x| Some(x));
5019 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5021 None => return Ok(None),
5025 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5026 // expression without semicolon
5027 if classify::expr_requires_semi_to_be_stmt(expr) {
5028 // Just check for errors and recover; do not eat semicolon yet.
5030 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5033 self.recover_stmt();
5037 StmtKind::Local(..) => {
5038 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5039 if macro_legacy_warnings && self.token != token::Semi {
5040 self.warn_missing_semicolon();
5042 self.expect_one_of(&[], &[token::Semi])?;
5048 if self.eat(&token::Semi) {
5049 stmt = stmt.add_trailing_semicolon();
5052 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5056 fn warn_missing_semicolon(&self) {
5057 self.diagnostic().struct_span_warn(self.span, {
5058 &format!("expected `;`, found {}", self.this_token_descr())
5060 "This was erroneously allowed and will become a hard error in a future release"
5064 fn err_dotdotdot_syntax(&self, span: Span) {
5065 self.diagnostic().struct_span_err(span, {
5066 "unexpected token: `...`"
5067 }).span_suggestion_with_applicability(
5068 span, "use `..` for an exclusive range", "..".to_owned(),
5069 Applicability::MaybeIncorrect
5070 ).span_suggestion_with_applicability(
5071 span, "or `..=` for an inclusive range", "..=".to_owned(),
5072 Applicability::MaybeIncorrect
5076 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5077 // BOUND = TY_BOUND | LT_BOUND
5078 // LT_BOUND = LIFETIME (e.g., `'a`)
5079 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5080 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5081 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
5082 let mut bounds = Vec::new();
5084 // This needs to be synchronized with `Token::can_begin_bound`.
5085 let is_bound_start = self.check_path() || self.check_lifetime() ||
5086 self.check(&token::Question) ||
5087 self.check_keyword(keywords::For) ||
5088 self.check(&token::OpenDelim(token::Paren));
5091 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5092 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5093 if self.token.is_lifetime() {
5094 if let Some(question_span) = question {
5095 self.span_err(question_span,
5096 "`?` may only modify trait bounds, not lifetime bounds");
5098 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5100 self.expect(&token::CloseDelim(token::Paren))?;
5101 self.span_err(self.prev_span,
5102 "parenthesized lifetime bounds are not supported");
5105 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5106 let path = self.parse_path(PathStyle::Type)?;
5108 self.expect(&token::CloseDelim(token::Paren))?;
5110 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
5111 let modifier = if question.is_some() {
5112 TraitBoundModifier::Maybe
5114 TraitBoundModifier::None
5116 bounds.push(GenericBound::Trait(poly_trait, modifier));
5122 if !allow_plus || !self.eat_plus() {
5130 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
5131 self.parse_generic_bounds_common(true)
5134 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5135 // BOUND = LT_BOUND (e.g., `'a`)
5136 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5137 let mut lifetimes = Vec::new();
5138 while self.check_lifetime() {
5139 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5141 if !self.eat_plus() {
5148 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
5149 fn parse_ty_param(&mut self,
5150 preceding_attrs: Vec<Attribute>)
5151 -> PResult<'a, GenericParam> {
5152 let ident = self.parse_ident()?;
5154 // Parse optional colon and param bounds.
5155 let bounds = if self.eat(&token::Colon) {
5156 self.parse_generic_bounds()?
5161 let default = if self.eat(&token::Eq) {
5162 Some(self.parse_ty()?)
5169 id: ast::DUMMY_NODE_ID,
5170 attrs: preceding_attrs.into(),
5172 kind: GenericParamKind::Type {
5178 /// Parses the following grammar:
5179 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5180 fn parse_trait_item_assoc_ty(&mut self)
5181 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5182 let ident = self.parse_ident()?;
5183 let mut generics = self.parse_generics()?;
5185 // Parse optional colon and param bounds.
5186 let bounds = if self.eat(&token::Colon) {
5187 self.parse_generic_bounds()?
5191 generics.where_clause = self.parse_where_clause()?;
5193 let default = if self.eat(&token::Eq) {
5194 Some(self.parse_ty()?)
5198 self.expect(&token::Semi)?;
5200 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5203 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5204 /// trailing comma and erroneous trailing attributes.
5205 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5206 let mut lifetimes = Vec::new();
5207 let mut params = Vec::new();
5208 let mut seen_ty_param: Option<Span> = None;
5209 let mut last_comma_span = None;
5210 let mut bad_lifetime_pos = vec![];
5211 let mut suggestions = vec![];
5213 let attrs = self.parse_outer_attributes()?;
5214 if self.check_lifetime() {
5215 let lifetime = self.expect_lifetime();
5216 // Parse lifetime parameter.
5217 let bounds = if self.eat(&token::Colon) {
5218 self.parse_lt_param_bounds()
5222 lifetimes.push(ast::GenericParam {
5223 ident: lifetime.ident,
5225 attrs: attrs.into(),
5227 kind: ast::GenericParamKind::Lifetime,
5229 if let Some(sp) = seen_ty_param {
5230 let param_span = self.prev_span;
5231 let ate_comma = self.eat(&token::Comma);
5232 let remove_sp = if ate_comma {
5233 param_span.until(self.span)
5235 last_comma_span.unwrap_or(param_span).to(param_span)
5237 bad_lifetime_pos.push(param_span);
5239 if let Ok(snippet) = self.sess.source_map().span_to_snippet(param_span) {
5240 suggestions.push((remove_sp, String::new()));
5241 suggestions.push((sp.shrink_to_lo(), format!("{}, ", snippet)));
5244 last_comma_span = Some(self.prev_span);
5248 } else if self.check_ident() {
5249 // Parse type parameter.
5250 params.push(self.parse_ty_param(attrs)?);
5251 if seen_ty_param.is_none() {
5252 seen_ty_param = Some(self.prev_span);
5255 // Check for trailing attributes and stop parsing.
5256 if !attrs.is_empty() {
5257 let param_kind = if seen_ty_param.is_some() { "type" } else { "lifetime" };
5258 self.struct_span_err(
5260 &format!("trailing attribute after {} parameters", param_kind),
5262 .span_label(attrs[0].span, "attributes must go before parameters")
5268 if !self.eat(&token::Comma) {
5271 last_comma_span = Some(self.prev_span);
5273 if !bad_lifetime_pos.is_empty() {
5274 let mut err = self.struct_span_err(
5276 "lifetime parameters must be declared prior to type parameters",
5278 if !suggestions.is_empty() {
5279 err.multipart_suggestion_with_applicability(
5280 "move the lifetime parameter prior to the first type parameter",
5282 Applicability::MachineApplicable,
5287 lifetimes.extend(params); // ensure the correct order of lifetimes and type params
5291 /// Parse a set of optional generic type parameter declarations. Where
5292 /// clauses are not parsed here, and must be added later via
5293 /// `parse_where_clause()`.
5295 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5296 /// | ( < lifetimes , typaramseq ( , )? > )
5297 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5298 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5299 maybe_whole!(self, NtGenerics, |x| x);
5301 let span_lo = self.span;
5303 let params = self.parse_generic_params()?;
5307 where_clause: WhereClause {
5308 id: ast::DUMMY_NODE_ID,
5309 predicates: Vec::new(),
5310 span: syntax_pos::DUMMY_SP,
5312 span: span_lo.to(self.prev_span),
5315 Ok(ast::Generics::default())
5319 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5320 /// possibly including trailing comma.
5321 fn parse_generic_args(&mut self)
5322 -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5323 let mut args = Vec::new();
5324 let mut bindings = Vec::new();
5325 let mut seen_type = false;
5326 let mut seen_binding = false;
5328 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5329 // Parse lifetime argument.
5330 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5331 if seen_type || seen_binding {
5332 self.struct_span_err(
5334 "lifetime parameters must be declared prior to type parameters"
5336 .span_label(self.prev_span, "must be declared prior to type parameters")
5339 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5340 // Parse associated type binding.
5342 let ident = self.parse_ident()?;
5344 let ty = self.parse_ty()?;
5345 bindings.push(TypeBinding {
5346 id: ast::DUMMY_NODE_ID,
5349 span: lo.to(self.prev_span),
5351 seen_binding = true;
5352 } else if self.check_type() {
5353 // Parse type argument.
5354 let ty_param = self.parse_ty()?;
5356 self.span_err(ty_param.span,
5357 "type parameters must be declared prior to associated type bindings");
5359 args.push(GenericArg::Type(ty_param));
5365 if !self.eat(&token::Comma) {
5369 Ok((args, bindings))
5372 /// Parses an optional `where` clause and places it in `generics`.
5374 /// ```ignore (only-for-syntax-highlight)
5375 /// where T : Trait<U, V> + 'b, 'a : 'b
5377 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5378 maybe_whole!(self, NtWhereClause, |x| x);
5380 let mut where_clause = WhereClause {
5381 id: ast::DUMMY_NODE_ID,
5382 predicates: Vec::new(),
5383 span: syntax_pos::DUMMY_SP,
5386 if !self.eat_keyword(keywords::Where) {
5387 return Ok(where_clause);
5389 let lo = self.prev_span;
5391 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5392 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5393 // change we parse those generics now, but report an error.
5394 if self.choose_generics_over_qpath() {
5395 let generics = self.parse_generics()?;
5396 self.struct_span_err(
5398 "generic parameters on `where` clauses are reserved for future use",
5400 .span_label(generics.span, "currently unsupported")
5406 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5407 let lifetime = self.expect_lifetime();
5408 // Bounds starting with a colon are mandatory, but possibly empty.
5409 self.expect(&token::Colon)?;
5410 let bounds = self.parse_lt_param_bounds();
5411 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5412 ast::WhereRegionPredicate {
5413 span: lo.to(self.prev_span),
5418 } else if self.check_type() {
5419 // Parse optional `for<'a, 'b>`.
5420 // This `for` is parsed greedily and applies to the whole predicate,
5421 // the bounded type can have its own `for` applying only to it.
5422 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5423 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5424 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5425 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5427 // Parse type with mandatory colon and (possibly empty) bounds,
5428 // or with mandatory equality sign and the second type.
5429 let ty = self.parse_ty()?;
5430 if self.eat(&token::Colon) {
5431 let bounds = self.parse_generic_bounds()?;
5432 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5433 ast::WhereBoundPredicate {
5434 span: lo.to(self.prev_span),
5435 bound_generic_params: lifetime_defs,
5440 // FIXME: Decide what should be used here, `=` or `==`.
5441 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5442 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5443 let rhs_ty = self.parse_ty()?;
5444 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5445 ast::WhereEqPredicate {
5446 span: lo.to(self.prev_span),
5449 id: ast::DUMMY_NODE_ID,
5453 return self.unexpected();
5459 if !self.eat(&token::Comma) {
5464 where_clause.span = lo.to(self.prev_span);
5468 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5469 -> PResult<'a, (Vec<Arg> , bool)> {
5470 self.expect(&token::OpenDelim(token::Paren))?;
5473 let mut variadic = false;
5474 let args: Vec<Option<Arg>> =
5475 self.parse_seq_to_before_end(
5476 &token::CloseDelim(token::Paren),
5477 SeqSep::trailing_allowed(token::Comma),
5479 if p.token == token::DotDotDot {
5483 if p.token != token::CloseDelim(token::Paren) {
5486 "`...` must be last in argument list for variadic function");
5490 let span = p.prev_span;
5491 if p.token == token::CloseDelim(token::Paren) {
5492 // continue parsing to present any further errors
5495 "only foreign functions are allowed to be variadic"
5497 Ok(Some(dummy_arg(span)))
5499 // this function definition looks beyond recovery, stop parsing
5501 "only foreign functions are allowed to be variadic");
5506 match p.parse_arg_general(named_args, false) {
5507 Ok(arg) => Ok(Some(arg)),
5510 let lo = p.prev_span;
5511 // Skip every token until next possible arg or end.
5512 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5513 // Create a placeholder argument for proper arg count (#34264).
5514 let span = lo.to(p.prev_span);
5515 Ok(Some(dummy_arg(span)))
5522 self.eat(&token::CloseDelim(token::Paren));
5524 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5526 if variadic && args.is_empty() {
5528 "variadic function must be declared with at least one named argument");
5531 Ok((args, variadic))
5534 /// Parse the argument list and result type of a function declaration
5535 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5537 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5538 let ret_ty = self.parse_ret_ty(true)?;
5547 /// Returns the parsed optional self argument and whether a self shortcut was used.
5548 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5549 let expect_ident = |this: &mut Self| match this.token {
5550 // Preserve hygienic context.
5551 token::Ident(ident, _) =>
5552 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5555 let isolated_self = |this: &mut Self, n| {
5556 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
5557 this.look_ahead(n + 1, |t| t != &token::ModSep)
5560 // Parse optional self parameter of a method.
5561 // Only a limited set of initial token sequences is considered self parameters, anything
5562 // else is parsed as a normal function parameter list, so some lookahead is required.
5563 let eself_lo = self.span;
5564 let (eself, eself_ident, eself_hi) = match self.token {
5565 token::BinOp(token::And) => {
5571 (if isolated_self(self, 1) {
5573 SelfKind::Region(None, Mutability::Immutable)
5574 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5575 isolated_self(self, 2) {
5578 SelfKind::Region(None, Mutability::Mutable)
5579 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5580 isolated_self(self, 2) {
5582 let lt = self.expect_lifetime();
5583 SelfKind::Region(Some(lt), Mutability::Immutable)
5584 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5585 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5586 isolated_self(self, 3) {
5588 let lt = self.expect_lifetime();
5590 SelfKind::Region(Some(lt), Mutability::Mutable)
5593 }, expect_ident(self), self.prev_span)
5595 token::BinOp(token::Star) => {
5600 // Emit special error for `self` cases.
5601 (if isolated_self(self, 1) {
5603 self.span_err(self.span, "cannot pass `self` by raw pointer");
5604 SelfKind::Value(Mutability::Immutable)
5605 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5606 isolated_self(self, 2) {
5609 self.span_err(self.span, "cannot pass `self` by raw pointer");
5610 SelfKind::Value(Mutability::Immutable)
5613 }, expect_ident(self), self.prev_span)
5615 token::Ident(..) => {
5616 if isolated_self(self, 0) {
5619 let eself_ident = expect_ident(self);
5620 let eself_hi = self.prev_span;
5621 (if self.eat(&token::Colon) {
5622 let ty = self.parse_ty()?;
5623 SelfKind::Explicit(ty, Mutability::Immutable)
5625 SelfKind::Value(Mutability::Immutable)
5626 }, eself_ident, eself_hi)
5627 } else if self.token.is_keyword(keywords::Mut) &&
5628 isolated_self(self, 1) {
5632 let eself_ident = expect_ident(self);
5633 let eself_hi = self.prev_span;
5634 (if self.eat(&token::Colon) {
5635 let ty = self.parse_ty()?;
5636 SelfKind::Explicit(ty, Mutability::Mutable)
5638 SelfKind::Value(Mutability::Mutable)
5639 }, eself_ident, eself_hi)
5644 _ => return Ok(None),
5647 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5648 Ok(Some(Arg::from_self(eself, eself_ident)))
5651 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5652 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5653 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5655 self.expect(&token::OpenDelim(token::Paren))?;
5657 // Parse optional self argument
5658 let self_arg = self.parse_self_arg()?;
5660 // Parse the rest of the function parameter list.
5661 let sep = SeqSep::trailing_allowed(token::Comma);
5662 let fn_inputs = if let Some(self_arg) = self_arg {
5663 if self.check(&token::CloseDelim(token::Paren)) {
5665 } else if self.eat(&token::Comma) {
5666 let mut fn_inputs = vec![self_arg];
5667 fn_inputs.append(&mut self.parse_seq_to_before_end(
5668 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5672 return self.unexpected();
5675 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5678 // Parse closing paren and return type.
5679 self.expect(&token::CloseDelim(token::Paren))?;
5682 output: self.parse_ret_ty(true)?,
5687 // parse the |arg, arg| header on a lambda
5688 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5689 let inputs_captures = {
5690 if self.eat(&token::OrOr) {
5693 self.expect(&token::BinOp(token::Or))?;
5694 let args = self.parse_seq_to_before_tokens(
5695 &[&token::BinOp(token::Or), &token::OrOr],
5696 SeqSep::trailing_allowed(token::Comma),
5697 TokenExpectType::NoExpect,
5698 |p| p.parse_fn_block_arg()
5704 let output = self.parse_ret_ty(true)?;
5707 inputs: inputs_captures,
5713 /// Parse the name and optional generic types of a function header.
5714 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5715 let id = self.parse_ident()?;
5716 let generics = self.parse_generics()?;
5720 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5721 attrs: Vec<Attribute>) -> P<Item> {
5725 id: ast::DUMMY_NODE_ID,
5733 /// Parse an item-position function declaration.
5734 fn parse_item_fn(&mut self,
5737 constness: Spanned<Constness>,
5739 -> PResult<'a, ItemInfo> {
5740 let (ident, mut generics) = self.parse_fn_header()?;
5741 let decl = self.parse_fn_decl(false)?;
5742 generics.where_clause = self.parse_where_clause()?;
5743 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5744 let header = FnHeader { unsafety, asyncness, constness, abi };
5745 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5748 /// true if we are looking at `const ID`, false for things like `const fn` etc
5749 fn is_const_item(&mut self) -> bool {
5750 self.token.is_keyword(keywords::Const) &&
5751 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5752 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5755 /// parses all the "front matter" for a `fn` declaration, up to
5756 /// and including the `fn` keyword:
5760 /// - `const unsafe fn`
5763 fn parse_fn_front_matter(&mut self)
5771 let is_const_fn = self.eat_keyword(keywords::Const);
5772 let const_span = self.prev_span;
5773 let unsafety = self.parse_unsafety();
5774 let asyncness = self.parse_asyncness();
5775 let (constness, unsafety, abi) = if is_const_fn {
5776 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5778 let abi = if self.eat_keyword(keywords::Extern) {
5779 self.parse_opt_abi()?.unwrap_or(Abi::C)
5783 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5785 self.expect_keyword(keywords::Fn)?;
5786 Ok((constness, unsafety, asyncness, abi))
5789 /// Parse an impl item.
5790 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5791 maybe_whole!(self, NtImplItem, |x| x);
5792 let attrs = self.parse_outer_attributes()?;
5793 let (mut item, tokens) = self.collect_tokens(|this| {
5794 this.parse_impl_item_(at_end, attrs)
5797 // See `parse_item` for why this clause is here.
5798 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5799 item.tokens = Some(tokens);
5804 fn parse_impl_item_(&mut self,
5806 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5808 let vis = self.parse_visibility(false)?;
5809 let defaultness = self.parse_defaultness();
5810 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5811 let (name, alias, generics) = type_?;
5812 let kind = match alias {
5813 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5814 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5816 (name, kind, generics)
5817 } else if self.is_const_item() {
5818 // This parses the grammar:
5819 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5820 self.expect_keyword(keywords::Const)?;
5821 let name = self.parse_ident()?;
5822 self.expect(&token::Colon)?;
5823 let typ = self.parse_ty()?;
5824 self.expect(&token::Eq)?;
5825 let expr = self.parse_expr()?;
5826 self.expect(&token::Semi)?;
5827 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5829 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5830 attrs.extend(inner_attrs);
5831 (name, node, generics)
5835 id: ast::DUMMY_NODE_ID,
5836 span: lo.to(self.prev_span),
5847 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5849 VisibilityKind::Inherited => {}
5851 let is_macro_rules: bool = match self.token {
5852 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5855 let mut err = if is_macro_rules {
5856 let mut err = self.diagnostic()
5857 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5858 err.span_suggestion_with_applicability(
5860 "try exporting the macro",
5861 "#[macro_export]".to_owned(),
5862 Applicability::MaybeIncorrect // speculative
5866 let mut err = self.diagnostic()
5867 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5868 err.help("try adjusting the macro to put `pub` inside the invocation");
5876 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5877 -> DiagnosticBuilder<'a>
5879 let expected_kinds = if item_type == "extern" {
5880 "missing `fn`, `type`, or `static`"
5882 "missing `fn`, `type`, or `const`"
5885 // Given this code `path(`, it seems like this is not
5886 // setting the visibility of a macro invocation, but rather
5887 // a mistyped method declaration.
5888 // Create a diagnostic pointing out that `fn` is missing.
5890 // x | pub path(&self) {
5891 // | ^ missing `fn`, `type`, or `const`
5893 // ^^ `sp` below will point to this
5894 let sp = prev_span.between(self.prev_span);
5895 let mut err = self.diagnostic().struct_span_err(
5897 &format!("{} for {}-item declaration",
5898 expected_kinds, item_type));
5899 err.span_label(sp, expected_kinds);
5903 /// Parse a method or a macro invocation in a trait impl.
5904 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5905 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5906 ast::ImplItemKind)> {
5907 // code copied from parse_macro_use_or_failure... abstraction!
5908 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5910 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5911 ast::ImplItemKind::Macro(mac)))
5913 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5914 let ident = self.parse_ident()?;
5915 let mut generics = self.parse_generics()?;
5916 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5917 generics.where_clause = self.parse_where_clause()?;
5919 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5920 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5921 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5922 ast::MethodSig { header, decl },
5928 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5929 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5930 let ident = self.parse_ident()?;
5931 let mut tps = self.parse_generics()?;
5933 // Parse optional colon and supertrait bounds.
5934 let bounds = if self.eat(&token::Colon) {
5935 self.parse_generic_bounds()?
5940 if self.eat(&token::Eq) {
5941 // it's a trait alias
5942 let bounds = self.parse_generic_bounds()?;
5943 tps.where_clause = self.parse_where_clause()?;
5944 self.expect(&token::Semi)?;
5945 if unsafety != Unsafety::Normal {
5946 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5948 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5950 // it's a normal trait
5951 tps.where_clause = self.parse_where_clause()?;
5952 self.expect(&token::OpenDelim(token::Brace))?;
5953 let mut trait_items = vec![];
5954 while !self.eat(&token::CloseDelim(token::Brace)) {
5955 let mut at_end = false;
5956 match self.parse_trait_item(&mut at_end) {
5957 Ok(item) => trait_items.push(item),
5961 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5966 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5970 fn choose_generics_over_qpath(&self) -> bool {
5971 // There's an ambiguity between generic parameters and qualified paths in impls.
5972 // If we see `<` it may start both, so we have to inspect some following tokens.
5973 // The following combinations can only start generics,
5974 // but not qualified paths (with one exception):
5975 // `<` `>` - empty generic parameters
5976 // `<` `#` - generic parameters with attributes
5977 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5978 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5979 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5980 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5981 // The only truly ambiguous case is
5982 // `<` IDENT `>` `::` IDENT ...
5983 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5984 // because this is what almost always expected in practice, qualified paths in impls
5985 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5986 self.token == token::Lt &&
5987 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5988 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5989 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5990 t == &token::Colon || t == &token::Eq))
5993 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5994 self.expect(&token::OpenDelim(token::Brace))?;
5995 let attrs = self.parse_inner_attributes()?;
5997 let mut impl_items = Vec::new();
5998 while !self.eat(&token::CloseDelim(token::Brace)) {
5999 let mut at_end = false;
6000 match self.parse_impl_item(&mut at_end) {
6001 Ok(impl_item) => impl_items.push(impl_item),
6005 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6010 Ok((impl_items, attrs))
6013 /// Parses an implementation item, `impl` keyword is already parsed.
6014 /// impl<'a, T> TYPE { /* impl items */ }
6015 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6016 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6017 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6018 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6019 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6020 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6021 -> PResult<'a, ItemInfo> {
6022 // First, parse generic parameters if necessary.
6023 let mut generics = if self.choose_generics_over_qpath() {
6024 self.parse_generics()?
6026 ast::Generics::default()
6029 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6030 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6032 ast::ImplPolarity::Negative
6034 ast::ImplPolarity::Positive
6037 // Parse both types and traits as a type, then reinterpret if necessary.
6038 let ty_first = self.parse_ty()?;
6040 // If `for` is missing we try to recover.
6041 let has_for = self.eat_keyword(keywords::For);
6042 let missing_for_span = self.prev_span.between(self.span);
6044 let ty_second = if self.token == token::DotDot {
6045 // We need to report this error after `cfg` expansion for compatibility reasons
6046 self.bump(); // `..`, do not add it to expected tokens
6047 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
6048 } else if has_for || self.token.can_begin_type() {
6049 Some(self.parse_ty()?)
6054 generics.where_clause = self.parse_where_clause()?;
6056 let (impl_items, attrs) = self.parse_impl_body()?;
6058 let item_kind = match ty_second {
6059 Some(ty_second) => {
6060 // impl Trait for Type
6062 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6063 .span_suggestion_short_with_applicability(
6066 " for ".to_string(),
6067 Applicability::MachineApplicable,
6071 let ty_first = ty_first.into_inner();
6072 let path = match ty_first.node {
6073 // This notably includes paths passed through `ty` macro fragments (#46438).
6074 TyKind::Path(None, path) => path,
6076 self.span_err(ty_first.span, "expected a trait, found type");
6077 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
6080 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6082 ItemKind::Impl(unsafety, polarity, defaultness,
6083 generics, Some(trait_ref), ty_second, impl_items)
6087 ItemKind::Impl(unsafety, polarity, defaultness,
6088 generics, None, ty_first, impl_items)
6092 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6095 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6096 if self.eat_keyword(keywords::For) {
6098 let params = self.parse_generic_params()?;
6100 // We rely on AST validation to rule out invalid cases: There must not be type
6101 // parameters, and the lifetime parameters must not have bounds.
6108 /// Parse struct Foo { ... }
6109 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6110 let class_name = self.parse_ident()?;
6112 let mut generics = self.parse_generics()?;
6114 // There is a special case worth noting here, as reported in issue #17904.
6115 // If we are parsing a tuple struct it is the case that the where clause
6116 // should follow the field list. Like so:
6118 // struct Foo<T>(T) where T: Copy;
6120 // If we are parsing a normal record-style struct it is the case
6121 // that the where clause comes before the body, and after the generics.
6122 // So if we look ahead and see a brace or a where-clause we begin
6123 // parsing a record style struct.
6125 // Otherwise if we look ahead and see a paren we parse a tuple-style
6128 let vdata = if self.token.is_keyword(keywords::Where) {
6129 generics.where_clause = self.parse_where_clause()?;
6130 if self.eat(&token::Semi) {
6131 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6132 VariantData::Unit(ast::DUMMY_NODE_ID)
6134 // If we see: `struct Foo<T> where T: Copy { ... }`
6135 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6137 // No `where` so: `struct Foo<T>;`
6138 } else if self.eat(&token::Semi) {
6139 VariantData::Unit(ast::DUMMY_NODE_ID)
6140 // Record-style struct definition
6141 } else if self.token == token::OpenDelim(token::Brace) {
6142 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6143 // Tuple-style struct definition with optional where-clause.
6144 } else if self.token == token::OpenDelim(token::Paren) {
6145 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6146 generics.where_clause = self.parse_where_clause()?;
6147 self.expect(&token::Semi)?;
6150 let token_str = self.this_token_descr();
6151 let mut err = self.fatal(&format!(
6152 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6155 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6159 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6162 /// Parse union Foo { ... }
6163 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6164 let class_name = self.parse_ident()?;
6166 let mut generics = self.parse_generics()?;
6168 let vdata = if self.token.is_keyword(keywords::Where) {
6169 generics.where_clause = self.parse_where_clause()?;
6170 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6171 } else if self.token == token::OpenDelim(token::Brace) {
6172 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6174 let token_str = self.this_token_descr();
6175 let mut err = self.fatal(&format!(
6176 "expected `where` or `{{` after union name, found {}", token_str));
6177 err.span_label(self.span, "expected `where` or `{` after union name");
6181 Ok((class_name, ItemKind::Union(vdata, generics), None))
6184 fn consume_block(&mut self, delim: token::DelimToken) {
6185 let mut brace_depth = 0;
6187 if self.eat(&token::OpenDelim(delim)) {
6189 } else if self.eat(&token::CloseDelim(delim)) {
6190 if brace_depth == 0 {
6196 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6204 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6205 let mut fields = Vec::new();
6206 if self.eat(&token::OpenDelim(token::Brace)) {
6207 while self.token != token::CloseDelim(token::Brace) {
6208 let field = self.parse_struct_decl_field().map_err(|e| {
6209 self.recover_stmt();
6213 Ok(field) => fields.push(field),
6219 self.eat(&token::CloseDelim(token::Brace));
6221 let token_str = self.this_token_descr();
6222 let mut err = self.fatal(&format!(
6223 "expected `where`, or `{{` after struct name, found {}", token_str));
6224 err.span_label(self.span, "expected `where`, or `{` after struct name");
6231 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6232 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6233 // Unit like structs are handled in parse_item_struct function
6234 let fields = self.parse_unspanned_seq(
6235 &token::OpenDelim(token::Paren),
6236 &token::CloseDelim(token::Paren),
6237 SeqSep::trailing_allowed(token::Comma),
6239 let attrs = p.parse_outer_attributes()?;
6241 let vis = p.parse_visibility(true)?;
6242 let ty = p.parse_ty()?;
6244 span: lo.to(ty.span),
6247 id: ast::DUMMY_NODE_ID,
6256 /// Parse a structure field declaration
6257 fn parse_single_struct_field(&mut self,
6260 attrs: Vec<Attribute> )
6261 -> PResult<'a, StructField> {
6262 let mut seen_comma: bool = false;
6263 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6264 if self.token == token::Comma {
6271 token::CloseDelim(token::Brace) => {}
6272 token::DocComment(_) => {
6273 let previous_span = self.prev_span;
6274 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6275 self.bump(); // consume the doc comment
6276 let comma_after_doc_seen = self.eat(&token::Comma);
6277 // `seen_comma` is always false, because we are inside doc block
6278 // condition is here to make code more readable
6279 if seen_comma == false && comma_after_doc_seen == true {
6282 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6285 if seen_comma == false {
6286 let sp = self.sess.source_map().next_point(previous_span);
6287 err.span_suggestion_with_applicability(
6289 "missing comma here",
6291 Applicability::MachineApplicable
6298 let sp = self.sess.source_map().next_point(self.prev_span);
6299 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6300 self.this_token_descr()));
6301 if self.token.is_ident() {
6302 // This is likely another field; emit the diagnostic and keep going
6303 err.span_suggestion_with_applicability(
6305 "try adding a comma",
6307 Applicability::MachineApplicable,
6318 /// Parse an element of a struct definition
6319 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6320 let attrs = self.parse_outer_attributes()?;
6322 let vis = self.parse_visibility(false)?;
6323 self.parse_single_struct_field(lo, vis, attrs)
6326 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6327 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6328 /// If the following element can't be a tuple (i.e., it's a function definition,
6329 /// it's not a tuple struct field) and the contents within the parens
6330 /// isn't valid, emit a proper diagnostic.
6331 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6332 maybe_whole!(self, NtVis, |x| x);
6334 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6335 if self.is_crate_vis() {
6336 self.bump(); // `crate`
6337 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6340 if !self.eat_keyword(keywords::Pub) {
6341 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6342 // keyword to grab a span from for inherited visibility; an empty span at the
6343 // beginning of the current token would seem to be the "Schelling span".
6344 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6346 let lo = self.prev_span;
6348 if self.check(&token::OpenDelim(token::Paren)) {
6349 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6350 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6351 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6352 // by the following tokens.
6353 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6356 self.bump(); // `crate`
6357 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6359 lo.to(self.prev_span),
6360 VisibilityKind::Crate(CrateSugar::PubCrate),
6363 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6366 self.bump(); // `in`
6367 let path = self.parse_path(PathStyle::Mod)?; // `path`
6368 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6369 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6371 id: ast::DUMMY_NODE_ID,
6374 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6375 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6376 t.is_keyword(keywords::SelfLower))
6378 // `pub(self)` or `pub(super)`
6380 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6381 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6382 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6384 id: ast::DUMMY_NODE_ID,
6387 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6388 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6390 let msg = "incorrect visibility restriction";
6391 let suggestion = r##"some possible visibility restrictions are:
6392 `pub(crate)`: visible only on the current crate
6393 `pub(super)`: visible only in the current module's parent
6394 `pub(in path::to::module)`: visible only on the specified path"##;
6395 let path = self.parse_path(PathStyle::Mod)?;
6396 let sp = self.prev_span;
6397 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6398 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6399 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6400 err.help(suggestion);
6401 err.span_suggestion_with_applicability(
6402 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6404 err.emit(); // emit diagnostic, but continue with public visibility
6408 Ok(respan(lo, VisibilityKind::Public))
6411 /// Parse defaultness: `default` or nothing.
6412 fn parse_defaultness(&mut self) -> Defaultness {
6413 // `pub` is included for better error messages
6414 if self.check_keyword(keywords::Default) &&
6415 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6416 t.is_keyword(keywords::Const) ||
6417 t.is_keyword(keywords::Fn) ||
6418 t.is_keyword(keywords::Unsafe) ||
6419 t.is_keyword(keywords::Extern) ||
6420 t.is_keyword(keywords::Type) ||
6421 t.is_keyword(keywords::Pub)) {
6422 self.bump(); // `default`
6423 Defaultness::Default
6429 /// Given a termination token, parse all of the items in a module
6430 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6431 let mut items = vec![];
6432 while let Some(item) = self.parse_item()? {
6436 if !self.eat(term) {
6437 let token_str = self.this_token_descr();
6438 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6439 if self.token == token::Semi {
6440 let msg = "consider removing this semicolon";
6441 err.span_suggestion_short_with_applicability(
6442 self.span, msg, String::new(), Applicability::MachineApplicable
6444 if !items.is_empty() { // Issue #51603
6445 let previous_item = &items[items.len()-1];
6446 let previous_item_kind_name = match previous_item.node {
6447 // say "braced struct" because tuple-structs and
6448 // braceless-empty-struct declarations do take a semicolon
6449 ItemKind::Struct(..) => Some("braced struct"),
6450 ItemKind::Enum(..) => Some("enum"),
6451 ItemKind::Trait(..) => Some("trait"),
6452 ItemKind::Union(..) => Some("union"),
6455 if let Some(name) = previous_item_kind_name {
6456 err.help(&format!("{} declarations are not followed by a semicolon",
6461 err.span_label(self.span, "expected item");
6466 let hi = if self.span.is_dummy() {
6473 inner: inner_lo.to(hi),
6479 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6480 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6481 self.expect(&token::Colon)?;
6482 let ty = self.parse_ty()?;
6483 self.expect(&token::Eq)?;
6484 let e = self.parse_expr()?;
6485 self.expect(&token::Semi)?;
6486 let item = match m {
6487 Some(m) => ItemKind::Static(ty, m, e),
6488 None => ItemKind::Const(ty, e),
6490 Ok((id, item, None))
6493 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6494 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6495 let (in_cfg, outer_attrs) = {
6496 let mut strip_unconfigured = ::config::StripUnconfigured {
6498 features: None, // don't perform gated feature checking
6500 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6501 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6504 let id_span = self.span;
6505 let id = self.parse_ident()?;
6506 if self.eat(&token::Semi) {
6507 if in_cfg && self.recurse_into_file_modules {
6508 // This mod is in an external file. Let's go get it!
6509 let ModulePathSuccess { path, directory_ownership, warn } =
6510 self.submod_path(id, &outer_attrs, id_span)?;
6511 let (module, mut attrs) =
6512 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6513 // Record that we fetched the mod from an external file
6515 let attr = Attribute {
6516 id: attr::mk_attr_id(),
6517 style: ast::AttrStyle::Outer,
6518 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6519 tokens: TokenStream::empty(),
6520 is_sugared_doc: false,
6521 span: syntax_pos::DUMMY_SP,
6523 attr::mark_known(&attr);
6526 Ok((id, ItemKind::Mod(module), Some(attrs)))
6528 let placeholder = ast::Mod {
6529 inner: syntax_pos::DUMMY_SP,
6533 Ok((id, ItemKind::Mod(placeholder), None))
6536 let old_directory = self.directory.clone();
6537 self.push_directory(id, &outer_attrs);
6539 self.expect(&token::OpenDelim(token::Brace))?;
6540 let mod_inner_lo = self.span;
6541 let attrs = self.parse_inner_attributes()?;
6542 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6544 self.directory = old_directory;
6545 Ok((id, ItemKind::Mod(module), Some(attrs)))
6549 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6550 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6551 self.directory.path.to_mut().push(&path.as_str());
6552 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6554 // We have to push on the current module name in the case of relative
6555 // paths in order to ensure that any additional module paths from inline
6556 // `mod x { ... }` come after the relative extension.
6558 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6559 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6560 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6561 if let Some(ident) = relative.take() { // remove the relative offset
6562 self.directory.path.to_mut().push(ident.as_str());
6565 self.directory.path.to_mut().push(&id.as_str());
6569 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6570 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6573 // On windows, the base path might have the form
6574 // `\\?\foo\bar` in which case it does not tolerate
6575 // mixed `/` and `\` separators, so canonicalize
6578 let s = s.replace("/", "\\");
6579 Some(dir_path.join(s))
6585 /// Returns either a path to a module, or .
6586 pub fn default_submod_path(
6588 relative: Option<ast::Ident>,
6590 source_map: &SourceMap) -> ModulePath
6592 // If we're in a foo.rs file instead of a mod.rs file,
6593 // we need to look for submodules in
6594 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6595 // `./<id>.rs` and `./<id>/mod.rs`.
6596 let relative_prefix_string;
6597 let relative_prefix = if let Some(ident) = relative {
6598 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6599 &relative_prefix_string
6604 let mod_name = id.to_string();
6605 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6606 let secondary_path_str = format!("{}{}{}mod.rs",
6607 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6608 let default_path = dir_path.join(&default_path_str);
6609 let secondary_path = dir_path.join(&secondary_path_str);
6610 let default_exists = source_map.file_exists(&default_path);
6611 let secondary_exists = source_map.file_exists(&secondary_path);
6613 let result = match (default_exists, secondary_exists) {
6614 (true, false) => Ok(ModulePathSuccess {
6616 directory_ownership: DirectoryOwnership::Owned {
6621 (false, true) => Ok(ModulePathSuccess {
6622 path: secondary_path,
6623 directory_ownership: DirectoryOwnership::Owned {
6628 (false, false) => Err(Error::FileNotFoundForModule {
6629 mod_name: mod_name.clone(),
6630 default_path: default_path_str,
6631 secondary_path: secondary_path_str,
6632 dir_path: dir_path.display().to_string(),
6634 (true, true) => Err(Error::DuplicatePaths {
6635 mod_name: mod_name.clone(),
6636 default_path: default_path_str,
6637 secondary_path: secondary_path_str,
6643 path_exists: default_exists || secondary_exists,
6648 fn submod_path(&mut self,
6650 outer_attrs: &[Attribute],
6652 -> PResult<'a, ModulePathSuccess> {
6653 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6654 return Ok(ModulePathSuccess {
6655 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6656 // All `#[path]` files are treated as though they are a `mod.rs` file.
6657 // This means that `mod foo;` declarations inside `#[path]`-included
6658 // files are siblings,
6660 // Note that this will produce weirdness when a file named `foo.rs` is
6661 // `#[path]` included and contains a `mod foo;` declaration.
6662 // If you encounter this, it's your own darn fault :P
6663 Some(_) => DirectoryOwnership::Owned { relative: None },
6664 _ => DirectoryOwnership::UnownedViaMod(true),
6671 let relative = match self.directory.ownership {
6672 DirectoryOwnership::Owned { relative } => relative,
6673 DirectoryOwnership::UnownedViaBlock |
6674 DirectoryOwnership::UnownedViaMod(_) => None,
6676 let paths = Parser::default_submod_path(
6677 id, relative, &self.directory.path, self.sess.source_map());
6679 match self.directory.ownership {
6680 DirectoryOwnership::Owned { .. } => {
6681 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6683 DirectoryOwnership::UnownedViaBlock => {
6685 "Cannot declare a non-inline module inside a block \
6686 unless it has a path attribute";
6687 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6688 if paths.path_exists {
6689 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6691 err.span_note(id_sp, &msg);
6695 DirectoryOwnership::UnownedViaMod(warn) => {
6697 if let Ok(result) = paths.result {
6698 return Ok(ModulePathSuccess { warn: true, ..result });
6701 let mut err = self.diagnostic().struct_span_err(id_sp,
6702 "cannot declare a new module at this location");
6703 if !id_sp.is_dummy() {
6704 let src_path = self.sess.source_map().span_to_filename(id_sp);
6705 if let FileName::Real(src_path) = src_path {
6706 if let Some(stem) = src_path.file_stem() {
6707 let mut dest_path = src_path.clone();
6708 dest_path.set_file_name(stem);
6709 dest_path.push("mod.rs");
6710 err.span_note(id_sp,
6711 &format!("maybe move this module `{}` to its own \
6712 directory via `{}`", src_path.display(),
6713 dest_path.display()));
6717 if paths.path_exists {
6718 err.span_note(id_sp,
6719 &format!("... or maybe `use` the module `{}` instead \
6720 of possibly redeclaring it",
6728 /// Read a module from a source file.
6729 fn eval_src_mod(&mut self,
6731 directory_ownership: DirectoryOwnership,
6734 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6735 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6736 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6737 let mut err = String::from("circular modules: ");
6738 let len = included_mod_stack.len();
6739 for p in &included_mod_stack[i.. len] {
6740 err.push_str(&p.to_string_lossy());
6741 err.push_str(" -> ");
6743 err.push_str(&path.to_string_lossy());
6744 return Err(self.span_fatal(id_sp, &err[..]));
6746 included_mod_stack.push(path.clone());
6747 drop(included_mod_stack);
6750 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6751 p0.cfg_mods = self.cfg_mods;
6752 let mod_inner_lo = p0.span;
6753 let mod_attrs = p0.parse_inner_attributes()?;
6754 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6756 self.sess.included_mod_stack.borrow_mut().pop();
6760 /// Parse a function declaration from a foreign module
6761 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6762 -> PResult<'a, ForeignItem> {
6763 self.expect_keyword(keywords::Fn)?;
6765 let (ident, mut generics) = self.parse_fn_header()?;
6766 let decl = self.parse_fn_decl(true)?;
6767 generics.where_clause = self.parse_where_clause()?;
6769 self.expect(&token::Semi)?;
6770 Ok(ast::ForeignItem {
6773 node: ForeignItemKind::Fn(decl, generics),
6774 id: ast::DUMMY_NODE_ID,
6780 /// Parse a static item from a foreign module.
6781 /// Assumes that the `static` keyword is already parsed.
6782 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6783 -> PResult<'a, ForeignItem> {
6784 let mutbl = self.eat_keyword(keywords::Mut);
6785 let ident = self.parse_ident()?;
6786 self.expect(&token::Colon)?;
6787 let ty = self.parse_ty()?;
6789 self.expect(&token::Semi)?;
6793 node: ForeignItemKind::Static(ty, mutbl),
6794 id: ast::DUMMY_NODE_ID,
6800 /// Parse a type from a foreign module
6801 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6802 -> PResult<'a, ForeignItem> {
6803 self.expect_keyword(keywords::Type)?;
6805 let ident = self.parse_ident()?;
6807 self.expect(&token::Semi)?;
6808 Ok(ast::ForeignItem {
6811 node: ForeignItemKind::Ty,
6812 id: ast::DUMMY_NODE_ID,
6818 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6819 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6820 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6822 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
6823 self.parse_path_segment_ident()
6827 let mut idents = vec![];
6828 let mut replacement = vec![];
6829 let mut fixed_crate_name = false;
6830 // Accept `extern crate name-like-this` for better diagnostics
6831 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6832 if self.token == dash { // Do not include `-` as part of the expected tokens list
6833 while self.eat(&dash) {
6834 fixed_crate_name = true;
6835 replacement.push((self.prev_span, "_".to_string()));
6836 idents.push(self.parse_ident()?);
6839 if fixed_crate_name {
6840 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6841 let mut fixed_name = format!("{}", ident.name);
6842 for part in idents {
6843 fixed_name.push_str(&format!("_{}", part.name));
6845 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6847 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6848 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6849 err.multipart_suggestion(suggestion_msg, replacement);
6855 /// Parse extern crate links
6859 /// extern crate foo;
6860 /// extern crate bar as foo;
6861 fn parse_item_extern_crate(&mut self,
6863 visibility: Visibility,
6864 attrs: Vec<Attribute>)
6865 -> PResult<'a, P<Item>> {
6866 // Accept `extern crate name-like-this` for better diagnostics
6867 let orig_name = self.parse_crate_name_with_dashes()?;
6868 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6869 (rename, Some(orig_name.name))
6873 self.expect(&token::Semi)?;
6875 let span = lo.to(self.prev_span);
6876 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6879 /// Parse `extern` for foreign ABIs
6882 /// `extern` is expected to have been
6883 /// consumed before calling this method
6889 fn parse_item_foreign_mod(&mut self,
6891 opt_abi: Option<Abi>,
6892 visibility: Visibility,
6893 mut attrs: Vec<Attribute>)
6894 -> PResult<'a, P<Item>> {
6895 self.expect(&token::OpenDelim(token::Brace))?;
6897 let abi = opt_abi.unwrap_or(Abi::C);
6899 attrs.extend(self.parse_inner_attributes()?);
6901 let mut foreign_items = vec![];
6902 while !self.eat(&token::CloseDelim(token::Brace)) {
6903 foreign_items.push(self.parse_foreign_item()?);
6906 let prev_span = self.prev_span;
6907 let m = ast::ForeignMod {
6909 items: foreign_items
6911 let invalid = keywords::Invalid.ident();
6912 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6915 /// Parse `type Foo = Bar;`
6917 /// `existential type Foo: Bar;`
6919 /// `return None` without modifying the parser state
6920 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6921 // This parses the grammar:
6922 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6923 if self.check_keyword(keywords::Type) ||
6924 self.check_keyword(keywords::Existential) &&
6925 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
6926 let existential = self.eat_keyword(keywords::Existential);
6927 assert!(self.eat_keyword(keywords::Type));
6928 Some(self.parse_existential_or_alias(existential))
6934 /// Parse type alias or existential type
6935 fn parse_existential_or_alias(
6938 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6939 let ident = self.parse_ident()?;
6940 let mut tps = self.parse_generics()?;
6941 tps.where_clause = self.parse_where_clause()?;
6942 let alias = if existential {
6943 self.expect(&token::Colon)?;
6944 let bounds = self.parse_generic_bounds()?;
6945 AliasKind::Existential(bounds)
6947 self.expect(&token::Eq)?;
6948 let ty = self.parse_ty()?;
6951 self.expect(&token::Semi)?;
6952 Ok((ident, alias, tps))
6955 /// Parse the part of an "enum" decl following the '{'
6956 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6957 let mut variants = Vec::new();
6958 let mut all_nullary = true;
6959 let mut any_disr = None;
6960 while self.token != token::CloseDelim(token::Brace) {
6961 let variant_attrs = self.parse_outer_attributes()?;
6962 let vlo = self.span;
6965 let mut disr_expr = None;
6966 let ident = self.parse_ident()?;
6967 if self.check(&token::OpenDelim(token::Brace)) {
6968 // Parse a struct variant.
6969 all_nullary = false;
6970 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6971 ast::DUMMY_NODE_ID);
6972 } else if self.check(&token::OpenDelim(token::Paren)) {
6973 all_nullary = false;
6974 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6975 ast::DUMMY_NODE_ID);
6976 } else if self.eat(&token::Eq) {
6977 disr_expr = Some(AnonConst {
6978 id: ast::DUMMY_NODE_ID,
6979 value: self.parse_expr()?,
6981 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6982 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6984 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6987 let vr = ast::Variant_ {
6989 attrs: variant_attrs,
6993 variants.push(respan(vlo.to(self.prev_span), vr));
6995 if !self.eat(&token::Comma) { break; }
6997 self.expect(&token::CloseDelim(token::Brace))?;
6999 Some(disr_span) if !all_nullary =>
7000 self.span_err(disr_span,
7001 "discriminator values can only be used with a field-less enum"),
7005 Ok(ast::EnumDef { variants })
7008 /// Parse an "enum" declaration
7009 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7010 let id = self.parse_ident()?;
7011 let mut generics = self.parse_generics()?;
7012 generics.where_clause = self.parse_where_clause()?;
7013 self.expect(&token::OpenDelim(token::Brace))?;
7015 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7016 self.recover_stmt();
7017 self.eat(&token::CloseDelim(token::Brace));
7020 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7023 /// Parses a string as an ABI spec on an extern type or module. Consumes
7024 /// the `extern` keyword, if one is found.
7025 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7027 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7029 self.expect_no_suffix(sp, "ABI spec", suf);
7031 match abi::lookup(&s.as_str()) {
7032 Some(abi) => Ok(Some(abi)),
7034 let prev_span = self.prev_span;
7035 let mut err = struct_span_err!(
7036 self.sess.span_diagnostic,
7039 "invalid ABI: found `{}`",
7041 err.span_label(prev_span, "invalid ABI");
7042 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7053 fn is_static_global(&mut self) -> bool {
7054 if self.check_keyword(keywords::Static) {
7055 // Check if this could be a closure
7056 !self.look_ahead(1, |token| {
7057 if token.is_keyword(keywords::Move) {
7061 token::BinOp(token::Or) | token::OrOr => true,
7072 attrs: Vec<Attribute>,
7073 macros_allowed: bool,
7074 attributes_allowed: bool,
7075 ) -> PResult<'a, Option<P<Item>>> {
7076 let (ret, tokens) = self.collect_tokens(|this| {
7077 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
7080 // Once we've parsed an item and recorded the tokens we got while
7081 // parsing we may want to store `tokens` into the item we're about to
7082 // return. Note, though, that we specifically didn't capture tokens
7083 // related to outer attributes. The `tokens` field here may later be
7084 // used with procedural macros to convert this item back into a token
7085 // stream, but during expansion we may be removing attributes as we go
7088 // If we've got inner attributes then the `tokens` we've got above holds
7089 // these inner attributes. If an inner attribute is expanded we won't
7090 // actually remove it from the token stream, so we'll just keep yielding
7091 // it (bad!). To work around this case for now we just avoid recording
7092 // `tokens` if we detect any inner attributes. This should help keep
7093 // expansion correct, but we should fix this bug one day!
7096 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7097 i.tokens = Some(tokens);
7104 /// Parse one of the items allowed by the flags.
7105 fn parse_item_implementation(
7107 attrs: Vec<Attribute>,
7108 macros_allowed: bool,
7109 attributes_allowed: bool,
7110 ) -> PResult<'a, Option<P<Item>>> {
7111 maybe_whole!(self, NtItem, |item| {
7112 let mut item = item.into_inner();
7113 let mut attrs = attrs;
7114 mem::swap(&mut item.attrs, &mut attrs);
7115 item.attrs.extend(attrs);
7121 let visibility = self.parse_visibility(false)?;
7123 if self.eat_keyword(keywords::Use) {
7125 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7126 self.expect(&token::Semi)?;
7128 let span = lo.to(self.prev_span);
7129 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7130 return Ok(Some(item));
7133 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
7134 self.bump(); // `extern`
7135 if self.eat_keyword(keywords::Crate) {
7136 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7139 let opt_abi = self.parse_opt_abi()?;
7141 if self.eat_keyword(keywords::Fn) {
7142 // EXTERN FUNCTION ITEM
7143 let fn_span = self.prev_span;
7144 let abi = opt_abi.unwrap_or(Abi::C);
7145 let (ident, item_, extra_attrs) =
7146 self.parse_item_fn(Unsafety::Normal,
7148 respan(fn_span, Constness::NotConst),
7150 let prev_span = self.prev_span;
7151 let item = self.mk_item(lo.to(prev_span),
7155 maybe_append(attrs, extra_attrs));
7156 return Ok(Some(item));
7157 } else if self.check(&token::OpenDelim(token::Brace)) {
7158 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7164 if self.is_static_global() {
7167 let m = if self.eat_keyword(keywords::Mut) {
7170 Mutability::Immutable
7172 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7173 let prev_span = self.prev_span;
7174 let item = self.mk_item(lo.to(prev_span),
7178 maybe_append(attrs, extra_attrs));
7179 return Ok(Some(item));
7181 if self.eat_keyword(keywords::Const) {
7182 let const_span = self.prev_span;
7183 if self.check_keyword(keywords::Fn)
7184 || (self.check_keyword(keywords::Unsafe)
7185 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7186 // CONST FUNCTION ITEM
7187 let unsafety = self.parse_unsafety();
7189 let (ident, item_, extra_attrs) =
7190 self.parse_item_fn(unsafety,
7192 respan(const_span, Constness::Const),
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));
7204 if self.eat_keyword(keywords::Mut) {
7205 let prev_span = self.prev_span;
7206 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
7207 .help("did you mean to declare a static?")
7210 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7211 let prev_span = self.prev_span;
7212 let item = self.mk_item(lo.to(prev_span),
7216 maybe_append(attrs, extra_attrs));
7217 return Ok(Some(item));
7220 // `unsafe async fn` or `async fn`
7222 self.check_keyword(keywords::Unsafe) &&
7223 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7225 self.check_keyword(keywords::Async) &&
7226 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7229 // ASYNC FUNCTION ITEM
7230 let unsafety = self.parse_unsafety();
7231 self.expect_keyword(keywords::Async)?;
7232 self.expect_keyword(keywords::Fn)?;
7233 let fn_span = self.prev_span;
7234 let (ident, item_, extra_attrs) =
7235 self.parse_item_fn(unsafety,
7237 closure_id: ast::DUMMY_NODE_ID,
7238 return_impl_trait_id: ast::DUMMY_NODE_ID,
7240 respan(fn_span, Constness::NotConst),
7242 let prev_span = self.prev_span;
7243 let item = self.mk_item(lo.to(prev_span),
7247 maybe_append(attrs, extra_attrs));
7248 return Ok(Some(item));
7250 if self.check_keyword(keywords::Unsafe) &&
7251 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7252 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7254 // UNSAFE TRAIT ITEM
7255 self.bump(); // `unsafe`
7256 let is_auto = if self.eat_keyword(keywords::Trait) {
7259 self.expect_keyword(keywords::Auto)?;
7260 self.expect_keyword(keywords::Trait)?;
7263 let (ident, item_, extra_attrs) =
7264 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
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 self.check_keyword(keywords::Impl) ||
7274 self.check_keyword(keywords::Unsafe) &&
7275 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7276 self.check_keyword(keywords::Default) &&
7277 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7278 self.check_keyword(keywords::Default) &&
7279 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7281 let defaultness = self.parse_defaultness();
7282 let unsafety = self.parse_unsafety();
7283 self.expect_keyword(keywords::Impl)?;
7284 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7285 let span = lo.to(self.prev_span);
7286 return Ok(Some(self.mk_item(span, ident, item, visibility,
7287 maybe_append(attrs, extra_attrs))));
7289 if self.check_keyword(keywords::Fn) {
7292 let fn_span = self.prev_span;
7293 let (ident, item_, extra_attrs) =
7294 self.parse_item_fn(Unsafety::Normal,
7296 respan(fn_span, Constness::NotConst),
7298 let prev_span = self.prev_span;
7299 let item = self.mk_item(lo.to(prev_span),
7303 maybe_append(attrs, extra_attrs));
7304 return Ok(Some(item));
7306 if self.check_keyword(keywords::Unsafe)
7307 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7308 // UNSAFE FUNCTION ITEM
7309 self.bump(); // `unsafe`
7310 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7311 self.check(&token::OpenDelim(token::Brace));
7312 let abi = if self.eat_keyword(keywords::Extern) {
7313 self.parse_opt_abi()?.unwrap_or(Abi::C)
7317 self.expect_keyword(keywords::Fn)?;
7318 let fn_span = self.prev_span;
7319 let (ident, item_, extra_attrs) =
7320 self.parse_item_fn(Unsafety::Unsafe,
7322 respan(fn_span, Constness::NotConst),
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.eat_keyword(keywords::Mod) {
7334 let (ident, item_, extra_attrs) =
7335 self.parse_item_mod(&attrs[..])?;
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(type_) = self.eat_type() {
7345 let (ident, alias, generics) = type_?;
7347 let item_ = match alias {
7348 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7349 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7351 let prev_span = self.prev_span;
7352 let item = self.mk_item(lo.to(prev_span),
7357 return Ok(Some(item));
7359 if self.eat_keyword(keywords::Enum) {
7361 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7362 let prev_span = self.prev_span;
7363 let item = self.mk_item(lo.to(prev_span),
7367 maybe_append(attrs, extra_attrs));
7368 return Ok(Some(item));
7370 if self.check_keyword(keywords::Trait)
7371 || (self.check_keyword(keywords::Auto)
7372 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7374 let is_auto = if self.eat_keyword(keywords::Trait) {
7377 self.expect_keyword(keywords::Auto)?;
7378 self.expect_keyword(keywords::Trait)?;
7382 let (ident, item_, extra_attrs) =
7383 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7384 let prev_span = self.prev_span;
7385 let item = self.mk_item(lo.to(prev_span),
7389 maybe_append(attrs, extra_attrs));
7390 return Ok(Some(item));
7392 if self.eat_keyword(keywords::Struct) {
7394 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7395 let prev_span = self.prev_span;
7396 let item = self.mk_item(lo.to(prev_span),
7400 maybe_append(attrs, extra_attrs));
7401 return Ok(Some(item));
7403 if self.is_union_item() {
7406 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7407 let prev_span = self.prev_span;
7408 let item = self.mk_item(lo.to(prev_span),
7412 maybe_append(attrs, extra_attrs));
7413 return Ok(Some(item));
7415 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7416 return Ok(Some(macro_def));
7419 // Verify whether we have encountered a struct or method definition where the user forgot to
7420 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7421 if visibility.node.is_pub() &&
7422 self.check_ident() &&
7423 self.look_ahead(1, |t| *t != token::Not)
7425 // Space between `pub` keyword and the identifier
7428 // ^^^ `sp` points here
7429 let sp = self.prev_span.between(self.span);
7430 let full_sp = self.prev_span.to(self.span);
7431 let ident_sp = self.span;
7432 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7433 // possible public struct definition where `struct` was forgotten
7434 let ident = self.parse_ident().unwrap();
7435 let msg = format!("add `struct` here to parse `{}` as a public struct",
7437 let mut err = self.diagnostic()
7438 .struct_span_err(sp, "missing `struct` for struct definition");
7439 err.span_suggestion_short_with_applicability(
7440 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7443 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7444 let ident = self.parse_ident().unwrap();
7446 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
7451 self.consume_block(token::Paren);
7452 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7453 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7455 ("fn", kw_name, false)
7456 } else if self.check(&token::OpenDelim(token::Brace)) {
7458 ("fn", kw_name, false)
7459 } else if self.check(&token::Colon) {
7463 ("fn` or `struct", "function or struct", true)
7465 self.consume_block(token::Brace);
7467 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7468 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7470 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7474 err.span_suggestion_short_with_applicability(
7475 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7478 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7479 err.span_suggestion_with_applicability(
7481 "if you meant to call a macro, try",
7482 format!("{}!", snippet),
7483 // this is the `ambiguous` conditional branch
7484 Applicability::MaybeIncorrect
7487 err.help("if you meant to call a macro, remove the `pub` \
7488 and add a trailing `!` after the identifier");
7492 } else if self.look_ahead(1, |t| *t == token::Lt) {
7493 let ident = self.parse_ident().unwrap();
7494 self.eat_to_tokens(&[&token::Gt]);
7496 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7497 if let Ok(Some(_)) = self.parse_self_arg() {
7498 ("fn", "method", false)
7500 ("fn", "function", false)
7502 } else if self.check(&token::OpenDelim(token::Brace)) {
7503 ("struct", "struct", false)
7505 ("fn` or `struct", "function or struct", true)
7507 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7508 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7510 err.span_suggestion_short_with_applicability(
7512 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7513 format!(" {} ", kw),
7514 Applicability::MachineApplicable,
7520 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7523 /// Parse a foreign item.
7524 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7525 maybe_whole!(self, NtForeignItem, |ni| ni);
7527 let attrs = self.parse_outer_attributes()?;
7529 let visibility = self.parse_visibility(false)?;
7531 // FOREIGN STATIC ITEM
7532 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7533 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7534 if self.token.is_keyword(keywords::Const) {
7536 .struct_span_err(self.span, "extern items cannot be `const`")
7537 .span_suggestion_with_applicability(
7539 "try using a static value",
7540 "static".to_owned(),
7541 Applicability::MachineApplicable
7544 self.bump(); // `static` or `const`
7545 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7547 // FOREIGN FUNCTION ITEM
7548 if self.check_keyword(keywords::Fn) {
7549 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7551 // FOREIGN TYPE ITEM
7552 if self.check_keyword(keywords::Type) {
7553 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7556 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7560 ident: keywords::Invalid.ident(),
7561 span: lo.to(self.prev_span),
7562 id: ast::DUMMY_NODE_ID,
7565 node: ForeignItemKind::Macro(mac),
7570 if !attrs.is_empty() {
7571 self.expected_item_err(&attrs);
7579 /// This is the fall-through for parsing items.
7580 fn parse_macro_use_or_failure(
7582 attrs: Vec<Attribute> ,
7583 macros_allowed: bool,
7584 attributes_allowed: bool,
7586 visibility: Visibility
7587 ) -> PResult<'a, Option<P<Item>>> {
7588 if macros_allowed && self.token.is_path_start() {
7589 // MACRO INVOCATION ITEM
7591 let prev_span = self.prev_span;
7592 self.complain_if_pub_macro(&visibility.node, prev_span);
7594 let mac_lo = self.span;
7597 let pth = self.parse_path(PathStyle::Mod)?;
7598 self.expect(&token::Not)?;
7600 // a 'special' identifier (like what `macro_rules!` uses)
7601 // is optional. We should eventually unify invoc syntax
7603 let id = if self.token.is_ident() {
7606 keywords::Invalid.ident() // no special identifier
7608 // eat a matched-delimiter token tree:
7609 let (delim, tts) = self.expect_delimited_token_tree()?;
7610 if delim != MacDelimiter::Brace {
7611 if !self.eat(&token::Semi) {
7612 self.span_err(self.prev_span,
7613 "macros that expand to items must either \
7614 be surrounded with braces or followed by \
7619 let hi = self.prev_span;
7620 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7621 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7622 return Ok(Some(item));
7625 // FAILURE TO PARSE ITEM
7626 match visibility.node {
7627 VisibilityKind::Inherited => {}
7629 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7633 if !attributes_allowed && !attrs.is_empty() {
7634 self.expected_item_err(&attrs);
7639 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7640 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7641 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7643 if self.token.is_path_start() && !self.is_extern_non_path() {
7644 let prev_span = self.prev_span;
7646 let pth = self.parse_path(PathStyle::Mod)?;
7648 if pth.segments.len() == 1 {
7649 if !self.eat(&token::Not) {
7650 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7653 self.expect(&token::Not)?;
7656 if let Some(vis) = vis {
7657 self.complain_if_pub_macro(&vis.node, prev_span);
7662 // eat a matched-delimiter token tree:
7663 let (delim, tts) = self.expect_delimited_token_tree()?;
7664 if delim != MacDelimiter::Brace {
7665 self.expect(&token::Semi)?
7668 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7674 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7675 where F: FnOnce(&mut Self) -> PResult<'a, R>
7677 // Record all tokens we parse when parsing this item.
7678 let mut tokens = Vec::new();
7679 let prev_collecting = match self.token_cursor.frame.last_token {
7680 LastToken::Collecting(ref mut list) => {
7681 Some(mem::replace(list, Vec::new()))
7683 LastToken::Was(ref mut last) => {
7684 tokens.extend(last.take());
7688 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7689 let prev = self.token_cursor.stack.len();
7691 let last_token = if self.token_cursor.stack.len() == prev {
7692 &mut self.token_cursor.frame.last_token
7694 &mut self.token_cursor.stack[prev].last_token
7697 // Pull our the toekns that we've collected from the call to `f` above
7698 let mut collected_tokens = match *last_token {
7699 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7700 LastToken::Was(_) => panic!("our vector went away?"),
7703 // If we're not at EOF our current token wasn't actually consumed by
7704 // `f`, but it'll still be in our list that we pulled out. In that case
7706 let extra_token = if self.token != token::Eof {
7707 collected_tokens.pop()
7712 // If we were previously collecting tokens, then this was a recursive
7713 // call. In that case we need to record all the tokens we collected in
7714 // our parent list as well. To do that we push a clone of our stream
7715 // onto the previous list.
7716 let stream = collected_tokens.into_iter().collect::<TokenStream>();
7717 match prev_collecting {
7719 list.push(stream.clone());
7720 list.extend(extra_token);
7721 *last_token = LastToken::Collecting(list);
7724 *last_token = LastToken::Was(extra_token);
7731 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7732 let attrs = self.parse_outer_attributes()?;
7733 self.parse_item_(attrs, true, false)
7737 fn is_import_coupler(&mut self) -> bool {
7738 self.check(&token::ModSep) &&
7739 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7740 *t == token::BinOp(token::Star))
7745 /// USE_TREE = [`::`] `*` |
7746 /// [`::`] `{` USE_TREE_LIST `}` |
7748 /// PATH `::` `{` USE_TREE_LIST `}` |
7749 /// PATH [`as` IDENT]
7750 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7753 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7754 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7755 self.check(&token::BinOp(token::Star)) ||
7756 self.is_import_coupler() {
7757 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7758 let mod_sep_ctxt = self.span.ctxt();
7759 if self.eat(&token::ModSep) {
7760 prefix.segments.push(
7761 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7765 if self.eat(&token::BinOp(token::Star)) {
7768 UseTreeKind::Nested(self.parse_use_tree_list()?)
7771 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7772 prefix = self.parse_path(PathStyle::Mod)?;
7774 if self.eat(&token::ModSep) {
7775 if self.eat(&token::BinOp(token::Star)) {
7778 UseTreeKind::Nested(self.parse_use_tree_list()?)
7781 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7785 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7788 /// Parse UseTreeKind::Nested(list)
7790 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7791 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7792 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7793 &token::CloseDelim(token::Brace),
7794 SeqSep::trailing_allowed(token::Comma), |this| {
7795 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7799 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7800 if self.eat_keyword(keywords::As) {
7801 self.parse_ident_or_underscore().map(Some)
7807 /// Parses a source module as a crate. This is the main
7808 /// entry point for the parser.
7809 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7812 attrs: self.parse_inner_attributes()?,
7813 module: self.parse_mod_items(&token::Eof, lo)?,
7814 span: lo.to(self.span),
7818 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7819 let ret = match self.token {
7820 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7821 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7828 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7829 match self.parse_optional_str() {
7830 Some((s, style, suf)) => {
7831 let sp = self.prev_span;
7832 self.expect_no_suffix(sp, "string literal", suf);
7836 let msg = "expected string literal";
7837 let mut err = self.fatal(msg);
7838 err.span_label(self.span, msg);