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, TokenTree, TokenStream, TreeAndJoint};
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)]
106 #[derive(Clone, Copy, PartialEq, Debug)]
112 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
113 /// dropped into the token stream, which happens while parsing the result of
114 /// macro expansion). Placement of these is not as complex as I feared it would
115 /// be. The important thing is to make sure that lookahead doesn't balk at
116 /// `token::Interpolated` tokens.
117 macro_rules! maybe_whole_expr {
119 if let token::Interpolated(nt) = $p.token.clone() {
121 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
123 return Ok((*e).clone());
125 token::NtPath(ref path) => {
128 let kind = ExprKind::Path(None, (*path).clone());
129 return Ok($p.mk_expr(span, kind, ThinVec::new()));
131 token::NtBlock(ref block) => {
134 let kind = ExprKind::Block((*block).clone(), None);
135 return Ok($p.mk_expr(span, kind, ThinVec::new()));
143 /// As maybe_whole_expr, but for things other than expressions
144 macro_rules! maybe_whole {
145 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
146 if let token::Interpolated(nt) = $p.token.clone() {
147 if let token::$constructor($x) = nt.0.clone() {
155 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
156 if let Some(ref mut rhs) = rhs {
162 #[derive(Debug, Clone, Copy, PartialEq)]
173 trait RecoverQPath: Sized {
174 const PATH_STYLE: PathStyle = PathStyle::Expr;
175 fn to_ty(&self) -> Option<P<Ty>>;
176 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
177 fn to_string(&self) -> String;
180 impl RecoverQPath for Ty {
181 const PATH_STYLE: PathStyle = PathStyle::Type;
182 fn to_ty(&self) -> Option<P<Ty>> {
183 Some(P(self.clone()))
185 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
186 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
188 fn to_string(&self) -> String {
189 pprust::ty_to_string(self)
193 impl RecoverQPath for Pat {
194 fn to_ty(&self) -> Option<P<Ty>> {
197 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
198 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
200 fn to_string(&self) -> String {
201 pprust::pat_to_string(self)
205 impl RecoverQPath for Expr {
206 fn to_ty(&self) -> Option<P<Ty>> {
209 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
210 Self { span: path.span, node: ExprKind::Path(qself, path),
211 id: self.id, attrs: self.attrs.clone() }
213 fn to_string(&self) -> String {
214 pprust::expr_to_string(self)
218 /* ident is handled by common.rs */
221 pub struct Parser<'a> {
222 pub sess: &'a ParseSess,
223 /// the current token:
224 pub token: token::Token,
225 /// the span of the current token:
227 /// the span of the previous token:
228 meta_var_span: Option<Span>,
230 /// the previous token kind
231 prev_token_kind: PrevTokenKind,
232 restrictions: Restrictions,
233 /// Used to determine the path to externally loaded source files
234 crate directory: Directory<'a>,
235 /// Whether to parse sub-modules in other files.
236 pub recurse_into_file_modules: bool,
237 /// Name of the root module this parser originated from. If `None`, then the
238 /// name is not known. This does not change while the parser is descending
239 /// into modules, and sub-parsers have new values for this name.
240 pub root_module_name: Option<String>,
241 crate expected_tokens: Vec<TokenType>,
242 token_cursor: TokenCursor,
243 desugar_doc_comments: bool,
244 /// Whether we should configure out of line modules as we parse.
251 frame: TokenCursorFrame,
252 stack: Vec<TokenCursorFrame>,
256 struct TokenCursorFrame {
257 delim: token::DelimToken,
260 tree_cursor: tokenstream::Cursor,
262 last_token: LastToken,
265 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
266 /// by the parser, and then that's transitively used to record the tokens that
267 /// each parse AST item is created with.
269 /// Right now this has two states, either collecting tokens or not collecting
270 /// tokens. If we're collecting tokens we just save everything off into a local
271 /// `Vec`. This should eventually though likely save tokens from the original
272 /// token stream and just use slicing of token streams to avoid creation of a
273 /// whole new vector.
275 /// The second state is where we're passively not recording tokens, but the last
276 /// token is still tracked for when we want to start recording tokens. This
277 /// "last token" means that when we start recording tokens we'll want to ensure
278 /// that this, the first token, is included in the output.
280 /// You can find some more example usage of this in the `collect_tokens` method
284 Collecting(Vec<TreeAndJoint>),
285 Was(Option<TreeAndJoint>),
288 impl TokenCursorFrame {
289 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
293 open_delim: delim == token::NoDelim,
294 tree_cursor: tts.clone().into_trees(),
295 close_delim: delim == token::NoDelim,
296 last_token: LastToken::Was(None),
302 fn next(&mut self) -> TokenAndSpan {
304 let tree = if !self.frame.open_delim {
305 self.frame.open_delim = true;
306 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
307 } else if let Some(tree) = self.frame.tree_cursor.next() {
309 } else if !self.frame.close_delim {
310 self.frame.close_delim = true;
311 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
312 } else if let Some(frame) = self.stack.pop() {
316 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
319 match self.frame.last_token {
320 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
321 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
325 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
326 TokenTree::Delimited(sp, delim, tts) => {
327 let frame = TokenCursorFrame::new(sp, delim, &tts);
328 self.stack.push(mem::replace(&mut self.frame, frame));
334 fn next_desugared(&mut self) -> TokenAndSpan {
335 let (sp, name) = match self.next() {
336 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
340 let stripped = strip_doc_comment_decoration(&name.as_str());
342 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
343 // required to wrap the text.
344 let mut num_of_hashes = 0;
346 for ch in stripped.chars() {
349 '#' if count > 0 => count + 1,
352 num_of_hashes = cmp::max(num_of_hashes, count);
355 let delim_span = DelimSpan::from_single(sp);
356 let body = TokenTree::Delimited(
359 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
360 TokenTree::Token(sp, token::Eq),
361 TokenTree::Token(sp, token::Literal(
362 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
364 .iter().cloned().collect::<TokenStream>().into(),
367 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
370 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
371 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
372 .iter().cloned().collect::<TokenStream>().into()
374 [TokenTree::Token(sp, token::Pound), body]
375 .iter().cloned().collect::<TokenStream>().into()
383 #[derive(Clone, PartialEq)]
384 crate enum TokenType {
386 Keyword(keywords::Keyword),
395 fn to_string(&self) -> String {
397 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
398 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
399 TokenType::Operator => "an operator".to_string(),
400 TokenType::Lifetime => "lifetime".to_string(),
401 TokenType::Ident => "identifier".to_string(),
402 TokenType::Path => "path".to_string(),
403 TokenType::Type => "type".to_string(),
408 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
409 /// `IDENT<<u8 as Trait>::AssocTy>`.
411 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
412 /// that IDENT is not the ident of a fn trait
413 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
414 t == &token::ModSep || t == &token::Lt ||
415 t == &token::BinOp(token::Shl)
418 /// Information about the path to a module.
419 pub struct ModulePath {
422 pub result: Result<ModulePathSuccess, Error>,
425 pub struct ModulePathSuccess {
427 pub directory_ownership: DirectoryOwnership,
432 FileNotFoundForModule {
434 default_path: String,
435 secondary_path: String,
440 default_path: String,
441 secondary_path: String,
444 InclusiveRangeWithNoEnd,
448 fn span_err<S: Into<MultiSpan>>(self,
450 handler: &errors::Handler) -> DiagnosticBuilder {
452 Error::FileNotFoundForModule { ref mod_name,
456 let mut err = struct_span_err!(handler, sp, E0583,
457 "file not found for module `{}`", mod_name);
458 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
464 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
465 let mut err = struct_span_err!(handler, sp, E0584,
466 "file for module `{}` found at both {} and {}",
470 err.help("delete or rename one of them to remove the ambiguity");
473 Error::UselessDocComment => {
474 let mut err = struct_span_err!(handler, sp, E0585,
475 "found a documentation comment that doesn't document anything");
476 err.help("doc comments must come before what they document, maybe a comment was \
477 intended with `//`?");
480 Error::InclusiveRangeWithNoEnd => {
481 let mut err = struct_span_err!(handler, sp, E0586,
482 "inclusive range with no end");
483 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
493 AttributesParsed(ThinVec<Attribute>),
494 AlreadyParsed(P<Expr>),
497 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
498 fn from(o: Option<ThinVec<Attribute>>) -> Self {
499 if let Some(attrs) = o {
500 LhsExpr::AttributesParsed(attrs)
502 LhsExpr::NotYetParsed
507 impl From<P<Expr>> for LhsExpr {
508 fn from(expr: P<Expr>) -> Self {
509 LhsExpr::AlreadyParsed(expr)
513 /// Create a placeholder argument.
514 fn dummy_arg(span: Span) -> Arg {
515 let ident = Ident::new(keywords::Invalid.name(), span);
517 id: ast::DUMMY_NODE_ID,
518 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
524 id: ast::DUMMY_NODE_ID
526 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
529 #[derive(Copy, Clone, Debug)]
530 enum TokenExpectType {
535 impl<'a> Parser<'a> {
536 pub fn new(sess: &'a ParseSess,
538 directory: Option<Directory<'a>>,
539 recurse_into_file_modules: bool,
540 desugar_doc_comments: bool)
542 let mut parser = Parser {
544 token: token::Whitespace,
545 span: syntax_pos::DUMMY_SP,
546 prev_span: syntax_pos::DUMMY_SP,
548 prev_token_kind: PrevTokenKind::Other,
549 restrictions: Restrictions::empty(),
550 recurse_into_file_modules,
551 directory: Directory {
552 path: Cow::from(PathBuf::new()),
553 ownership: DirectoryOwnership::Owned { relative: None }
555 root_module_name: None,
556 expected_tokens: Vec::new(),
557 token_cursor: TokenCursor {
558 frame: TokenCursorFrame::new(
565 desugar_doc_comments,
569 let tok = parser.next_tok();
570 parser.token = tok.tok;
571 parser.span = tok.sp;
573 if let Some(directory) = directory {
574 parser.directory = directory;
575 } else if !parser.span.is_dummy() {
576 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
578 parser.directory.path = Cow::from(path);
582 parser.process_potential_macro_variable();
586 fn next_tok(&mut self) -> TokenAndSpan {
587 let mut next = if self.desugar_doc_comments {
588 self.token_cursor.next_desugared()
590 self.token_cursor.next()
592 if next.sp.is_dummy() {
593 // Tweak the location for better diagnostics, but keep syntactic context intact.
594 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
599 /// Convert the current token to a string using self's reader
600 pub fn this_token_to_string(&self) -> String {
601 pprust::token_to_string(&self.token)
604 fn token_descr(&self) -> Option<&'static str> {
605 Some(match &self.token {
606 t if t.is_special_ident() => "reserved identifier",
607 t if t.is_used_keyword() => "keyword",
608 t if t.is_unused_keyword() => "reserved keyword",
609 token::DocComment(..) => "doc comment",
614 fn this_token_descr(&self) -> String {
615 if let Some(prefix) = self.token_descr() {
616 format!("{} `{}`", prefix, self.this_token_to_string())
618 format!("`{}`", self.this_token_to_string())
622 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
623 let token_str = pprust::token_to_string(t);
624 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
627 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
628 match self.expect_one_of(&[], &[]) {
630 Ok(_) => unreachable!(),
634 /// Expect and consume the token t. Signal an error if
635 /// the next token is not t.
636 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
637 if self.expected_tokens.is_empty() {
638 if self.token == *t {
642 let token_str = pprust::token_to_string(t);
643 let this_token_str = self.this_token_descr();
644 let mut err = self.fatal(&format!("expected `{}`, found {}",
648 let sp = if self.token == token::Token::Eof {
649 // EOF, don't want to point at the following char, but rather the last token
652 self.sess.source_map().next_point(self.prev_span)
654 let label_exp = format!("expected `{}`", token_str);
655 let cm = self.sess.source_map();
656 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
657 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
658 // When the spans are in the same line, it means that the only content
659 // between them is whitespace, point only at the found token.
660 err.span_label(self.span, label_exp);
663 err.span_label(sp, label_exp);
664 err.span_label(self.span, "unexpected token");
670 self.expect_one_of(slice::from_ref(t), &[])
674 /// Expect next token to be edible or inedible token. If edible,
675 /// then consume it; if inedible, then return without consuming
676 /// anything. Signal a fatal error if next token is unexpected.
677 pub fn expect_one_of(&mut self,
678 edible: &[token::Token],
679 inedible: &[token::Token]) -> PResult<'a, ()>{
680 fn tokens_to_string(tokens: &[TokenType]) -> String {
681 let mut i = tokens.iter();
682 // This might be a sign we need a connect method on Iterator.
684 .map_or(String::new(), |t| t.to_string());
685 i.enumerate().fold(b, |mut b, (i, a)| {
686 if tokens.len() > 2 && i == tokens.len() - 2 {
688 } else if tokens.len() == 2 && i == tokens.len() - 2 {
693 b.push_str(&a.to_string());
697 if edible.contains(&self.token) {
700 } else if inedible.contains(&self.token) {
701 // leave it in the input
704 let mut expected = edible.iter()
705 .map(|x| TokenType::Token(x.clone()))
706 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
707 .chain(self.expected_tokens.iter().cloned())
708 .collect::<Vec<_>>();
709 expected.sort_by_cached_key(|x| x.to_string());
711 let expect = tokens_to_string(&expected[..]);
712 let actual = self.this_token_to_string();
713 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
714 let short_expect = if expected.len() > 6 {
715 format!("{} possible tokens", expected.len())
719 (format!("expected one of {}, found `{}`", expect, actual),
720 (self.sess.source_map().next_point(self.prev_span),
721 format!("expected one of {} here", short_expect)))
722 } else if expected.is_empty() {
723 (format!("unexpected token: `{}`", actual),
724 (self.prev_span, "unexpected token after this".to_string()))
726 (format!("expected {}, found `{}`", expect, actual),
727 (self.sess.source_map().next_point(self.prev_span),
728 format!("expected {} here", expect)))
730 let mut err = self.fatal(&msg_exp);
731 if self.token.is_ident_named("and") {
732 err.span_suggestion_short_with_applicability(
734 "use `&&` instead of `and` for the boolean operator",
736 Applicability::MaybeIncorrect,
739 if self.token.is_ident_named("or") {
740 err.span_suggestion_short_with_applicability(
742 "use `||` instead of `or` for the boolean operator",
744 Applicability::MaybeIncorrect,
747 let sp = if self.token == token::Token::Eof {
748 // This is EOF, don't want to point at the following char, but rather the last token
754 let cm = self.sess.source_map();
755 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
756 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
757 // When the spans are in the same line, it means that the only content between
758 // them is whitespace, point at the found token in that case:
760 // X | () => { syntax error };
761 // | ^^^^^ expected one of 8 possible tokens here
763 // instead of having:
765 // X | () => { syntax error };
766 // | -^^^^^ unexpected token
768 // | expected one of 8 possible tokens here
769 err.span_label(self.span, label_exp);
771 _ if self.prev_span == syntax_pos::DUMMY_SP => {
772 // Account for macro context where the previous span might not be
773 // available to avoid incorrect output (#54841).
774 err.span_label(self.span, "unexpected token");
777 err.span_label(sp, label_exp);
778 err.span_label(self.span, "unexpected token");
785 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
786 fn interpolated_or_expr_span(&self,
787 expr: PResult<'a, P<Expr>>)
788 -> PResult<'a, (Span, P<Expr>)> {
790 if self.prev_token_kind == PrevTokenKind::Interpolated {
798 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
799 let mut err = self.struct_span_err(self.span,
800 &format!("expected identifier, found {}",
801 self.this_token_descr()));
802 if let token::Ident(ident, false) = &self.token {
803 if ident.is_reserved() && !ident.is_path_segment_keyword() &&
804 ident.name != keywords::Underscore.name()
806 err.span_suggestion_with_applicability(
808 "you can escape reserved keywords to use them as identifiers",
809 format!("r#{}", ident),
810 Applicability::MaybeIncorrect,
814 if let Some(token_descr) = self.token_descr() {
815 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
817 err.span_label(self.span, "expected identifier");
818 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
819 err.span_suggestion_with_applicability(
823 Applicability::MachineApplicable,
830 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
831 self.parse_ident_common(true)
834 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
836 token::Ident(ident, _) => {
837 if self.token.is_reserved_ident() {
838 let mut err = self.expected_ident_found();
845 let span = self.span;
847 Ok(Ident::new(ident.name, span))
850 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
851 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
853 self.expected_ident_found()
859 /// Check if the next token is `tok`, and return `true` if so.
861 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
863 crate fn check(&mut self, tok: &token::Token) -> bool {
864 let is_present = self.token == *tok;
865 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
869 /// Consume token 'tok' if it exists. Returns true if the given
870 /// token was present, false otherwise.
871 pub fn eat(&mut self, tok: &token::Token) -> bool {
872 let is_present = self.check(tok);
873 if is_present { self.bump() }
877 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
878 self.expected_tokens.push(TokenType::Keyword(kw));
879 self.token.is_keyword(kw)
882 /// If the next token is the given keyword, eat it and return
883 /// true. Otherwise, return false.
884 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
885 if self.check_keyword(kw) {
893 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
894 if self.token.is_keyword(kw) {
902 /// If the given word is not a keyword, signal an error.
903 /// If the next token is not the given word, signal an error.
904 /// Otherwise, eat it.
905 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
906 if !self.eat_keyword(kw) {
913 fn check_ident(&mut self) -> bool {
914 if self.token.is_ident() {
917 self.expected_tokens.push(TokenType::Ident);
922 fn check_path(&mut self) -> bool {
923 if self.token.is_path_start() {
926 self.expected_tokens.push(TokenType::Path);
931 fn check_type(&mut self) -> bool {
932 if self.token.can_begin_type() {
935 self.expected_tokens.push(TokenType::Type);
940 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
941 /// and continue. If a `+` is not seen, return false.
943 /// This is using when token splitting += into +.
944 /// See issue 47856 for an example of when this may occur.
945 fn eat_plus(&mut self) -> bool {
946 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
948 token::BinOp(token::Plus) => {
952 token::BinOpEq(token::Plus) => {
953 let span = self.span.with_lo(self.span.lo() + BytePos(1));
954 self.bump_with(token::Eq, span);
962 /// Checks to see if the next token is either `+` or `+=`.
963 /// Otherwise returns false.
964 fn check_plus(&mut self) -> bool {
965 if self.token.is_like_plus() {
969 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
974 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
975 /// `&` and continue. If an `&` is not seen, signal an error.
976 fn expect_and(&mut self) -> PResult<'a, ()> {
977 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
979 token::BinOp(token::And) => {
984 let span = self.span.with_lo(self.span.lo() + BytePos(1));
985 Ok(self.bump_with(token::BinOp(token::And), span))
987 _ => self.unexpected()
991 /// Expect and consume an `|`. If `||` is seen, replace it with a single
992 /// `|` and continue. If an `|` is not seen, signal an error.
993 fn expect_or(&mut self) -> PResult<'a, ()> {
994 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
996 token::BinOp(token::Or) => {
1001 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1002 Ok(self.bump_with(token::BinOp(token::Or), span))
1004 _ => self.unexpected()
1008 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1010 None => {/* everything ok */}
1012 let text = suf.as_str();
1013 if text.is_empty() {
1014 self.span_bug(sp, "found empty literal suffix in Some")
1016 let msg = format!("{} with a suffix is invalid", kind);
1017 self.struct_span_err(sp, &msg)
1018 .span_label(sp, msg)
1024 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
1025 /// `<` and continue. If a `<` is not seen, return false.
1027 /// This is meant to be used when parsing generics on a path to get the
1029 fn eat_lt(&mut self) -> bool {
1030 self.expected_tokens.push(TokenType::Token(token::Lt));
1036 token::BinOp(token::Shl) => {
1037 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1038 self.bump_with(token::Lt, span);
1045 fn expect_lt(&mut self) -> PResult<'a, ()> {
1053 /// Expect and consume a GT. if a >> is seen, replace it
1054 /// with a single > and continue. If a GT is not seen,
1055 /// signal an error.
1056 fn expect_gt(&mut self) -> PResult<'a, ()> {
1057 self.expected_tokens.push(TokenType::Token(token::Gt));
1063 token::BinOp(token::Shr) => {
1064 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1065 Ok(self.bump_with(token::Gt, span))
1067 token::BinOpEq(token::Shr) => {
1068 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1069 Ok(self.bump_with(token::Ge, span))
1072 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1073 Ok(self.bump_with(token::Eq, span))
1075 _ => self.unexpected()
1079 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1080 /// passes through any errors encountered. Used for error recovery.
1081 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1082 let handler = self.diagnostic();
1084 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1086 TokenExpectType::Expect,
1087 |p| Ok(p.parse_token_tree())) {
1088 handler.cancel(err);
1092 /// Parse a sequence, including the closing delimiter. The function
1093 /// f must consume tokens until reaching the next separator or
1094 /// closing bracket.
1095 pub fn parse_seq_to_end<T, F>(&mut self,
1099 -> PResult<'a, Vec<T>> where
1100 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1102 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1107 /// Parse a sequence, not including the closing delimiter. The function
1108 /// f must consume tokens until reaching the next separator or
1109 /// closing bracket.
1110 pub fn parse_seq_to_before_end<T, F>(&mut self,
1114 -> PResult<'a, Vec<T>>
1115 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1117 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1120 fn parse_seq_to_before_tokens<T, F>(
1122 kets: &[&token::Token],
1124 expect: TokenExpectType,
1126 ) -> PResult<'a, Vec<T>>
1127 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1129 let mut first: bool = true;
1131 while !kets.iter().any(|k| {
1133 TokenExpectType::Expect => self.check(k),
1134 TokenExpectType::NoExpect => self.token == **k,
1138 token::CloseDelim(..) | token::Eof => break,
1141 if let Some(ref t) = sep.sep {
1145 if let Err(mut e) = self.expect(t) {
1146 // Attempt to keep parsing if it was a similar separator
1147 if let Some(ref tokens) = t.similar_tokens() {
1148 if tokens.contains(&self.token) {
1153 // Attempt to keep parsing if it was an omitted separator
1167 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1169 TokenExpectType::Expect => self.check(k),
1170 TokenExpectType::NoExpect => self.token == **k,
1183 /// Parse a sequence, including the closing delimiter. The function
1184 /// f must consume tokens until reaching the next separator or
1185 /// closing bracket.
1186 fn parse_unspanned_seq<T, F>(&mut self,
1191 -> PResult<'a, Vec<T>> where
1192 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1195 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1200 /// Advance the parser by one token
1201 pub fn bump(&mut self) {
1202 if self.prev_token_kind == PrevTokenKind::Eof {
1203 // Bumping after EOF is a bad sign, usually an infinite loop.
1204 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1207 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1209 // Record last token kind for possible error recovery.
1210 self.prev_token_kind = match self.token {
1211 token::DocComment(..) => PrevTokenKind::DocComment,
1212 token::Comma => PrevTokenKind::Comma,
1213 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1214 token::Interpolated(..) => PrevTokenKind::Interpolated,
1215 token::Eof => PrevTokenKind::Eof,
1216 token::Ident(..) => PrevTokenKind::Ident,
1217 _ => PrevTokenKind::Other,
1220 let next = self.next_tok();
1221 self.span = next.sp;
1222 self.token = next.tok;
1223 self.expected_tokens.clear();
1224 // check after each token
1225 self.process_potential_macro_variable();
1228 /// Advance the parser using provided token as a next one. Use this when
1229 /// consuming a part of a token. For example a single `<` from `<<`.
1230 fn bump_with(&mut self, next: token::Token, span: Span) {
1231 self.prev_span = self.span.with_hi(span.lo());
1232 // It would be incorrect to record the kind of the current token, but
1233 // fortunately for tokens currently using `bump_with`, the
1234 // prev_token_kind will be of no use anyway.
1235 self.prev_token_kind = PrevTokenKind::Other;
1238 self.expected_tokens.clear();
1241 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1242 F: FnOnce(&token::Token) -> R,
1245 return f(&self.token)
1248 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1249 Some(tree) => match tree {
1250 TokenTree::Token(_, tok) => tok,
1251 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1253 None => token::CloseDelim(self.token_cursor.frame.delim),
1257 fn look_ahead_span(&self, dist: usize) -> Span {
1262 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1263 Some(TokenTree::Token(span, _)) => span,
1264 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1265 None => self.look_ahead_span(dist - 1),
1268 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1269 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1271 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1272 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1274 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1275 err.span_err(sp, self.diagnostic())
1277 fn bug(&self, m: &str) -> ! {
1278 self.sess.span_diagnostic.span_bug(self.span, m)
1280 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1281 self.sess.span_diagnostic.span_err(sp, m)
1283 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1284 self.sess.span_diagnostic.struct_span_err(sp, m)
1286 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1287 self.sess.span_diagnostic.span_bug(sp, m)
1289 crate fn abort_if_errors(&self) {
1290 self.sess.span_diagnostic.abort_if_errors();
1293 fn cancel(&self, err: &mut DiagnosticBuilder) {
1294 self.sess.span_diagnostic.cancel(err)
1297 crate fn diagnostic(&self) -> &'a errors::Handler {
1298 &self.sess.span_diagnostic
1301 /// Is the current token one of the keywords that signals a bare function
1303 fn token_is_bare_fn_keyword(&mut self) -> bool {
1304 self.check_keyword(keywords::Fn) ||
1305 self.check_keyword(keywords::Unsafe) ||
1306 self.check_keyword(keywords::Extern)
1309 /// parse a `TyKind::BareFn` type:
1310 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1313 [unsafe] [extern "ABI"] fn (S) -> T
1323 let unsafety = self.parse_unsafety();
1324 let abi = if self.eat_keyword(keywords::Extern) {
1325 self.parse_opt_abi()?.unwrap_or(Abi::C)
1330 self.expect_keyword(keywords::Fn)?;
1331 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1332 let ret_ty = self.parse_ret_ty(false)?;
1333 let decl = P(FnDecl {
1338 Ok(TyKind::BareFn(P(BareFnTy {
1346 /// Parse asyncness: `async` or nothing
1347 fn parse_asyncness(&mut self) -> IsAsync {
1348 if self.eat_keyword(keywords::Async) {
1350 closure_id: ast::DUMMY_NODE_ID,
1351 return_impl_trait_id: ast::DUMMY_NODE_ID,
1358 /// Parse unsafety: `unsafe` or nothing.
1359 fn parse_unsafety(&mut self) -> Unsafety {
1360 if self.eat_keyword(keywords::Unsafe) {
1367 /// Parse the items in a trait declaration
1368 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1369 maybe_whole!(self, NtTraitItem, |x| x);
1370 let attrs = self.parse_outer_attributes()?;
1371 let (mut item, tokens) = self.collect_tokens(|this| {
1372 this.parse_trait_item_(at_end, attrs)
1374 // See `parse_item` for why this clause is here.
1375 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1376 item.tokens = Some(tokens);
1381 fn parse_trait_item_(&mut self,
1383 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1386 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1387 self.parse_trait_item_assoc_ty()?
1388 } else if self.is_const_item() {
1389 self.expect_keyword(keywords::Const)?;
1390 let ident = self.parse_ident()?;
1391 self.expect(&token::Colon)?;
1392 let ty = self.parse_ty()?;
1393 let default = if self.eat(&token::Eq) {
1394 let expr = self.parse_expr()?;
1395 self.expect(&token::Semi)?;
1398 self.expect(&token::Semi)?;
1401 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1402 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1403 // trait item macro.
1404 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1406 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1408 let ident = self.parse_ident()?;
1409 let mut generics = self.parse_generics()?;
1411 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1412 // This is somewhat dubious; We don't want to allow
1413 // argument names to be left off if there is a
1416 // We don't allow argument names to be left off in edition 2018.
1417 p.parse_arg_general(p.span.rust_2018(), true)
1419 generics.where_clause = self.parse_where_clause()?;
1421 let sig = ast::MethodSig {
1431 let body = match self.token {
1435 debug!("parse_trait_methods(): parsing required method");
1438 token::OpenDelim(token::Brace) => {
1439 debug!("parse_trait_methods(): parsing provided method");
1441 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1442 attrs.extend(inner_attrs.iter().cloned());
1445 token::Interpolated(ref nt) => {
1447 token::NtBlock(..) => {
1449 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1450 attrs.extend(inner_attrs.iter().cloned());
1454 let token_str = self.this_token_descr();
1455 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1457 err.span_label(self.span, "expected `;` or `{`");
1463 let token_str = self.this_token_descr();
1464 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1466 err.span_label(self.span, "expected `;` or `{`");
1470 (ident, ast::TraitItemKind::Method(sig, body), generics)
1474 id: ast::DUMMY_NODE_ID,
1479 span: lo.to(self.prev_span),
1484 /// Parse optional return type [ -> TY ] in function decl
1485 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1486 if self.eat(&token::RArrow) {
1487 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1489 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1494 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1495 self.parse_ty_common(true, true)
1498 /// Parse a type in restricted contexts where `+` is not permitted.
1499 /// Example 1: `&'a TYPE`
1500 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1501 /// Example 2: `value1 as TYPE + value2`
1502 /// `+` is prohibited to avoid interactions with expression grammar.
1503 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1504 self.parse_ty_common(false, true)
1507 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1508 -> PResult<'a, P<Ty>> {
1509 maybe_whole!(self, NtTy, |x| x);
1512 let mut impl_dyn_multi = false;
1513 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1514 // `(TYPE)` is a parenthesized type.
1515 // `(TYPE,)` is a tuple with a single field of type TYPE.
1516 let mut ts = vec![];
1517 let mut last_comma = false;
1518 while self.token != token::CloseDelim(token::Paren) {
1519 ts.push(self.parse_ty()?);
1520 if self.eat(&token::Comma) {
1527 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1528 self.expect(&token::CloseDelim(token::Paren))?;
1530 if ts.len() == 1 && !last_comma {
1531 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1532 let maybe_bounds = allow_plus && self.token.is_like_plus();
1534 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1535 TyKind::Path(None, ref path) if maybe_bounds => {
1536 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1538 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1539 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1540 let path = match bounds[0] {
1541 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1542 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1544 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1547 _ => TyKind::Paren(P(ty))
1552 } else if self.eat(&token::Not) {
1555 } else if self.eat(&token::BinOp(token::Star)) {
1557 TyKind::Ptr(self.parse_ptr()?)
1558 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1560 let t = self.parse_ty()?;
1561 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1562 let t = match self.maybe_parse_fixed_length_of_vec()? {
1563 None => TyKind::Slice(t),
1564 Some(length) => TyKind::Array(t, AnonConst {
1565 id: ast::DUMMY_NODE_ID,
1569 self.expect(&token::CloseDelim(token::Bracket))?;
1571 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1574 self.parse_borrowed_pointee()?
1575 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1577 // In order to not be ambiguous, the type must be surrounded by parens.
1578 self.expect(&token::OpenDelim(token::Paren))?;
1580 id: ast::DUMMY_NODE_ID,
1581 value: self.parse_expr()?,
1583 self.expect(&token::CloseDelim(token::Paren))?;
1585 } else if self.eat_keyword(keywords::Underscore) {
1586 // A type to be inferred `_`
1588 } else if self.token_is_bare_fn_keyword() {
1589 // Function pointer type
1590 self.parse_ty_bare_fn(Vec::new())?
1591 } else if self.check_keyword(keywords::For) {
1592 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1593 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1594 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1596 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1597 if self.token_is_bare_fn_keyword() {
1598 self.parse_ty_bare_fn(lifetime_defs)?
1600 let path = self.parse_path(PathStyle::Type)?;
1601 let parse_plus = allow_plus && self.check_plus();
1602 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1604 } else if self.eat_keyword(keywords::Impl) {
1605 // Always parse bounds greedily for better error recovery.
1606 let bounds = self.parse_generic_bounds()?;
1607 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1608 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1609 } else if self.check_keyword(keywords::Dyn) &&
1610 (self.span.rust_2018() ||
1611 self.look_ahead(1, |t| t.can_begin_bound() &&
1612 !can_continue_type_after_non_fn_ident(t))) {
1613 self.bump(); // `dyn`
1614 // Always parse bounds greedily for better error recovery.
1615 let bounds = self.parse_generic_bounds()?;
1616 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1617 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1618 } else if self.check(&token::Question) ||
1619 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1620 // Bound list (trait object type)
1621 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1622 TraitObjectSyntax::None)
1623 } else if self.eat_lt() {
1625 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1626 TyKind::Path(Some(qself), path)
1627 } else if self.token.is_path_start() {
1629 let path = self.parse_path(PathStyle::Type)?;
1630 if self.eat(&token::Not) {
1631 // Macro invocation in type position
1632 let (delim, tts) = self.expect_delimited_token_tree()?;
1633 let node = Mac_ { path, tts, delim };
1634 TyKind::Mac(respan(lo.to(self.prev_span), node))
1636 // Just a type path or bound list (trait object type) starting with a trait.
1638 // `Trait1 + Trait2 + 'a`
1639 if allow_plus && self.check_plus() {
1640 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1642 TyKind::Path(None, path)
1646 let msg = format!("expected type, found {}", self.this_token_descr());
1647 return Err(self.fatal(&msg));
1650 let span = lo.to(self.prev_span);
1651 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1653 // Try to recover from use of `+` with incorrect priority.
1654 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1655 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1656 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1661 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1662 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1663 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1664 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1666 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1667 bounds.append(&mut self.parse_generic_bounds()?);
1669 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1672 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1673 if !allow_plus && impl_dyn_multi {
1674 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1675 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1676 .span_suggestion_with_applicability(
1678 "use parentheses to disambiguate",
1680 Applicability::MachineApplicable
1685 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1686 // Do not add `+` to expected tokens.
1687 if !allow_plus || !self.token.is_like_plus() {
1692 let bounds = self.parse_generic_bounds()?;
1693 let sum_span = ty.span.to(self.prev_span);
1695 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1696 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1699 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1700 let sum_with_parens = pprust::to_string(|s| {
1701 use print::pprust::PrintState;
1704 s.print_opt_lifetime(lifetime)?;
1705 s.print_mutability(mut_ty.mutbl)?;
1707 s.print_type(&mut_ty.ty)?;
1708 s.print_type_bounds(" +", &bounds)?;
1711 err.span_suggestion_with_applicability(
1713 "try adding parentheses",
1715 Applicability::MachineApplicable
1718 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1719 err.span_label(sum_span, "perhaps you forgot parentheses?");
1722 err.span_label(sum_span, "expected a path");
1729 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1730 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1732 // Do not add `::` to expected tokens.
1733 if !allow_recovery || self.token != token::ModSep {
1736 let ty = match base.to_ty() {
1738 None => return Ok(base),
1741 self.bump(); // `::`
1742 let mut segments = Vec::new();
1743 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1745 let span = ty.span.to(self.prev_span);
1746 let path_span = span.to(span); // use an empty path since `position` == 0
1747 let recovered = base.to_recovered(
1748 Some(QSelf { ty, path_span, position: 0 }),
1749 ast::Path { segments, span },
1753 .struct_span_err(span, "missing angle brackets in associated item path")
1754 .span_suggestion_with_applicability( // this is a best-effort recovery
1755 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1761 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1762 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1763 let mutbl = self.parse_mutability();
1764 let ty = self.parse_ty_no_plus()?;
1765 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1768 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1769 let mutbl = if self.eat_keyword(keywords::Mut) {
1771 } else if self.eat_keyword(keywords::Const) {
1772 Mutability::Immutable
1774 let span = self.prev_span;
1775 let msg = "expected mut or const in raw pointer type";
1776 self.struct_span_err(span, msg)
1777 .span_label(span, msg)
1778 .help("use `*mut T` or `*const T` as appropriate")
1780 Mutability::Immutable
1782 let t = self.parse_ty_no_plus()?;
1783 Ok(MutTy { ty: t, mutbl: mutbl })
1786 fn is_named_argument(&mut self) -> bool {
1787 let offset = match self.token {
1788 token::Interpolated(ref nt) => match nt.0 {
1789 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1792 token::BinOp(token::And) | token::AndAnd => 1,
1793 _ if self.token.is_keyword(keywords::Mut) => 1,
1797 self.look_ahead(offset, |t| t.is_ident()) &&
1798 self.look_ahead(offset + 1, |t| t == &token::Colon)
1801 /// Skip unexpected attributes and doc comments in this position and emit an appropriate error.
1802 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1803 if let token::DocComment(_) = self.token {
1804 let mut err = self.diagnostic().struct_span_err(
1806 &format!("documentation comments cannot be applied to {}", applied_to),
1808 err.span_label(self.span, "doc comments are not allowed here");
1811 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1812 *t == token::OpenDelim(token::Bracket)
1815 // Skip every token until next possible arg.
1816 while self.token != token::CloseDelim(token::Bracket) {
1819 let sp = lo.to(self.span);
1821 let mut err = self.diagnostic().struct_span_err(
1823 &format!("attributes cannot be applied to {}", applied_to),
1825 err.span_label(sp, "attributes are not allowed here");
1830 /// This version of parse arg doesn't necessarily require
1831 /// identifier names.
1832 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool) -> PResult<'a, Arg> {
1833 maybe_whole!(self, NtArg, |x| x);
1835 if let Ok(Some(_)) = self.parse_self_arg() {
1836 let mut err = self.struct_span_err(self.prev_span,
1837 "unexpected `self` argument in function");
1838 err.span_label(self.prev_span,
1839 "`self` is only valid as the first argument of an associated function");
1843 let (pat, ty) = if require_name || self.is_named_argument() {
1844 debug!("parse_arg_general parse_pat (require_name:{})",
1846 self.eat_incorrect_doc_comment("method arguments");
1847 let pat = self.parse_pat(Some("argument name"))?;
1849 if let Err(mut err) = self.expect(&token::Colon) {
1850 // If we find a pattern followed by an identifier, it could be an (incorrect)
1851 // C-style parameter declaration.
1852 if self.check_ident() && self.look_ahead(1, |t| {
1853 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1855 let ident = self.parse_ident().unwrap();
1856 let span = pat.span.with_hi(ident.span.hi());
1858 err.span_suggestion_with_applicability(
1860 "declare the type after the parameter binding",
1861 String::from("<identifier>: <type>"),
1862 Applicability::HasPlaceholders,
1864 } else if require_name && is_trait_item {
1865 if let PatKind::Ident(_, ident, _) = pat.node {
1866 err.span_suggestion_with_applicability(
1868 "explicitly ignore parameter",
1869 format!("_: {}", ident),
1870 Applicability::MachineApplicable,
1874 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1880 self.eat_incorrect_doc_comment("a method argument's type");
1881 (pat, self.parse_ty()?)
1883 debug!("parse_arg_general ident_to_pat");
1884 let parser_snapshot_before_ty = self.clone();
1885 self.eat_incorrect_doc_comment("a method argument's type");
1886 let mut ty = self.parse_ty();
1887 if ty.is_ok() && self.token != token::Comma &&
1888 self.token != token::CloseDelim(token::Paren) {
1889 // This wasn't actually a type, but a pattern looking like a type,
1890 // so we are going to rollback and re-parse for recovery.
1891 ty = self.unexpected();
1895 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1897 id: ast::DUMMY_NODE_ID,
1898 node: PatKind::Ident(
1899 BindingMode::ByValue(Mutability::Immutable), ident, None),
1905 // Recover from attempting to parse the argument as a type without pattern.
1907 mem::replace(self, parser_snapshot_before_ty);
1908 let pat = self.parse_pat(Some("argument name"))?;
1909 self.expect(&token::Colon)?;
1910 let ty = self.parse_ty()?;
1912 let mut err = self.diagnostic().struct_span_err_with_code(
1914 "patterns aren't allowed in methods without bodies",
1915 DiagnosticId::Error("E0642".into()),
1917 err.span_suggestion_short_with_applicability(
1919 "give this argument a name or use an underscore to ignore it",
1921 Applicability::MachineApplicable,
1925 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1927 node: PatKind::Wild,
1929 id: ast::DUMMY_NODE_ID
1936 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1939 /// Parse a single function argument
1940 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1941 self.parse_arg_general(true, false)
1944 /// Parse an argument in a lambda header e.g., |arg, arg|
1945 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1946 let pat = self.parse_pat(Some("argument name"))?;
1947 let t = if self.eat(&token::Colon) {
1951 id: ast::DUMMY_NODE_ID,
1952 node: TyKind::Infer,
1953 span: self.prev_span,
1959 id: ast::DUMMY_NODE_ID
1963 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1964 if self.eat(&token::Semi) {
1965 Ok(Some(self.parse_expr()?))
1971 /// Matches token_lit = LIT_INTEGER | ...
1972 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1973 let out = match self.token {
1974 token::Interpolated(ref nt) => match nt.0 {
1975 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1976 ExprKind::Lit(ref lit) => { lit.node.clone() }
1977 _ => { return self.unexpected_last(&self.token); }
1979 _ => { return self.unexpected_last(&self.token); }
1981 token::Literal(lit, suf) => {
1982 let diag = Some((self.span, &self.sess.span_diagnostic));
1983 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1987 self.expect_no_suffix(sp, lit.literal_name(), suf)
1992 token::Dot if self.look_ahead(1, |t| match t {
1993 token::Literal(parse::token::Lit::Integer(_) , None) => true,
1995 }) => { // recover from `let x = .4;`
1998 if let token::Literal(
1999 parse::token::Lit::Integer(val),
2003 let sp = lo.to(self.prev_span);
2004 let mut err = self.diagnostic()
2005 .struct_span_err(sp, "numeric float literals must have a significant");
2006 err.span_suggestion_with_applicability(
2008 "numeric float literals must have a significant",
2009 format!("0.{}", val),
2010 Applicability::MachineApplicable,
2013 return Ok(ast::LitKind::Float(val, ast::FloatTy::F32));
2018 _ => { return self.unexpected_last(&self.token); }
2025 /// Matches lit = true | false | token_lit
2026 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2028 let lit = if self.eat_keyword(keywords::True) {
2030 } else if self.eat_keyword(keywords::False) {
2031 LitKind::Bool(false)
2033 let lit = self.parse_lit_token()?;
2036 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2039 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
2040 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2041 maybe_whole_expr!(self);
2043 let minus_lo = self.span;
2044 let minus_present = self.eat(&token::BinOp(token::Minus));
2046 let literal = self.parse_lit()?;
2047 let hi = self.prev_span;
2048 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2051 let minus_hi = self.prev_span;
2052 let unary = self.mk_unary(UnOp::Neg, expr);
2053 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2059 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2061 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2062 let span = self.span;
2064 Ok(Ident::new(ident.name, span))
2066 _ => self.parse_ident(),
2070 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2072 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2073 let span = self.span;
2075 Ok(Ident::new(ident.name, span))
2077 _ => self.parse_ident(),
2081 /// Parses qualified path.
2082 /// Assumes that the leading `<` has been parsed already.
2084 /// `qualified_path = <type [as trait_ref]>::path`
2089 /// `<T as U>::F::a<S>` (without disambiguator)
2090 /// `<T as U>::F::a::<S>` (with disambiguator)
2091 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2092 let lo = self.prev_span;
2093 let ty = self.parse_ty()?;
2095 // `path` will contain the prefix of the path up to the `>`,
2096 // if any (e.g., `U` in the `<T as U>::*` examples
2097 // above). `path_span` has the span of that path, or an empty
2098 // span in the case of something like `<T>::Bar`.
2099 let (mut path, path_span);
2100 if self.eat_keyword(keywords::As) {
2101 let path_lo = self.span;
2102 path = self.parse_path(PathStyle::Type)?;
2103 path_span = path_lo.to(self.prev_span);
2105 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2106 path_span = self.span.to(self.span);
2109 self.expect(&token::Gt)?;
2110 self.expect(&token::ModSep)?;
2112 let qself = QSelf { ty, path_span, position: path.segments.len() };
2113 self.parse_path_segments(&mut path.segments, style, true)?;
2115 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2118 /// Parses simple paths.
2120 /// `path = [::] segment+`
2121 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2124 /// `a::b::C<D>` (without disambiguator)
2125 /// `a::b::C::<D>` (with disambiguator)
2126 /// `Fn(Args)` (without disambiguator)
2127 /// `Fn::(Args)` (with disambiguator)
2128 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2129 self.parse_path_common(style, true)
2132 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2133 -> PResult<'a, ast::Path> {
2134 maybe_whole!(self, NtPath, |path| {
2135 if style == PathStyle::Mod &&
2136 path.segments.iter().any(|segment| segment.args.is_some()) {
2137 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2142 let lo = self.meta_var_span.unwrap_or(self.span);
2143 let mut segments = Vec::new();
2144 let mod_sep_ctxt = self.span.ctxt();
2145 if self.eat(&token::ModSep) {
2146 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2148 self.parse_path_segments(&mut segments, style, enable_warning)?;
2150 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2153 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2154 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2155 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2156 let meta_ident = match self.token {
2157 token::Interpolated(ref nt) => match nt.0 {
2158 token::NtMeta(ref meta) => match meta.node {
2159 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2166 if let Some(path) = meta_ident {
2170 self.parse_path(style)
2173 fn parse_path_segments(&mut self,
2174 segments: &mut Vec<PathSegment>,
2176 enable_warning: bool)
2177 -> PResult<'a, ()> {
2179 segments.push(self.parse_path_segment(style, enable_warning)?);
2181 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2187 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2188 -> PResult<'a, PathSegment> {
2189 let ident = self.parse_path_segment_ident()?;
2191 let is_args_start = |token: &token::Token| match *token {
2192 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2195 let check_args_start = |this: &mut Self| {
2196 this.expected_tokens.extend_from_slice(
2197 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2199 is_args_start(&this.token)
2202 Ok(if style == PathStyle::Type && check_args_start(self) ||
2203 style != PathStyle::Mod && self.check(&token::ModSep)
2204 && self.look_ahead(1, |t| is_args_start(t)) {
2205 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2207 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2208 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2209 .span_label(self.prev_span, "try removing `::`").emit();
2212 let args = if self.eat_lt() {
2214 let (args, bindings) = self.parse_generic_args()?;
2216 let span = lo.to(self.prev_span);
2217 AngleBracketedArgs { args, bindings, span }.into()
2221 let inputs = self.parse_seq_to_before_tokens(
2222 &[&token::CloseDelim(token::Paren)],
2223 SeqSep::trailing_allowed(token::Comma),
2224 TokenExpectType::Expect,
2227 let span = lo.to(self.prev_span);
2228 let output = if self.eat(&token::RArrow) {
2229 Some(self.parse_ty_common(false, false)?)
2233 ParenthesisedArgs { inputs, output, span }.into()
2236 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2238 // Generic arguments are not found.
2239 PathSegment::from_ident(ident)
2243 crate fn check_lifetime(&mut self) -> bool {
2244 self.expected_tokens.push(TokenType::Lifetime);
2245 self.token.is_lifetime()
2248 /// Parse single lifetime 'a or panic.
2249 crate fn expect_lifetime(&mut self) -> Lifetime {
2250 if let Some(ident) = self.token.lifetime() {
2251 let span = self.span;
2253 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2255 self.span_bug(self.span, "not a lifetime")
2259 fn eat_label(&mut self) -> Option<Label> {
2260 if let Some(ident) = self.token.lifetime() {
2261 let span = self.span;
2263 Some(Label { ident: Ident::new(ident.name, span) })
2269 /// Parse mutability (`mut` or nothing).
2270 fn parse_mutability(&mut self) -> Mutability {
2271 if self.eat_keyword(keywords::Mut) {
2274 Mutability::Immutable
2278 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2279 if let token::Literal(token::Integer(name), None) = self.token {
2281 Ok(Ident::new(name, self.prev_span))
2283 self.parse_ident_common(false)
2287 /// Parse ident (COLON expr)?
2288 fn parse_field(&mut self) -> PResult<'a, Field> {
2289 let attrs = self.parse_outer_attributes()?;
2292 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2293 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2294 let fieldname = self.parse_field_name()?;
2296 (fieldname, self.parse_expr()?, false)
2298 let fieldname = self.parse_ident_common(false)?;
2300 // Mimic `x: x` for the `x` field shorthand.
2301 let path = ast::Path::from_ident(fieldname);
2302 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2303 (fieldname, expr, true)
2307 span: lo.to(expr.span),
2310 attrs: attrs.into(),
2314 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2315 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2318 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2319 ExprKind::Unary(unop, expr)
2322 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2323 ExprKind::Binary(binop, lhs, rhs)
2326 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2327 ExprKind::Call(f, args)
2330 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2331 ExprKind::Index(expr, idx)
2334 fn mk_range(&mut self,
2335 start: Option<P<Expr>>,
2336 end: Option<P<Expr>>,
2337 limits: RangeLimits)
2338 -> PResult<'a, ast::ExprKind> {
2339 if end.is_none() && limits == RangeLimits::Closed {
2340 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2342 Ok(ExprKind::Range(start, end, limits))
2346 fn mk_assign_op(&mut self, binop: ast::BinOp,
2347 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2348 ExprKind::AssignOp(binop, lhs, rhs)
2351 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2353 id: ast::DUMMY_NODE_ID,
2354 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2360 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2361 let delim = match self.token {
2362 token::OpenDelim(delim) => delim,
2364 let msg = "expected open delimiter";
2365 let mut err = self.fatal(msg);
2366 err.span_label(self.span, msg);
2370 let tts = match self.parse_token_tree() {
2371 TokenTree::Delimited(_, _, tts) => tts,
2372 _ => unreachable!(),
2374 let delim = match delim {
2375 token::Paren => MacDelimiter::Parenthesis,
2376 token::Bracket => MacDelimiter::Bracket,
2377 token::Brace => MacDelimiter::Brace,
2378 token::NoDelim => self.bug("unexpected no delimiter"),
2380 Ok((delim, tts.into()))
2383 /// At the bottom (top?) of the precedence hierarchy,
2384 /// parse things like parenthesized exprs,
2385 /// macros, return, etc.
2387 /// N.B., this does not parse outer attributes,
2388 /// and is private because it only works
2389 /// correctly if called from parse_dot_or_call_expr().
2390 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2391 maybe_whole_expr!(self);
2393 // Outer attributes are already parsed and will be
2394 // added to the return value after the fact.
2396 // Therefore, prevent sub-parser from parsing
2397 // attributes by giving them a empty "already parsed" list.
2398 let mut attrs = ThinVec::new();
2401 let mut hi = self.span;
2405 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2407 token::OpenDelim(token::Paren) => {
2410 attrs.extend(self.parse_inner_attributes()?);
2412 // (e) is parenthesized e
2413 // (e,) is a tuple with only one field, e
2414 let mut es = vec![];
2415 let mut trailing_comma = false;
2416 while self.token != token::CloseDelim(token::Paren) {
2417 es.push(self.parse_expr()?);
2418 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2419 if self.eat(&token::Comma) {
2420 trailing_comma = true;
2422 trailing_comma = false;
2428 hi = self.prev_span;
2429 ex = if es.len() == 1 && !trailing_comma {
2430 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2435 token::OpenDelim(token::Brace) => {
2436 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2438 token::BinOp(token::Or) | token::OrOr => {
2439 return self.parse_lambda_expr(attrs);
2441 token::OpenDelim(token::Bracket) => {
2444 attrs.extend(self.parse_inner_attributes()?);
2446 if self.eat(&token::CloseDelim(token::Bracket)) {
2448 ex = ExprKind::Array(Vec::new());
2451 let first_expr = self.parse_expr()?;
2452 if self.eat(&token::Semi) {
2453 // Repeating array syntax: [ 0; 512 ]
2454 let count = AnonConst {
2455 id: ast::DUMMY_NODE_ID,
2456 value: self.parse_expr()?,
2458 self.expect(&token::CloseDelim(token::Bracket))?;
2459 ex = ExprKind::Repeat(first_expr, count);
2460 } else if self.eat(&token::Comma) {
2461 // Vector with two or more elements.
2462 let remaining_exprs = self.parse_seq_to_end(
2463 &token::CloseDelim(token::Bracket),
2464 SeqSep::trailing_allowed(token::Comma),
2465 |p| Ok(p.parse_expr()?)
2467 let mut exprs = vec![first_expr];
2468 exprs.extend(remaining_exprs);
2469 ex = ExprKind::Array(exprs);
2471 // Vector with one element.
2472 self.expect(&token::CloseDelim(token::Bracket))?;
2473 ex = ExprKind::Array(vec![first_expr]);
2476 hi = self.prev_span;
2480 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2482 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2484 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2486 if self.is_async_block() { // check for `async {` and `async move {`
2487 return self.parse_async_block(attrs);
2489 return self.parse_lambda_expr(attrs);
2492 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2493 return self.parse_lambda_expr(attrs);
2495 if self.eat_keyword(keywords::If) {
2496 return self.parse_if_expr(attrs);
2498 if self.eat_keyword(keywords::For) {
2499 let lo = self.prev_span;
2500 return self.parse_for_expr(None, lo, attrs);
2502 if self.eat_keyword(keywords::While) {
2503 let lo = self.prev_span;
2504 return self.parse_while_expr(None, lo, attrs);
2506 if let Some(label) = self.eat_label() {
2507 let lo = label.ident.span;
2508 self.expect(&token::Colon)?;
2509 if self.eat_keyword(keywords::While) {
2510 return self.parse_while_expr(Some(label), lo, attrs)
2512 if self.eat_keyword(keywords::For) {
2513 return self.parse_for_expr(Some(label), lo, attrs)
2515 if self.eat_keyword(keywords::Loop) {
2516 return self.parse_loop_expr(Some(label), lo, attrs)
2518 if self.token == token::OpenDelim(token::Brace) {
2519 return self.parse_block_expr(Some(label),
2521 BlockCheckMode::Default,
2524 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2525 let mut err = self.fatal(msg);
2526 err.span_label(self.span, msg);
2529 if self.eat_keyword(keywords::Loop) {
2530 let lo = self.prev_span;
2531 return self.parse_loop_expr(None, lo, attrs);
2533 if self.eat_keyword(keywords::Continue) {
2534 let label = self.eat_label();
2535 let ex = ExprKind::Continue(label);
2536 let hi = self.prev_span;
2537 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2539 if self.eat_keyword(keywords::Match) {
2540 let match_sp = self.prev_span;
2541 return self.parse_match_expr(attrs).map_err(|mut err| {
2542 err.span_label(match_sp, "while parsing this match expression");
2546 if self.eat_keyword(keywords::Unsafe) {
2547 return self.parse_block_expr(
2550 BlockCheckMode::Unsafe(ast::UserProvided),
2553 if self.is_do_catch_block() {
2554 let mut db = self.fatal("found removed `do catch` syntax");
2555 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2558 if self.is_try_block() {
2560 assert!(self.eat_keyword(keywords::Try));
2561 return self.parse_try_block(lo, attrs);
2563 if self.eat_keyword(keywords::Return) {
2564 if self.token.can_begin_expr() {
2565 let e = self.parse_expr()?;
2567 ex = ExprKind::Ret(Some(e));
2569 ex = ExprKind::Ret(None);
2571 } else if self.eat_keyword(keywords::Break) {
2572 let label = self.eat_label();
2573 let e = if self.token.can_begin_expr()
2574 && !(self.token == token::OpenDelim(token::Brace)
2575 && self.restrictions.contains(
2576 Restrictions::NO_STRUCT_LITERAL)) {
2577 Some(self.parse_expr()?)
2581 ex = ExprKind::Break(label, e);
2582 hi = self.prev_span;
2583 } else if self.eat_keyword(keywords::Yield) {
2584 if self.token.can_begin_expr() {
2585 let e = self.parse_expr()?;
2587 ex = ExprKind::Yield(Some(e));
2589 ex = ExprKind::Yield(None);
2591 } else if self.token.is_keyword(keywords::Let) {
2592 // Catch this syntax error here, instead of in `parse_ident`, so
2593 // that we can explicitly mention that let is not to be used as an expression
2594 let mut db = self.fatal("expected expression, found statement (`let`)");
2595 db.span_label(self.span, "expected expression");
2596 db.note("variable declaration using `let` is a statement");
2598 } else if self.token.is_path_start() {
2599 let pth = self.parse_path(PathStyle::Expr)?;
2601 // `!`, as an operator, is prefix, so we know this isn't that
2602 if self.eat(&token::Not) {
2603 // MACRO INVOCATION expression
2604 let (delim, tts) = self.expect_delimited_token_tree()?;
2605 let hi = self.prev_span;
2606 let node = Mac_ { path: pth, tts, delim };
2607 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2609 if self.check(&token::OpenDelim(token::Brace)) {
2610 // This is a struct literal, unless we're prohibited
2611 // from parsing struct literals here.
2612 let prohibited = self.restrictions.contains(
2613 Restrictions::NO_STRUCT_LITERAL
2616 return self.parse_struct_expr(lo, pth, attrs);
2621 ex = ExprKind::Path(None, pth);
2623 match self.parse_literal_maybe_minus() {
2626 ex = expr.node.clone();
2629 self.cancel(&mut err);
2630 let msg = format!("expected expression, found {}",
2631 self.this_token_descr());
2632 let mut err = self.fatal(&msg);
2633 err.span_label(self.span, "expected expression");
2641 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2642 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2647 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2648 -> PResult<'a, P<Expr>> {
2649 let struct_sp = lo.to(self.prev_span);
2651 let mut fields = Vec::new();
2652 let mut base = None;
2654 attrs.extend(self.parse_inner_attributes()?);
2656 while self.token != token::CloseDelim(token::Brace) {
2657 if self.eat(&token::DotDot) {
2658 let exp_span = self.prev_span;
2659 match self.parse_expr() {
2665 self.recover_stmt();
2668 if self.token == token::Comma {
2669 let mut err = self.sess.span_diagnostic.mut_span_err(
2670 exp_span.to(self.prev_span),
2671 "cannot use a comma after the base struct",
2673 err.span_suggestion_short_with_applicability(
2675 "remove this comma",
2677 Applicability::MachineApplicable
2679 err.note("the base struct must always be the last field");
2681 self.recover_stmt();
2686 let mut recovery_field = None;
2687 if let token::Ident(ident, _) = self.token {
2688 if !self.token.is_reserved_ident() {
2689 let mut ident = ident.clone();
2690 ident.span = self.span;
2691 recovery_field = Some(ast::Field {
2694 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2696 attrs: ThinVec::new(),
2700 match self.parse_field() {
2701 Ok(f) => fields.push(f),
2703 e.span_label(struct_sp, "while parsing this struct");
2705 if let Some(f) = recovery_field {
2709 // If the next token is a comma, then try to parse
2710 // what comes next as additional fields, rather than
2711 // bailing out until next `}`.
2712 if self.token != token::Comma {
2713 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2714 if self.token != token::Comma {
2721 match self.expect_one_of(&[token::Comma],
2722 &[token::CloseDelim(token::Brace)]) {
2725 e.span_label(struct_sp, "while parsing this struct");
2727 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2728 self.eat(&token::Comma);
2733 let span = lo.to(self.span);
2734 self.expect(&token::CloseDelim(token::Brace))?;
2735 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2738 fn parse_or_use_outer_attributes(&mut self,
2739 already_parsed_attrs: Option<ThinVec<Attribute>>)
2740 -> PResult<'a, ThinVec<Attribute>> {
2741 if let Some(attrs) = already_parsed_attrs {
2744 self.parse_outer_attributes().map(|a| a.into())
2748 /// Parse a block or unsafe block
2749 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2750 lo: Span, blk_mode: BlockCheckMode,
2751 outer_attrs: ThinVec<Attribute>)
2752 -> PResult<'a, P<Expr>> {
2753 self.expect(&token::OpenDelim(token::Brace))?;
2755 let mut attrs = outer_attrs;
2756 attrs.extend(self.parse_inner_attributes()?);
2758 let blk = self.parse_block_tail(lo, blk_mode)?;
2759 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2762 /// parse a.b or a(13) or a[4] or just a
2763 fn parse_dot_or_call_expr(&mut self,
2764 already_parsed_attrs: Option<ThinVec<Attribute>>)
2765 -> PResult<'a, P<Expr>> {
2766 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2768 let b = self.parse_bottom_expr();
2769 let (span, b) = self.interpolated_or_expr_span(b)?;
2770 self.parse_dot_or_call_expr_with(b, span, attrs)
2773 fn parse_dot_or_call_expr_with(&mut self,
2776 mut attrs: ThinVec<Attribute>)
2777 -> PResult<'a, P<Expr>> {
2778 // Stitch the list of outer attributes onto the return value.
2779 // A little bit ugly, but the best way given the current code
2781 self.parse_dot_or_call_expr_with_(e0, lo)
2783 expr.map(|mut expr| {
2784 attrs.extend::<Vec<_>>(expr.attrs.into());
2787 ExprKind::If(..) | ExprKind::IfLet(..) => {
2788 if !expr.attrs.is_empty() {
2789 // Just point to the first attribute in there...
2790 let span = expr.attrs[0].span;
2793 "attributes are not yet allowed on `if` \
2804 // Assuming we have just parsed `.`, continue parsing into an expression.
2805 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2806 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2807 Ok(match self.token {
2808 token::OpenDelim(token::Paren) => {
2809 // Method call `expr.f()`
2810 let mut args = self.parse_unspanned_seq(
2811 &token::OpenDelim(token::Paren),
2812 &token::CloseDelim(token::Paren),
2813 SeqSep::trailing_allowed(token::Comma),
2814 |p| Ok(p.parse_expr()?)
2816 args.insert(0, self_arg);
2818 let span = lo.to(self.prev_span);
2819 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2822 // Field access `expr.f`
2823 if let Some(args) = segment.args {
2824 self.span_err(args.span(),
2825 "field expressions may not have generic arguments");
2828 let span = lo.to(self.prev_span);
2829 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2834 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2839 while self.eat(&token::Question) {
2840 let hi = self.prev_span;
2841 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2845 if self.eat(&token::Dot) {
2847 token::Ident(..) => {
2848 e = self.parse_dot_suffix(e, lo)?;
2850 token::Literal(token::Integer(name), _) => {
2851 let span = self.span;
2853 let field = ExprKind::Field(e, Ident::new(name, span));
2854 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2856 token::Literal(token::Float(n), _suf) => {
2858 let fstr = n.as_str();
2859 let mut err = self.diagnostic()
2860 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
2861 err.span_label(self.prev_span, "unexpected token");
2862 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2863 let float = match fstr.parse::<f64>().ok() {
2867 let sugg = pprust::to_string(|s| {
2868 use print::pprust::PrintState;
2872 s.print_usize(float.trunc() as usize)?;
2875 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2877 err.span_suggestion_with_applicability(
2878 lo.to(self.prev_span),
2879 "try parenthesizing the first index",
2881 Applicability::MachineApplicable
2888 // FIXME Could factor this out into non_fatal_unexpected or something.
2889 let actual = self.this_token_to_string();
2890 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2895 if self.expr_is_complete(&e) { break; }
2898 token::OpenDelim(token::Paren) => {
2899 let es = self.parse_unspanned_seq(
2900 &token::OpenDelim(token::Paren),
2901 &token::CloseDelim(token::Paren),
2902 SeqSep::trailing_allowed(token::Comma),
2903 |p| Ok(p.parse_expr()?)
2905 hi = self.prev_span;
2907 let nd = self.mk_call(e, es);
2908 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2912 // Could be either an index expression or a slicing expression.
2913 token::OpenDelim(token::Bracket) => {
2915 let ix = self.parse_expr()?;
2917 self.expect(&token::CloseDelim(token::Bracket))?;
2918 let index = self.mk_index(e, ix);
2919 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2927 crate fn process_potential_macro_variable(&mut self) {
2928 let (token, span) = match self.token {
2929 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2930 self.look_ahead(1, |t| t.is_ident()) => {
2932 let name = match self.token {
2933 token::Ident(ident, _) => ident,
2936 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2937 err.span_label(self.span, "unknown macro variable");
2942 token::Interpolated(ref nt) => {
2943 self.meta_var_span = Some(self.span);
2944 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2945 // and lifetime tokens, so the former are never encountered during normal parsing.
2947 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2948 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2958 /// parse a single token tree from the input.
2959 crate fn parse_token_tree(&mut self) -> TokenTree {
2961 token::OpenDelim(..) => {
2962 let frame = mem::replace(&mut self.token_cursor.frame,
2963 self.token_cursor.stack.pop().unwrap());
2964 self.span = frame.span.entire();
2966 TokenTree::Delimited(
2969 frame.tree_cursor.stream.into(),
2972 token::CloseDelim(_) | token::Eof => unreachable!(),
2974 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2976 TokenTree::Token(span, token)
2981 // parse a stream of tokens into a list of TokenTree's,
2983 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2984 let mut tts = Vec::new();
2985 while self.token != token::Eof {
2986 tts.push(self.parse_token_tree());
2991 pub fn parse_tokens(&mut self) -> TokenStream {
2992 let mut result = Vec::new();
2995 token::Eof | token::CloseDelim(..) => break,
2996 _ => result.push(self.parse_token_tree().into()),
2999 TokenStream::new(result)
3002 /// Parse a prefix-unary-operator expr
3003 fn parse_prefix_expr(&mut self,
3004 already_parsed_attrs: Option<ThinVec<Attribute>>)
3005 -> PResult<'a, P<Expr>> {
3006 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3008 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3009 let (hi, ex) = match self.token {
3012 let e = self.parse_prefix_expr(None);
3013 let (span, e) = self.interpolated_or_expr_span(e)?;
3014 (lo.to(span), self.mk_unary(UnOp::Not, e))
3016 // Suggest `!` for bitwise negation when encountering a `~`
3019 let e = self.parse_prefix_expr(None);
3020 let (span, e) = self.interpolated_or_expr_span(e)?;
3021 let span_of_tilde = lo;
3022 let mut err = self.diagnostic()
3023 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3024 err.span_suggestion_short_with_applicability(
3026 "use `!` to perform bitwise negation",
3028 Applicability::MachineApplicable
3031 (lo.to(span), self.mk_unary(UnOp::Not, e))
3033 token::BinOp(token::Minus) => {
3035 let e = self.parse_prefix_expr(None);
3036 let (span, e) = self.interpolated_or_expr_span(e)?;
3037 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3039 token::BinOp(token::Star) => {
3041 let e = self.parse_prefix_expr(None);
3042 let (span, e) = self.interpolated_or_expr_span(e)?;
3043 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3045 token::BinOp(token::And) | token::AndAnd => {
3047 let m = self.parse_mutability();
3048 let e = self.parse_prefix_expr(None);
3049 let (span, e) = self.interpolated_or_expr_span(e)?;
3050 (lo.to(span), ExprKind::AddrOf(m, e))
3052 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3054 let place = self.parse_expr_res(
3055 Restrictions::NO_STRUCT_LITERAL,
3058 let blk = self.parse_block()?;
3059 let span = blk.span;
3060 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3061 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3063 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3065 let e = self.parse_prefix_expr(None);
3066 let (span, e) = self.interpolated_or_expr_span(e)?;
3067 (lo.to(span), ExprKind::Box(e))
3069 token::Ident(..) if self.token.is_ident_named("not") => {
3070 // `not` is just an ordinary identifier in Rust-the-language,
3071 // but as `rustc`-the-compiler, we can issue clever diagnostics
3072 // for confused users who really want to say `!`
3073 let token_cannot_continue_expr = |t: &token::Token| match *t {
3074 // These tokens can start an expression after `!`, but
3075 // can't continue an expression after an ident
3076 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3077 token::Literal(..) | token::Pound => true,
3078 token::Interpolated(ref nt) => match nt.0 {
3079 token::NtIdent(..) | token::NtExpr(..) |
3080 token::NtBlock(..) | token::NtPath(..) => true,
3085 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3086 if cannot_continue_expr {
3088 // Emit the error ...
3089 let mut err = self.diagnostic()
3090 .struct_span_err(self.span,
3091 &format!("unexpected {} after identifier",
3092 self.this_token_descr()));
3093 // span the `not` plus trailing whitespace to avoid
3094 // trailing whitespace after the `!` in our suggestion
3095 let to_replace = self.sess.source_map()
3096 .span_until_non_whitespace(lo.to(self.span));
3097 err.span_suggestion_short_with_applicability(
3099 "use `!` to perform logical negation",
3101 Applicability::MachineApplicable
3104 // —and recover! (just as if we were in the block
3105 // for the `token::Not` arm)
3106 let e = self.parse_prefix_expr(None);
3107 let (span, e) = self.interpolated_or_expr_span(e)?;
3108 (lo.to(span), self.mk_unary(UnOp::Not, e))
3110 return self.parse_dot_or_call_expr(Some(attrs));
3113 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3115 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3118 /// Parse an associative expression
3120 /// This parses an expression accounting for associativity and precedence of the operators in
3123 fn parse_assoc_expr(&mut self,
3124 already_parsed_attrs: Option<ThinVec<Attribute>>)
3125 -> PResult<'a, P<Expr>> {
3126 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3129 /// Parse an associative expression with operators of at least `min_prec` precedence
3130 fn parse_assoc_expr_with(&mut self,
3133 -> PResult<'a, P<Expr>> {
3134 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3137 let attrs = match lhs {
3138 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3141 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3142 return self.parse_prefix_range_expr(attrs);
3144 self.parse_prefix_expr(attrs)?
3148 if self.expr_is_complete(&lhs) {
3149 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3152 self.expected_tokens.push(TokenType::Operator);
3153 while let Some(op) = AssocOp::from_token(&self.token) {
3155 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3156 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3157 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3158 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3159 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3160 (PrevTokenKind::Interpolated, _) => self.prev_span,
3161 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3162 if path.segments.len() == 1 => self.prev_span,
3166 let cur_op_span = self.span;
3167 let restrictions = if op.is_assign_like() {
3168 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3172 if op.precedence() < min_prec {
3175 // Check for deprecated `...` syntax
3176 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3177 self.err_dotdotdot_syntax(self.span);
3181 if op.is_comparison() {
3182 self.check_no_chained_comparison(&lhs, &op);
3185 if op == AssocOp::As {
3186 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3188 } else if op == AssocOp::Colon {
3189 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3192 err.span_label(self.span,
3193 "expecting a type here because of type ascription");
3194 let cm = self.sess.source_map();
3195 let cur_pos = cm.lookup_char_pos(self.span.lo());
3196 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3197 if cur_pos.line != op_pos.line {
3198 err.span_suggestion_with_applicability(
3200 "try using a semicolon",
3202 Applicability::MaybeIncorrect // speculative
3209 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3210 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3211 // generalise it to the Fixity::None code.
3213 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3214 // two variants are handled with `parse_prefix_range_expr` call above.
3215 let rhs = if self.is_at_start_of_range_notation_rhs() {
3216 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3217 LhsExpr::NotYetParsed)?)
3221 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3226 let limits = if op == AssocOp::DotDot {
3227 RangeLimits::HalfOpen
3232 let r = self.mk_range(Some(lhs), rhs, limits)?;
3233 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3237 let rhs = match op.fixity() {
3238 Fixity::Right => self.with_res(
3239 restrictions - Restrictions::STMT_EXPR,
3241 this.parse_assoc_expr_with(op.precedence(),
3242 LhsExpr::NotYetParsed)
3244 Fixity::Left => self.with_res(
3245 restrictions - Restrictions::STMT_EXPR,
3247 this.parse_assoc_expr_with(op.precedence() + 1,
3248 LhsExpr::NotYetParsed)
3250 // We currently have no non-associative operators that are not handled above by
3251 // the special cases. The code is here only for future convenience.
3252 Fixity::None => self.with_res(
3253 restrictions - Restrictions::STMT_EXPR,
3255 this.parse_assoc_expr_with(op.precedence() + 1,
3256 LhsExpr::NotYetParsed)
3260 let span = lhs_span.to(rhs.span);
3262 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3263 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3264 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3265 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3266 AssocOp::Greater | AssocOp::GreaterEqual => {
3267 let ast_op = op.to_ast_binop().unwrap();
3268 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3269 self.mk_expr(span, binary, ThinVec::new())
3272 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3273 AssocOp::ObsoleteInPlace =>
3274 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3275 AssocOp::AssignOp(k) => {
3277 token::Plus => BinOpKind::Add,
3278 token::Minus => BinOpKind::Sub,
3279 token::Star => BinOpKind::Mul,
3280 token::Slash => BinOpKind::Div,
3281 token::Percent => BinOpKind::Rem,
3282 token::Caret => BinOpKind::BitXor,
3283 token::And => BinOpKind::BitAnd,
3284 token::Or => BinOpKind::BitOr,
3285 token::Shl => BinOpKind::Shl,
3286 token::Shr => BinOpKind::Shr,
3288 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3289 self.mk_expr(span, aopexpr, ThinVec::new())
3291 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3292 self.bug("AssocOp should have been handled by special case")
3296 if op.fixity() == Fixity::None { break }
3301 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3302 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3303 -> PResult<'a, P<Expr>> {
3304 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3305 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3308 // Save the state of the parser before parsing type normally, in case there is a
3309 // LessThan comparison after this cast.
3310 let parser_snapshot_before_type = self.clone();
3311 match self.parse_ty_no_plus() {
3313 Ok(mk_expr(self, rhs))
3315 Err(mut type_err) => {
3316 // Rewind to before attempting to parse the type with generics, to recover
3317 // from situations like `x as usize < y` in which we first tried to parse
3318 // `usize < y` as a type with generic arguments.
3319 let parser_snapshot_after_type = self.clone();
3320 mem::replace(self, parser_snapshot_before_type);
3322 match self.parse_path(PathStyle::Expr) {
3324 let (op_noun, op_verb) = match self.token {
3325 token::Lt => ("comparison", "comparing"),
3326 token::BinOp(token::Shl) => ("shift", "shifting"),
3328 // We can end up here even without `<` being the next token, for
3329 // example because `parse_ty_no_plus` returns `Err` on keywords,
3330 // but `parse_path` returns `Ok` on them due to error recovery.
3331 // Return original error and parser state.
3332 mem::replace(self, parser_snapshot_after_type);
3333 return Err(type_err);
3337 // Successfully parsed the type path leaving a `<` yet to parse.
3340 // Report non-fatal diagnostics, keep `x as usize` as an expression
3341 // in AST and continue parsing.
3342 let msg = format!("`<` is interpreted as a start of generic \
3343 arguments for `{}`, not a {}", path, op_noun);
3344 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3345 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3346 "interpreted as generic arguments");
3347 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3349 let expr = mk_expr(self, P(Ty {
3351 node: TyKind::Path(None, path),
3352 id: ast::DUMMY_NODE_ID
3355 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3356 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3357 err.span_suggestion_with_applicability(
3359 &format!("try {} the cast value", op_verb),
3360 format!("({})", expr_str),
3361 Applicability::MachineApplicable
3367 Err(mut path_err) => {
3368 // Couldn't parse as a path, return original error and parser state.
3370 mem::replace(self, parser_snapshot_after_type);
3378 /// Produce an error if comparison operators are chained (RFC #558).
3379 /// We only need to check lhs, not rhs, because all comparison ops
3380 /// have same precedence and are left-associative
3381 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3382 debug_assert!(outer_op.is_comparison(),
3383 "check_no_chained_comparison: {:?} is not comparison",
3386 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3387 // respan to include both operators
3388 let op_span = op.span.to(self.span);
3389 let mut err = self.diagnostic().struct_span_err(op_span,
3390 "chained comparison operators require parentheses");
3391 if op.node == BinOpKind::Lt &&
3392 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3393 *outer_op == AssocOp::Greater // even in a case like the following:
3394 { // Foo<Bar<Baz<Qux, ()>>>
3396 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3397 err.help("or use `(...)` if you meant to specify fn arguments");
3405 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3406 fn parse_prefix_range_expr(&mut self,
3407 already_parsed_attrs: Option<ThinVec<Attribute>>)
3408 -> PResult<'a, P<Expr>> {
3409 // Check for deprecated `...` syntax
3410 if self.token == token::DotDotDot {
3411 self.err_dotdotdot_syntax(self.span);
3414 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3415 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3417 let tok = self.token.clone();
3418 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3420 let mut hi = self.span;
3422 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3423 // RHS must be parsed with more associativity than the dots.
3424 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3425 Some(self.parse_assoc_expr_with(next_prec,
3426 LhsExpr::NotYetParsed)
3434 let limits = if tok == token::DotDot {
3435 RangeLimits::HalfOpen
3440 let r = self.mk_range(None, opt_end, limits)?;
3441 Ok(self.mk_expr(lo.to(hi), r, attrs))
3444 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3445 if self.token.can_begin_expr() {
3446 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3447 if self.token == token::OpenDelim(token::Brace) {
3448 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3456 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3457 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3458 if self.check_keyword(keywords::Let) {
3459 return self.parse_if_let_expr(attrs);
3461 let lo = self.prev_span;
3462 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3464 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3465 // verify that the last statement is either an implicit return (no `;`) or an explicit
3466 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3467 // the dead code lint.
3468 if self.eat_keyword(keywords::Else) || !cond.returns() {
3469 let sp = self.sess.source_map().next_point(lo);
3470 let mut err = self.diagnostic()
3471 .struct_span_err(sp, "missing condition for `if` statemement");
3472 err.span_label(sp, "expected if condition here");
3475 let not_block = self.token != token::OpenDelim(token::Brace);
3476 let thn = self.parse_block().map_err(|mut err| {
3478 err.span_label(lo, "this `if` statement has a condition, but no block");
3482 let mut els: Option<P<Expr>> = None;
3483 let mut hi = thn.span;
3484 if self.eat_keyword(keywords::Else) {
3485 let elexpr = self.parse_else_expr()?;
3489 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3492 /// Parse an 'if let' expression ('if' token already eaten)
3493 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3494 -> PResult<'a, P<Expr>> {
3495 let lo = self.prev_span;
3496 self.expect_keyword(keywords::Let)?;
3497 let pats = self.parse_pats()?;
3498 self.expect(&token::Eq)?;
3499 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3500 let thn = self.parse_block()?;
3501 let (hi, els) = if self.eat_keyword(keywords::Else) {
3502 let expr = self.parse_else_expr()?;
3503 (expr.span, Some(expr))
3507 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3510 // `move |args| expr`
3511 fn parse_lambda_expr(&mut self,
3512 attrs: ThinVec<Attribute>)
3513 -> PResult<'a, P<Expr>>
3516 let movability = if self.eat_keyword(keywords::Static) {
3521 let asyncness = if self.span.rust_2018() {
3522 self.parse_asyncness()
3526 let capture_clause = if self.eat_keyword(keywords::Move) {
3531 let decl = self.parse_fn_block_decl()?;
3532 let decl_hi = self.prev_span;
3533 let body = match decl.output {
3534 FunctionRetTy::Default(_) => {
3535 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3536 self.parse_expr_res(restrictions, None)?
3539 // If an explicit return type is given, require a
3540 // block to appear (RFC 968).
3541 let body_lo = self.span;
3542 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3548 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3552 // `else` token already eaten
3553 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3554 if self.eat_keyword(keywords::If) {
3555 return self.parse_if_expr(ThinVec::new());
3557 let blk = self.parse_block()?;
3558 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3562 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3563 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3565 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3566 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3568 let pat = self.parse_top_level_pat()?;
3569 if !self.eat_keyword(keywords::In) {
3570 let in_span = self.prev_span.between(self.span);
3571 let mut err = self.sess.span_diagnostic
3572 .struct_span_err(in_span, "missing `in` in `for` loop");
3573 err.span_suggestion_short_with_applicability(
3574 in_span, "try adding `in` here", " in ".into(),
3575 // has been misleading, at least in the past (closed Issue #48492)
3576 Applicability::MaybeIncorrect
3580 let in_span = self.prev_span;
3581 if self.eat_keyword(keywords::In) {
3582 // a common typo: `for _ in in bar {}`
3583 let mut err = self.sess.span_diagnostic.struct_span_err(
3585 "expected iterable, found keyword `in`",
3587 err.span_suggestion_short_with_applicability(
3588 in_span.until(self.prev_span),
3589 "remove the duplicated `in`",
3591 Applicability::MachineApplicable,
3593 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3594 err.note("for more information on the status of emplacement syntax, see <\
3595 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3598 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3599 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3600 attrs.extend(iattrs);
3602 let hi = self.prev_span;
3603 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3606 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3607 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3609 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3610 if self.token.is_keyword(keywords::Let) {
3611 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3613 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3614 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3615 attrs.extend(iattrs);
3616 let span = span_lo.to(body.span);
3617 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3620 /// Parse a 'while let' expression ('while' token already eaten)
3621 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3623 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3624 self.expect_keyword(keywords::Let)?;
3625 let pats = self.parse_pats()?;
3626 self.expect(&token::Eq)?;
3627 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3628 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3629 attrs.extend(iattrs);
3630 let span = span_lo.to(body.span);
3631 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3634 // parse `loop {...}`, `loop` token already eaten
3635 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3637 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3638 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3639 attrs.extend(iattrs);
3640 let span = span_lo.to(body.span);
3641 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3644 /// Parse an `async move {...}` expression
3645 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3646 -> PResult<'a, P<Expr>>
3648 let span_lo = self.span;
3649 self.expect_keyword(keywords::Async)?;
3650 let capture_clause = if self.eat_keyword(keywords::Move) {
3655 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3656 attrs.extend(iattrs);
3658 span_lo.to(body.span),
3659 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3662 /// Parse a `try {...}` expression (`try` token already eaten)
3663 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3664 -> PResult<'a, P<Expr>>
3666 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3667 attrs.extend(iattrs);
3668 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3671 // `match` token already eaten
3672 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3673 let match_span = self.prev_span;
3674 let lo = self.prev_span;
3675 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3677 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3678 if self.token == token::Token::Semi {
3679 e.span_suggestion_short_with_applicability(
3681 "try removing this `match`",
3683 Applicability::MaybeIncorrect // speculative
3688 attrs.extend(self.parse_inner_attributes()?);
3690 let mut arms: Vec<Arm> = Vec::new();
3691 while self.token != token::CloseDelim(token::Brace) {
3692 match self.parse_arm() {
3693 Ok(arm) => arms.push(arm),
3695 // Recover by skipping to the end of the block.
3697 self.recover_stmt();
3698 let span = lo.to(self.span);
3699 if self.token == token::CloseDelim(token::Brace) {
3702 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3708 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3711 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3712 maybe_whole!(self, NtArm, |x| x);
3714 let attrs = self.parse_outer_attributes()?;
3715 let pats = self.parse_pats()?;
3716 let guard = if self.eat_keyword(keywords::If) {
3717 Some(Guard::If(self.parse_expr()?))
3721 let arrow_span = self.span;
3722 self.expect(&token::FatArrow)?;
3723 let arm_start_span = self.span;
3725 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3726 .map_err(|mut err| {
3727 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3731 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3732 && self.token != token::CloseDelim(token::Brace);
3735 let cm = self.sess.source_map();
3736 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3737 .map_err(|mut err| {
3738 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3739 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3740 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3741 && expr_lines.lines.len() == 2
3742 && self.token == token::FatArrow => {
3743 // We check whether there's any trailing code in the parse span,
3744 // if there isn't, we very likely have the following:
3747 // | -- - missing comma
3753 // | parsed until here as `"y" & X`
3754 err.span_suggestion_short_with_applicability(
3755 cm.next_point(arm_start_span),
3756 "missing a comma here to end this `match` arm",
3758 Applicability::MachineApplicable
3762 err.span_label(arrow_span,
3763 "while parsing the `match` arm starting here");
3769 self.eat(&token::Comma);
3780 /// Parse an expression
3782 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3783 self.parse_expr_res(Restrictions::empty(), None)
3786 /// Evaluate the closure with restrictions in place.
3788 /// After the closure is evaluated, restrictions are reset.
3789 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3790 where F: FnOnce(&mut Self) -> T
3792 let old = self.restrictions;
3793 self.restrictions = r;
3795 self.restrictions = old;
3800 /// Parse an expression, subject to the given restrictions
3802 fn parse_expr_res(&mut self, r: Restrictions,
3803 already_parsed_attrs: Option<ThinVec<Attribute>>)
3804 -> PResult<'a, P<Expr>> {
3805 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3808 /// Parse the RHS of a local variable declaration (e.g., '= 14;')
3809 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3810 if self.eat(&token::Eq) {
3811 Ok(Some(self.parse_expr()?))
3813 Ok(Some(self.parse_expr()?))
3819 /// Parse patterns, separated by '|' s
3820 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3821 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
3822 self.eat(&token::BinOp(token::Or));
3824 let mut pats = Vec::new();
3826 pats.push(self.parse_top_level_pat()?);
3828 if self.token == token::OrOr {
3829 let mut err = self.struct_span_err(self.span,
3830 "unexpected token `||` after pattern");
3831 err.span_suggestion_with_applicability(
3833 "use a single `|` to specify multiple patterns",
3835 Applicability::MachineApplicable
3839 } else if self.eat(&token::BinOp(token::Or)) {
3847 // Parses a parenthesized list of patterns like
3848 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3849 // - a vector of the patterns that were parsed
3850 // - an option indicating the index of the `..` element
3851 // - a boolean indicating whether a trailing comma was present.
3852 // Trailing commas are significant because (p) and (p,) are different patterns.
3853 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3854 self.expect(&token::OpenDelim(token::Paren))?;
3855 let result = self.parse_pat_list()?;
3856 self.expect(&token::CloseDelim(token::Paren))?;
3860 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3861 let mut fields = Vec::new();
3862 let mut ddpos = None;
3863 let mut trailing_comma = false;
3865 if self.eat(&token::DotDot) {
3866 if ddpos.is_none() {
3867 ddpos = Some(fields.len());
3869 // Emit a friendly error, ignore `..` and continue parsing
3870 self.struct_span_err(
3872 "`..` can only be used once per tuple or tuple struct pattern",
3874 .span_label(self.prev_span, "can only be used once per pattern")
3877 } else if !self.check(&token::CloseDelim(token::Paren)) {
3878 fields.push(self.parse_pat(None)?);
3883 trailing_comma = self.eat(&token::Comma);
3884 if !trailing_comma {
3889 if ddpos == Some(fields.len()) && trailing_comma {
3890 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3891 let msg = "trailing comma is not permitted after `..`";
3892 self.struct_span_err(self.prev_span, msg)
3893 .span_label(self.prev_span, msg)
3897 Ok((fields, ddpos, trailing_comma))
3900 fn parse_pat_vec_elements(
3902 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3903 let mut before = Vec::new();
3904 let mut slice = None;
3905 let mut after = Vec::new();
3906 let mut first = true;
3907 let mut before_slice = true;
3909 while self.token != token::CloseDelim(token::Bracket) {
3913 self.expect(&token::Comma)?;
3915 if self.token == token::CloseDelim(token::Bracket)
3916 && (before_slice || !after.is_empty()) {
3922 if self.eat(&token::DotDot) {
3924 if self.check(&token::Comma) ||
3925 self.check(&token::CloseDelim(token::Bracket)) {
3926 slice = Some(P(Pat {
3927 id: ast::DUMMY_NODE_ID,
3928 node: PatKind::Wild,
3929 span: self.prev_span,
3931 before_slice = false;
3937 let subpat = self.parse_pat(None)?;
3938 if before_slice && self.eat(&token::DotDot) {
3939 slice = Some(subpat);
3940 before_slice = false;
3941 } else if before_slice {
3942 before.push(subpat);
3948 Ok((before, slice, after))
3954 attrs: Vec<Attribute>
3955 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3956 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3958 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3959 // Parsing a pattern of the form "fieldname: pat"
3960 let fieldname = self.parse_field_name()?;
3962 let pat = self.parse_pat(None)?;
3964 (pat, fieldname, false)
3966 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3967 let is_box = self.eat_keyword(keywords::Box);
3968 let boxed_span = self.span;
3969 let is_ref = self.eat_keyword(keywords::Ref);
3970 let is_mut = self.eat_keyword(keywords::Mut);
3971 let fieldname = self.parse_ident()?;
3972 hi = self.prev_span;
3974 let bind_type = match (is_ref, is_mut) {
3975 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3976 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3977 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3978 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3980 let fieldpat = P(Pat {
3981 id: ast::DUMMY_NODE_ID,
3982 node: PatKind::Ident(bind_type, fieldname, None),
3983 span: boxed_span.to(hi),
3986 let subpat = if is_box {
3988 id: ast::DUMMY_NODE_ID,
3989 node: PatKind::Box(fieldpat),
3995 (subpat, fieldname, true)
3998 Ok(source_map::Spanned {
4000 node: ast::FieldPat {
4004 attrs: attrs.into(),
4009 /// Parse the fields of a struct-like pattern
4010 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4011 let mut fields = Vec::new();
4012 let mut etc = false;
4013 let mut ate_comma = true;
4014 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4015 let mut etc_span = None;
4017 while self.token != token::CloseDelim(token::Brace) {
4018 let attrs = self.parse_outer_attributes()?;
4021 // check that a comma comes after every field
4023 let err = self.struct_span_err(self.prev_span, "expected `,`");
4024 if let Some(mut delayed) = delayed_err {
4031 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4033 let mut etc_sp = self.span;
4035 if self.token == token::DotDotDot { // Issue #46718
4036 // Accept `...` as if it were `..` to avoid further errors
4037 let mut err = self.struct_span_err(self.span,
4038 "expected field pattern, found `...`");
4039 err.span_suggestion_with_applicability(
4041 "to omit remaining fields, use one fewer `.`",
4043 Applicability::MachineApplicable
4047 self.bump(); // `..` || `...`
4049 if self.token == token::CloseDelim(token::Brace) {
4050 etc_span = Some(etc_sp);
4053 let token_str = self.this_token_descr();
4054 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4056 err.span_label(self.span, "expected `}`");
4057 let mut comma_sp = None;
4058 if self.token == token::Comma { // Issue #49257
4059 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4060 err.span_label(etc_sp,
4061 "`..` must be at the end and cannot have a trailing comma");
4062 comma_sp = Some(self.span);
4067 etc_span = Some(etc_sp.until(self.span));
4068 if self.token == token::CloseDelim(token::Brace) {
4069 // If the struct looks otherwise well formed, recover and continue.
4070 if let Some(sp) = comma_sp {
4071 err.span_suggestion_short_with_applicability(
4073 "remove this comma",
4075 Applicability::MachineApplicable,
4080 } else if self.token.is_ident() && ate_comma {
4081 // Accept fields coming after `..,`.
4082 // This way we avoid "pattern missing fields" errors afterwards.
4083 // We delay this error until the end in order to have a span for a
4085 if let Some(mut delayed_err) = delayed_err {
4089 delayed_err = Some(err);
4092 if let Some(mut err) = delayed_err {
4099 fields.push(match self.parse_pat_field(lo, attrs) {
4102 if let Some(mut delayed_err) = delayed_err {
4108 ate_comma = self.eat(&token::Comma);
4111 if let Some(mut err) = delayed_err {
4112 if let Some(etc_span) = etc_span {
4113 err.multipart_suggestion_with_applicability(
4114 "move the `..` to the end of the field list",
4116 (etc_span, String::new()),
4117 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4119 Applicability::MachineApplicable,
4124 return Ok((fields, etc));
4127 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4128 if self.token.is_path_start() {
4130 let (qself, path) = if self.eat_lt() {
4131 // Parse a qualified path
4132 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4135 // Parse an unqualified path
4136 (None, self.parse_path(PathStyle::Expr)?)
4138 let hi = self.prev_span;
4139 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4141 self.parse_literal_maybe_minus()
4145 // helper function to decide whether to parse as ident binding or to try to do
4146 // something more complex like range patterns
4147 fn parse_as_ident(&mut self) -> bool {
4148 self.look_ahead(1, |t| match *t {
4149 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4150 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4151 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4152 // range pattern branch
4153 token::DotDot => None,
4155 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4156 token::Comma | token::CloseDelim(token::Bracket) => true,
4161 /// A wrapper around `parse_pat` with some special error handling for the
4162 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4163 /// to subpatterns within such).
4164 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4165 let pat = self.parse_pat(None)?;
4166 if self.token == token::Comma {
4167 // An unexpected comma after a top-level pattern is a clue that the
4168 // user (perhaps more accustomed to some other language) forgot the
4169 // parentheses in what should have been a tuple pattern; return a
4170 // suggestion-enhanced error here rather than choking on the comma
4172 let comma_span = self.span;
4174 if let Err(mut err) = self.parse_pat_list() {
4175 // We didn't expect this to work anyway; we just wanted
4176 // to advance to the end of the comma-sequence so we know
4177 // the span to suggest parenthesizing
4180 let seq_span = pat.span.to(self.prev_span);
4181 let mut err = self.struct_span_err(comma_span,
4182 "unexpected `,` in pattern");
4183 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4184 err.span_suggestion_with_applicability(
4186 "try adding parentheses",
4187 format!("({})", seq_snippet),
4188 Applicability::MachineApplicable
4196 /// Parse a pattern.
4197 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4198 self.parse_pat_with_range_pat(true, expected)
4201 /// Parse a pattern, with a setting whether modern range patterns e.g., `a..=b`, `a..b` are
4203 fn parse_pat_with_range_pat(
4205 allow_range_pat: bool,
4206 expected: Option<&'static str>,
4207 ) -> PResult<'a, P<Pat>> {
4208 maybe_whole!(self, NtPat, |x| x);
4213 token::BinOp(token::And) | token::AndAnd => {
4214 // Parse &pat / &mut pat
4216 let mutbl = self.parse_mutability();
4217 if let token::Lifetime(ident) = self.token {
4218 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4220 err.span_label(self.span, "unexpected lifetime");
4223 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4224 pat = PatKind::Ref(subpat, mutbl);
4226 token::OpenDelim(token::Paren) => {
4227 // Parse (pat,pat,pat,...) as tuple pattern
4228 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4229 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4230 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4232 PatKind::Tuple(fields, ddpos)
4235 token::OpenDelim(token::Bracket) => {
4236 // Parse [pat,pat,...] as slice pattern
4238 let (before, slice, after) = self.parse_pat_vec_elements()?;
4239 self.expect(&token::CloseDelim(token::Bracket))?;
4240 pat = PatKind::Slice(before, slice, after);
4242 // At this point, token != &, &&, (, [
4243 _ => if self.eat_keyword(keywords::Underscore) {
4245 pat = PatKind::Wild;
4246 } else if self.eat_keyword(keywords::Mut) {
4247 // Parse mut ident @ pat / mut ref ident @ pat
4248 let mutref_span = self.prev_span.to(self.span);
4249 let binding_mode = if self.eat_keyword(keywords::Ref) {
4251 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4252 .span_suggestion_with_applicability(
4254 "try switching the order",
4256 Applicability::MachineApplicable
4258 BindingMode::ByRef(Mutability::Mutable)
4260 BindingMode::ByValue(Mutability::Mutable)
4262 pat = self.parse_pat_ident(binding_mode)?;
4263 } else if self.eat_keyword(keywords::Ref) {
4264 // Parse ref ident @ pat / ref mut ident @ pat
4265 let mutbl = self.parse_mutability();
4266 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4267 } else if self.eat_keyword(keywords::Box) {
4269 let subpat = self.parse_pat_with_range_pat(false, None)?;
4270 pat = PatKind::Box(subpat);
4271 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4272 self.parse_as_ident() {
4273 // Parse ident @ pat
4274 // This can give false positives and parse nullary enums,
4275 // they are dealt with later in resolve
4276 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4277 pat = self.parse_pat_ident(binding_mode)?;
4278 } else if self.token.is_path_start() {
4279 // Parse pattern starting with a path
4280 let (qself, path) = if self.eat_lt() {
4281 // Parse a qualified path
4282 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4285 // Parse an unqualified path
4286 (None, self.parse_path(PathStyle::Expr)?)
4289 token::Not if qself.is_none() => {
4290 // Parse macro invocation
4292 let (delim, tts) = self.expect_delimited_token_tree()?;
4293 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4294 pat = PatKind::Mac(mac);
4296 token::DotDotDot | token::DotDotEq | token::DotDot => {
4297 let end_kind = match self.token {
4298 token::DotDot => RangeEnd::Excluded,
4299 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4300 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4301 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4304 let op_span = self.span;
4306 let span = lo.to(self.prev_span);
4307 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4309 let end = self.parse_pat_range_end()?;
4310 let op = Spanned { span: op_span, node: end_kind };
4311 pat = PatKind::Range(begin, end, op);
4313 token::OpenDelim(token::Brace) => {
4314 if qself.is_some() {
4315 let msg = "unexpected `{` after qualified path";
4316 let mut err = self.fatal(msg);
4317 err.span_label(self.span, msg);
4320 // Parse struct pattern
4322 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4324 self.recover_stmt();
4328 pat = PatKind::Struct(path, fields, etc);
4330 token::OpenDelim(token::Paren) => {
4331 if qself.is_some() {
4332 let msg = "unexpected `(` after qualified path";
4333 let mut err = self.fatal(msg);
4334 err.span_label(self.span, msg);
4337 // Parse tuple struct or enum pattern
4338 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4339 pat = PatKind::TupleStruct(path, fields, ddpos)
4341 _ => pat = PatKind::Path(qself, path),
4344 // Try to parse everything else as literal with optional minus
4345 match self.parse_literal_maybe_minus() {
4347 let op_span = self.span;
4348 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4349 self.check(&token::DotDotDot) {
4350 let end_kind = if self.eat(&token::DotDotDot) {
4351 RangeEnd::Included(RangeSyntax::DotDotDot)
4352 } else if self.eat(&token::DotDotEq) {
4353 RangeEnd::Included(RangeSyntax::DotDotEq)
4354 } else if self.eat(&token::DotDot) {
4357 panic!("impossible case: we already matched \
4358 on a range-operator token")
4360 let end = self.parse_pat_range_end()?;
4361 let op = Spanned { span: op_span, node: end_kind };
4362 pat = PatKind::Range(begin, end, op);
4364 pat = PatKind::Lit(begin);
4368 self.cancel(&mut err);
4369 let expected = expected.unwrap_or("pattern");
4371 "expected {}, found {}",
4373 self.this_token_descr(),
4375 let mut err = self.fatal(&msg);
4376 err.span_label(self.span, format!("expected {}", expected));
4383 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4384 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4386 if !allow_range_pat {
4389 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4391 PatKind::Range(..) => {
4392 let mut err = self.struct_span_err(
4394 "the range pattern here has ambiguous interpretation",
4396 err.span_suggestion_with_applicability(
4398 "add parentheses to clarify the precedence",
4399 format!("({})", pprust::pat_to_string(&pat)),
4400 // "ambiguous interpretation" implies that we have to be guessing
4401 Applicability::MaybeIncorrect
4412 /// Parse ident or ident @ pat
4413 /// used by the copy foo and ref foo patterns to give a good
4414 /// error message when parsing mistakes like ref foo(a,b)
4415 fn parse_pat_ident(&mut self,
4416 binding_mode: ast::BindingMode)
4417 -> PResult<'a, PatKind> {
4418 let ident = self.parse_ident()?;
4419 let sub = if self.eat(&token::At) {
4420 Some(self.parse_pat(Some("binding pattern"))?)
4425 // just to be friendly, if they write something like
4427 // we end up here with ( as the current token. This shortly
4428 // leads to a parse error. Note that if there is no explicit
4429 // binding mode then we do not end up here, because the lookahead
4430 // will direct us over to parse_enum_variant()
4431 if self.token == token::OpenDelim(token::Paren) {
4432 return Err(self.span_fatal(
4434 "expected identifier, found enum pattern"))
4437 Ok(PatKind::Ident(binding_mode, ident, sub))
4440 /// Parse a local variable declaration
4441 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4442 let lo = self.prev_span;
4443 let pat = self.parse_top_level_pat()?;
4445 let (err, ty) = if self.eat(&token::Colon) {
4446 // Save the state of the parser before parsing type normally, in case there is a `:`
4447 // instead of an `=` typo.
4448 let parser_snapshot_before_type = self.clone();
4449 let colon_sp = self.prev_span;
4450 match self.parse_ty() {
4451 Ok(ty) => (None, Some(ty)),
4453 // Rewind to before attempting to parse the type and continue parsing
4454 let parser_snapshot_after_type = self.clone();
4455 mem::replace(self, parser_snapshot_before_type);
4457 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4458 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4459 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4465 let init = match (self.parse_initializer(err.is_some()), err) {
4466 (Ok(init), None) => { // init parsed, ty parsed
4469 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4470 // Could parse the type as if it were the initializer, it is likely there was a
4471 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4472 err.span_suggestion_short_with_applicability(
4474 "use `=` if you meant to assign",
4476 Applicability::MachineApplicable
4479 // As this was parsed successfully, continue as if the code has been fixed for the
4480 // rest of the file. It will still fail due to the emitted error, but we avoid
4484 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4486 // Couldn't parse the type nor the initializer, only raise the type error and
4487 // return to the parser state before parsing the type as the initializer.
4488 // let x: <parse_error>;
4489 mem::replace(self, snapshot);
4492 (Err(err), None) => { // init error, ty parsed
4493 // Couldn't parse the initializer and we're not attempting to recover a failed
4494 // parse of the type, return the error.
4498 let hi = if self.token == token::Semi {
4507 id: ast::DUMMY_NODE_ID,
4513 /// Parse a structure field
4514 fn parse_name_and_ty(&mut self,
4517 attrs: Vec<Attribute>)
4518 -> PResult<'a, StructField> {
4519 let name = self.parse_ident()?;
4520 self.expect(&token::Colon)?;
4521 let ty = self.parse_ty()?;
4523 span: lo.to(self.prev_span),
4526 id: ast::DUMMY_NODE_ID,
4532 /// Emit an expected item after attributes error.
4533 fn expected_item_err(&self, attrs: &[Attribute]) {
4534 let message = match attrs.last() {
4535 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4536 _ => "expected item after attributes",
4539 self.span_err(self.prev_span, message);
4542 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4543 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4544 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4545 Ok(self.parse_stmt_(true))
4548 // Eat tokens until we can be relatively sure we reached the end of the
4549 // statement. This is something of a best-effort heuristic.
4551 // We terminate when we find an unmatched `}` (without consuming it).
4552 fn recover_stmt(&mut self) {
4553 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4556 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4557 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4558 // approximate - it can mean we break too early due to macros, but that
4559 // should only lead to sub-optimal recovery, not inaccurate parsing).
4561 // If `break_on_block` is `Break`, then we will stop consuming tokens
4562 // after finding (and consuming) a brace-delimited block.
4563 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4564 let mut brace_depth = 0;
4565 let mut bracket_depth = 0;
4566 let mut in_block = false;
4567 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4568 break_on_semi, break_on_block);
4570 debug!("recover_stmt_ loop {:?}", self.token);
4572 token::OpenDelim(token::DelimToken::Brace) => {
4575 if break_on_block == BlockMode::Break &&
4577 bracket_depth == 0 {
4581 token::OpenDelim(token::DelimToken::Bracket) => {
4585 token::CloseDelim(token::DelimToken::Brace) => {
4586 if brace_depth == 0 {
4587 debug!("recover_stmt_ return - close delim {:?}", self.token);
4592 if in_block && bracket_depth == 0 && brace_depth == 0 {
4593 debug!("recover_stmt_ return - block end {:?}", self.token);
4597 token::CloseDelim(token::DelimToken::Bracket) => {
4599 if bracket_depth < 0 {
4605 debug!("recover_stmt_ return - Eof");
4610 if break_on_semi == SemiColonMode::Break &&
4612 bracket_depth == 0 {
4613 debug!("recover_stmt_ return - Semi");
4618 if break_on_semi == SemiColonMode::Comma &&
4620 bracket_depth == 0 {
4621 debug!("recover_stmt_ return - Semi");
4634 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4635 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4637 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4642 fn is_async_block(&mut self) -> bool {
4643 self.token.is_keyword(keywords::Async) &&
4646 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4647 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4649 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4654 fn is_do_catch_block(&mut self) -> bool {
4655 self.token.is_keyword(keywords::Do) &&
4656 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4657 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4658 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4661 fn is_try_block(&mut self) -> bool {
4662 self.token.is_keyword(keywords::Try) &&
4663 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4664 self.span.rust_2018() &&
4665 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4666 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4669 fn is_union_item(&self) -> bool {
4670 self.token.is_keyword(keywords::Union) &&
4671 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4674 fn is_crate_vis(&self) -> bool {
4675 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4678 fn is_existential_type_decl(&self) -> bool {
4679 self.token.is_keyword(keywords::Existential) &&
4680 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4683 fn is_auto_trait_item(&mut self) -> bool {
4685 (self.token.is_keyword(keywords::Auto)
4686 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4687 || // unsafe auto trait
4688 (self.token.is_keyword(keywords::Unsafe) &&
4689 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4690 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4693 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4694 -> PResult<'a, Option<P<Item>>> {
4695 let token_lo = self.span;
4696 let (ident, def) = match self.token {
4697 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4699 let ident = self.parse_ident()?;
4700 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4701 match self.parse_token_tree() {
4702 TokenTree::Delimited(_, _, tts) => tts,
4703 _ => unreachable!(),
4705 } else if self.check(&token::OpenDelim(token::Paren)) {
4706 let args = self.parse_token_tree();
4707 let body = if self.check(&token::OpenDelim(token::Brace)) {
4708 self.parse_token_tree()
4713 TokenStream::new(vec![
4715 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4723 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4725 token::Ident(ident, _) if ident.name == "macro_rules" &&
4726 self.look_ahead(1, |t| *t == token::Not) => {
4727 let prev_span = self.prev_span;
4728 self.complain_if_pub_macro(&vis.node, prev_span);
4732 let ident = self.parse_ident()?;
4733 let (delim, tokens) = self.expect_delimited_token_tree()?;
4734 if delim != MacDelimiter::Brace {
4735 if !self.eat(&token::Semi) {
4736 let msg = "macros that expand to items must either \
4737 be surrounded with braces or followed by a semicolon";
4738 self.span_err(self.prev_span, msg);
4742 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4744 _ => return Ok(None),
4747 let span = lo.to(self.prev_span);
4748 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4751 fn parse_stmt_without_recovery(&mut self,
4752 macro_legacy_warnings: bool)
4753 -> PResult<'a, Option<Stmt>> {
4754 maybe_whole!(self, NtStmt, |x| Some(x));
4756 let attrs = self.parse_outer_attributes()?;
4759 Ok(Some(if self.eat_keyword(keywords::Let) {
4761 id: ast::DUMMY_NODE_ID,
4762 node: StmtKind::Local(self.parse_local(attrs.into())?),
4763 span: lo.to(self.prev_span),
4765 } else if let Some(macro_def) = self.eat_macro_def(
4767 &source_map::respan(lo, VisibilityKind::Inherited),
4771 id: ast::DUMMY_NODE_ID,
4772 node: StmtKind::Item(macro_def),
4773 span: lo.to(self.prev_span),
4775 // Starts like a simple path, being careful to avoid contextual keywords
4776 // such as a union items, item with `crate` visibility or auto trait items.
4777 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4778 // like a path (1 token), but it fact not a path.
4779 // `union::b::c` - path, `union U { ... }` - not a path.
4780 // `crate::b::c` - path, `crate struct S;` - not a path.
4781 } else if self.token.is_path_start() &&
4782 !self.token.is_qpath_start() &&
4783 !self.is_union_item() &&
4784 !self.is_crate_vis() &&
4785 !self.is_existential_type_decl() &&
4786 !self.is_auto_trait_item() {
4787 let pth = self.parse_path(PathStyle::Expr)?;
4789 if !self.eat(&token::Not) {
4790 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4791 self.parse_struct_expr(lo, pth, ThinVec::new())?
4793 let hi = self.prev_span;
4794 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4797 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4798 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4799 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4802 return Ok(Some(Stmt {
4803 id: ast::DUMMY_NODE_ID,
4804 node: StmtKind::Expr(expr),
4805 span: lo.to(self.prev_span),
4809 // it's a macro invocation
4810 let id = match self.token {
4811 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4812 _ => self.parse_ident()?,
4815 // check that we're pointing at delimiters (need to check
4816 // again after the `if`, because of `parse_ident`
4817 // consuming more tokens).
4819 token::OpenDelim(_) => {}
4821 // we only expect an ident if we didn't parse one
4823 let ident_str = if id.name == keywords::Invalid.name() {
4828 let tok_str = self.this_token_descr();
4829 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4832 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4837 let (delim, tts) = self.expect_delimited_token_tree()?;
4838 let hi = self.prev_span;
4840 let style = if delim == MacDelimiter::Brace {
4841 MacStmtStyle::Braces
4843 MacStmtStyle::NoBraces
4846 if id.name == keywords::Invalid.name() {
4847 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4848 let node = if delim == MacDelimiter::Brace ||
4849 self.token == token::Semi || self.token == token::Eof {
4850 StmtKind::Mac(P((mac, style, attrs.into())))
4852 // We used to incorrectly stop parsing macro-expanded statements here.
4853 // If the next token will be an error anyway but could have parsed with the
4854 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4855 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4856 // These can continue an expression, so we can't stop parsing and warn.
4857 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4858 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4859 token::BinOp(token::And) | token::BinOp(token::Or) |
4860 token::AndAnd | token::OrOr |
4861 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4864 self.warn_missing_semicolon();
4865 StmtKind::Mac(P((mac, style, attrs.into())))
4867 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4868 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4869 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4873 id: ast::DUMMY_NODE_ID,
4878 // if it has a special ident, it's definitely an item
4880 // Require a semicolon or braces.
4881 if style != MacStmtStyle::Braces {
4882 if !self.eat(&token::Semi) {
4883 self.span_err(self.prev_span,
4884 "macros that expand to items must \
4885 either be surrounded with braces or \
4886 followed by a semicolon");
4889 let span = lo.to(hi);
4891 id: ast::DUMMY_NODE_ID,
4893 node: StmtKind::Item({
4895 span, id /*id is good here*/,
4896 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4897 respan(lo, VisibilityKind::Inherited),
4903 // FIXME: Bad copy of attrs
4904 let old_directory_ownership =
4905 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4906 let item = self.parse_item_(attrs.clone(), false, true)?;
4907 self.directory.ownership = old_directory_ownership;
4911 id: ast::DUMMY_NODE_ID,
4912 span: lo.to(i.span),
4913 node: StmtKind::Item(i),
4916 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4917 if !attrs.is_empty() {
4918 if s.prev_token_kind == PrevTokenKind::DocComment {
4919 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4920 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4921 s.span_err(s.span, "expected statement after outer attribute");
4926 // Do not attempt to parse an expression if we're done here.
4927 if self.token == token::Semi {
4928 unused_attrs(&attrs, self);
4933 if self.token == token::CloseDelim(token::Brace) {
4934 unused_attrs(&attrs, self);
4938 // Remainder are line-expr stmts.
4939 let e = self.parse_expr_res(
4940 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4942 id: ast::DUMMY_NODE_ID,
4943 span: lo.to(e.span),
4944 node: StmtKind::Expr(e),
4951 /// Is this expression a successfully-parsed statement?
4952 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4953 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4954 !classify::expr_requires_semi_to_be_stmt(e)
4957 /// Parse a block. No inner attrs are allowed.
4958 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4959 maybe_whole!(self, NtBlock, |x| x);
4963 if !self.eat(&token::OpenDelim(token::Brace)) {
4965 let tok = self.this_token_descr();
4966 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4967 let do_not_suggest_help =
4968 self.token.is_keyword(keywords::In) || self.token == token::Colon;
4970 if self.token.is_ident_named("and") {
4971 e.span_suggestion_short_with_applicability(
4973 "use `&&` instead of `and` for the boolean operator",
4975 Applicability::MaybeIncorrect,
4978 if self.token.is_ident_named("or") {
4979 e.span_suggestion_short_with_applicability(
4981 "use `||` instead of `or` for the boolean operator",
4983 Applicability::MaybeIncorrect,
4987 // Check to see if the user has written something like
4992 // Which is valid in other languages, but not Rust.
4993 match self.parse_stmt_without_recovery(false) {
4995 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4996 || do_not_suggest_help {
4997 // if the next token is an open brace (e.g., `if a b {`), the place-
4998 // inside-a-block suggestion would be more likely wrong than right
4999 e.span_label(sp, "expected `{`");
5002 let mut stmt_span = stmt.span;
5003 // expand the span to include the semicolon, if it exists
5004 if self.eat(&token::Semi) {
5005 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5007 let sugg = pprust::to_string(|s| {
5008 use print::pprust::{PrintState, INDENT_UNIT};
5009 s.ibox(INDENT_UNIT)?;
5011 s.print_stmt(&stmt)?;
5012 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5014 e.span_suggestion_with_applicability(
5016 "try placing this code inside a block",
5018 // speculative, has been misleading in the past (closed Issue #46836)
5019 Applicability::MaybeIncorrect
5023 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5024 self.cancel(&mut e);
5028 e.span_label(sp, "expected `{`");
5032 self.parse_block_tail(lo, BlockCheckMode::Default)
5035 /// Parse a block. Inner attrs are allowed.
5036 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5037 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5040 self.expect(&token::OpenDelim(token::Brace))?;
5041 Ok((self.parse_inner_attributes()?,
5042 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5045 /// Parse the rest of a block expression or function body
5046 /// Precondition: already parsed the '{'.
5047 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5048 let mut stmts = vec![];
5049 while !self.eat(&token::CloseDelim(token::Brace)) {
5050 let stmt = match self.parse_full_stmt(false) {
5053 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5055 id: ast::DUMMY_NODE_ID,
5056 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5062 if let Some(stmt) = stmt {
5064 } else if self.token == token::Eof {
5067 // Found only `;` or `}`.
5073 id: ast::DUMMY_NODE_ID,
5075 span: lo.to(self.prev_span),
5079 /// Parse a statement, including the trailing semicolon.
5080 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5081 // skip looking for a trailing semicolon when we have an interpolated statement
5082 maybe_whole!(self, NtStmt, |x| Some(x));
5084 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5086 None => return Ok(None),
5090 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5091 // expression without semicolon
5092 if classify::expr_requires_semi_to_be_stmt(expr) {
5093 // Just check for errors and recover; do not eat semicolon yet.
5095 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5098 self.recover_stmt();
5102 StmtKind::Local(..) => {
5103 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5104 if macro_legacy_warnings && self.token != token::Semi {
5105 self.warn_missing_semicolon();
5107 self.expect_one_of(&[], &[token::Semi])?;
5113 if self.eat(&token::Semi) {
5114 stmt = stmt.add_trailing_semicolon();
5117 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5121 fn warn_missing_semicolon(&self) {
5122 self.diagnostic().struct_span_warn(self.span, {
5123 &format!("expected `;`, found {}", self.this_token_descr())
5125 "This was erroneously allowed and will become a hard error in a future release"
5129 fn err_dotdotdot_syntax(&self, span: Span) {
5130 self.diagnostic().struct_span_err(span, {
5131 "unexpected token: `...`"
5132 }).span_suggestion_with_applicability(
5133 span, "use `..` for an exclusive range", "..".to_owned(),
5134 Applicability::MaybeIncorrect
5135 ).span_suggestion_with_applicability(
5136 span, "or `..=` for an inclusive range", "..=".to_owned(),
5137 Applicability::MaybeIncorrect
5141 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5142 // BOUND = TY_BOUND | LT_BOUND
5143 // LT_BOUND = LIFETIME (e.g., `'a`)
5144 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5145 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5146 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
5147 let mut bounds = Vec::new();
5149 // This needs to be synchronized with `Token::can_begin_bound`.
5150 let is_bound_start = self.check_path() || self.check_lifetime() ||
5151 self.check(&token::Question) ||
5152 self.check_keyword(keywords::For) ||
5153 self.check(&token::OpenDelim(token::Paren));
5156 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5157 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5158 if self.token.is_lifetime() {
5159 if let Some(question_span) = question {
5160 self.span_err(question_span,
5161 "`?` may only modify trait bounds, not lifetime bounds");
5163 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5165 self.expect(&token::CloseDelim(token::Paren))?;
5166 self.span_err(self.prev_span,
5167 "parenthesized lifetime bounds are not supported");
5170 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5171 let path = self.parse_path(PathStyle::Type)?;
5173 self.expect(&token::CloseDelim(token::Paren))?;
5175 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
5176 let modifier = if question.is_some() {
5177 TraitBoundModifier::Maybe
5179 TraitBoundModifier::None
5181 bounds.push(GenericBound::Trait(poly_trait, modifier));
5187 if !allow_plus || !self.eat_plus() {
5195 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
5196 self.parse_generic_bounds_common(true)
5199 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5200 // BOUND = LT_BOUND (e.g., `'a`)
5201 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5202 let mut lifetimes = Vec::new();
5203 while self.check_lifetime() {
5204 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5206 if !self.eat_plus() {
5213 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
5214 fn parse_ty_param(&mut self,
5215 preceding_attrs: Vec<Attribute>)
5216 -> PResult<'a, GenericParam> {
5217 let ident = self.parse_ident()?;
5219 // Parse optional colon and param bounds.
5220 let bounds = if self.eat(&token::Colon) {
5221 self.parse_generic_bounds()?
5226 let default = if self.eat(&token::Eq) {
5227 Some(self.parse_ty()?)
5234 id: ast::DUMMY_NODE_ID,
5235 attrs: preceding_attrs.into(),
5237 kind: GenericParamKind::Type {
5243 /// Parses the following grammar:
5244 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5245 fn parse_trait_item_assoc_ty(&mut self)
5246 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5247 let ident = self.parse_ident()?;
5248 let mut generics = self.parse_generics()?;
5250 // Parse optional colon and param bounds.
5251 let bounds = if self.eat(&token::Colon) {
5252 self.parse_generic_bounds()?
5256 generics.where_clause = self.parse_where_clause()?;
5258 let default = if self.eat(&token::Eq) {
5259 Some(self.parse_ty()?)
5263 self.expect(&token::Semi)?;
5265 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5268 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5269 /// trailing comma and erroneous trailing attributes.
5270 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5271 let mut lifetimes = Vec::new();
5272 let mut params = Vec::new();
5273 let mut seen_ty_param: Option<Span> = None;
5274 let mut last_comma_span = None;
5275 let mut bad_lifetime_pos = vec![];
5276 let mut suggestions = vec![];
5278 let attrs = self.parse_outer_attributes()?;
5279 if self.check_lifetime() {
5280 let lifetime = self.expect_lifetime();
5281 // Parse lifetime parameter.
5282 let bounds = if self.eat(&token::Colon) {
5283 self.parse_lt_param_bounds()
5287 lifetimes.push(ast::GenericParam {
5288 ident: lifetime.ident,
5290 attrs: attrs.into(),
5292 kind: ast::GenericParamKind::Lifetime,
5294 if let Some(sp) = seen_ty_param {
5295 let remove_sp = last_comma_span.unwrap_or(self.prev_span).to(self.prev_span);
5296 bad_lifetime_pos.push(self.prev_span);
5297 if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.prev_span) {
5298 suggestions.push((remove_sp, String::new()));
5301 format!("{}, ", snippet)));
5304 } else if self.check_ident() {
5305 // Parse type parameter.
5306 params.push(self.parse_ty_param(attrs)?);
5307 if seen_ty_param.is_none() {
5308 seen_ty_param = Some(self.prev_span);
5311 // Check for trailing attributes and stop parsing.
5312 if !attrs.is_empty() {
5313 let param_kind = if seen_ty_param.is_some() { "type" } else { "lifetime" };
5314 self.struct_span_err(
5316 &format!("trailing attribute after {} parameters", param_kind),
5318 .span_label(attrs[0].span, "attributes must go before parameters")
5324 if !self.eat(&token::Comma) {
5327 last_comma_span = Some(self.prev_span);
5329 if !bad_lifetime_pos.is_empty() {
5330 let mut err = self.struct_span_err(
5332 "lifetime parameters must be declared prior to type parameters",
5334 if !suggestions.is_empty() {
5335 err.multipart_suggestion_with_applicability(
5336 "move the lifetime parameter prior to the first type parameter",
5338 Applicability::MachineApplicable,
5343 lifetimes.extend(params); // ensure the correct order of lifetimes and type params
5347 /// Parse a set of optional generic type parameter declarations. Where
5348 /// clauses are not parsed here, and must be added later via
5349 /// `parse_where_clause()`.
5351 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5352 /// | ( < lifetimes , typaramseq ( , )? > )
5353 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5354 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5355 maybe_whole!(self, NtGenerics, |x| x);
5357 let span_lo = self.span;
5359 let params = self.parse_generic_params()?;
5363 where_clause: WhereClause {
5364 id: ast::DUMMY_NODE_ID,
5365 predicates: Vec::new(),
5366 span: syntax_pos::DUMMY_SP,
5368 span: span_lo.to(self.prev_span),
5371 Ok(ast::Generics::default())
5375 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5376 /// possibly including trailing comma.
5377 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5378 let mut args = Vec::new();
5379 let mut bindings = Vec::new();
5380 let mut seen_type = false;
5381 let mut seen_binding = false;
5382 let mut first_type_or_binding_span: Option<Span> = None;
5383 let mut bad_lifetime_pos = vec![];
5384 let mut last_comma_span = None;
5385 let mut suggestions = vec![];
5387 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5388 // Parse lifetime argument.
5389 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5390 if seen_type || seen_binding {
5391 let remove_sp = last_comma_span.unwrap_or(self.prev_span).to(self.prev_span);
5392 bad_lifetime_pos.push(self.prev_span);
5393 if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.prev_span) {
5394 suggestions.push((remove_sp, String::new()));
5396 first_type_or_binding_span.unwrap().shrink_to_lo(),
5397 format!("{}, ", snippet)));
5400 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5401 // Parse associated type binding.
5403 let ident = self.parse_ident()?;
5405 let ty = self.parse_ty()?;
5406 let span = lo.to(self.prev_span);
5407 bindings.push(TypeBinding {
5408 id: ast::DUMMY_NODE_ID,
5413 seen_binding = true;
5414 if first_type_or_binding_span.is_none() {
5415 first_type_or_binding_span = Some(span);
5417 } else if self.check_type() {
5418 // Parse type argument.
5419 let ty_param = self.parse_ty()?;
5421 self.struct_span_err(
5423 "type parameters must be declared prior to associated type bindings"
5427 "must be declared prior to associated type bindings",
5431 if first_type_or_binding_span.is_none() {
5432 first_type_or_binding_span = Some(ty_param.span);
5434 args.push(GenericArg::Type(ty_param));
5440 if !self.eat(&token::Comma) {
5443 last_comma_span = Some(self.prev_span);
5446 if !bad_lifetime_pos.is_empty() {
5447 let mut err = self.struct_span_err(
5448 bad_lifetime_pos.clone(),
5449 "lifetime parameters must be declared prior to type parameters"
5451 for sp in &bad_lifetime_pos {
5452 err.span_label(*sp, "must be declared prior to type parameters");
5454 if !suggestions.is_empty() {
5455 err.multipart_suggestion_with_applicability(
5457 "move the lifetime parameter{} prior to the first type parameter",
5458 if bad_lifetime_pos.len() > 1 { "s" } else { "" },
5461 Applicability::MachineApplicable,
5466 Ok((args, bindings))
5469 /// Parses an optional `where` clause and places it in `generics`.
5471 /// ```ignore (only-for-syntax-highlight)
5472 /// where T : Trait<U, V> + 'b, 'a : 'b
5474 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5475 maybe_whole!(self, NtWhereClause, |x| x);
5477 let mut where_clause = WhereClause {
5478 id: ast::DUMMY_NODE_ID,
5479 predicates: Vec::new(),
5480 span: syntax_pos::DUMMY_SP,
5483 if !self.eat_keyword(keywords::Where) {
5484 return Ok(where_clause);
5486 let lo = self.prev_span;
5488 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5489 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5490 // change we parse those generics now, but report an error.
5491 if self.choose_generics_over_qpath() {
5492 let generics = self.parse_generics()?;
5493 self.struct_span_err(
5495 "generic parameters on `where` clauses are reserved for future use",
5497 .span_label(generics.span, "currently unsupported")
5503 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5504 let lifetime = self.expect_lifetime();
5505 // Bounds starting with a colon are mandatory, but possibly empty.
5506 self.expect(&token::Colon)?;
5507 let bounds = self.parse_lt_param_bounds();
5508 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5509 ast::WhereRegionPredicate {
5510 span: lo.to(self.prev_span),
5515 } else if self.check_type() {
5516 // Parse optional `for<'a, 'b>`.
5517 // This `for` is parsed greedily and applies to the whole predicate,
5518 // the bounded type can have its own `for` applying only to it.
5519 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5520 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5521 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5522 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5524 // Parse type with mandatory colon and (possibly empty) bounds,
5525 // or with mandatory equality sign and the second type.
5526 let ty = self.parse_ty()?;
5527 if self.eat(&token::Colon) {
5528 let bounds = self.parse_generic_bounds()?;
5529 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5530 ast::WhereBoundPredicate {
5531 span: lo.to(self.prev_span),
5532 bound_generic_params: lifetime_defs,
5537 // FIXME: Decide what should be used here, `=` or `==`.
5538 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5539 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5540 let rhs_ty = self.parse_ty()?;
5541 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5542 ast::WhereEqPredicate {
5543 span: lo.to(self.prev_span),
5546 id: ast::DUMMY_NODE_ID,
5550 return self.unexpected();
5556 if !self.eat(&token::Comma) {
5561 where_clause.span = lo.to(self.prev_span);
5565 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5566 -> PResult<'a, (Vec<Arg> , bool)> {
5567 self.expect(&token::OpenDelim(token::Paren))?;
5570 let mut variadic = false;
5571 let args: Vec<Option<Arg>> =
5572 self.parse_seq_to_before_end(
5573 &token::CloseDelim(token::Paren),
5574 SeqSep::trailing_allowed(token::Comma),
5576 if p.token == token::DotDotDot {
5580 if p.token != token::CloseDelim(token::Paren) {
5583 "`...` must be last in argument list for variadic function");
5587 let span = p.prev_span;
5588 if p.token == token::CloseDelim(token::Paren) {
5589 // continue parsing to present any further errors
5592 "only foreign functions are allowed to be variadic"
5594 Ok(Some(dummy_arg(span)))
5596 // this function definition looks beyond recovery, stop parsing
5598 "only foreign functions are allowed to be variadic");
5603 match p.parse_arg_general(named_args, false) {
5604 Ok(arg) => Ok(Some(arg)),
5607 let lo = p.prev_span;
5608 // Skip every token until next possible arg or end.
5609 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5610 // Create a placeholder argument for proper arg count (#34264).
5611 let span = lo.to(p.prev_span);
5612 Ok(Some(dummy_arg(span)))
5619 self.eat(&token::CloseDelim(token::Paren));
5621 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5623 if variadic && args.is_empty() {
5625 "variadic function must be declared with at least one named argument");
5628 Ok((args, variadic))
5631 /// Parse the argument list and result type of a function declaration
5632 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5634 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5635 let ret_ty = self.parse_ret_ty(true)?;
5644 /// Returns the parsed optional self argument and whether a self shortcut was used.
5645 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5646 let expect_ident = |this: &mut Self| match this.token {
5647 // Preserve hygienic context.
5648 token::Ident(ident, _) =>
5649 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5652 let isolated_self = |this: &mut Self, n| {
5653 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
5654 this.look_ahead(n + 1, |t| t != &token::ModSep)
5657 // Parse optional self parameter of a method.
5658 // Only a limited set of initial token sequences is considered self parameters, anything
5659 // else is parsed as a normal function parameter list, so some lookahead is required.
5660 let eself_lo = self.span;
5661 let (eself, eself_ident, eself_hi) = match self.token {
5662 token::BinOp(token::And) => {
5668 (if isolated_self(self, 1) {
5670 SelfKind::Region(None, Mutability::Immutable)
5671 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5672 isolated_self(self, 2) {
5675 SelfKind::Region(None, Mutability::Mutable)
5676 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5677 isolated_self(self, 2) {
5679 let lt = self.expect_lifetime();
5680 SelfKind::Region(Some(lt), Mutability::Immutable)
5681 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5682 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5683 isolated_self(self, 3) {
5685 let lt = self.expect_lifetime();
5687 SelfKind::Region(Some(lt), Mutability::Mutable)
5690 }, expect_ident(self), self.prev_span)
5692 token::BinOp(token::Star) => {
5697 // Emit special error for `self` cases.
5698 let msg = "cannot pass `self` by raw pointer";
5699 (if isolated_self(self, 1) {
5701 self.struct_span_err(self.span, msg)
5702 .span_label(self.span, msg)
5704 SelfKind::Value(Mutability::Immutable)
5705 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5706 isolated_self(self, 2) {
5709 self.struct_span_err(self.span, msg)
5710 .span_label(self.span, msg)
5712 SelfKind::Value(Mutability::Immutable)
5715 }, expect_ident(self), self.prev_span)
5717 token::Ident(..) => {
5718 if isolated_self(self, 0) {
5721 let eself_ident = expect_ident(self);
5722 let eself_hi = self.prev_span;
5723 (if self.eat(&token::Colon) {
5724 let ty = self.parse_ty()?;
5725 SelfKind::Explicit(ty, Mutability::Immutable)
5727 SelfKind::Value(Mutability::Immutable)
5728 }, eself_ident, eself_hi)
5729 } else if self.token.is_keyword(keywords::Mut) &&
5730 isolated_self(self, 1) {
5734 let eself_ident = expect_ident(self);
5735 let eself_hi = self.prev_span;
5736 (if self.eat(&token::Colon) {
5737 let ty = self.parse_ty()?;
5738 SelfKind::Explicit(ty, Mutability::Mutable)
5740 SelfKind::Value(Mutability::Mutable)
5741 }, eself_ident, eself_hi)
5746 _ => return Ok(None),
5749 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5750 Ok(Some(Arg::from_self(eself, eself_ident)))
5753 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5754 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5755 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5757 self.expect(&token::OpenDelim(token::Paren))?;
5759 // Parse optional self argument
5760 let self_arg = self.parse_self_arg()?;
5762 // Parse the rest of the function parameter list.
5763 let sep = SeqSep::trailing_allowed(token::Comma);
5764 let fn_inputs = if let Some(self_arg) = self_arg {
5765 if self.check(&token::CloseDelim(token::Paren)) {
5767 } else if self.eat(&token::Comma) {
5768 let mut fn_inputs = vec![self_arg];
5769 fn_inputs.append(&mut self.parse_seq_to_before_end(
5770 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5774 return self.unexpected();
5777 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5780 // Parse closing paren and return type.
5781 self.expect(&token::CloseDelim(token::Paren))?;
5784 output: self.parse_ret_ty(true)?,
5789 // parse the |arg, arg| header on a lambda
5790 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5791 let inputs_captures = {
5792 if self.eat(&token::OrOr) {
5795 self.expect(&token::BinOp(token::Or))?;
5796 let args = self.parse_seq_to_before_tokens(
5797 &[&token::BinOp(token::Or), &token::OrOr],
5798 SeqSep::trailing_allowed(token::Comma),
5799 TokenExpectType::NoExpect,
5800 |p| p.parse_fn_block_arg()
5806 let output = self.parse_ret_ty(true)?;
5809 inputs: inputs_captures,
5815 /// Parse the name and optional generic types of a function header.
5816 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5817 let id = self.parse_ident()?;
5818 let generics = self.parse_generics()?;
5822 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5823 attrs: Vec<Attribute>) -> P<Item> {
5827 id: ast::DUMMY_NODE_ID,
5835 /// Parse an item-position function declaration.
5836 fn parse_item_fn(&mut self,
5839 constness: Spanned<Constness>,
5841 -> PResult<'a, ItemInfo> {
5842 let (ident, mut generics) = self.parse_fn_header()?;
5843 let decl = self.parse_fn_decl(false)?;
5844 generics.where_clause = self.parse_where_clause()?;
5845 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5846 let header = FnHeader { unsafety, asyncness, constness, abi };
5847 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5850 /// true if we are looking at `const ID`, false for things like `const fn` etc
5851 fn is_const_item(&mut self) -> bool {
5852 self.token.is_keyword(keywords::Const) &&
5853 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5854 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5857 /// parses all the "front matter" for a `fn` declaration, up to
5858 /// and including the `fn` keyword:
5862 /// - `const unsafe fn`
5865 fn parse_fn_front_matter(&mut self)
5873 let is_const_fn = self.eat_keyword(keywords::Const);
5874 let const_span = self.prev_span;
5875 let unsafety = self.parse_unsafety();
5876 let asyncness = self.parse_asyncness();
5877 let (constness, unsafety, abi) = if is_const_fn {
5878 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5880 let abi = if self.eat_keyword(keywords::Extern) {
5881 self.parse_opt_abi()?.unwrap_or(Abi::C)
5885 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5887 self.expect_keyword(keywords::Fn)?;
5888 Ok((constness, unsafety, asyncness, abi))
5891 /// Parse an impl item.
5892 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5893 maybe_whole!(self, NtImplItem, |x| x);
5894 let attrs = self.parse_outer_attributes()?;
5895 let (mut item, tokens) = self.collect_tokens(|this| {
5896 this.parse_impl_item_(at_end, attrs)
5899 // See `parse_item` for why this clause is here.
5900 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5901 item.tokens = Some(tokens);
5906 fn parse_impl_item_(&mut self,
5908 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5910 let vis = self.parse_visibility(false)?;
5911 let defaultness = self.parse_defaultness();
5912 let (name, node, generics) = if let Some(type_) = self.eat_type() {
5913 let (name, alias, generics) = type_?;
5914 let kind = match alias {
5915 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5916 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5918 (name, kind, generics)
5919 } else if self.is_const_item() {
5920 // This parses the grammar:
5921 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5922 self.expect_keyword(keywords::Const)?;
5923 let name = self.parse_ident()?;
5924 self.expect(&token::Colon)?;
5925 let typ = self.parse_ty()?;
5926 self.expect(&token::Eq)?;
5927 let expr = self.parse_expr()?;
5928 self.expect(&token::Semi)?;
5929 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5931 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5932 attrs.extend(inner_attrs);
5933 (name, node, generics)
5937 id: ast::DUMMY_NODE_ID,
5938 span: lo.to(self.prev_span),
5949 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5951 VisibilityKind::Inherited => {}
5953 let is_macro_rules: bool = match self.token {
5954 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5957 let mut err = if is_macro_rules {
5958 let mut err = self.diagnostic()
5959 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5960 err.span_suggestion_with_applicability(
5962 "try exporting the macro",
5963 "#[macro_export]".to_owned(),
5964 Applicability::MaybeIncorrect // speculative
5968 let mut err = self.diagnostic()
5969 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5970 err.help("try adjusting the macro to put `pub` inside the invocation");
5978 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5979 -> DiagnosticBuilder<'a>
5981 let expected_kinds = if item_type == "extern" {
5982 "missing `fn`, `type`, or `static`"
5984 "missing `fn`, `type`, or `const`"
5987 // Given this code `path(`, it seems like this is not
5988 // setting the visibility of a macro invocation, but rather
5989 // a mistyped method declaration.
5990 // Create a diagnostic pointing out that `fn` is missing.
5992 // x | pub path(&self) {
5993 // | ^ missing `fn`, `type`, or `const`
5995 // ^^ `sp` below will point to this
5996 let sp = prev_span.between(self.prev_span);
5997 let mut err = self.diagnostic().struct_span_err(
5999 &format!("{} for {}-item declaration",
6000 expected_kinds, item_type));
6001 err.span_label(sp, expected_kinds);
6005 /// Parse a method or a macro invocation in a trait impl.
6006 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6007 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6008 ast::ImplItemKind)> {
6009 // code copied from parse_macro_use_or_failure... abstraction!
6010 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6012 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6013 ast::ImplItemKind::Macro(mac)))
6015 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
6016 let ident = self.parse_ident()?;
6017 let mut generics = self.parse_generics()?;
6018 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6019 generics.where_clause = self.parse_where_clause()?;
6021 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6022 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6023 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6024 ast::MethodSig { header, decl },
6030 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
6031 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6032 let ident = self.parse_ident()?;
6033 let mut tps = self.parse_generics()?;
6035 // Parse optional colon and supertrait bounds.
6036 let bounds = if self.eat(&token::Colon) {
6037 self.parse_generic_bounds()?
6042 if self.eat(&token::Eq) {
6043 // it's a trait alias
6044 let bounds = self.parse_generic_bounds()?;
6045 tps.where_clause = self.parse_where_clause()?;
6046 self.expect(&token::Semi)?;
6047 if unsafety != Unsafety::Normal {
6048 let msg = "trait aliases cannot be unsafe";
6049 self.struct_span_err(self.prev_span, msg)
6050 .span_label(self.prev_span, msg)
6053 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6055 // it's a normal trait
6056 tps.where_clause = self.parse_where_clause()?;
6057 self.expect(&token::OpenDelim(token::Brace))?;
6058 let mut trait_items = vec![];
6059 while !self.eat(&token::CloseDelim(token::Brace)) {
6060 let mut at_end = false;
6061 match self.parse_trait_item(&mut at_end) {
6062 Ok(item) => trait_items.push(item),
6066 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6071 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6075 fn choose_generics_over_qpath(&self) -> bool {
6076 // There's an ambiguity between generic parameters and qualified paths in impls.
6077 // If we see `<` it may start both, so we have to inspect some following tokens.
6078 // The following combinations can only start generics,
6079 // but not qualified paths (with one exception):
6080 // `<` `>` - empty generic parameters
6081 // `<` `#` - generic parameters with attributes
6082 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6083 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6084 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6085 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6086 // The only truly ambiguous case is
6087 // `<` IDENT `>` `::` IDENT ...
6088 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6089 // because this is what almost always expected in practice, qualified paths in impls
6090 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6091 self.token == token::Lt &&
6092 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6093 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6094 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6095 t == &token::Colon || t == &token::Eq))
6098 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6099 self.expect(&token::OpenDelim(token::Brace))?;
6100 let attrs = self.parse_inner_attributes()?;
6102 let mut impl_items = Vec::new();
6103 while !self.eat(&token::CloseDelim(token::Brace)) {
6104 let mut at_end = false;
6105 match self.parse_impl_item(&mut at_end) {
6106 Ok(impl_item) => impl_items.push(impl_item),
6110 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6115 Ok((impl_items, attrs))
6118 /// Parses an implementation item, `impl` keyword is already parsed.
6119 /// impl<'a, T> TYPE { /* impl items */ }
6120 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6121 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6122 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6123 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6124 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6125 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6126 -> PResult<'a, ItemInfo> {
6127 // First, parse generic parameters if necessary.
6128 let mut generics = if self.choose_generics_over_qpath() {
6129 self.parse_generics()?
6131 ast::Generics::default()
6134 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6135 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6137 ast::ImplPolarity::Negative
6139 ast::ImplPolarity::Positive
6142 // Parse both types and traits as a type, then reinterpret if necessary.
6143 let ty_first = self.parse_ty()?;
6145 // If `for` is missing we try to recover.
6146 let has_for = self.eat_keyword(keywords::For);
6147 let missing_for_span = self.prev_span.between(self.span);
6149 let ty_second = if self.token == token::DotDot {
6150 // We need to report this error after `cfg` expansion for compatibility reasons
6151 self.bump(); // `..`, do not add it to expected tokens
6152 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
6153 } else if has_for || self.token.can_begin_type() {
6154 Some(self.parse_ty()?)
6159 generics.where_clause = self.parse_where_clause()?;
6161 let (impl_items, attrs) = self.parse_impl_body()?;
6163 let item_kind = match ty_second {
6164 Some(ty_second) => {
6165 // impl Trait for Type
6167 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6168 .span_suggestion_short_with_applicability(
6171 " for ".to_string(),
6172 Applicability::MachineApplicable,
6176 let ty_first = ty_first.into_inner();
6177 let path = match ty_first.node {
6178 // This notably includes paths passed through `ty` macro fragments (#46438).
6179 TyKind::Path(None, path) => path,
6181 self.span_err(ty_first.span, "expected a trait, found type");
6182 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
6185 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6187 ItemKind::Impl(unsafety, polarity, defaultness,
6188 generics, Some(trait_ref), ty_second, impl_items)
6192 ItemKind::Impl(unsafety, polarity, defaultness,
6193 generics, None, ty_first, impl_items)
6197 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6200 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6201 if self.eat_keyword(keywords::For) {
6203 let params = self.parse_generic_params()?;
6205 // We rely on AST validation to rule out invalid cases: There must not be type
6206 // parameters, and the lifetime parameters must not have bounds.
6213 /// Parse struct Foo { ... }
6214 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6215 let class_name = self.parse_ident()?;
6217 let mut generics = self.parse_generics()?;
6219 // There is a special case worth noting here, as reported in issue #17904.
6220 // If we are parsing a tuple struct it is the case that the where clause
6221 // should follow the field list. Like so:
6223 // struct Foo<T>(T) where T: Copy;
6225 // If we are parsing a normal record-style struct it is the case
6226 // that the where clause comes before the body, and after the generics.
6227 // So if we look ahead and see a brace or a where-clause we begin
6228 // parsing a record style struct.
6230 // Otherwise if we look ahead and see a paren we parse a tuple-style
6233 let vdata = if self.token.is_keyword(keywords::Where) {
6234 generics.where_clause = self.parse_where_clause()?;
6235 if self.eat(&token::Semi) {
6236 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6237 VariantData::Unit(ast::DUMMY_NODE_ID)
6239 // If we see: `struct Foo<T> where T: Copy { ... }`
6240 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6242 // No `where` so: `struct Foo<T>;`
6243 } else if self.eat(&token::Semi) {
6244 VariantData::Unit(ast::DUMMY_NODE_ID)
6245 // Record-style struct definition
6246 } else if self.token == token::OpenDelim(token::Brace) {
6247 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6248 // Tuple-style struct definition with optional where-clause.
6249 } else if self.token == token::OpenDelim(token::Paren) {
6250 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6251 generics.where_clause = self.parse_where_clause()?;
6252 self.expect(&token::Semi)?;
6255 let token_str = self.this_token_descr();
6256 let mut err = self.fatal(&format!(
6257 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6260 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6264 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6267 /// Parse union Foo { ... }
6268 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6269 let class_name = self.parse_ident()?;
6271 let mut generics = self.parse_generics()?;
6273 let vdata = if self.token.is_keyword(keywords::Where) {
6274 generics.where_clause = self.parse_where_clause()?;
6275 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6276 } else if self.token == token::OpenDelim(token::Brace) {
6277 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6279 let token_str = self.this_token_descr();
6280 let mut err = self.fatal(&format!(
6281 "expected `where` or `{{` after union name, found {}", token_str));
6282 err.span_label(self.span, "expected `where` or `{` after union name");
6286 Ok((class_name, ItemKind::Union(vdata, generics), None))
6289 fn consume_block(&mut self, delim: token::DelimToken) {
6290 let mut brace_depth = 0;
6292 if self.eat(&token::OpenDelim(delim)) {
6294 } else if self.eat(&token::CloseDelim(delim)) {
6295 if brace_depth == 0 {
6301 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6309 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6310 let mut fields = Vec::new();
6311 if self.eat(&token::OpenDelim(token::Brace)) {
6312 while self.token != token::CloseDelim(token::Brace) {
6313 let field = self.parse_struct_decl_field().map_err(|e| {
6314 self.recover_stmt();
6318 Ok(field) => fields.push(field),
6324 self.eat(&token::CloseDelim(token::Brace));
6326 let token_str = self.this_token_descr();
6327 let mut err = self.fatal(&format!(
6328 "expected `where`, or `{{` after struct name, found {}", token_str));
6329 err.span_label(self.span, "expected `where`, or `{` after struct name");
6336 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6337 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6338 // Unit like structs are handled in parse_item_struct function
6339 let fields = self.parse_unspanned_seq(
6340 &token::OpenDelim(token::Paren),
6341 &token::CloseDelim(token::Paren),
6342 SeqSep::trailing_allowed(token::Comma),
6344 let attrs = p.parse_outer_attributes()?;
6346 let vis = p.parse_visibility(true)?;
6347 let ty = p.parse_ty()?;
6349 span: lo.to(ty.span),
6352 id: ast::DUMMY_NODE_ID,
6361 /// Parse a structure field declaration
6362 fn parse_single_struct_field(&mut self,
6365 attrs: Vec<Attribute> )
6366 -> PResult<'a, StructField> {
6367 let mut seen_comma: bool = false;
6368 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6369 if self.token == token::Comma {
6376 token::CloseDelim(token::Brace) => {}
6377 token::DocComment(_) => {
6378 let previous_span = self.prev_span;
6379 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6380 self.bump(); // consume the doc comment
6381 let comma_after_doc_seen = self.eat(&token::Comma);
6382 // `seen_comma` is always false, because we are inside doc block
6383 // condition is here to make code more readable
6384 if seen_comma == false && comma_after_doc_seen == true {
6387 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6390 if seen_comma == false {
6391 let sp = self.sess.source_map().next_point(previous_span);
6392 err.span_suggestion_with_applicability(
6394 "missing comma here",
6396 Applicability::MachineApplicable
6403 let sp = self.sess.source_map().next_point(self.prev_span);
6404 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6405 self.this_token_descr()));
6406 if self.token.is_ident() {
6407 // This is likely another field; emit the diagnostic and keep going
6408 err.span_suggestion_with_applicability(
6410 "try adding a comma",
6412 Applicability::MachineApplicable,
6423 /// Parse an element of a struct definition
6424 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6425 let attrs = self.parse_outer_attributes()?;
6427 let vis = self.parse_visibility(false)?;
6428 self.parse_single_struct_field(lo, vis, attrs)
6431 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6432 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6433 /// If the following element can't be a tuple (i.e., it's a function definition,
6434 /// it's not a tuple struct field) and the contents within the parens
6435 /// isn't valid, emit a proper diagnostic.
6436 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6437 maybe_whole!(self, NtVis, |x| x);
6439 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6440 if self.is_crate_vis() {
6441 self.bump(); // `crate`
6442 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6445 if !self.eat_keyword(keywords::Pub) {
6446 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6447 // keyword to grab a span from for inherited visibility; an empty span at the
6448 // beginning of the current token would seem to be the "Schelling span".
6449 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6451 let lo = self.prev_span;
6453 if self.check(&token::OpenDelim(token::Paren)) {
6454 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6455 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6456 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6457 // by the following tokens.
6458 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6461 self.bump(); // `crate`
6462 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6464 lo.to(self.prev_span),
6465 VisibilityKind::Crate(CrateSugar::PubCrate),
6468 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6471 self.bump(); // `in`
6472 let path = self.parse_path(PathStyle::Mod)?; // `path`
6473 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6474 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6476 id: ast::DUMMY_NODE_ID,
6479 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6480 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6481 t.is_keyword(keywords::SelfLower))
6483 // `pub(self)` or `pub(super)`
6485 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6486 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6487 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6489 id: ast::DUMMY_NODE_ID,
6492 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6493 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6495 let msg = "incorrect visibility restriction";
6496 let suggestion = r##"some possible visibility restrictions are:
6497 `pub(crate)`: visible only on the current crate
6498 `pub(super)`: visible only in the current module's parent
6499 `pub(in path::to::module)`: visible only on the specified path"##;
6500 let path = self.parse_path(PathStyle::Mod)?;
6501 let sp = self.prev_span;
6502 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6503 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6504 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6505 err.help(suggestion);
6506 err.span_suggestion_with_applicability(
6507 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6509 err.emit(); // emit diagnostic, but continue with public visibility
6513 Ok(respan(lo, VisibilityKind::Public))
6516 /// Parse defaultness: `default` or nothing.
6517 fn parse_defaultness(&mut self) -> Defaultness {
6518 // `pub` is included for better error messages
6519 if self.check_keyword(keywords::Default) &&
6520 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6521 t.is_keyword(keywords::Const) ||
6522 t.is_keyword(keywords::Fn) ||
6523 t.is_keyword(keywords::Unsafe) ||
6524 t.is_keyword(keywords::Extern) ||
6525 t.is_keyword(keywords::Type) ||
6526 t.is_keyword(keywords::Pub)) {
6527 self.bump(); // `default`
6528 Defaultness::Default
6534 fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
6535 if self.eat(&token::Semi) {
6536 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
6537 err.span_suggestion_short_with_applicability(
6539 "remove this semicolon",
6541 Applicability::MachineApplicable,
6543 if !items.is_empty() {
6544 let previous_item = &items[items.len()-1];
6545 let previous_item_kind_name = match previous_item.node {
6546 // say "braced struct" because tuple-structs and
6547 // braceless-empty-struct declarations do take a semicolon
6548 ItemKind::Struct(..) => Some("braced struct"),
6549 ItemKind::Enum(..) => Some("enum"),
6550 ItemKind::Trait(..) => Some("trait"),
6551 ItemKind::Union(..) => Some("union"),
6554 if let Some(name) = previous_item_kind_name {
6555 err.help(&format!("{} declarations are not followed by a semicolon", name));
6565 /// Given a termination token, parse all of the items in a module
6566 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6567 let mut items = vec![];
6568 while let Some(item) = self.parse_item()? {
6570 self.maybe_consume_incorrect_semicolon(&items);
6573 if !self.eat(term) {
6574 let token_str = self.this_token_descr();
6575 if !self.maybe_consume_incorrect_semicolon(&items) {
6576 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6577 err.span_label(self.span, "expected item");
6582 let hi = if self.span.is_dummy() {
6589 inner: inner_lo.to(hi),
6595 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6596 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6597 self.expect(&token::Colon)?;
6598 let ty = self.parse_ty()?;
6599 self.expect(&token::Eq)?;
6600 let e = self.parse_expr()?;
6601 self.expect(&token::Semi)?;
6602 let item = match m {
6603 Some(m) => ItemKind::Static(ty, m, e),
6604 None => ItemKind::Const(ty, e),
6606 Ok((id, item, None))
6609 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6610 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6611 let (in_cfg, outer_attrs) = {
6612 let mut strip_unconfigured = ::config::StripUnconfigured {
6614 features: None, // don't perform gated feature checking
6616 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6617 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6620 let id_span = self.span;
6621 let id = self.parse_ident()?;
6622 if self.eat(&token::Semi) {
6623 if in_cfg && self.recurse_into_file_modules {
6624 // This mod is in an external file. Let's go get it!
6625 let ModulePathSuccess { path, directory_ownership, warn } =
6626 self.submod_path(id, &outer_attrs, id_span)?;
6627 let (module, mut attrs) =
6628 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6629 // Record that we fetched the mod from an external file
6631 let attr = Attribute {
6632 id: attr::mk_attr_id(),
6633 style: ast::AttrStyle::Outer,
6634 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6635 tokens: TokenStream::empty(),
6636 is_sugared_doc: false,
6637 span: syntax_pos::DUMMY_SP,
6639 attr::mark_known(&attr);
6642 Ok((id, ItemKind::Mod(module), Some(attrs)))
6644 let placeholder = ast::Mod {
6645 inner: syntax_pos::DUMMY_SP,
6649 Ok((id, ItemKind::Mod(placeholder), None))
6652 let old_directory = self.directory.clone();
6653 self.push_directory(id, &outer_attrs);
6655 self.expect(&token::OpenDelim(token::Brace))?;
6656 let mod_inner_lo = self.span;
6657 let attrs = self.parse_inner_attributes()?;
6658 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6660 self.directory = old_directory;
6661 Ok((id, ItemKind::Mod(module), Some(attrs)))
6665 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6666 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6667 self.directory.path.to_mut().push(&path.as_str());
6668 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6670 // We have to push on the current module name in the case of relative
6671 // paths in order to ensure that any additional module paths from inline
6672 // `mod x { ... }` come after the relative extension.
6674 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6675 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6676 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6677 if let Some(ident) = relative.take() { // remove the relative offset
6678 self.directory.path.to_mut().push(ident.as_str());
6681 self.directory.path.to_mut().push(&id.as_str());
6685 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6686 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6689 // On windows, the base path might have the form
6690 // `\\?\foo\bar` in which case it does not tolerate
6691 // mixed `/` and `\` separators, so canonicalize
6694 let s = s.replace("/", "\\");
6695 Some(dir_path.join(s))
6701 /// Returns either a path to a module, or .
6702 pub fn default_submod_path(
6704 relative: Option<ast::Ident>,
6706 source_map: &SourceMap) -> ModulePath
6708 // If we're in a foo.rs file instead of a mod.rs file,
6709 // we need to look for submodules in
6710 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6711 // `./<id>.rs` and `./<id>/mod.rs`.
6712 let relative_prefix_string;
6713 let relative_prefix = if let Some(ident) = relative {
6714 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6715 &relative_prefix_string
6720 let mod_name = id.to_string();
6721 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6722 let secondary_path_str = format!("{}{}{}mod.rs",
6723 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6724 let default_path = dir_path.join(&default_path_str);
6725 let secondary_path = dir_path.join(&secondary_path_str);
6726 let default_exists = source_map.file_exists(&default_path);
6727 let secondary_exists = source_map.file_exists(&secondary_path);
6729 let result = match (default_exists, secondary_exists) {
6730 (true, false) => Ok(ModulePathSuccess {
6732 directory_ownership: DirectoryOwnership::Owned {
6737 (false, true) => Ok(ModulePathSuccess {
6738 path: secondary_path,
6739 directory_ownership: DirectoryOwnership::Owned {
6744 (false, false) => Err(Error::FileNotFoundForModule {
6745 mod_name: mod_name.clone(),
6746 default_path: default_path_str,
6747 secondary_path: secondary_path_str,
6748 dir_path: dir_path.display().to_string(),
6750 (true, true) => Err(Error::DuplicatePaths {
6751 mod_name: mod_name.clone(),
6752 default_path: default_path_str,
6753 secondary_path: secondary_path_str,
6759 path_exists: default_exists || secondary_exists,
6764 fn submod_path(&mut self,
6766 outer_attrs: &[Attribute],
6768 -> PResult<'a, ModulePathSuccess> {
6769 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6770 return Ok(ModulePathSuccess {
6771 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6772 // All `#[path]` files are treated as though they are a `mod.rs` file.
6773 // This means that `mod foo;` declarations inside `#[path]`-included
6774 // files are siblings,
6776 // Note that this will produce weirdness when a file named `foo.rs` is
6777 // `#[path]` included and contains a `mod foo;` declaration.
6778 // If you encounter this, it's your own darn fault :P
6779 Some(_) => DirectoryOwnership::Owned { relative: None },
6780 _ => DirectoryOwnership::UnownedViaMod(true),
6787 let relative = match self.directory.ownership {
6788 DirectoryOwnership::Owned { relative } => relative,
6789 DirectoryOwnership::UnownedViaBlock |
6790 DirectoryOwnership::UnownedViaMod(_) => None,
6792 let paths = Parser::default_submod_path(
6793 id, relative, &self.directory.path, self.sess.source_map());
6795 match self.directory.ownership {
6796 DirectoryOwnership::Owned { .. } => {
6797 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6799 DirectoryOwnership::UnownedViaBlock => {
6801 "Cannot declare a non-inline module inside a block \
6802 unless it has a path attribute";
6803 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6804 if paths.path_exists {
6805 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6807 err.span_note(id_sp, &msg);
6811 DirectoryOwnership::UnownedViaMod(warn) => {
6813 if let Ok(result) = paths.result {
6814 return Ok(ModulePathSuccess { warn: true, ..result });
6817 let mut err = self.diagnostic().struct_span_err(id_sp,
6818 "cannot declare a new module at this location");
6819 if !id_sp.is_dummy() {
6820 let src_path = self.sess.source_map().span_to_filename(id_sp);
6821 if let FileName::Real(src_path) = src_path {
6822 if let Some(stem) = src_path.file_stem() {
6823 let mut dest_path = src_path.clone();
6824 dest_path.set_file_name(stem);
6825 dest_path.push("mod.rs");
6826 err.span_note(id_sp,
6827 &format!("maybe move this module `{}` to its own \
6828 directory via `{}`", src_path.display(),
6829 dest_path.display()));
6833 if paths.path_exists {
6834 err.span_note(id_sp,
6835 &format!("... or maybe `use` the module `{}` instead \
6836 of possibly redeclaring it",
6844 /// Read a module from a source file.
6845 fn eval_src_mod(&mut self,
6847 directory_ownership: DirectoryOwnership,
6850 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6851 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6852 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6853 let mut err = String::from("circular modules: ");
6854 let len = included_mod_stack.len();
6855 for p in &included_mod_stack[i.. len] {
6856 err.push_str(&p.to_string_lossy());
6857 err.push_str(" -> ");
6859 err.push_str(&path.to_string_lossy());
6860 return Err(self.span_fatal(id_sp, &err[..]));
6862 included_mod_stack.push(path.clone());
6863 drop(included_mod_stack);
6866 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6867 p0.cfg_mods = self.cfg_mods;
6868 let mod_inner_lo = p0.span;
6869 let mod_attrs = p0.parse_inner_attributes()?;
6870 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6872 self.sess.included_mod_stack.borrow_mut().pop();
6876 /// Parse a function declaration from a foreign module
6877 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6878 -> PResult<'a, ForeignItem> {
6879 self.expect_keyword(keywords::Fn)?;
6881 let (ident, mut generics) = self.parse_fn_header()?;
6882 let decl = self.parse_fn_decl(true)?;
6883 generics.where_clause = self.parse_where_clause()?;
6885 self.expect(&token::Semi)?;
6886 Ok(ast::ForeignItem {
6889 node: ForeignItemKind::Fn(decl, generics),
6890 id: ast::DUMMY_NODE_ID,
6896 /// Parse a static item from a foreign module.
6897 /// Assumes that the `static` keyword is already parsed.
6898 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6899 -> PResult<'a, ForeignItem> {
6900 let mutbl = self.eat_keyword(keywords::Mut);
6901 let ident = self.parse_ident()?;
6902 self.expect(&token::Colon)?;
6903 let ty = self.parse_ty()?;
6905 self.expect(&token::Semi)?;
6909 node: ForeignItemKind::Static(ty, mutbl),
6910 id: ast::DUMMY_NODE_ID,
6916 /// Parse a type from a foreign module
6917 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6918 -> PResult<'a, ForeignItem> {
6919 self.expect_keyword(keywords::Type)?;
6921 let ident = self.parse_ident()?;
6923 self.expect(&token::Semi)?;
6924 Ok(ast::ForeignItem {
6927 node: ForeignItemKind::Ty,
6928 id: ast::DUMMY_NODE_ID,
6934 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6935 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6936 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6938 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
6939 self.parse_path_segment_ident()
6943 let mut idents = vec![];
6944 let mut replacement = vec![];
6945 let mut fixed_crate_name = false;
6946 // Accept `extern crate name-like-this` for better diagnostics
6947 let dash = token::Token::BinOp(token::BinOpToken::Minus);
6948 if self.token == dash { // Do not include `-` as part of the expected tokens list
6949 while self.eat(&dash) {
6950 fixed_crate_name = true;
6951 replacement.push((self.prev_span, "_".to_string()));
6952 idents.push(self.parse_ident()?);
6955 if fixed_crate_name {
6956 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6957 let mut fixed_name = format!("{}", ident.name);
6958 for part in idents {
6959 fixed_name.push_str(&format!("_{}", part.name));
6961 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6963 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6964 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6965 err.multipart_suggestion_with_applicability(
6968 Applicability::MachineApplicable,
6975 /// Parse extern crate links
6979 /// extern crate foo;
6980 /// extern crate bar as foo;
6981 fn parse_item_extern_crate(&mut self,
6983 visibility: Visibility,
6984 attrs: Vec<Attribute>)
6985 -> PResult<'a, P<Item>> {
6986 // Accept `extern crate name-like-this` for better diagnostics
6987 let orig_name = self.parse_crate_name_with_dashes()?;
6988 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6989 (rename, Some(orig_name.name))
6993 self.expect(&token::Semi)?;
6995 let span = lo.to(self.prev_span);
6996 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6999 /// Parse `extern` for foreign ABIs
7002 /// `extern` is expected to have been
7003 /// consumed before calling this method
7009 fn parse_item_foreign_mod(&mut self,
7011 opt_abi: Option<Abi>,
7012 visibility: Visibility,
7013 mut attrs: Vec<Attribute>)
7014 -> PResult<'a, P<Item>> {
7015 self.expect(&token::OpenDelim(token::Brace))?;
7017 let abi = opt_abi.unwrap_or(Abi::C);
7019 attrs.extend(self.parse_inner_attributes()?);
7021 let mut foreign_items = vec![];
7022 while !self.eat(&token::CloseDelim(token::Brace)) {
7023 foreign_items.push(self.parse_foreign_item()?);
7026 let prev_span = self.prev_span;
7027 let m = ast::ForeignMod {
7029 items: foreign_items
7031 let invalid = keywords::Invalid.ident();
7032 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7035 /// Parse `type Foo = Bar;`
7037 /// `existential type Foo: Bar;`
7039 /// `return None` without modifying the parser state
7040 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7041 // This parses the grammar:
7042 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7043 if self.check_keyword(keywords::Type) ||
7044 self.check_keyword(keywords::Existential) &&
7045 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7046 let existential = self.eat_keyword(keywords::Existential);
7047 assert!(self.eat_keyword(keywords::Type));
7048 Some(self.parse_existential_or_alias(existential))
7054 /// Parse type alias or existential type
7055 fn parse_existential_or_alias(
7058 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7059 let ident = self.parse_ident()?;
7060 let mut tps = self.parse_generics()?;
7061 tps.where_clause = self.parse_where_clause()?;
7062 let alias = if existential {
7063 self.expect(&token::Colon)?;
7064 let bounds = self.parse_generic_bounds()?;
7065 AliasKind::Existential(bounds)
7067 self.expect(&token::Eq)?;
7068 let ty = self.parse_ty()?;
7071 self.expect(&token::Semi)?;
7072 Ok((ident, alias, tps))
7075 /// Parse the part of an "enum" decl following the '{'
7076 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7077 let mut variants = Vec::new();
7078 let mut all_nullary = true;
7079 let mut any_disr = vec![];
7080 while self.token != token::CloseDelim(token::Brace) {
7081 let variant_attrs = self.parse_outer_attributes()?;
7082 let vlo = self.span;
7085 let mut disr_expr = None;
7086 let ident = self.parse_ident()?;
7087 if self.check(&token::OpenDelim(token::Brace)) {
7088 // Parse a struct variant.
7089 all_nullary = false;
7090 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
7091 ast::DUMMY_NODE_ID);
7092 } else if self.check(&token::OpenDelim(token::Paren)) {
7093 all_nullary = false;
7094 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
7095 ast::DUMMY_NODE_ID);
7096 } else if self.eat(&token::Eq) {
7097 disr_expr = Some(AnonConst {
7098 id: ast::DUMMY_NODE_ID,
7099 value: self.parse_expr()?,
7101 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7104 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7106 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7109 let vr = ast::Variant_ {
7111 attrs: variant_attrs,
7115 variants.push(respan(vlo.to(self.prev_span), vr));
7117 if !self.eat(&token::Comma) { break; }
7119 self.expect(&token::CloseDelim(token::Brace))?;
7120 if !any_disr.is_empty() && !all_nullary {
7121 let mut err =self.struct_span_err(
7123 "discriminator values can only be used with a field-less enum",
7125 for sp in any_disr {
7126 err.span_label(sp, "only valid in field-less enums");
7131 Ok(ast::EnumDef { variants })
7134 /// Parse an "enum" declaration
7135 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7136 let id = self.parse_ident()?;
7137 let mut generics = self.parse_generics()?;
7138 generics.where_clause = self.parse_where_clause()?;
7139 self.expect(&token::OpenDelim(token::Brace))?;
7141 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7142 self.recover_stmt();
7143 self.eat(&token::CloseDelim(token::Brace));
7146 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7149 /// Parses a string as an ABI spec on an extern type or module. Consumes
7150 /// the `extern` keyword, if one is found.
7151 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7153 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7155 self.expect_no_suffix(sp, "ABI spec", suf);
7157 match abi::lookup(&s.as_str()) {
7158 Some(abi) => Ok(Some(abi)),
7160 let prev_span = self.prev_span;
7161 let mut err = struct_span_err!(
7162 self.sess.span_diagnostic,
7165 "invalid ABI: found `{}`",
7167 err.span_label(prev_span, "invalid ABI");
7168 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7179 fn is_static_global(&mut self) -> bool {
7180 if self.check_keyword(keywords::Static) {
7181 // Check if this could be a closure
7182 !self.look_ahead(1, |token| {
7183 if token.is_keyword(keywords::Move) {
7187 token::BinOp(token::Or) | token::OrOr => true,
7198 attrs: Vec<Attribute>,
7199 macros_allowed: bool,
7200 attributes_allowed: bool,
7201 ) -> PResult<'a, Option<P<Item>>> {
7202 let (ret, tokens) = self.collect_tokens(|this| {
7203 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
7206 // Once we've parsed an item and recorded the tokens we got while
7207 // parsing we may want to store `tokens` into the item we're about to
7208 // return. Note, though, that we specifically didn't capture tokens
7209 // related to outer attributes. The `tokens` field here may later be
7210 // used with procedural macros to convert this item back into a token
7211 // stream, but during expansion we may be removing attributes as we go
7214 // If we've got inner attributes then the `tokens` we've got above holds
7215 // these inner attributes. If an inner attribute is expanded we won't
7216 // actually remove it from the token stream, so we'll just keep yielding
7217 // it (bad!). To work around this case for now we just avoid recording
7218 // `tokens` if we detect any inner attributes. This should help keep
7219 // expansion correct, but we should fix this bug one day!
7222 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7223 i.tokens = Some(tokens);
7230 /// Parse one of the items allowed by the flags.
7231 fn parse_item_implementation(
7233 attrs: Vec<Attribute>,
7234 macros_allowed: bool,
7235 attributes_allowed: bool,
7236 ) -> PResult<'a, Option<P<Item>>> {
7237 maybe_whole!(self, NtItem, |item| {
7238 let mut item = item.into_inner();
7239 let mut attrs = attrs;
7240 mem::swap(&mut item.attrs, &mut attrs);
7241 item.attrs.extend(attrs);
7247 let visibility = self.parse_visibility(false)?;
7249 if self.eat_keyword(keywords::Use) {
7251 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7252 self.expect(&token::Semi)?;
7254 let span = lo.to(self.prev_span);
7255 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7256 return Ok(Some(item));
7259 if self.eat_keyword(keywords::Extern) {
7260 if self.eat_keyword(keywords::Crate) {
7261 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7264 let opt_abi = self.parse_opt_abi()?;
7266 if self.eat_keyword(keywords::Fn) {
7267 // EXTERN FUNCTION ITEM
7268 let fn_span = self.prev_span;
7269 let abi = opt_abi.unwrap_or(Abi::C);
7270 let (ident, item_, extra_attrs) =
7271 self.parse_item_fn(Unsafety::Normal,
7273 respan(fn_span, Constness::NotConst),
7275 let prev_span = self.prev_span;
7276 let item = self.mk_item(lo.to(prev_span),
7280 maybe_append(attrs, extra_attrs));
7281 return Ok(Some(item));
7282 } else if self.check(&token::OpenDelim(token::Brace)) {
7283 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7289 if self.is_static_global() {
7292 let m = if self.eat_keyword(keywords::Mut) {
7295 Mutability::Immutable
7297 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
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.eat_keyword(keywords::Const) {
7307 let const_span = self.prev_span;
7308 if self.check_keyword(keywords::Fn)
7309 || (self.check_keyword(keywords::Unsafe)
7310 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7311 // CONST FUNCTION ITEM
7312 let unsafety = self.parse_unsafety();
7314 let (ident, item_, extra_attrs) =
7315 self.parse_item_fn(unsafety,
7317 respan(const_span, Constness::Const),
7319 let prev_span = self.prev_span;
7320 let item = self.mk_item(lo.to(prev_span),
7324 maybe_append(attrs, extra_attrs));
7325 return Ok(Some(item));
7329 if self.eat_keyword(keywords::Mut) {
7330 let prev_span = self.prev_span;
7331 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
7332 .help("did you mean to declare a static?")
7335 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
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));
7345 // `unsafe async fn` or `async fn`
7347 self.check_keyword(keywords::Unsafe) &&
7348 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7350 self.check_keyword(keywords::Async) &&
7351 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7354 // ASYNC FUNCTION ITEM
7355 let unsafety = self.parse_unsafety();
7356 self.expect_keyword(keywords::Async)?;
7357 self.expect_keyword(keywords::Fn)?;
7358 let fn_span = self.prev_span;
7359 let (ident, item_, extra_attrs) =
7360 self.parse_item_fn(unsafety,
7362 closure_id: ast::DUMMY_NODE_ID,
7363 return_impl_trait_id: ast::DUMMY_NODE_ID,
7365 respan(fn_span, Constness::NotConst),
7367 let prev_span = self.prev_span;
7368 let item = self.mk_item(lo.to(prev_span),
7372 maybe_append(attrs, extra_attrs));
7373 return Ok(Some(item));
7375 if self.check_keyword(keywords::Unsafe) &&
7376 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7377 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7379 // UNSAFE TRAIT ITEM
7380 self.bump(); // `unsafe`
7381 let is_auto = if self.eat_keyword(keywords::Trait) {
7384 self.expect_keyword(keywords::Auto)?;
7385 self.expect_keyword(keywords::Trait)?;
7388 let (ident, item_, extra_attrs) =
7389 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7390 let prev_span = self.prev_span;
7391 let item = self.mk_item(lo.to(prev_span),
7395 maybe_append(attrs, extra_attrs));
7396 return Ok(Some(item));
7398 if self.check_keyword(keywords::Impl) ||
7399 self.check_keyword(keywords::Unsafe) &&
7400 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7401 self.check_keyword(keywords::Default) &&
7402 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7403 self.check_keyword(keywords::Default) &&
7404 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7406 let defaultness = self.parse_defaultness();
7407 let unsafety = self.parse_unsafety();
7408 self.expect_keyword(keywords::Impl)?;
7409 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7410 let span = lo.to(self.prev_span);
7411 return Ok(Some(self.mk_item(span, ident, item, visibility,
7412 maybe_append(attrs, extra_attrs))));
7414 if self.check_keyword(keywords::Fn) {
7417 let fn_span = self.prev_span;
7418 let (ident, item_, extra_attrs) =
7419 self.parse_item_fn(Unsafety::Normal,
7421 respan(fn_span, Constness::NotConst),
7423 let prev_span = self.prev_span;
7424 let item = self.mk_item(lo.to(prev_span),
7428 maybe_append(attrs, extra_attrs));
7429 return Ok(Some(item));
7431 if self.check_keyword(keywords::Unsafe)
7432 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7433 // UNSAFE FUNCTION ITEM
7434 self.bump(); // `unsafe`
7435 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7436 self.check(&token::OpenDelim(token::Brace));
7437 let abi = if self.eat_keyword(keywords::Extern) {
7438 self.parse_opt_abi()?.unwrap_or(Abi::C)
7442 self.expect_keyword(keywords::Fn)?;
7443 let fn_span = self.prev_span;
7444 let (ident, item_, extra_attrs) =
7445 self.parse_item_fn(Unsafety::Unsafe,
7447 respan(fn_span, Constness::NotConst),
7449 let prev_span = self.prev_span;
7450 let item = self.mk_item(lo.to(prev_span),
7454 maybe_append(attrs, extra_attrs));
7455 return Ok(Some(item));
7457 if self.eat_keyword(keywords::Mod) {
7459 let (ident, item_, extra_attrs) =
7460 self.parse_item_mod(&attrs[..])?;
7461 let prev_span = self.prev_span;
7462 let item = self.mk_item(lo.to(prev_span),
7466 maybe_append(attrs, extra_attrs));
7467 return Ok(Some(item));
7469 if let Some(type_) = self.eat_type() {
7470 let (ident, alias, generics) = type_?;
7472 let item_ = match alias {
7473 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7474 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7476 let prev_span = self.prev_span;
7477 let item = self.mk_item(lo.to(prev_span),
7482 return Ok(Some(item));
7484 if self.eat_keyword(keywords::Enum) {
7486 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7487 let prev_span = self.prev_span;
7488 let item = self.mk_item(lo.to(prev_span),
7492 maybe_append(attrs, extra_attrs));
7493 return Ok(Some(item));
7495 if self.check_keyword(keywords::Trait)
7496 || (self.check_keyword(keywords::Auto)
7497 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7499 let is_auto = if self.eat_keyword(keywords::Trait) {
7502 self.expect_keyword(keywords::Auto)?;
7503 self.expect_keyword(keywords::Trait)?;
7507 let (ident, item_, extra_attrs) =
7508 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7509 let prev_span = self.prev_span;
7510 let item = self.mk_item(lo.to(prev_span),
7514 maybe_append(attrs, extra_attrs));
7515 return Ok(Some(item));
7517 if self.eat_keyword(keywords::Struct) {
7519 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7520 let prev_span = self.prev_span;
7521 let item = self.mk_item(lo.to(prev_span),
7525 maybe_append(attrs, extra_attrs));
7526 return Ok(Some(item));
7528 if self.is_union_item() {
7531 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7532 let prev_span = self.prev_span;
7533 let item = self.mk_item(lo.to(prev_span),
7537 maybe_append(attrs, extra_attrs));
7538 return Ok(Some(item));
7540 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7541 return Ok(Some(macro_def));
7544 // Verify whether we have encountered a struct or method definition where the user forgot to
7545 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7546 if visibility.node.is_pub() &&
7547 self.check_ident() &&
7548 self.look_ahead(1, |t| *t != token::Not)
7550 // Space between `pub` keyword and the identifier
7553 // ^^^ `sp` points here
7554 let sp = self.prev_span.between(self.span);
7555 let full_sp = self.prev_span.to(self.span);
7556 let ident_sp = self.span;
7557 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7558 // possible public struct definition where `struct` was forgotten
7559 let ident = self.parse_ident().unwrap();
7560 let msg = format!("add `struct` here to parse `{}` as a public struct",
7562 let mut err = self.diagnostic()
7563 .struct_span_err(sp, "missing `struct` for struct definition");
7564 err.span_suggestion_short_with_applicability(
7565 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7568 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7569 let ident = self.parse_ident().unwrap();
7571 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
7576 self.consume_block(token::Paren);
7577 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7578 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7580 ("fn", kw_name, false)
7581 } else if self.check(&token::OpenDelim(token::Brace)) {
7583 ("fn", kw_name, false)
7584 } else if self.check(&token::Colon) {
7588 ("fn` or `struct", "function or struct", true)
7590 self.consume_block(token::Brace);
7592 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7593 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7595 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7599 err.span_suggestion_short_with_applicability(
7600 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7603 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7604 err.span_suggestion_with_applicability(
7606 "if you meant to call a macro, try",
7607 format!("{}!", snippet),
7608 // this is the `ambiguous` conditional branch
7609 Applicability::MaybeIncorrect
7612 err.help("if you meant to call a macro, remove the `pub` \
7613 and add a trailing `!` after the identifier");
7617 } else if self.look_ahead(1, |t| *t == token::Lt) {
7618 let ident = self.parse_ident().unwrap();
7619 self.eat_to_tokens(&[&token::Gt]);
7621 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7622 if let Ok(Some(_)) = self.parse_self_arg() {
7623 ("fn", "method", false)
7625 ("fn", "function", false)
7627 } else if self.check(&token::OpenDelim(token::Brace)) {
7628 ("struct", "struct", false)
7630 ("fn` or `struct", "function or struct", true)
7632 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7633 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7635 err.span_suggestion_short_with_applicability(
7637 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7638 format!(" {} ", kw),
7639 Applicability::MachineApplicable,
7645 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7648 /// Parse a foreign item.
7649 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7650 maybe_whole!(self, NtForeignItem, |ni| ni);
7652 let attrs = self.parse_outer_attributes()?;
7654 let visibility = self.parse_visibility(false)?;
7656 // FOREIGN STATIC ITEM
7657 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7658 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7659 if self.token.is_keyword(keywords::Const) {
7661 .struct_span_err(self.span, "extern items cannot be `const`")
7662 .span_suggestion_with_applicability(
7664 "try using a static value",
7665 "static".to_owned(),
7666 Applicability::MachineApplicable
7669 self.bump(); // `static` or `const`
7670 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7672 // FOREIGN FUNCTION ITEM
7673 if self.check_keyword(keywords::Fn) {
7674 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7676 // FOREIGN TYPE ITEM
7677 if self.check_keyword(keywords::Type) {
7678 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7681 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7685 ident: keywords::Invalid.ident(),
7686 span: lo.to(self.prev_span),
7687 id: ast::DUMMY_NODE_ID,
7690 node: ForeignItemKind::Macro(mac),
7695 if !attrs.is_empty() {
7696 self.expected_item_err(&attrs);
7704 /// This is the fall-through for parsing items.
7705 fn parse_macro_use_or_failure(
7707 attrs: Vec<Attribute> ,
7708 macros_allowed: bool,
7709 attributes_allowed: bool,
7711 visibility: Visibility
7712 ) -> PResult<'a, Option<P<Item>>> {
7713 if macros_allowed && self.token.is_path_start() {
7714 // MACRO INVOCATION ITEM
7716 let prev_span = self.prev_span;
7717 self.complain_if_pub_macro(&visibility.node, prev_span);
7719 let mac_lo = self.span;
7722 let pth = self.parse_path(PathStyle::Mod)?;
7723 self.expect(&token::Not)?;
7725 // a 'special' identifier (like what `macro_rules!` uses)
7726 // is optional. We should eventually unify invoc syntax
7728 let id = if self.token.is_ident() {
7731 keywords::Invalid.ident() // no special identifier
7733 // eat a matched-delimiter token tree:
7734 let (delim, tts) = self.expect_delimited_token_tree()?;
7735 if delim != MacDelimiter::Brace {
7736 if !self.eat(&token::Semi) {
7737 self.span_err(self.prev_span,
7738 "macros that expand to items must either \
7739 be surrounded with braces or followed by \
7744 let hi = self.prev_span;
7745 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7746 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7747 return Ok(Some(item));
7750 // FAILURE TO PARSE ITEM
7751 match visibility.node {
7752 VisibilityKind::Inherited => {}
7754 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7758 if !attributes_allowed && !attrs.is_empty() {
7759 self.expected_item_err(&attrs);
7764 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7765 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7766 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7768 if self.token.is_path_start() {
7769 let prev_span = self.prev_span;
7771 let pth = self.parse_path(PathStyle::Mod)?;
7773 if pth.segments.len() == 1 {
7774 if !self.eat(&token::Not) {
7775 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7778 self.expect(&token::Not)?;
7781 if let Some(vis) = vis {
7782 self.complain_if_pub_macro(&vis.node, prev_span);
7787 // eat a matched-delimiter token tree:
7788 let (delim, tts) = self.expect_delimited_token_tree()?;
7789 if delim != MacDelimiter::Brace {
7790 self.expect(&token::Semi)?
7793 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7799 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7800 where F: FnOnce(&mut Self) -> PResult<'a, R>
7802 // Record all tokens we parse when parsing this item.
7803 let mut tokens = Vec::new();
7804 let prev_collecting = match self.token_cursor.frame.last_token {
7805 LastToken::Collecting(ref mut list) => {
7806 Some(mem::replace(list, Vec::new()))
7808 LastToken::Was(ref mut last) => {
7809 tokens.extend(last.take());
7813 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7814 let prev = self.token_cursor.stack.len();
7816 let last_token = if self.token_cursor.stack.len() == prev {
7817 &mut self.token_cursor.frame.last_token
7819 &mut self.token_cursor.stack[prev].last_token
7822 // Pull out the tokens that we've collected from the call to `f` above.
7823 let mut collected_tokens = match *last_token {
7824 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7825 LastToken::Was(_) => panic!("our vector went away?"),
7828 // If we're not at EOF our current token wasn't actually consumed by
7829 // `f`, but it'll still be in our list that we pulled out. In that case
7831 let extra_token = if self.token != token::Eof {
7832 collected_tokens.pop()
7837 // If we were previously collecting tokens, then this was a recursive
7838 // call. In that case we need to record all the tokens we collected in
7839 // our parent list as well. To do that we push a clone of our stream
7840 // onto the previous list.
7841 match prev_collecting {
7843 list.extend(collected_tokens.iter().cloned());
7844 list.extend(extra_token);
7845 *last_token = LastToken::Collecting(list);
7848 *last_token = LastToken::Was(extra_token);
7852 Ok((ret?, TokenStream::new(collected_tokens)))
7855 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7856 let attrs = self.parse_outer_attributes()?;
7857 self.parse_item_(attrs, true, false)
7861 fn is_import_coupler(&mut self) -> bool {
7862 self.check(&token::ModSep) &&
7863 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7864 *t == token::BinOp(token::Star))
7869 /// USE_TREE = [`::`] `*` |
7870 /// [`::`] `{` USE_TREE_LIST `}` |
7872 /// PATH `::` `{` USE_TREE_LIST `}` |
7873 /// PATH [`as` IDENT]
7874 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7877 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7878 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7879 self.check(&token::BinOp(token::Star)) ||
7880 self.is_import_coupler() {
7881 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7882 let mod_sep_ctxt = self.span.ctxt();
7883 if self.eat(&token::ModSep) {
7884 prefix.segments.push(
7885 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7889 if self.eat(&token::BinOp(token::Star)) {
7892 UseTreeKind::Nested(self.parse_use_tree_list()?)
7895 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7896 prefix = self.parse_path(PathStyle::Mod)?;
7898 if self.eat(&token::ModSep) {
7899 if self.eat(&token::BinOp(token::Star)) {
7902 UseTreeKind::Nested(self.parse_use_tree_list()?)
7905 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7909 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7912 /// Parse UseTreeKind::Nested(list)
7914 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7915 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7916 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7917 &token::CloseDelim(token::Brace),
7918 SeqSep::trailing_allowed(token::Comma), |this| {
7919 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7923 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7924 if self.eat_keyword(keywords::As) {
7925 self.parse_ident_or_underscore().map(Some)
7931 /// Parses a source module as a crate. This is the main
7932 /// entry point for the parser.
7933 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7936 attrs: self.parse_inner_attributes()?,
7937 module: self.parse_mod_items(&token::Eof, lo)?,
7938 span: lo.to(self.span),
7942 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7943 let ret = match self.token {
7944 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7945 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7952 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7953 match self.parse_optional_str() {
7954 Some((s, style, suf)) => {
7955 let sp = self.prev_span;
7956 self.expect_no_suffix(sp, "string literal", suf);
7960 let msg = "expected string literal";
7961 let mut err = self.fatal(msg);
7962 err.span_label(self.span, msg);