1 use crate::ast::{AngleBracketedArgs, ParenthesizedArgs, AttrStyle, BareFnTy};
2 use crate::ast::{GenericBound, TraitBoundModifier};
3 use crate::ast::Unsafety;
4 use crate::ast::{Mod, AnonConst, Arg, Arm, Guard, Attribute, BindingMode, TraitItemKind};
6 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
7 use crate::ast::{Constness, Crate};
8 use crate::ast::Defaultness;
9 use crate::ast::EnumDef;
10 use crate::ast::{Expr, ExprKind, RangeLimits};
11 use crate::ast::{Field, FnDecl, FnHeader};
12 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
13 use crate::ast::{GenericParam, GenericParamKind};
14 use crate::ast::GenericArg;
15 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
16 use crate::ast::{Label, Lifetime, Lit, LitKind};
17 use crate::ast::Local;
18 use crate::ast::MacStmtStyle;
19 use crate::ast::{Mac, Mac_, MacDelimiter};
20 use crate::ast::{MutTy, Mutability};
21 use crate::ast::{Pat, PatKind, PathSegment};
22 use crate::ast::{PolyTraitRef, QSelf};
23 use crate::ast::{Stmt, StmtKind};
24 use crate::ast::{VariantData, StructField};
25 use crate::ast::StrStyle;
26 use crate::ast::SelfKind;
27 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
28 use crate::ast::{Ty, TyKind, TypeBinding, GenericBounds};
29 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
30 use crate::ast::{UseTree, UseTreeKind};
31 use crate::ast::{BinOpKind, UnOp};
32 use crate::ast::{RangeEnd, RangeSyntax};
33 use crate::{ast, attr};
34 use crate::ext::base::DummyResult;
35 use crate::source_map::{self, SourceMap, Spanned, respan};
36 use crate::parse::{self, SeqSep, classify, token};
37 use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace};
38 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
39 use crate::parse::token::DelimToken;
40 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
41 use crate::util::parser::{AssocOp, Fixity};
42 use crate::print::pprust;
44 use crate::parse::PResult;
46 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
47 use crate::symbol::{Symbol, keywords};
49 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
50 use rustc_target::spec::abi::{self, Abi};
51 use syntax_pos::{Span, MultiSpan, BytePos, FileName};
52 use log::{debug, trace};
57 use std::path::{self, Path, PathBuf};
61 /// Whether the type alias or associated type is a concrete type or an existential type
63 /// Just a new name for the same type
65 /// Only trait impls of the type will be usable, not the actual type itself
66 Existential(GenericBounds),
70 struct Restrictions: u8 {
71 const STMT_EXPR = 1 << 0;
72 const NO_STRUCT_LITERAL = 1 << 1;
76 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
78 /// Specifies how to parse a path.
79 #[derive(Copy, Clone, PartialEq)]
81 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
82 /// with something else. For example, in expressions `segment < ....` can be interpreted
83 /// as a comparison and `segment ( ....` can be interpreted as a function call.
84 /// In all such contexts the non-path interpretation is preferred by default for practical
85 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
86 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
88 /// In other contexts, notably in types, no ambiguity exists and paths can be written
89 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
90 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
92 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
93 /// visibilities or attributes.
94 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
95 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
96 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
97 /// tokens when something goes wrong.
101 #[derive(Clone, Copy, PartialEq, Debug)]
108 #[derive(Clone, Copy, PartialEq, Debug)]
114 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
115 /// dropped into the token stream, which happens while parsing the result of
116 /// macro expansion). Placement of these is not as complex as I feared it would
117 /// be. The important thing is to make sure that lookahead doesn't balk at
118 /// `token::Interpolated` tokens.
119 macro_rules! maybe_whole_expr {
121 if let token::Interpolated(nt) = &$p.token {
123 token::NtExpr(e) | token::NtLiteral(e) => {
128 token::NtPath(path) => {
129 let path = path.clone();
131 return Ok($p.mk_expr($p.span, ExprKind::Path(None, path), ThinVec::new()));
133 token::NtBlock(block) => {
134 let block = block.clone();
136 return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
144 /// As maybe_whole_expr, but for things other than expressions
145 macro_rules! maybe_whole {
146 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
147 if let token::Interpolated(nt) = &$p.token {
148 if let token::$constructor(x) = &**nt {
157 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
158 macro_rules! maybe_recover_from_interpolated_ty_qpath {
159 ($self: expr, $allow_qpath_recovery: expr) => {
160 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
161 if let token::Interpolated(nt) = &$self.token {
162 if let token::NtTy(ty) = &**nt {
165 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
172 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
173 if let Some(ref mut rhs) = rhs {
179 #[derive(Debug, Clone, Copy, PartialEq)]
190 trait RecoverQPath: Sized + 'static {
191 const PATH_STYLE: PathStyle = PathStyle::Expr;
192 fn to_ty(&self) -> Option<P<Ty>>;
193 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
196 impl RecoverQPath for Ty {
197 const PATH_STYLE: PathStyle = PathStyle::Type;
198 fn to_ty(&self) -> Option<P<Ty>> {
199 Some(P(self.clone()))
201 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
202 Self { span: path.span, node: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
206 impl RecoverQPath for Pat {
207 fn to_ty(&self) -> Option<P<Ty>> {
210 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
211 Self { span: path.span, node: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
215 impl RecoverQPath for Expr {
216 fn to_ty(&self) -> Option<P<Ty>> {
219 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
220 Self { span: path.span, node: ExprKind::Path(qself, path),
221 attrs: ThinVec::new(), id: ast::DUMMY_NODE_ID }
225 /* ident is handled by common.rs */
228 pub struct Parser<'a> {
229 pub sess: &'a ParseSess,
230 /// the current token:
231 pub token: token::Token,
232 /// the span of the current token:
234 /// the span of the previous token:
235 meta_var_span: Option<Span>,
237 /// the previous token kind
238 prev_token_kind: PrevTokenKind,
239 restrictions: Restrictions,
240 /// Used to determine the path to externally loaded source files
241 crate directory: Directory<'a>,
242 /// Whether to parse sub-modules in other files.
243 pub recurse_into_file_modules: bool,
244 /// Name of the root module this parser originated from. If `None`, then the
245 /// name is not known. This does not change while the parser is descending
246 /// into modules, and sub-parsers have new values for this name.
247 pub root_module_name: Option<String>,
248 crate expected_tokens: Vec<TokenType>,
249 token_cursor: TokenCursor,
250 desugar_doc_comments: bool,
251 /// Whether we should configure out of line modules as we parse.
253 /// This field is used to keep track of how many left angle brackets we have seen. This is
254 /// required in order to detect extra leading left angle brackets (`<` characters) and error
257 /// See the comments in the `parse_path_segment` function for more details.
258 crate unmatched_angle_bracket_count: u32,
259 crate max_angle_bracket_count: u32,
260 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
261 /// it gets removed from here. Every entry left at the end gets emitted as an independent
263 crate unclosed_delims: Vec<UnmatchedBrace>,
264 last_unexpected_token_span: Option<Span>,
267 impl<'a> Drop for Parser<'a> {
269 let diag = self.diagnostic();
270 emit_unclosed_delims(&mut self.unclosed_delims, diag);
276 frame: TokenCursorFrame,
277 stack: Vec<TokenCursorFrame>,
281 struct TokenCursorFrame {
282 delim: token::DelimToken,
285 tree_cursor: tokenstream::Cursor,
287 last_token: LastToken,
290 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
291 /// by the parser, and then that's transitively used to record the tokens that
292 /// each parse AST item is created with.
294 /// Right now this has two states, either collecting tokens or not collecting
295 /// tokens. If we're collecting tokens we just save everything off into a local
296 /// `Vec`. This should eventually though likely save tokens from the original
297 /// token stream and just use slicing of token streams to avoid creation of a
298 /// whole new vector.
300 /// The second state is where we're passively not recording tokens, but the last
301 /// token is still tracked for when we want to start recording tokens. This
302 /// "last token" means that when we start recording tokens we'll want to ensure
303 /// that this, the first token, is included in the output.
305 /// You can find some more example usage of this in the `collect_tokens` method
309 Collecting(Vec<TreeAndJoint>),
310 Was(Option<TreeAndJoint>),
313 impl TokenCursorFrame {
314 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
318 open_delim: delim == token::NoDelim,
319 tree_cursor: tts.clone().into_trees(),
320 close_delim: delim == token::NoDelim,
321 last_token: LastToken::Was(None),
327 fn next(&mut self) -> TokenAndSpan {
329 let tree = if !self.frame.open_delim {
330 self.frame.open_delim = true;
331 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
332 } else if let Some(tree) = self.frame.tree_cursor.next() {
334 } else if !self.frame.close_delim {
335 self.frame.close_delim = true;
336 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
337 } else if let Some(frame) = self.stack.pop() {
341 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
344 match self.frame.last_token {
345 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
346 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
350 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
351 TokenTree::Delimited(sp, delim, tts) => {
352 let frame = TokenCursorFrame::new(sp, delim, &tts);
353 self.stack.push(mem::replace(&mut self.frame, frame));
359 fn next_desugared(&mut self) -> TokenAndSpan {
360 let (sp, name) = match self.next() {
361 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
365 let stripped = strip_doc_comment_decoration(&name.as_str());
367 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
368 // required to wrap the text.
369 let mut num_of_hashes = 0;
371 for ch in stripped.chars() {
374 '#' if count > 0 => count + 1,
377 num_of_hashes = cmp::max(num_of_hashes, count);
380 let delim_span = DelimSpan::from_single(sp);
381 let body = TokenTree::Delimited(
384 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
385 TokenTree::Token(sp, token::Eq),
386 TokenTree::Token(sp, token::Literal(
387 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
389 .iter().cloned().collect::<TokenStream>().into(),
392 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
395 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
396 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
397 .iter().cloned().collect::<TokenStream>().into()
399 [TokenTree::Token(sp, token::Pound), body]
400 .iter().cloned().collect::<TokenStream>().into()
408 #[derive(Clone, PartialEq)]
409 crate enum TokenType {
411 Keyword(keywords::Keyword),
421 fn to_string(&self) -> String {
423 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
424 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
425 TokenType::Operator => "an operator".to_string(),
426 TokenType::Lifetime => "lifetime".to_string(),
427 TokenType::Ident => "identifier".to_string(),
428 TokenType::Path => "path".to_string(),
429 TokenType::Type => "type".to_string(),
430 TokenType::Const => "const".to_string(),
435 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
436 /// `IDENT<<u8 as Trait>::AssocTy>`.
438 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
439 /// that `IDENT` is not the ident of a fn trait.
440 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
441 t == &token::ModSep || t == &token::Lt ||
442 t == &token::BinOp(token::Shl)
445 /// Information about the path to a module.
446 pub struct ModulePath {
449 pub result: Result<ModulePathSuccess, Error>,
452 pub struct ModulePathSuccess {
454 pub directory_ownership: DirectoryOwnership,
459 FileNotFoundForModule {
461 default_path: String,
462 secondary_path: String,
467 default_path: String,
468 secondary_path: String,
471 InclusiveRangeWithNoEnd,
475 fn span_err<S: Into<MultiSpan>>(self,
477 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
479 Error::FileNotFoundForModule { ref mod_name,
483 let mut err = struct_span_err!(handler, sp, E0583,
484 "file not found for module `{}`", mod_name);
485 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
491 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
492 let mut err = struct_span_err!(handler, sp, E0584,
493 "file for module `{}` found at both {} and {}",
497 err.help("delete or rename one of them to remove the ambiguity");
500 Error::UselessDocComment => {
501 let mut err = struct_span_err!(handler, sp, E0585,
502 "found a documentation comment that doesn't document anything");
503 err.help("doc comments must come before what they document, maybe a comment was \
504 intended with `//`?");
507 Error::InclusiveRangeWithNoEnd => {
508 let mut err = struct_span_err!(handler, sp, E0586,
509 "inclusive range with no end");
510 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
520 AttributesParsed(ThinVec<Attribute>),
521 AlreadyParsed(P<Expr>),
524 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
525 fn from(o: Option<ThinVec<Attribute>>) -> Self {
526 if let Some(attrs) = o {
527 LhsExpr::AttributesParsed(attrs)
529 LhsExpr::NotYetParsed
534 impl From<P<Expr>> for LhsExpr {
535 fn from(expr: P<Expr>) -> Self {
536 LhsExpr::AlreadyParsed(expr)
540 /// Creates a placeholder argument.
541 fn dummy_arg(span: Span) -> Arg {
542 let ident = Ident::new(keywords::Invalid.name(), span);
544 id: ast::DUMMY_NODE_ID,
545 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
551 id: ast::DUMMY_NODE_ID
553 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
556 #[derive(Copy, Clone, Debug)]
557 enum TokenExpectType {
562 impl<'a> Parser<'a> {
563 pub fn new(sess: &'a ParseSess,
565 directory: Option<Directory<'a>>,
566 recurse_into_file_modules: bool,
567 desugar_doc_comments: bool)
569 let mut parser = Parser {
571 token: token::Whitespace,
572 span: syntax_pos::DUMMY_SP,
573 prev_span: syntax_pos::DUMMY_SP,
575 prev_token_kind: PrevTokenKind::Other,
576 restrictions: Restrictions::empty(),
577 recurse_into_file_modules,
578 directory: Directory {
579 path: Cow::from(PathBuf::new()),
580 ownership: DirectoryOwnership::Owned { relative: None }
582 root_module_name: None,
583 expected_tokens: Vec::new(),
584 token_cursor: TokenCursor {
585 frame: TokenCursorFrame::new(
592 desugar_doc_comments,
594 unmatched_angle_bracket_count: 0,
595 max_angle_bracket_count: 0,
596 unclosed_delims: Vec::new(),
597 last_unexpected_token_span: None,
600 let tok = parser.next_tok();
601 parser.token = tok.tok;
602 parser.span = tok.sp;
604 if let Some(directory) = directory {
605 parser.directory = directory;
606 } else if !parser.span.is_dummy() {
607 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
609 parser.directory.path = Cow::from(path);
613 parser.process_potential_macro_variable();
617 fn next_tok(&mut self) -> TokenAndSpan {
618 let mut next = if self.desugar_doc_comments {
619 self.token_cursor.next_desugared()
621 self.token_cursor.next()
623 if next.sp.is_dummy() {
624 // Tweak the location for better diagnostics, but keep syntactic context intact.
625 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
630 /// Converts the current token to a string using `self`'s reader.
631 pub fn this_token_to_string(&self) -> String {
632 pprust::token_to_string(&self.token)
635 fn token_descr(&self) -> Option<&'static str> {
636 Some(match &self.token {
637 t if t.is_special_ident() => "reserved identifier",
638 t if t.is_used_keyword() => "keyword",
639 t if t.is_unused_keyword() => "reserved keyword",
640 token::DocComment(..) => "doc comment",
645 fn this_token_descr(&self) -> String {
646 if let Some(prefix) = self.token_descr() {
647 format!("{} `{}`", prefix, self.this_token_to_string())
649 format!("`{}`", self.this_token_to_string())
653 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
654 let token_str = pprust::token_to_string(t);
655 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
658 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
659 match self.expect_one_of(&[], &[]) {
661 Ok(_) => unreachable!(),
665 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
666 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
667 if self.expected_tokens.is_empty() {
668 if self.token == *t {
672 let token_str = pprust::token_to_string(t);
673 let this_token_str = self.this_token_descr();
674 let mut err = self.fatal(&format!("expected `{}`, found {}",
678 let sp = if self.token == token::Token::Eof {
679 // EOF, don't want to point at the following char, but rather the last token
682 self.sess.source_map().next_point(self.prev_span)
684 let label_exp = format!("expected `{}`", token_str);
685 match self.recover_closing_delimiter(&[t.clone()], err) {
688 return Ok(recovered);
691 let cm = self.sess.source_map();
692 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
693 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
694 // When the spans are in the same line, it means that the only content
695 // between them is whitespace, point only at the found token.
696 err.span_label(self.span, label_exp);
699 err.span_label(sp, label_exp);
700 err.span_label(self.span, "unexpected token");
706 self.expect_one_of(slice::from_ref(t), &[])
710 fn recover_closing_delimiter(
712 tokens: &[token::Token],
713 mut err: DiagnosticBuilder<'a>,
714 ) -> PResult<'a, bool> {
716 // we want to use the last closing delim that would apply
717 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
718 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
719 && Some(self.span) > unmatched.unclosed_span
726 // Recover and assume that the detected unclosed delimiter was meant for
727 // this location. Emit the diagnostic and act as if the delimiter was
728 // present for the parser's sake.
730 // Don't attempt to recover from this unclosed delimiter more than once.
731 let unmatched = self.unclosed_delims.remove(pos);
732 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
734 // We want to suggest the inclusion of the closing delimiter where it makes
735 // the most sense, which is immediately after the last token:
740 // | help: `)` may belong here (FIXME: #58270)
742 // unclosed delimiter
743 if let Some(sp) = unmatched.unclosed_span {
744 err.span_label(sp, "unclosed delimiter");
746 err.span_suggestion_short(
747 self.sess.source_map().next_point(self.prev_span),
748 &format!("{} may belong here", delim.to_string()),
750 Applicability::MaybeIncorrect,
753 self.expected_tokens.clear(); // reduce errors
760 /// Expect next token to be edible or inedible token. If edible,
761 /// then consume it; if inedible, then return without consuming
762 /// anything. Signal a fatal error if next token is unexpected.
763 pub fn expect_one_of(
765 edible: &[token::Token],
766 inedible: &[token::Token],
767 ) -> PResult<'a, bool /* recovered */> {
768 fn tokens_to_string(tokens: &[TokenType]) -> String {
769 let mut i = tokens.iter();
770 // This might be a sign we need a connect method on Iterator.
772 .map_or(String::new(), |t| t.to_string());
773 i.enumerate().fold(b, |mut b, (i, a)| {
774 if tokens.len() > 2 && i == tokens.len() - 2 {
776 } else if tokens.len() == 2 && i == tokens.len() - 2 {
781 b.push_str(&a.to_string());
785 if edible.contains(&self.token) {
788 } else if inedible.contains(&self.token) {
789 // leave it in the input
791 } else if self.last_unexpected_token_span == Some(self.span) {
794 let mut expected = edible.iter()
795 .map(|x| TokenType::Token(x.clone()))
796 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
797 .chain(self.expected_tokens.iter().cloned())
798 .collect::<Vec<_>>();
799 expected.sort_by_cached_key(|x| x.to_string());
801 let expect = tokens_to_string(&expected[..]);
802 let actual = self.this_token_to_string();
803 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
804 let short_expect = if expected.len() > 6 {
805 format!("{} possible tokens", expected.len())
809 (format!("expected one of {}, found `{}`", expect, actual),
810 (self.sess.source_map().next_point(self.prev_span),
811 format!("expected one of {} here", short_expect)))
812 } else if expected.is_empty() {
813 (format!("unexpected token: `{}`", actual),
814 (self.prev_span, "unexpected token after this".to_string()))
816 (format!("expected {}, found `{}`", expect, actual),
817 (self.sess.source_map().next_point(self.prev_span),
818 format!("expected {} here", expect)))
820 self.last_unexpected_token_span = Some(self.span);
821 let mut err = self.fatal(&msg_exp);
822 if self.token.is_ident_named("and") {
823 err.span_suggestion_short(
825 "use `&&` instead of `and` for the boolean operator",
827 Applicability::MaybeIncorrect,
830 if self.token.is_ident_named("or") {
831 err.span_suggestion_short(
833 "use `||` instead of `or` for the boolean operator",
835 Applicability::MaybeIncorrect,
838 let sp = if self.token == token::Token::Eof {
839 // This is EOF, don't want to point at the following char, but rather the last token
844 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
845 TokenType::Token(t) => Some(t.clone()),
847 }).collect::<Vec<_>>(), err) {
850 return Ok(recovered);
854 let cm = self.sess.source_map();
855 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
856 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
857 // When the spans are in the same line, it means that the only content between
858 // them is whitespace, point at the found token in that case:
860 // X | () => { syntax error };
861 // | ^^^^^ expected one of 8 possible tokens here
863 // instead of having:
865 // X | () => { syntax error };
866 // | -^^^^^ unexpected token
868 // | expected one of 8 possible tokens here
869 err.span_label(self.span, label_exp);
871 _ if self.prev_span == syntax_pos::DUMMY_SP => {
872 // Account for macro context where the previous span might not be
873 // available to avoid incorrect output (#54841).
874 err.span_label(self.span, "unexpected token");
877 err.span_label(sp, label_exp);
878 err.span_label(self.span, "unexpected token");
885 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
886 fn interpolated_or_expr_span(&self,
887 expr: PResult<'a, P<Expr>>)
888 -> PResult<'a, (Span, P<Expr>)> {
890 if self.prev_token_kind == PrevTokenKind::Interpolated {
898 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
899 let mut err = self.struct_span_err(self.span,
900 &format!("expected identifier, found {}",
901 self.this_token_descr()));
902 if let token::Ident(ident, false) = &self.token {
903 if ident.is_raw_guess() {
906 "you can escape reserved keywords to use them as identifiers",
907 format!("r#{}", ident),
908 Applicability::MaybeIncorrect,
912 if let Some(token_descr) = self.token_descr() {
913 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
915 err.span_label(self.span, "expected identifier");
916 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
921 Applicability::MachineApplicable,
928 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
929 self.parse_ident_common(true)
932 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
934 token::Ident(ident, _) => {
935 if self.token.is_reserved_ident() {
936 let mut err = self.expected_ident_found();
943 let span = self.span;
945 Ok(Ident::new(ident.name, span))
948 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
949 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
951 self.expected_ident_found()
957 /// Checks if the next token is `tok`, and returns `true` if so.
959 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
961 crate fn check(&mut self, tok: &token::Token) -> bool {
962 let is_present = self.token == *tok;
963 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
967 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
968 pub fn eat(&mut self, tok: &token::Token) -> bool {
969 let is_present = self.check(tok);
970 if is_present { self.bump() }
974 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
975 self.expected_tokens.push(TokenType::Keyword(kw));
976 self.token.is_keyword(kw)
979 /// If the next token is the given keyword, eats it and returns
980 /// `true`. Otherwise, returns `false`.
981 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
982 if self.check_keyword(kw) {
990 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
991 if self.token.is_keyword(kw) {
999 /// If the given word is not a keyword, signals an error.
1000 /// If the next token is not the given word, signals an error.
1001 /// Otherwise, eats it.
1002 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
1003 if !self.eat_keyword(kw) {
1010 fn check_ident(&mut self) -> bool {
1011 if self.token.is_ident() {
1014 self.expected_tokens.push(TokenType::Ident);
1019 fn check_path(&mut self) -> bool {
1020 if self.token.is_path_start() {
1023 self.expected_tokens.push(TokenType::Path);
1028 fn check_type(&mut self) -> bool {
1029 if self.token.can_begin_type() {
1032 self.expected_tokens.push(TokenType::Type);
1037 fn check_const_arg(&mut self) -> bool {
1038 if self.token.can_begin_const_arg() {
1041 self.expected_tokens.push(TokenType::Const);
1046 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
1047 /// and continues. If a `+` is not seen, returns `false`.
1049 /// This is used when token-splitting `+=` into `+`.
1050 /// See issue #47856 for an example of when this may occur.
1051 fn eat_plus(&mut self) -> bool {
1052 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1054 token::BinOp(token::Plus) => {
1058 token::BinOpEq(token::Plus) => {
1059 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1060 self.bump_with(token::Eq, span);
1068 /// Checks to see if the next token is either `+` or `+=`.
1069 /// Otherwise returns `false`.
1070 fn check_plus(&mut self) -> bool {
1071 if self.token.is_like_plus() {
1075 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1080 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1081 /// `&` and continues. If an `&` is not seen, signals an error.
1082 fn expect_and(&mut self) -> PResult<'a, ()> {
1083 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1085 token::BinOp(token::And) => {
1090 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1091 Ok(self.bump_with(token::BinOp(token::And), span))
1093 _ => self.unexpected()
1097 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1098 /// `|` and continues. If an `|` is not seen, signals an error.
1099 fn expect_or(&mut self) -> PResult<'a, ()> {
1100 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1102 token::BinOp(token::Or) => {
1107 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1108 Ok(self.bump_with(token::BinOp(token::Or), span))
1110 _ => self.unexpected()
1114 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1116 None => {/* everything ok */}
1118 let text = suf.as_str();
1119 if text.is_empty() {
1120 self.span_bug(sp, "found empty literal suffix in Some")
1122 let msg = format!("{} with a suffix is invalid", kind);
1123 self.struct_span_err(sp, &msg)
1124 .span_label(sp, msg)
1130 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1131 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1132 /// and continue. If a `<` is not seen, returns false.
1134 /// This is meant to be used when parsing generics on a path to get the
1136 fn eat_lt(&mut self) -> bool {
1137 self.expected_tokens.push(TokenType::Token(token::Lt));
1138 let ate = match self.token {
1143 token::BinOp(token::Shl) => {
1144 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1145 self.bump_with(token::Lt, span);
1149 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1150 self.bump_with(token::BinOp(token::Minus), span);
1157 // See doc comment for `unmatched_angle_bracket_count`.
1158 self.unmatched_angle_bracket_count += 1;
1159 self.max_angle_bracket_count += 1;
1160 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1166 fn expect_lt(&mut self) -> PResult<'a, ()> {
1174 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1175 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1176 fn expect_gt(&mut self) -> PResult<'a, ()> {
1177 self.expected_tokens.push(TokenType::Token(token::Gt));
1178 let ate = match self.token {
1183 token::BinOp(token::Shr) => {
1184 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1185 Some(self.bump_with(token::Gt, span))
1187 token::BinOpEq(token::Shr) => {
1188 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1189 Some(self.bump_with(token::Ge, span))
1192 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1193 Some(self.bump_with(token::Eq, span))
1200 // See doc comment for `unmatched_angle_bracket_count`.
1201 if self.unmatched_angle_bracket_count > 0 {
1202 self.unmatched_angle_bracket_count -= 1;
1203 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1208 None => self.unexpected(),
1212 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1213 /// passes through any errors encountered. Used for error recovery.
1214 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1215 let handler = self.diagnostic();
1217 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1219 TokenExpectType::Expect,
1220 |p| Ok(p.parse_token_tree())) {
1221 handler.cancel(err);
1225 /// Parses a sequence, including the closing delimiter. The function
1226 /// `f` must consume tokens until reaching the next separator or
1227 /// closing bracket.
1228 pub fn parse_seq_to_end<T, F>(&mut self,
1232 -> PResult<'a, Vec<T>> where
1233 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1235 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1242 /// Parses a sequence, not including the closing delimiter. The function
1243 /// `f` must consume tokens until reaching the next separator or
1244 /// closing bracket.
1245 pub fn parse_seq_to_before_end<T, F>(
1250 ) -> PResult<'a, (Vec<T>, bool)>
1251 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1253 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1256 fn parse_seq_to_before_tokens<T, F>(
1258 kets: &[&token::Token],
1260 expect: TokenExpectType,
1262 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1263 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1265 let mut first = true;
1266 let mut recovered = false;
1268 while !kets.iter().any(|k| {
1270 TokenExpectType::Expect => self.check(k),
1271 TokenExpectType::NoExpect => self.token == **k,
1275 token::CloseDelim(..) | token::Eof => break,
1278 if let Some(ref t) = sep.sep {
1282 match self.expect(t) {
1289 // Attempt to keep parsing if it was a similar separator
1290 if let Some(ref tokens) = t.similar_tokens() {
1291 if tokens.contains(&self.token) {
1296 // Attempt to keep parsing if it was an omitted separator
1311 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1313 TokenExpectType::Expect => self.check(k),
1314 TokenExpectType::NoExpect => self.token == **k,
1327 /// Parses a sequence, including the closing delimiter. The function
1328 /// `f` must consume tokens until reaching the next separator or
1329 /// closing bracket.
1330 fn parse_unspanned_seq<T, F>(
1336 ) -> PResult<'a, Vec<T>> where
1337 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1340 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1347 /// Advance the parser by one token
1348 pub fn bump(&mut self) {
1349 if self.prev_token_kind == PrevTokenKind::Eof {
1350 // Bumping after EOF is a bad sign, usually an infinite loop.
1351 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1354 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1356 // Record last token kind for possible error recovery.
1357 self.prev_token_kind = match self.token {
1358 token::DocComment(..) => PrevTokenKind::DocComment,
1359 token::Comma => PrevTokenKind::Comma,
1360 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1361 token::Interpolated(..) => PrevTokenKind::Interpolated,
1362 token::Eof => PrevTokenKind::Eof,
1363 token::Ident(..) => PrevTokenKind::Ident,
1364 _ => PrevTokenKind::Other,
1367 let next = self.next_tok();
1368 self.span = next.sp;
1369 self.token = next.tok;
1370 self.expected_tokens.clear();
1371 // check after each token
1372 self.process_potential_macro_variable();
1375 /// Advance the parser using provided token as a next one. Use this when
1376 /// consuming a part of a token. For example a single `<` from `<<`.
1377 fn bump_with(&mut self, next: token::Token, span: Span) {
1378 self.prev_span = self.span.with_hi(span.lo());
1379 // It would be incorrect to record the kind of the current token, but
1380 // fortunately for tokens currently using `bump_with`, the
1381 // prev_token_kind will be of no use anyway.
1382 self.prev_token_kind = PrevTokenKind::Other;
1385 self.expected_tokens.clear();
1388 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1389 F: FnOnce(&token::Token) -> R,
1392 return f(&self.token)
1395 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1396 Some(tree) => match tree {
1397 TokenTree::Token(_, tok) => tok,
1398 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1400 None => token::CloseDelim(self.token_cursor.frame.delim),
1404 fn look_ahead_span(&self, dist: usize) -> Span {
1409 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1410 Some(TokenTree::Token(span, _)) => span,
1411 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1412 None => self.look_ahead_span(dist - 1),
1415 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1416 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1418 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1419 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1421 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1422 err.span_err(sp, self.diagnostic())
1424 fn bug(&self, m: &str) -> ! {
1425 self.sess.span_diagnostic.span_bug(self.span, m)
1427 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1428 self.sess.span_diagnostic.span_err(sp, m)
1430 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1431 self.sess.span_diagnostic.struct_span_err(sp, m)
1433 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1434 self.sess.span_diagnostic.span_bug(sp, m)
1437 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1438 self.sess.span_diagnostic.cancel(err)
1441 crate fn diagnostic(&self) -> &'a errors::Handler {
1442 &self.sess.span_diagnostic
1445 /// Is the current token one of the keywords that signals a bare function type?
1446 fn token_is_bare_fn_keyword(&mut self) -> bool {
1447 self.check_keyword(keywords::Fn) ||
1448 self.check_keyword(keywords::Unsafe) ||
1449 self.check_keyword(keywords::Extern)
1452 /// Parses a `TyKind::BareFn` type.
1453 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1456 [unsafe] [extern "ABI"] fn (S) -> T
1466 let unsafety = self.parse_unsafety();
1467 let abi = if self.eat_keyword(keywords::Extern) {
1468 self.parse_opt_abi()?.unwrap_or(Abi::C)
1473 self.expect_keyword(keywords::Fn)?;
1474 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1475 let ret_ty = self.parse_ret_ty(false)?;
1476 let decl = P(FnDecl {
1481 Ok(TyKind::BareFn(P(BareFnTy {
1489 /// Parses asyncness: `async` or nothing.
1490 fn parse_asyncness(&mut self) -> IsAsync {
1491 if self.eat_keyword(keywords::Async) {
1493 closure_id: ast::DUMMY_NODE_ID,
1494 return_impl_trait_id: ast::DUMMY_NODE_ID,
1501 /// Parses unsafety: `unsafe` or nothing.
1502 fn parse_unsafety(&mut self) -> Unsafety {
1503 if self.eat_keyword(keywords::Unsafe) {
1510 /// Parses the items in a trait declaration.
1511 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1512 maybe_whole!(self, NtTraitItem, |x| x);
1513 let attrs = self.parse_outer_attributes()?;
1514 let mut unclosed_delims = vec![];
1515 let (mut item, tokens) = self.collect_tokens(|this| {
1516 let item = this.parse_trait_item_(at_end, attrs);
1517 unclosed_delims.append(&mut this.unclosed_delims);
1520 self.unclosed_delims.append(&mut unclosed_delims);
1521 // See `parse_item` for why this clause is here.
1522 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1523 item.tokens = Some(tokens);
1528 fn parse_trait_item_(&mut self,
1530 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1533 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1534 self.parse_trait_item_assoc_ty()?
1535 } else if self.is_const_item() {
1536 self.expect_keyword(keywords::Const)?;
1537 let ident = self.parse_ident()?;
1538 self.expect(&token::Colon)?;
1539 let ty = self.parse_ty()?;
1540 let default = if self.eat(&token::Eq) {
1541 let expr = self.parse_expr()?;
1542 self.expect(&token::Semi)?;
1545 self.expect(&token::Semi)?;
1548 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1549 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1550 // trait item macro.
1551 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1553 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1555 let ident = self.parse_ident()?;
1556 let mut generics = self.parse_generics()?;
1558 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1559 // This is somewhat dubious; We don't want to allow
1560 // argument names to be left off if there is a
1563 // We don't allow argument names to be left off in edition 2018.
1564 p.parse_arg_general(p.span.rust_2018(), true, false)
1566 generics.where_clause = self.parse_where_clause()?;
1568 let sig = ast::MethodSig {
1578 let body = match self.token {
1582 debug!("parse_trait_methods(): parsing required method");
1585 token::OpenDelim(token::Brace) => {
1586 debug!("parse_trait_methods(): parsing provided method");
1588 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1589 attrs.extend(inner_attrs.iter().cloned());
1592 token::Interpolated(ref nt) => {
1594 token::NtBlock(..) => {
1596 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1597 attrs.extend(inner_attrs.iter().cloned());
1601 let token_str = self.this_token_descr();
1602 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1604 err.span_label(self.span, "expected `;` or `{`");
1610 let token_str = self.this_token_descr();
1611 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1613 err.span_label(self.span, "expected `;` or `{`");
1617 (ident, ast::TraitItemKind::Method(sig, body), generics)
1621 id: ast::DUMMY_NODE_ID,
1626 span: lo.to(self.prev_span),
1631 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1632 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1633 if self.eat(&token::RArrow) {
1634 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1636 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1641 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1642 self.parse_ty_common(true, true, false)
1645 /// Parses a type in restricted contexts where `+` is not permitted.
1647 /// Example 1: `&'a TYPE`
1648 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1649 /// Example 2: `value1 as TYPE + value2`
1650 /// `+` is prohibited to avoid interactions with expression grammar.
1651 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1652 self.parse_ty_common(false, true, false)
1655 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1656 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1657 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1658 maybe_whole!(self, NtTy, |x| x);
1661 let mut impl_dyn_multi = false;
1662 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1663 // `(TYPE)` is a parenthesized type.
1664 // `(TYPE,)` is a tuple with a single field of type TYPE.
1665 let mut ts = vec![];
1666 let mut last_comma = false;
1667 while self.token != token::CloseDelim(token::Paren) {
1668 ts.push(self.parse_ty()?);
1669 if self.eat(&token::Comma) {
1676 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1677 self.expect(&token::CloseDelim(token::Paren))?;
1679 if ts.len() == 1 && !last_comma {
1680 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1681 let maybe_bounds = allow_plus && self.token.is_like_plus();
1683 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1684 TyKind::Path(None, ref path) if maybe_bounds => {
1685 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1687 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1688 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1689 let path = match bounds[0] {
1690 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1691 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1693 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1696 _ => TyKind::Paren(P(ty))
1701 } else if self.eat(&token::Not) {
1704 } else if self.eat(&token::BinOp(token::Star)) {
1706 TyKind::Ptr(self.parse_ptr()?)
1707 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1709 let t = self.parse_ty()?;
1710 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1711 let t = match self.maybe_parse_fixed_length_of_vec()? {
1712 None => TyKind::Slice(t),
1713 Some(length) => TyKind::Array(t, AnonConst {
1714 id: ast::DUMMY_NODE_ID,
1718 self.expect(&token::CloseDelim(token::Bracket))?;
1720 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1723 self.parse_borrowed_pointee()?
1724 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1726 // In order to not be ambiguous, the type must be surrounded by parens.
1727 self.expect(&token::OpenDelim(token::Paren))?;
1729 id: ast::DUMMY_NODE_ID,
1730 value: self.parse_expr()?,
1732 self.expect(&token::CloseDelim(token::Paren))?;
1734 } else if self.eat_keyword(keywords::Underscore) {
1735 // A type to be inferred `_`
1737 } else if self.token_is_bare_fn_keyword() {
1738 // Function pointer type
1739 self.parse_ty_bare_fn(Vec::new())?
1740 } else if self.check_keyword(keywords::For) {
1741 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1742 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1743 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1745 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1746 if self.token_is_bare_fn_keyword() {
1747 self.parse_ty_bare_fn(lifetime_defs)?
1749 let path = self.parse_path(PathStyle::Type)?;
1750 let parse_plus = allow_plus && self.check_plus();
1751 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1753 } else if self.eat_keyword(keywords::Impl) {
1754 // Always parse bounds greedily for better error recovery.
1755 let bounds = self.parse_generic_bounds(None)?;
1756 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1757 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1758 } else if self.check_keyword(keywords::Dyn) &&
1759 (self.span.rust_2018() ||
1760 self.look_ahead(1, |t| t.can_begin_bound() &&
1761 !can_continue_type_after_non_fn_ident(t))) {
1762 self.bump(); // `dyn`
1763 // Always parse bounds greedily for better error recovery.
1764 let bounds = self.parse_generic_bounds(None)?;
1765 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1766 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1767 } else if self.check(&token::Question) ||
1768 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1769 // Bound list (trait object type)
1770 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1771 TraitObjectSyntax::None)
1772 } else if self.eat_lt() {
1774 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1775 TyKind::Path(Some(qself), path)
1776 } else if self.token.is_path_start() {
1778 let path = self.parse_path(PathStyle::Type)?;
1779 if self.eat(&token::Not) {
1780 // Macro invocation in type position
1781 let (delim, tts) = self.expect_delimited_token_tree()?;
1782 let node = Mac_ { path, tts, delim };
1783 TyKind::Mac(respan(lo.to(self.prev_span), node))
1785 // Just a type path or bound list (trait object type) starting with a trait.
1787 // `Trait1 + Trait2 + 'a`
1788 if allow_plus && self.check_plus() {
1789 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1791 TyKind::Path(None, path)
1794 } else if self.check(&token::DotDotDot) {
1795 if allow_c_variadic {
1796 self.eat(&token::DotDotDot);
1799 return Err(self.fatal(
1800 "only foreign functions are allowed to be C-variadic"
1804 let msg = format!("expected type, found {}", self.this_token_descr());
1805 return Err(self.fatal(&msg));
1808 let span = lo.to(self.prev_span);
1809 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1811 // Try to recover from use of `+` with incorrect priority.
1812 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1813 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1814 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1817 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1818 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1819 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1820 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1822 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1823 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1825 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1828 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1829 if !allow_plus && impl_dyn_multi {
1830 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1831 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1834 "use parentheses to disambiguate",
1836 Applicability::MachineApplicable
1841 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1842 // Do not add `+` to expected tokens.
1843 if !allow_plus || !self.token.is_like_plus() {
1848 let bounds = self.parse_generic_bounds(None)?;
1849 let sum_span = ty.span.to(self.prev_span);
1851 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1852 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1855 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1856 let sum_with_parens = pprust::to_string(|s| {
1857 use crate::print::pprust::PrintState;
1860 s.print_opt_lifetime(lifetime)?;
1861 s.print_mutability(mut_ty.mutbl)?;
1863 s.print_type(&mut_ty.ty)?;
1864 s.print_type_bounds(" +", &bounds)?;
1867 err.span_suggestion(
1869 "try adding parentheses",
1871 Applicability::MachineApplicable
1874 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1875 err.span_label(sum_span, "perhaps you forgot parentheses?");
1878 err.span_label(sum_span, "expected a path");
1885 /// Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1886 /// Attempt to convert the base expression/pattern/type into a type, parse the `::AssocItem`
1887 /// tail, and combine them into a `<Ty>::AssocItem` expression/pattern/type.
1888 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: P<T>, allow_recovery: bool)
1889 -> PResult<'a, P<T>> {
1890 // Do not add `::` to expected tokens.
1891 if allow_recovery && self.token == token::ModSep {
1892 if let Some(ty) = base.to_ty() {
1893 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1899 /// Given an already parsed `Ty` parse the `::AssocItem` tail and
1900 /// combine them into a `<Ty>::AssocItem` expression/pattern/type.
1901 fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(&mut self, ty_span: Span, ty: P<Ty>)
1902 -> PResult<'a, P<T>> {
1903 self.expect(&token::ModSep)?;
1905 let mut path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1906 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, true)?;
1907 path.span = ty_span.to(self.prev_span);
1909 let ty_str = self.sess.source_map().span_to_snippet(ty_span)
1910 .unwrap_or_else(|_| pprust::ty_to_string(&ty));
1912 .struct_span_err(path.span, "missing angle brackets in associated item path")
1913 .span_suggestion( // this is a best-effort recovery
1914 path.span, "try", format!("<{}>::{}", ty_str, path), Applicability::MaybeIncorrect
1917 let path_span = ty_span.shrink_to_hi(); // use an empty path since `position` == 0
1918 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
1921 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1922 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1923 let mutbl = self.parse_mutability();
1924 let ty = self.parse_ty_no_plus()?;
1925 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1928 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1929 let mutbl = if self.eat_keyword(keywords::Mut) {
1931 } else if self.eat_keyword(keywords::Const) {
1932 Mutability::Immutable
1934 let span = self.prev_span;
1935 let msg = "expected mut or const in raw pointer type";
1936 self.struct_span_err(span, msg)
1937 .span_label(span, msg)
1938 .help("use `*mut T` or `*const T` as appropriate")
1940 Mutability::Immutable
1942 let t = self.parse_ty_no_plus()?;
1943 Ok(MutTy { ty: t, mutbl: mutbl })
1946 fn is_named_argument(&mut self) -> bool {
1947 let offset = match self.token {
1948 token::Interpolated(ref nt) => match **nt {
1949 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1952 token::BinOp(token::And) | token::AndAnd => 1,
1953 _ if self.token.is_keyword(keywords::Mut) => 1,
1957 self.look_ahead(offset, |t| t.is_ident()) &&
1958 self.look_ahead(offset + 1, |t| t == &token::Colon)
1961 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1963 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1964 if let token::DocComment(_) = self.token {
1965 let mut err = self.diagnostic().struct_span_err(
1967 &format!("documentation comments cannot be applied to {}", applied_to),
1969 err.span_label(self.span, "doc comments are not allowed here");
1972 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1973 *t == token::OpenDelim(token::Bracket)
1976 // Skip every token until next possible arg.
1977 while self.token != token::CloseDelim(token::Bracket) {
1980 let sp = lo.to(self.span);
1982 let mut err = self.diagnostic().struct_span_err(
1984 &format!("attributes cannot be applied to {}", applied_to),
1986 err.span_label(sp, "attributes are not allowed here");
1991 /// This version of parse arg doesn't necessarily require identifier names.
1992 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
1993 allow_c_variadic: bool) -> PResult<'a, Arg> {
1994 maybe_whole!(self, NtArg, |x| x);
1996 if let Ok(Some(_)) = self.parse_self_arg() {
1997 let mut err = self.struct_span_err(self.prev_span,
1998 "unexpected `self` argument in function");
1999 err.span_label(self.prev_span,
2000 "`self` is only valid as the first argument of an associated function");
2004 let (pat, ty) = if require_name || self.is_named_argument() {
2005 debug!("parse_arg_general parse_pat (require_name:{})",
2007 self.eat_incorrect_doc_comment("method arguments");
2008 let pat = self.parse_pat(Some("argument name"))?;
2010 if let Err(mut err) = self.expect(&token::Colon) {
2011 // If we find a pattern followed by an identifier, it could be an (incorrect)
2012 // C-style parameter declaration.
2013 if self.check_ident() && self.look_ahead(1, |t| {
2014 *t == token::Comma || *t == token::CloseDelim(token::Paren)
2016 let ident = self.parse_ident().unwrap();
2017 let span = pat.span.with_hi(ident.span.hi());
2019 err.span_suggestion(
2021 "declare the type after the parameter binding",
2022 String::from("<identifier>: <type>"),
2023 Applicability::HasPlaceholders,
2025 } else if require_name && is_trait_item {
2026 if let PatKind::Ident(_, ident, _) = pat.node {
2027 err.span_suggestion(
2029 "explicitly ignore parameter",
2030 format!("_: {}", ident),
2031 Applicability::MachineApplicable,
2035 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
2041 self.eat_incorrect_doc_comment("a method argument's type");
2042 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
2044 debug!("parse_arg_general ident_to_pat");
2045 let parser_snapshot_before_ty = self.clone();
2046 self.eat_incorrect_doc_comment("a method argument's type");
2047 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
2048 if ty.is_ok() && self.token != token::Comma &&
2049 self.token != token::CloseDelim(token::Paren) {
2050 // This wasn't actually a type, but a pattern looking like a type,
2051 // so we are going to rollback and re-parse for recovery.
2052 ty = self.unexpected();
2056 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
2058 id: ast::DUMMY_NODE_ID,
2059 node: PatKind::Ident(
2060 BindingMode::ByValue(Mutability::Immutable), ident, None),
2066 // If this is a C-variadic argument and we hit an error, return the
2068 if self.token == token::DotDotDot {
2071 // Recover from attempting to parse the argument as a type without pattern.
2073 mem::replace(self, parser_snapshot_before_ty);
2074 let pat = self.parse_pat(Some("argument name"))?;
2075 self.expect(&token::Colon)?;
2076 let ty = self.parse_ty()?;
2078 let mut err = self.diagnostic().struct_span_err_with_code(
2080 "patterns aren't allowed in methods without bodies",
2081 DiagnosticId::Error("E0642".into()),
2083 err.span_suggestion_short(
2085 "give this argument a name or use an underscore to ignore it",
2087 Applicability::MachineApplicable,
2091 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2093 node: PatKind::Wild,
2095 id: ast::DUMMY_NODE_ID
2102 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
2105 /// Parses a single function argument.
2106 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2107 self.parse_arg_general(true, false, false)
2110 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2111 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2112 let pat = self.parse_pat(Some("argument name"))?;
2113 let t = if self.eat(&token::Colon) {
2117 id: ast::DUMMY_NODE_ID,
2118 node: TyKind::Infer,
2119 span: self.prev_span,
2125 id: ast::DUMMY_NODE_ID
2129 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2130 if self.eat(&token::Semi) {
2131 Ok(Some(self.parse_expr()?))
2137 /// Matches `token_lit = LIT_INTEGER | ...`.
2138 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2139 let out = match self.token {
2140 token::Interpolated(ref nt) => match **nt {
2141 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2142 ExprKind::Lit(ref lit) => { lit.node.clone() }
2143 _ => { return self.unexpected_last(&self.token); }
2145 _ => { return self.unexpected_last(&self.token); }
2147 token::Literal(lit, suf) => {
2148 let diag = Some((self.span, &self.sess.span_diagnostic));
2149 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2153 self.expect_no_suffix(sp, lit.literal_name(), suf)
2158 token::Dot if self.look_ahead(1, |t| match t {
2159 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2161 }) => { // recover from `let x = .4;`
2164 if let token::Literal(
2165 parse::token::Lit::Integer(val),
2168 let suffix = suffix.and_then(|s| {
2169 let s = s.as_str().get();
2170 if ["f32", "f64"].contains(&s) {
2177 let sp = lo.to(self.prev_span);
2178 let mut err = self.diagnostic()
2179 .struct_span_err(sp, "float literals must have an integer part");
2180 err.span_suggestion(
2182 "must have an integer part",
2183 format!("0.{}{}", val, suffix),
2184 Applicability::MachineApplicable,
2187 return Ok(match suffix {
2188 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2189 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2190 _ => ast::LitKind::FloatUnsuffixed(val),
2196 _ => { return self.unexpected_last(&self.token); }
2203 /// Matches `lit = true | false | token_lit`.
2204 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2206 let lit = if self.eat_keyword(keywords::True) {
2208 } else if self.eat_keyword(keywords::False) {
2209 LitKind::Bool(false)
2211 let lit = self.parse_lit_token()?;
2214 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2217 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2218 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2219 maybe_whole_expr!(self);
2221 let minus_lo = self.span;
2222 let minus_present = self.eat(&token::BinOp(token::Minus));
2224 let literal = self.parse_lit()?;
2225 let hi = self.prev_span;
2226 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2229 let minus_hi = self.prev_span;
2230 let unary = self.mk_unary(UnOp::Neg, expr);
2231 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2237 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2239 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2240 let span = self.span;
2242 Ok(Ident::new(ident.name, span))
2244 _ => self.parse_ident(),
2248 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2250 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2251 let span = self.span;
2253 Ok(Ident::new(ident.name, span))
2255 _ => self.parse_ident(),
2259 /// Parses a qualified path.
2260 /// Assumes that the leading `<` has been parsed already.
2262 /// `qualified_path = <type [as trait_ref]>::path`
2267 /// `<T as U>::F::a<S>` (without disambiguator)
2268 /// `<T as U>::F::a::<S>` (with disambiguator)
2269 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2270 let lo = self.prev_span;
2271 let ty = self.parse_ty()?;
2273 // `path` will contain the prefix of the path up to the `>`,
2274 // if any (e.g., `U` in the `<T as U>::*` examples
2275 // above). `path_span` has the span of that path, or an empty
2276 // span in the case of something like `<T>::Bar`.
2277 let (mut path, path_span);
2278 if self.eat_keyword(keywords::As) {
2279 let path_lo = self.span;
2280 path = self.parse_path(PathStyle::Type)?;
2281 path_span = path_lo.to(self.prev_span);
2283 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2284 path_span = self.span.to(self.span);
2287 // See doc comment for `unmatched_angle_bracket_count`.
2288 self.expect(&token::Gt)?;
2289 if self.unmatched_angle_bracket_count > 0 {
2290 self.unmatched_angle_bracket_count -= 1;
2291 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2294 self.expect(&token::ModSep)?;
2296 let qself = QSelf { ty, path_span, position: path.segments.len() };
2297 self.parse_path_segments(&mut path.segments, style, true)?;
2299 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2302 /// Parses simple paths.
2304 /// `path = [::] segment+`
2305 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2308 /// `a::b::C<D>` (without disambiguator)
2309 /// `a::b::C::<D>` (with disambiguator)
2310 /// `Fn(Args)` (without disambiguator)
2311 /// `Fn::(Args)` (with disambiguator)
2312 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2313 self.parse_path_common(style, true)
2316 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2317 -> PResult<'a, ast::Path> {
2318 maybe_whole!(self, NtPath, |path| {
2319 if style == PathStyle::Mod &&
2320 path.segments.iter().any(|segment| segment.args.is_some()) {
2321 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2326 let lo = self.meta_var_span.unwrap_or(self.span);
2327 let mut segments = Vec::new();
2328 let mod_sep_ctxt = self.span.ctxt();
2329 if self.eat(&token::ModSep) {
2330 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2332 self.parse_path_segments(&mut segments, style, enable_warning)?;
2334 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2337 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2338 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2340 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2341 let meta_ident = match self.token {
2342 token::Interpolated(ref nt) => match **nt {
2343 token::NtMeta(ref meta) => match meta.node {
2344 ast::MetaItemKind::Word => Some(meta.path.clone()),
2351 if let Some(path) = meta_ident {
2355 self.parse_path(style)
2358 fn parse_path_segments(&mut self,
2359 segments: &mut Vec<PathSegment>,
2361 enable_warning: bool)
2362 -> PResult<'a, ()> {
2364 let segment = self.parse_path_segment(style, enable_warning)?;
2365 if style == PathStyle::Expr {
2366 // In order to check for trailing angle brackets, we must have finished
2367 // recursing (`parse_path_segment` can indirectly call this function),
2368 // that is, the next token must be the highlighted part of the below example:
2370 // `Foo::<Bar as Baz<T>>::Qux`
2373 // As opposed to the below highlight (if we had only finished the first
2376 // `Foo::<Bar as Baz<T>>::Qux`
2379 // `PathStyle::Expr` is only provided at the root invocation and never in
2380 // `parse_path_segment` to recurse and therefore can be checked to maintain
2382 self.check_trailing_angle_brackets(&segment, token::ModSep);
2384 segments.push(segment);
2386 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2392 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2393 -> PResult<'a, PathSegment> {
2394 let ident = self.parse_path_segment_ident()?;
2396 let is_args_start = |token: &token::Token| match *token {
2397 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2400 let check_args_start = |this: &mut Self| {
2401 this.expected_tokens.extend_from_slice(
2402 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2404 is_args_start(&this.token)
2407 Ok(if style == PathStyle::Type && check_args_start(self) ||
2408 style != PathStyle::Mod && self.check(&token::ModSep)
2409 && self.look_ahead(1, |t| is_args_start(t)) {
2410 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2411 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2412 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2413 .span_label(self.prev_span, "try removing `::`").emit();
2417 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2418 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2419 // parsing a new path.
2420 if style == PathStyle::Expr {
2421 self.unmatched_angle_bracket_count = 0;
2422 self.max_angle_bracket_count = 0;
2425 let args = if self.eat_lt() {
2427 let (args, bindings) =
2428 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2430 let span = lo.to(self.prev_span);
2431 AngleBracketedArgs { args, bindings, span }.into()
2435 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2436 &[&token::CloseDelim(token::Paren)],
2437 SeqSep::trailing_allowed(token::Comma),
2438 TokenExpectType::Expect,
2443 let span = lo.to(self.prev_span);
2444 let output = if self.eat(&token::RArrow) {
2445 Some(self.parse_ty_common(false, false, false)?)
2449 ParenthesizedArgs { inputs, output, span }.into()
2452 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2454 // Generic arguments are not found.
2455 PathSegment::from_ident(ident)
2459 crate fn check_lifetime(&mut self) -> bool {
2460 self.expected_tokens.push(TokenType::Lifetime);
2461 self.token.is_lifetime()
2464 /// Parses a single lifetime `'a` or panics.
2465 crate fn expect_lifetime(&mut self) -> Lifetime {
2466 if let Some(ident) = self.token.lifetime() {
2467 let span = self.span;
2469 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2471 self.span_bug(self.span, "not a lifetime")
2475 fn eat_label(&mut self) -> Option<Label> {
2476 if let Some(ident) = self.token.lifetime() {
2477 let span = self.span;
2479 Some(Label { ident: Ident::new(ident.name, span) })
2485 /// Parses mutability (`mut` or nothing).
2486 fn parse_mutability(&mut self) -> Mutability {
2487 if self.eat_keyword(keywords::Mut) {
2490 Mutability::Immutable
2494 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2495 if let token::Literal(token::Integer(name), None) = self.token {
2497 Ok(Ident::new(name, self.prev_span))
2499 self.parse_ident_common(false)
2503 /// Parse ident (COLON expr)?
2504 fn parse_field(&mut self) -> PResult<'a, Field> {
2505 let attrs = self.parse_outer_attributes()?;
2508 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2509 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2510 t == &token::Colon || t == &token::Eq
2512 let fieldname = self.parse_field_name()?;
2514 // Check for an equals token. This means the source incorrectly attempts to
2515 // initialize a field with an eq rather than a colon.
2516 if self.token == token::Eq {
2518 .struct_span_err(self.span, "expected `:`, found `=`")
2520 fieldname.span.shrink_to_hi().to(self.span),
2521 "replace equals symbol with a colon",
2523 Applicability::MachineApplicable,
2528 (fieldname, self.parse_expr()?, false)
2530 let fieldname = self.parse_ident_common(false)?;
2532 // Mimic `x: x` for the `x` field shorthand.
2533 let path = ast::Path::from_ident(fieldname);
2534 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2535 (fieldname, expr, true)
2539 span: lo.to(expr.span),
2542 attrs: attrs.into(),
2546 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2547 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2550 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2551 ExprKind::Unary(unop, expr)
2554 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2555 ExprKind::Binary(binop, lhs, rhs)
2558 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2559 ExprKind::Call(f, args)
2562 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2563 ExprKind::Index(expr, idx)
2566 fn mk_range(&mut self,
2567 start: Option<P<Expr>>,
2568 end: Option<P<Expr>>,
2569 limits: RangeLimits)
2570 -> PResult<'a, ast::ExprKind> {
2571 if end.is_none() && limits == RangeLimits::Closed {
2572 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2574 Ok(ExprKind::Range(start, end, limits))
2578 fn mk_assign_op(&mut self, binop: ast::BinOp,
2579 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2580 ExprKind::AssignOp(binop, lhs, rhs)
2583 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2584 let delim = match self.token {
2585 token::OpenDelim(delim) => delim,
2587 let msg = "expected open delimiter";
2588 let mut err = self.fatal(msg);
2589 err.span_label(self.span, msg);
2593 let tts = match self.parse_token_tree() {
2594 TokenTree::Delimited(_, _, tts) => tts,
2595 _ => unreachable!(),
2597 let delim = match delim {
2598 token::Paren => MacDelimiter::Parenthesis,
2599 token::Bracket => MacDelimiter::Bracket,
2600 token::Brace => MacDelimiter::Brace,
2601 token::NoDelim => self.bug("unexpected no delimiter"),
2603 Ok((delim, tts.into()))
2606 /// At the bottom (top?) of the precedence hierarchy,
2607 /// Parses things like parenthesized exprs, macros, `return`, etc.
2609 /// N.B., this does not parse outer attributes, and is private because it only works
2610 /// correctly if called from `parse_dot_or_call_expr()`.
2611 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2612 maybe_recover_from_interpolated_ty_qpath!(self, true);
2613 maybe_whole_expr!(self);
2615 // Outer attributes are already parsed and will be
2616 // added to the return value after the fact.
2618 // Therefore, prevent sub-parser from parsing
2619 // attributes by giving them a empty "already parsed" list.
2620 let mut attrs = ThinVec::new();
2623 let mut hi = self.span;
2627 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2629 token::OpenDelim(token::Paren) => {
2632 attrs.extend(self.parse_inner_attributes()?);
2634 // (e) is parenthesized e
2635 // (e,) is a tuple with only one field, e
2636 let mut es = vec![];
2637 let mut trailing_comma = false;
2638 let mut recovered = false;
2639 while self.token != token::CloseDelim(token::Paren) {
2640 es.push(self.parse_expr()?);
2641 recovered = self.expect_one_of(
2643 &[token::Comma, token::CloseDelim(token::Paren)],
2645 if self.eat(&token::Comma) {
2646 trailing_comma = true;
2648 trailing_comma = false;
2656 hi = self.prev_span;
2657 ex = if es.len() == 1 && !trailing_comma {
2658 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2663 token::OpenDelim(token::Brace) => {
2664 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2666 token::BinOp(token::Or) | token::OrOr => {
2667 return self.parse_lambda_expr(attrs);
2669 token::OpenDelim(token::Bracket) => {
2672 attrs.extend(self.parse_inner_attributes()?);
2674 if self.eat(&token::CloseDelim(token::Bracket)) {
2676 ex = ExprKind::Array(Vec::new());
2679 let first_expr = self.parse_expr()?;
2680 if self.eat(&token::Semi) {
2681 // Repeating array syntax: [ 0; 512 ]
2682 let count = AnonConst {
2683 id: ast::DUMMY_NODE_ID,
2684 value: self.parse_expr()?,
2686 self.expect(&token::CloseDelim(token::Bracket))?;
2687 ex = ExprKind::Repeat(first_expr, count);
2688 } else if self.eat(&token::Comma) {
2689 // Vector with two or more elements.
2690 let remaining_exprs = self.parse_seq_to_end(
2691 &token::CloseDelim(token::Bracket),
2692 SeqSep::trailing_allowed(token::Comma),
2693 |p| Ok(p.parse_expr()?)
2695 let mut exprs = vec![first_expr];
2696 exprs.extend(remaining_exprs);
2697 ex = ExprKind::Array(exprs);
2699 // Vector with one element.
2700 self.expect(&token::CloseDelim(token::Bracket))?;
2701 ex = ExprKind::Array(vec![first_expr]);
2704 hi = self.prev_span;
2708 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2710 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2712 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2714 if self.is_async_block() { // check for `async {` and `async move {`
2715 return self.parse_async_block(attrs);
2717 return self.parse_lambda_expr(attrs);
2720 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2721 return self.parse_lambda_expr(attrs);
2723 if self.eat_keyword(keywords::If) {
2724 return self.parse_if_expr(attrs);
2726 if self.eat_keyword(keywords::For) {
2727 let lo = self.prev_span;
2728 return self.parse_for_expr(None, lo, attrs);
2730 if self.eat_keyword(keywords::While) {
2731 let lo = self.prev_span;
2732 return self.parse_while_expr(None, lo, attrs);
2734 if let Some(label) = self.eat_label() {
2735 let lo = label.ident.span;
2736 self.expect(&token::Colon)?;
2737 if self.eat_keyword(keywords::While) {
2738 return self.parse_while_expr(Some(label), lo, attrs)
2740 if self.eat_keyword(keywords::For) {
2741 return self.parse_for_expr(Some(label), lo, attrs)
2743 if self.eat_keyword(keywords::Loop) {
2744 return self.parse_loop_expr(Some(label), lo, attrs)
2746 if self.token == token::OpenDelim(token::Brace) {
2747 return self.parse_block_expr(Some(label),
2749 BlockCheckMode::Default,
2752 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2753 let mut err = self.fatal(msg);
2754 err.span_label(self.span, msg);
2757 if self.eat_keyword(keywords::Loop) {
2758 let lo = self.prev_span;
2759 return self.parse_loop_expr(None, lo, attrs);
2761 if self.eat_keyword(keywords::Continue) {
2762 let label = self.eat_label();
2763 let ex = ExprKind::Continue(label);
2764 let hi = self.prev_span;
2765 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2767 if self.eat_keyword(keywords::Match) {
2768 let match_sp = self.prev_span;
2769 return self.parse_match_expr(attrs).map_err(|mut err| {
2770 err.span_label(match_sp, "while parsing this match expression");
2774 if self.eat_keyword(keywords::Unsafe) {
2775 return self.parse_block_expr(
2778 BlockCheckMode::Unsafe(ast::UserProvided),
2781 if self.is_do_catch_block() {
2782 let mut db = self.fatal("found removed `do catch` syntax");
2783 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2786 if self.is_try_block() {
2788 assert!(self.eat_keyword(keywords::Try));
2789 return self.parse_try_block(lo, attrs);
2791 if self.eat_keyword(keywords::Return) {
2792 if self.token.can_begin_expr() {
2793 let e = self.parse_expr()?;
2795 ex = ExprKind::Ret(Some(e));
2797 ex = ExprKind::Ret(None);
2799 } else if self.eat_keyword(keywords::Break) {
2800 let label = self.eat_label();
2801 let e = if self.token.can_begin_expr()
2802 && !(self.token == token::OpenDelim(token::Brace)
2803 && self.restrictions.contains(
2804 Restrictions::NO_STRUCT_LITERAL)) {
2805 Some(self.parse_expr()?)
2809 ex = ExprKind::Break(label, e);
2810 hi = self.prev_span;
2811 } else if self.eat_keyword(keywords::Yield) {
2812 if self.token.can_begin_expr() {
2813 let e = self.parse_expr()?;
2815 ex = ExprKind::Yield(Some(e));
2817 ex = ExprKind::Yield(None);
2819 } else if self.token.is_keyword(keywords::Let) {
2820 // Catch this syntax error here, instead of in `parse_ident`, so
2821 // that we can explicitly mention that let is not to be used as an expression
2822 let mut db = self.fatal("expected expression, found statement (`let`)");
2823 db.span_label(self.span, "expected expression");
2824 db.note("variable declaration using `let` is a statement");
2826 } else if self.token.is_path_start() {
2827 let path = self.parse_path(PathStyle::Expr)?;
2829 // `!`, as an operator, is prefix, so we know this isn't that
2830 if self.eat(&token::Not) {
2831 // MACRO INVOCATION expression
2832 let (delim, tts) = self.expect_delimited_token_tree()?;
2833 hi = self.prev_span;
2834 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2835 } else if self.check(&token::OpenDelim(token::Brace)) &&
2836 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL) {
2837 // This is a struct literal, unless we're prohibited
2838 // from parsing struct literals here.
2839 return self.parse_struct_expr(lo, path, attrs);
2842 ex = ExprKind::Path(None, path);
2845 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2846 // Don't complain about bare semicolons after unclosed braces
2847 // recovery in order to keep the error count down. Fixing the
2848 // delimiters will possibly also fix the bare semicolon found in
2849 // expression context. For example, silence the following error:
2851 // error: expected expression, found `;`
2855 // | ^ expected expression
2858 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2860 match self.parse_literal_maybe_minus() {
2863 ex = expr.node.clone();
2866 self.cancel(&mut err);
2867 let msg = format!("expected expression, found {}",
2868 self.this_token_descr());
2869 let mut err = self.fatal(&msg);
2870 err.span_label(self.span, "expected expression");
2878 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2879 self.maybe_recover_from_bad_qpath(expr, true)
2882 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2883 -> PResult<'a, P<Expr>> {
2884 let struct_sp = lo.to(self.prev_span);
2886 let mut fields = Vec::new();
2887 let mut base = None;
2889 attrs.extend(self.parse_inner_attributes()?);
2891 while self.token != token::CloseDelim(token::Brace) {
2892 if self.eat(&token::DotDot) {
2893 let exp_span = self.prev_span;
2894 match self.parse_expr() {
2900 self.recover_stmt();
2903 if self.token == token::Comma {
2904 let mut err = self.sess.span_diagnostic.mut_span_err(
2905 exp_span.to(self.prev_span),
2906 "cannot use a comma after the base struct",
2908 err.span_suggestion_short(
2910 "remove this comma",
2912 Applicability::MachineApplicable
2914 err.note("the base struct must always be the last field");
2916 self.recover_stmt();
2921 let mut recovery_field = None;
2922 if let token::Ident(ident, _) = self.token {
2923 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2924 // Use in case of error after field-looking code: `S { foo: () with a }`
2925 let mut ident = ident.clone();
2926 ident.span = self.span;
2927 recovery_field = Some(ast::Field {
2930 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2931 is_shorthand: false,
2932 attrs: ThinVec::new(),
2936 let mut parsed_field = None;
2937 match self.parse_field() {
2938 Ok(f) => parsed_field = Some(f),
2940 e.span_label(struct_sp, "while parsing this struct");
2943 // If the next token is a comma, then try to parse
2944 // what comes next as additional fields, rather than
2945 // bailing out until next `}`.
2946 if self.token != token::Comma {
2947 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2948 if self.token != token::Comma {
2955 match self.expect_one_of(&[token::Comma],
2956 &[token::CloseDelim(token::Brace)]) {
2957 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2958 // only include the field if there's no parse error for the field name
2962 if let Some(f) = recovery_field {
2965 e.span_label(struct_sp, "while parsing this struct");
2967 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2968 self.eat(&token::Comma);
2973 let span = lo.to(self.span);
2974 self.expect(&token::CloseDelim(token::Brace))?;
2975 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2978 fn parse_or_use_outer_attributes(&mut self,
2979 already_parsed_attrs: Option<ThinVec<Attribute>>)
2980 -> PResult<'a, ThinVec<Attribute>> {
2981 if let Some(attrs) = already_parsed_attrs {
2984 self.parse_outer_attributes().map(|a| a.into())
2988 /// Parses a block or unsafe block.
2989 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2990 lo: Span, blk_mode: BlockCheckMode,
2991 outer_attrs: ThinVec<Attribute>)
2992 -> PResult<'a, P<Expr>> {
2993 self.expect(&token::OpenDelim(token::Brace))?;
2995 let mut attrs = outer_attrs;
2996 attrs.extend(self.parse_inner_attributes()?);
2998 let blk = self.parse_block_tail(lo, blk_mode)?;
2999 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
3002 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
3003 fn parse_dot_or_call_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 let b = self.parse_bottom_expr();
3009 let (span, b) = self.interpolated_or_expr_span(b)?;
3010 self.parse_dot_or_call_expr_with(b, span, attrs)
3013 fn parse_dot_or_call_expr_with(&mut self,
3016 mut attrs: ThinVec<Attribute>)
3017 -> PResult<'a, P<Expr>> {
3018 // Stitch the list of outer attributes onto the return value.
3019 // A little bit ugly, but the best way given the current code
3021 self.parse_dot_or_call_expr_with_(e0, lo)
3023 expr.map(|mut expr| {
3024 attrs.extend::<Vec<_>>(expr.attrs.into());
3027 ExprKind::If(..) | ExprKind::IfLet(..) => {
3028 if !expr.attrs.is_empty() {
3029 // Just point to the first attribute in there...
3030 let span = expr.attrs[0].span;
3033 "attributes are not yet allowed on `if` \
3044 // Assuming we have just parsed `.`, continue parsing into an expression.
3045 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3046 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
3047 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3049 Ok(match self.token {
3050 token::OpenDelim(token::Paren) => {
3051 // Method call `expr.f()`
3052 let mut args = self.parse_unspanned_seq(
3053 &token::OpenDelim(token::Paren),
3054 &token::CloseDelim(token::Paren),
3055 SeqSep::trailing_allowed(token::Comma),
3056 |p| Ok(p.parse_expr()?)
3058 args.insert(0, self_arg);
3060 let span = lo.to(self.prev_span);
3061 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3064 // Field access `expr.f`
3065 if let Some(args) = segment.args {
3066 self.span_err(args.span(),
3067 "field expressions may not have generic arguments");
3070 let span = lo.to(self.prev_span);
3071 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3076 /// This function checks if there are trailing angle brackets and produces
3077 /// a diagnostic to suggest removing them.
3079 /// ```ignore (diagnostic)
3080 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3081 /// ^^ help: remove extra angle brackets
3083 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3084 // This function is intended to be invoked after parsing a path segment where there are two
3087 // 1. A specific token is expected after the path segment.
3088 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3089 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3090 // 2. No specific token is expected after the path segment.
3091 // eg. `x.foo` (field access)
3093 // This function is called after parsing `.foo` and before parsing the token `end` (if
3094 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3097 // We only care about trailing angle brackets if we previously parsed angle bracket
3098 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3099 // removed in this case:
3101 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3103 // This case is particularly tricky as we won't notice it just looking at the tokens -
3104 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3105 // have already been parsed):
3107 // `x.foo::<u32>>>(3)`
3108 let parsed_angle_bracket_args = segment.args
3110 .map(|args| args.is_angle_bracketed())
3114 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3115 parsed_angle_bracket_args,
3117 if !parsed_angle_bracket_args {
3121 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3125 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3126 // (since we might have the field access case and the characters we're eating are
3127 // actual operators and not trailing characters - ie `x.foo >> 3`).
3128 let mut position = 0;
3130 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3131 // many of each (so we can correctly pluralize our error messages) and continue to
3133 let mut number_of_shr = 0;
3134 let mut number_of_gt = 0;
3135 while self.look_ahead(position, |t| {
3136 trace!("check_trailing_angle_brackets: t={:?}", t);
3137 if *t == token::BinOp(token::BinOpToken::Shr) {
3140 } else if *t == token::Gt {
3150 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3152 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3153 number_of_gt, number_of_shr,
3155 if number_of_gt < 1 && number_of_shr < 1 {
3159 // Finally, double check that we have our end token as otherwise this is the
3161 if self.look_ahead(position, |t| {
3162 trace!("check_trailing_angle_brackets: t={:?}", t);
3165 // Eat from where we started until the end token so that parsing can continue
3166 // as if we didn't have those extra angle brackets.
3167 self.eat_to_tokens(&[&end]);
3168 let span = lo.until(self.span);
3170 let plural = number_of_gt > 1 || number_of_shr >= 1;
3174 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3178 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3180 Applicability::MachineApplicable,
3186 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3191 while self.eat(&token::Question) {
3192 let hi = self.prev_span;
3193 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3197 if self.eat(&token::Dot) {
3199 token::Ident(..) => {
3200 e = self.parse_dot_suffix(e, lo)?;
3202 token::Literal(token::Integer(name), _) => {
3203 let span = self.span;
3205 let field = ExprKind::Field(e, Ident::new(name, span));
3206 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3208 token::Literal(token::Float(n), _suf) => {
3210 let fstr = n.as_str();
3211 let mut err = self.diagnostic()
3212 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3213 err.span_label(self.prev_span, "unexpected token");
3214 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3215 let float = match fstr.parse::<f64>().ok() {
3219 let sugg = pprust::to_string(|s| {
3220 use crate::print::pprust::PrintState;
3224 s.print_usize(float.trunc() as usize)?;
3227 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3229 err.span_suggestion(
3230 lo.to(self.prev_span),
3231 "try parenthesizing the first index",
3233 Applicability::MachineApplicable
3240 // FIXME Could factor this out into non_fatal_unexpected or something.
3241 let actual = self.this_token_to_string();
3242 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3247 if self.expr_is_complete(&e) { break; }
3250 token::OpenDelim(token::Paren) => {
3251 let es = self.parse_unspanned_seq(
3252 &token::OpenDelim(token::Paren),
3253 &token::CloseDelim(token::Paren),
3254 SeqSep::trailing_allowed(token::Comma),
3255 |p| Ok(p.parse_expr()?)
3257 hi = self.prev_span;
3259 let nd = self.mk_call(e, es);
3260 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
3264 // Could be either an index expression or a slicing expression.
3265 token::OpenDelim(token::Bracket) => {
3267 let ix = self.parse_expr()?;
3269 self.expect(&token::CloseDelim(token::Bracket))?;
3270 let index = self.mk_index(e, ix);
3271 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3279 crate fn process_potential_macro_variable(&mut self) {
3280 let (token, span) = match self.token {
3281 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3282 self.look_ahead(1, |t| t.is_ident()) => {
3284 let name = match self.token {
3285 token::Ident(ident, _) => ident,
3288 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3289 err.span_label(self.span, "unknown macro variable");
3294 token::Interpolated(ref nt) => {
3295 self.meta_var_span = Some(self.span);
3296 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3297 // and lifetime tokens, so the former are never encountered during normal parsing.
3299 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3300 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3310 /// Parses a single token tree from the input.
3311 crate fn parse_token_tree(&mut self) -> TokenTree {
3313 token::OpenDelim(..) => {
3314 let frame = mem::replace(&mut self.token_cursor.frame,
3315 self.token_cursor.stack.pop().unwrap());
3316 self.span = frame.span.entire();
3318 TokenTree::Delimited(
3321 frame.tree_cursor.stream.into(),
3324 token::CloseDelim(_) | token::Eof => unreachable!(),
3326 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3328 TokenTree::Token(span, token)
3333 // parse a stream of tokens into a list of TokenTree's,
3335 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3336 let mut tts = Vec::new();
3337 while self.token != token::Eof {
3338 tts.push(self.parse_token_tree());
3343 pub fn parse_tokens(&mut self) -> TokenStream {
3344 let mut result = Vec::new();
3347 token::Eof | token::CloseDelim(..) => break,
3348 _ => result.push(self.parse_token_tree().into()),
3351 TokenStream::new(result)
3354 /// Parse a prefix-unary-operator expr
3355 fn parse_prefix_expr(&mut self,
3356 already_parsed_attrs: Option<ThinVec<Attribute>>)
3357 -> PResult<'a, P<Expr>> {
3358 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3360 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3361 let (hi, ex) = match self.token {
3364 let e = self.parse_prefix_expr(None);
3365 let (span, e) = self.interpolated_or_expr_span(e)?;
3366 (lo.to(span), self.mk_unary(UnOp::Not, e))
3368 // Suggest `!` for bitwise negation when encountering a `~`
3371 let e = self.parse_prefix_expr(None);
3372 let (span, e) = self.interpolated_or_expr_span(e)?;
3373 let span_of_tilde = lo;
3374 let mut err = self.diagnostic()
3375 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3376 err.span_suggestion_short(
3378 "use `!` to perform bitwise negation",
3380 Applicability::MachineApplicable
3383 (lo.to(span), self.mk_unary(UnOp::Not, e))
3385 token::BinOp(token::Minus) => {
3387 let e = self.parse_prefix_expr(None);
3388 let (span, e) = self.interpolated_or_expr_span(e)?;
3389 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3391 token::BinOp(token::Star) => {
3393 let e = self.parse_prefix_expr(None);
3394 let (span, e) = self.interpolated_or_expr_span(e)?;
3395 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3397 token::BinOp(token::And) | token::AndAnd => {
3399 let m = self.parse_mutability();
3400 let e = self.parse_prefix_expr(None);
3401 let (span, e) = self.interpolated_or_expr_span(e)?;
3402 (lo.to(span), ExprKind::AddrOf(m, e))
3404 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3406 let place = self.parse_expr_res(
3407 Restrictions::NO_STRUCT_LITERAL,
3410 let blk = self.parse_block()?;
3411 let span = blk.span;
3412 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3413 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3415 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3417 let e = self.parse_prefix_expr(None);
3418 let (span, e) = self.interpolated_or_expr_span(e)?;
3419 (lo.to(span), ExprKind::Box(e))
3421 token::Ident(..) if self.token.is_ident_named("not") => {
3422 // `not` is just an ordinary identifier in Rust-the-language,
3423 // but as `rustc`-the-compiler, we can issue clever diagnostics
3424 // for confused users who really want to say `!`
3425 let token_cannot_continue_expr = |t: &token::Token| match *t {
3426 // These tokens can start an expression after `!`, but
3427 // can't continue an expression after an ident
3428 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3429 token::Literal(..) | token::Pound => true,
3430 token::Interpolated(ref nt) => match **nt {
3431 token::NtIdent(..) | token::NtExpr(..) |
3432 token::NtBlock(..) | token::NtPath(..) => true,
3437 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3438 if cannot_continue_expr {
3440 // Emit the error ...
3441 let mut err = self.diagnostic()
3442 .struct_span_err(self.span,
3443 &format!("unexpected {} after identifier",
3444 self.this_token_descr()));
3445 // span the `not` plus trailing whitespace to avoid
3446 // trailing whitespace after the `!` in our suggestion
3447 let to_replace = self.sess.source_map()
3448 .span_until_non_whitespace(lo.to(self.span));
3449 err.span_suggestion_short(
3451 "use `!` to perform logical negation",
3453 Applicability::MachineApplicable
3456 // —and recover! (just as if we were in the block
3457 // for the `token::Not` arm)
3458 let e = self.parse_prefix_expr(None);
3459 let (span, e) = self.interpolated_or_expr_span(e)?;
3460 (lo.to(span), self.mk_unary(UnOp::Not, e))
3462 return self.parse_dot_or_call_expr(Some(attrs));
3465 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3467 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3470 /// Parses an associative expression.
3472 /// This parses an expression accounting for associativity and precedence of the operators in
3475 fn parse_assoc_expr(&mut self,
3476 already_parsed_attrs: Option<ThinVec<Attribute>>)
3477 -> PResult<'a, P<Expr>> {
3478 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3481 /// Parses an associative expression with operators of at least `min_prec` precedence.
3482 fn parse_assoc_expr_with(&mut self,
3485 -> PResult<'a, P<Expr>> {
3486 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3489 let attrs = match lhs {
3490 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3493 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3494 return self.parse_prefix_range_expr(attrs);
3496 self.parse_prefix_expr(attrs)?
3500 if self.expr_is_complete(&lhs) {
3501 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3504 self.expected_tokens.push(TokenType::Operator);
3505 while let Some(op) = AssocOp::from_token(&self.token) {
3507 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3508 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3509 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3510 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3511 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3512 (PrevTokenKind::Interpolated, _) => self.prev_span,
3513 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3514 if path.segments.len() == 1 => self.prev_span,
3518 let cur_op_span = self.span;
3519 let restrictions = if op.is_assign_like() {
3520 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3524 if op.precedence() < min_prec {
3527 // Check for deprecated `...` syntax
3528 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3529 self.err_dotdotdot_syntax(self.span);
3533 if op.is_comparison() {
3534 self.check_no_chained_comparison(&lhs, &op);
3537 if op == AssocOp::As {
3538 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3540 } else if op == AssocOp::Colon {
3541 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3544 err.span_label(self.span,
3545 "expecting a type here because of type ascription");
3546 let cm = self.sess.source_map();
3547 let cur_pos = cm.lookup_char_pos(self.span.lo());
3548 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3549 if cur_pos.line != op_pos.line {
3550 err.span_suggestion(
3552 "try using a semicolon",
3554 Applicability::MaybeIncorrect // speculative
3561 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3562 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3563 // generalise it to the Fixity::None code.
3565 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3566 // two variants are handled with `parse_prefix_range_expr` call above.
3567 let rhs = if self.is_at_start_of_range_notation_rhs() {
3568 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3569 LhsExpr::NotYetParsed)?)
3573 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3578 let limits = if op == AssocOp::DotDot {
3579 RangeLimits::HalfOpen
3584 let r = self.mk_range(Some(lhs), rhs, limits)?;
3585 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3589 let rhs = match op.fixity() {
3590 Fixity::Right => self.with_res(
3591 restrictions - Restrictions::STMT_EXPR,
3593 this.parse_assoc_expr_with(op.precedence(),
3594 LhsExpr::NotYetParsed)
3596 Fixity::Left => self.with_res(
3597 restrictions - Restrictions::STMT_EXPR,
3599 this.parse_assoc_expr_with(op.precedence() + 1,
3600 LhsExpr::NotYetParsed)
3602 // We currently have no non-associative operators that are not handled above by
3603 // the special cases. The code is here only for future convenience.
3604 Fixity::None => self.with_res(
3605 restrictions - Restrictions::STMT_EXPR,
3607 this.parse_assoc_expr_with(op.precedence() + 1,
3608 LhsExpr::NotYetParsed)
3612 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3613 // including the attributes.
3617 .filter(|a| a.style == AttrStyle::Outer)
3619 .map_or(lhs_span, |a| a.span);
3620 let span = lhs_span.to(rhs.span);
3622 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3623 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3624 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3625 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3626 AssocOp::Greater | AssocOp::GreaterEqual => {
3627 let ast_op = op.to_ast_binop().unwrap();
3628 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3629 self.mk_expr(span, binary, ThinVec::new())
3632 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3633 AssocOp::ObsoleteInPlace =>
3634 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3635 AssocOp::AssignOp(k) => {
3637 token::Plus => BinOpKind::Add,
3638 token::Minus => BinOpKind::Sub,
3639 token::Star => BinOpKind::Mul,
3640 token::Slash => BinOpKind::Div,
3641 token::Percent => BinOpKind::Rem,
3642 token::Caret => BinOpKind::BitXor,
3643 token::And => BinOpKind::BitAnd,
3644 token::Or => BinOpKind::BitOr,
3645 token::Shl => BinOpKind::Shl,
3646 token::Shr => BinOpKind::Shr,
3648 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3649 self.mk_expr(span, aopexpr, ThinVec::new())
3651 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3652 self.bug("AssocOp should have been handled by special case")
3656 if op.fixity() == Fixity::None { break }
3661 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3662 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3663 -> PResult<'a, P<Expr>> {
3664 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3665 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3668 // Save the state of the parser before parsing type normally, in case there is a
3669 // LessThan comparison after this cast.
3670 let parser_snapshot_before_type = self.clone();
3671 match self.parse_ty_no_plus() {
3673 Ok(mk_expr(self, rhs))
3675 Err(mut type_err) => {
3676 // Rewind to before attempting to parse the type with generics, to recover
3677 // from situations like `x as usize < y` in which we first tried to parse
3678 // `usize < y` as a type with generic arguments.
3679 let parser_snapshot_after_type = self.clone();
3680 mem::replace(self, parser_snapshot_before_type);
3682 match self.parse_path(PathStyle::Expr) {
3684 let (op_noun, op_verb) = match self.token {
3685 token::Lt => ("comparison", "comparing"),
3686 token::BinOp(token::Shl) => ("shift", "shifting"),
3688 // We can end up here even without `<` being the next token, for
3689 // example because `parse_ty_no_plus` returns `Err` on keywords,
3690 // but `parse_path` returns `Ok` on them due to error recovery.
3691 // Return original error and parser state.
3692 mem::replace(self, parser_snapshot_after_type);
3693 return Err(type_err);
3697 // Successfully parsed the type path leaving a `<` yet to parse.
3700 // Report non-fatal diagnostics, keep `x as usize` as an expression
3701 // in AST and continue parsing.
3702 let msg = format!("`<` is interpreted as a start of generic \
3703 arguments for `{}`, not a {}", path, op_noun);
3704 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3705 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3706 "interpreted as generic arguments");
3707 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3709 let expr = mk_expr(self, P(Ty {
3711 node: TyKind::Path(None, path),
3712 id: ast::DUMMY_NODE_ID
3715 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3716 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3717 err.span_suggestion(
3719 &format!("try {} the cast value", op_verb),
3720 format!("({})", expr_str),
3721 Applicability::MachineApplicable
3727 Err(mut path_err) => {
3728 // Couldn't parse as a path, return original error and parser state.
3730 mem::replace(self, parser_snapshot_after_type);
3738 /// Produce an error if comparison operators are chained (RFC #558).
3739 /// We only need to check lhs, not rhs, because all comparison ops
3740 /// have same precedence and are left-associative
3741 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3742 debug_assert!(outer_op.is_comparison(),
3743 "check_no_chained_comparison: {:?} is not comparison",
3746 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3747 // respan to include both operators
3748 let op_span = op.span.to(self.span);
3749 let mut err = self.diagnostic().struct_span_err(op_span,
3750 "chained comparison operators require parentheses");
3751 if op.node == BinOpKind::Lt &&
3752 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3753 *outer_op == AssocOp::Greater // even in a case like the following:
3754 { // Foo<Bar<Baz<Qux, ()>>>
3756 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3757 err.help("or use `(...)` if you meant to specify fn arguments");
3765 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3766 fn parse_prefix_range_expr(&mut self,
3767 already_parsed_attrs: Option<ThinVec<Attribute>>)
3768 -> PResult<'a, P<Expr>> {
3769 // Check for deprecated `...` syntax
3770 if self.token == token::DotDotDot {
3771 self.err_dotdotdot_syntax(self.span);
3774 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3775 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3777 let tok = self.token.clone();
3778 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3780 let mut hi = self.span;
3782 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3783 // RHS must be parsed with more associativity than the dots.
3784 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3785 Some(self.parse_assoc_expr_with(next_prec,
3786 LhsExpr::NotYetParsed)
3794 let limits = if tok == token::DotDot {
3795 RangeLimits::HalfOpen
3800 let r = self.mk_range(None, opt_end, limits)?;
3801 Ok(self.mk_expr(lo.to(hi), r, attrs))
3804 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3805 if self.token.can_begin_expr() {
3806 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3807 if self.token == token::OpenDelim(token::Brace) {
3808 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3816 /// Parses an `if` or `if let` expression (`if` token already eaten).
3817 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3818 if self.check_keyword(keywords::Let) {
3819 return self.parse_if_let_expr(attrs);
3821 let lo = self.prev_span;
3822 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3824 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3825 // verify that the last statement is either an implicit return (no `;`) or an explicit
3826 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3827 // the dead code lint.
3828 if self.eat_keyword(keywords::Else) || !cond.returns() {
3829 let sp = self.sess.source_map().next_point(lo);
3830 let mut err = self.diagnostic()
3831 .struct_span_err(sp, "missing condition for `if` statemement");
3832 err.span_label(sp, "expected if condition here");
3835 let not_block = self.token != token::OpenDelim(token::Brace);
3836 let thn = self.parse_block().map_err(|mut err| {
3838 err.span_label(lo, "this `if` statement has a condition, but no block");
3842 let mut els: Option<P<Expr>> = None;
3843 let mut hi = thn.span;
3844 if self.eat_keyword(keywords::Else) {
3845 let elexpr = self.parse_else_expr()?;
3849 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3852 /// Parses an `if let` expression (`if` token already eaten).
3853 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3854 -> PResult<'a, P<Expr>> {
3855 let lo = self.prev_span;
3856 self.expect_keyword(keywords::Let)?;
3857 let pats = self.parse_pats()?;
3858 self.expect(&token::Eq)?;
3859 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3860 let thn = self.parse_block()?;
3861 let (hi, els) = if self.eat_keyword(keywords::Else) {
3862 let expr = self.parse_else_expr()?;
3863 (expr.span, Some(expr))
3867 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3870 /// Parses `move |args| expr`.
3871 fn parse_lambda_expr(&mut self,
3872 attrs: ThinVec<Attribute>)
3873 -> PResult<'a, P<Expr>>
3876 let movability = if self.eat_keyword(keywords::Static) {
3881 let asyncness = if self.span.rust_2018() {
3882 self.parse_asyncness()
3886 let capture_clause = if self.eat_keyword(keywords::Move) {
3891 let decl = self.parse_fn_block_decl()?;
3892 let decl_hi = self.prev_span;
3893 let body = match decl.output {
3894 FunctionRetTy::Default(_) => {
3895 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3896 self.parse_expr_res(restrictions, None)?
3899 // If an explicit return type is given, require a
3900 // block to appear (RFC 968).
3901 let body_lo = self.span;
3902 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3908 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3912 // `else` token already eaten
3913 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3914 if self.eat_keyword(keywords::If) {
3915 return self.parse_if_expr(ThinVec::new());
3917 let blk = self.parse_block()?;
3918 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3922 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3923 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3925 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3926 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3928 let pat = self.parse_top_level_pat()?;
3929 if !self.eat_keyword(keywords::In) {
3930 let in_span = self.prev_span.between(self.span);
3931 let mut err = self.sess.span_diagnostic
3932 .struct_span_err(in_span, "missing `in` in `for` loop");
3933 err.span_suggestion_short(
3934 in_span, "try adding `in` here", " in ".into(),
3935 // has been misleading, at least in the past (closed Issue #48492)
3936 Applicability::MaybeIncorrect
3940 let in_span = self.prev_span;
3941 if self.eat_keyword(keywords::In) {
3942 // a common typo: `for _ in in bar {}`
3943 let mut err = self.sess.span_diagnostic.struct_span_err(
3945 "expected iterable, found keyword `in`",
3947 err.span_suggestion_short(
3948 in_span.until(self.prev_span),
3949 "remove the duplicated `in`",
3951 Applicability::MachineApplicable,
3953 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3954 err.note("for more information on the status of emplacement syntax, see <\
3955 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3958 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3959 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3960 attrs.extend(iattrs);
3962 let hi = self.prev_span;
3963 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3966 /// Parses a `while` or `while let` expression (`while` token already eaten).
3967 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3969 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3970 if self.token.is_keyword(keywords::Let) {
3971 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3973 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3974 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3975 attrs.extend(iattrs);
3976 let span = span_lo.to(body.span);
3977 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3980 /// Parses a `while let` expression (`while` token already eaten).
3981 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3983 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3984 self.expect_keyword(keywords::Let)?;
3985 let pats = self.parse_pats()?;
3986 self.expect(&token::Eq)?;
3987 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3988 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3989 attrs.extend(iattrs);
3990 let span = span_lo.to(body.span);
3991 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3994 // parse `loop {...}`, `loop` token already eaten
3995 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3997 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3998 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3999 attrs.extend(iattrs);
4000 let span = span_lo.to(body.span);
4001 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
4004 /// Parses an `async move {...}` expression.
4005 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4006 -> PResult<'a, P<Expr>>
4008 let span_lo = self.span;
4009 self.expect_keyword(keywords::Async)?;
4010 let capture_clause = if self.eat_keyword(keywords::Move) {
4015 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4016 attrs.extend(iattrs);
4018 span_lo.to(body.span),
4019 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4022 /// Parses a `try {...}` expression (`try` token already eaten).
4023 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4024 -> PResult<'a, P<Expr>>
4026 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4027 attrs.extend(iattrs);
4028 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4031 // `match` token already eaten
4032 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4033 let match_span = self.prev_span;
4034 let lo = self.prev_span;
4035 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4037 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4038 if self.token == token::Token::Semi {
4039 e.span_suggestion_short(
4041 "try removing this `match`",
4043 Applicability::MaybeIncorrect // speculative
4048 attrs.extend(self.parse_inner_attributes()?);
4050 let mut arms: Vec<Arm> = Vec::new();
4051 while self.token != token::CloseDelim(token::Brace) {
4052 match self.parse_arm() {
4053 Ok(arm) => arms.push(arm),
4055 // Recover by skipping to the end of the block.
4057 self.recover_stmt();
4058 let span = lo.to(self.span);
4059 if self.token == token::CloseDelim(token::Brace) {
4062 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4068 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4071 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4072 maybe_whole!(self, NtArm, |x| x);
4074 let attrs = self.parse_outer_attributes()?;
4075 let pats = self.parse_pats()?;
4076 let guard = if self.eat_keyword(keywords::If) {
4077 Some(Guard::If(self.parse_expr()?))
4081 let arrow_span = self.span;
4082 self.expect(&token::FatArrow)?;
4083 let arm_start_span = self.span;
4085 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4086 .map_err(|mut err| {
4087 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4091 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4092 && self.token != token::CloseDelim(token::Brace);
4095 let cm = self.sess.source_map();
4096 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4097 .map_err(|mut err| {
4098 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4099 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4100 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4101 && expr_lines.lines.len() == 2
4102 && self.token == token::FatArrow => {
4103 // We check whether there's any trailing code in the parse span,
4104 // if there isn't, we very likely have the following:
4107 // | -- - missing comma
4113 // | parsed until here as `"y" & X`
4114 err.span_suggestion_short(
4115 cm.next_point(arm_start_span),
4116 "missing a comma here to end this `match` arm",
4118 Applicability::MachineApplicable
4122 err.span_label(arrow_span,
4123 "while parsing the `match` arm starting here");
4129 self.eat(&token::Comma);
4140 /// Parses an expression.
4142 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4143 self.parse_expr_res(Restrictions::empty(), None)
4146 /// Evaluates the closure with restrictions in place.
4148 /// Afters the closure is evaluated, restrictions are reset.
4149 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4150 where F: FnOnce(&mut Self) -> T
4152 let old = self.restrictions;
4153 self.restrictions = r;
4155 self.restrictions = old;
4160 /// Parses an expression, subject to the given restrictions.
4162 fn parse_expr_res(&mut self, r: Restrictions,
4163 already_parsed_attrs: Option<ThinVec<Attribute>>)
4164 -> PResult<'a, P<Expr>> {
4165 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4168 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4169 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4170 if self.eat(&token::Eq) {
4171 Ok(Some(self.parse_expr()?))
4173 Ok(Some(self.parse_expr()?))
4179 /// Parses patterns, separated by '|' s.
4180 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4181 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4182 self.eat(&token::BinOp(token::Or));
4184 let mut pats = Vec::new();
4186 pats.push(self.parse_top_level_pat()?);
4188 if self.token == token::OrOr {
4189 let mut err = self.struct_span_err(self.span,
4190 "unexpected token `||` after pattern");
4191 err.span_suggestion(
4193 "use a single `|` to specify multiple patterns",
4195 Applicability::MachineApplicable
4199 } else if self.eat(&token::BinOp(token::Or)) {
4200 // This is a No-op. Continue the loop to parse the next
4208 // Parses a parenthesized list of patterns like
4209 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4210 // - a vector of the patterns that were parsed
4211 // - an option indicating the index of the `..` element
4212 // - a boolean indicating whether a trailing comma was present.
4213 // Trailing commas are significant because (p) and (p,) are different patterns.
4214 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4215 self.expect(&token::OpenDelim(token::Paren))?;
4216 let result = self.parse_pat_list()?;
4217 self.expect(&token::CloseDelim(token::Paren))?;
4221 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4222 let mut fields = Vec::new();
4223 let mut ddpos = None;
4224 let mut prev_dd_sp = None;
4225 let mut trailing_comma = false;
4227 if self.eat(&token::DotDot) {
4228 if ddpos.is_none() {
4229 ddpos = Some(fields.len());
4230 prev_dd_sp = Some(self.prev_span);
4232 // Emit a friendly error, ignore `..` and continue parsing
4233 let mut err = self.struct_span_err(
4235 "`..` can only be used once per tuple or tuple struct pattern",
4237 err.span_label(self.prev_span, "can only be used once per pattern");
4238 if let Some(sp) = prev_dd_sp {
4239 err.span_label(sp, "previously present here");
4243 } else if !self.check(&token::CloseDelim(token::Paren)) {
4244 fields.push(self.parse_pat(None)?);
4249 trailing_comma = self.eat(&token::Comma);
4250 if !trailing_comma {
4255 if ddpos == Some(fields.len()) && trailing_comma {
4256 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4257 let msg = "trailing comma is not permitted after `..`";
4258 self.struct_span_err(self.prev_span, msg)
4259 .span_label(self.prev_span, msg)
4263 Ok((fields, ddpos, trailing_comma))
4266 fn parse_pat_vec_elements(
4268 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4269 let mut before = Vec::new();
4270 let mut slice = None;
4271 let mut after = Vec::new();
4272 let mut first = true;
4273 let mut before_slice = true;
4275 while self.token != token::CloseDelim(token::Bracket) {
4279 self.expect(&token::Comma)?;
4281 if self.token == token::CloseDelim(token::Bracket)
4282 && (before_slice || !after.is_empty()) {
4288 if self.eat(&token::DotDot) {
4290 if self.check(&token::Comma) ||
4291 self.check(&token::CloseDelim(token::Bracket)) {
4292 slice = Some(P(Pat {
4293 id: ast::DUMMY_NODE_ID,
4294 node: PatKind::Wild,
4295 span: self.prev_span,
4297 before_slice = false;
4303 let subpat = self.parse_pat(None)?;
4304 if before_slice && self.eat(&token::DotDot) {
4305 slice = Some(subpat);
4306 before_slice = false;
4307 } else if before_slice {
4308 before.push(subpat);
4314 Ok((before, slice, after))
4320 attrs: Vec<Attribute>
4321 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4322 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4324 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4325 // Parsing a pattern of the form "fieldname: pat"
4326 let fieldname = self.parse_field_name()?;
4328 let pat = self.parse_pat(None)?;
4330 (pat, fieldname, false)
4332 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4333 let is_box = self.eat_keyword(keywords::Box);
4334 let boxed_span = self.span;
4335 let is_ref = self.eat_keyword(keywords::Ref);
4336 let is_mut = self.eat_keyword(keywords::Mut);
4337 let fieldname = self.parse_ident()?;
4338 hi = self.prev_span;
4340 let bind_type = match (is_ref, is_mut) {
4341 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4342 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4343 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4344 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4346 let fieldpat = P(Pat {
4347 id: ast::DUMMY_NODE_ID,
4348 node: PatKind::Ident(bind_type, fieldname, None),
4349 span: boxed_span.to(hi),
4352 let subpat = if is_box {
4354 id: ast::DUMMY_NODE_ID,
4355 node: PatKind::Box(fieldpat),
4361 (subpat, fieldname, true)
4364 Ok(source_map::Spanned {
4366 node: ast::FieldPat {
4370 attrs: attrs.into(),
4375 /// Parses the fields of a struct-like pattern.
4376 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4377 let mut fields = Vec::new();
4378 let mut etc = false;
4379 let mut ate_comma = true;
4380 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4381 let mut etc_span = None;
4383 while self.token != token::CloseDelim(token::Brace) {
4384 let attrs = self.parse_outer_attributes()?;
4387 // check that a comma comes after every field
4389 let err = self.struct_span_err(self.prev_span, "expected `,`");
4390 if let Some(mut delayed) = delayed_err {
4397 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4399 let mut etc_sp = self.span;
4401 if self.token == token::DotDotDot { // Issue #46718
4402 // Accept `...` as if it were `..` to avoid further errors
4403 let mut err = self.struct_span_err(self.span,
4404 "expected field pattern, found `...`");
4405 err.span_suggestion(
4407 "to omit remaining fields, use one fewer `.`",
4409 Applicability::MachineApplicable
4413 self.bump(); // `..` || `...`
4415 if self.token == token::CloseDelim(token::Brace) {
4416 etc_span = Some(etc_sp);
4419 let token_str = self.this_token_descr();
4420 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4422 err.span_label(self.span, "expected `}`");
4423 let mut comma_sp = None;
4424 if self.token == token::Comma { // Issue #49257
4425 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4426 err.span_label(etc_sp,
4427 "`..` must be at the end and cannot have a trailing comma");
4428 comma_sp = Some(self.span);
4433 etc_span = Some(etc_sp.until(self.span));
4434 if self.token == token::CloseDelim(token::Brace) {
4435 // If the struct looks otherwise well formed, recover and continue.
4436 if let Some(sp) = comma_sp {
4437 err.span_suggestion_short(
4439 "remove this comma",
4441 Applicability::MachineApplicable,
4446 } else if self.token.is_ident() && ate_comma {
4447 // Accept fields coming after `..,`.
4448 // This way we avoid "pattern missing fields" errors afterwards.
4449 // We delay this error until the end in order to have a span for a
4451 if let Some(mut delayed_err) = delayed_err {
4455 delayed_err = Some(err);
4458 if let Some(mut err) = delayed_err {
4465 fields.push(match self.parse_pat_field(lo, attrs) {
4468 if let Some(mut delayed_err) = delayed_err {
4474 ate_comma = self.eat(&token::Comma);
4477 if let Some(mut err) = delayed_err {
4478 if let Some(etc_span) = etc_span {
4479 err.multipart_suggestion(
4480 "move the `..` to the end of the field list",
4482 (etc_span, String::new()),
4483 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4485 Applicability::MachineApplicable,
4490 return Ok((fields, etc));
4493 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4494 if self.token.is_path_start() {
4496 let (qself, path) = if self.eat_lt() {
4497 // Parse a qualified path
4498 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4501 // Parse an unqualified path
4502 (None, self.parse_path(PathStyle::Expr)?)
4504 let hi = self.prev_span;
4505 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4507 self.parse_literal_maybe_minus()
4511 // helper function to decide whether to parse as ident binding or to try to do
4512 // something more complex like range patterns
4513 fn parse_as_ident(&mut self) -> bool {
4514 self.look_ahead(1, |t| match *t {
4515 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4516 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4517 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4518 // range pattern branch
4519 token::DotDot => None,
4521 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4522 token::Comma | token::CloseDelim(token::Bracket) => true,
4527 /// A wrapper around `parse_pat` with some special error handling for the
4528 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4529 /// to subpatterns within such).
4530 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4531 let pat = self.parse_pat(None)?;
4532 if self.token == token::Comma {
4533 // An unexpected comma after a top-level pattern is a clue that the
4534 // user (perhaps more accustomed to some other language) forgot the
4535 // parentheses in what should have been a tuple pattern; return a
4536 // suggestion-enhanced error here rather than choking on the comma
4538 let comma_span = self.span;
4540 if let Err(mut err) = self.parse_pat_list() {
4541 // We didn't expect this to work anyway; we just wanted
4542 // to advance to the end of the comma-sequence so we know
4543 // the span to suggest parenthesizing
4546 let seq_span = pat.span.to(self.prev_span);
4547 let mut err = self.struct_span_err(comma_span,
4548 "unexpected `,` in pattern");
4549 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4550 err.span_suggestion(
4552 "try adding parentheses to match on a tuple..",
4553 format!("({})", seq_snippet),
4554 Applicability::MachineApplicable
4557 "..or a vertical bar to match on multiple alternatives",
4558 format!("{}", seq_snippet.replace(",", " |")),
4559 Applicability::MachineApplicable
4567 /// Parses a pattern.
4568 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4569 self.parse_pat_with_range_pat(true, expected)
4572 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4574 fn parse_pat_with_range_pat(
4576 allow_range_pat: bool,
4577 expected: Option<&'static str>,
4578 ) -> PResult<'a, P<Pat>> {
4579 maybe_recover_from_interpolated_ty_qpath!(self, true);
4580 maybe_whole!(self, NtPat, |x| x);
4585 token::BinOp(token::And) | token::AndAnd => {
4586 // Parse &pat / &mut pat
4588 let mutbl = self.parse_mutability();
4589 if let token::Lifetime(ident) = self.token {
4590 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4592 err.span_label(self.span, "unexpected lifetime");
4595 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4596 pat = PatKind::Ref(subpat, mutbl);
4598 token::OpenDelim(token::Paren) => {
4599 // Parse (pat,pat,pat,...) as tuple pattern
4600 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4601 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4602 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4604 PatKind::Tuple(fields, ddpos)
4607 token::OpenDelim(token::Bracket) => {
4608 // Parse [pat,pat,...] as slice pattern
4610 let (before, slice, after) = self.parse_pat_vec_elements()?;
4611 self.expect(&token::CloseDelim(token::Bracket))?;
4612 pat = PatKind::Slice(before, slice, after);
4614 // At this point, token != &, &&, (, [
4615 _ => if self.eat_keyword(keywords::Underscore) {
4617 pat = PatKind::Wild;
4618 } else if self.eat_keyword(keywords::Mut) {
4619 // Parse mut ident @ pat / mut ref ident @ pat
4620 let mutref_span = self.prev_span.to(self.span);
4621 let binding_mode = if self.eat_keyword(keywords::Ref) {
4623 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4626 "try switching the order",
4628 Applicability::MachineApplicable
4630 BindingMode::ByRef(Mutability::Mutable)
4632 BindingMode::ByValue(Mutability::Mutable)
4634 pat = self.parse_pat_ident(binding_mode)?;
4635 } else if self.eat_keyword(keywords::Ref) {
4636 // Parse ref ident @ pat / ref mut ident @ pat
4637 let mutbl = self.parse_mutability();
4638 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4639 } else if self.eat_keyword(keywords::Box) {
4641 let subpat = self.parse_pat_with_range_pat(false, None)?;
4642 pat = PatKind::Box(subpat);
4643 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4644 self.parse_as_ident() {
4645 // Parse ident @ pat
4646 // This can give false positives and parse nullary enums,
4647 // they are dealt with later in resolve
4648 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4649 pat = self.parse_pat_ident(binding_mode)?;
4650 } else if self.token.is_path_start() {
4651 // Parse pattern starting with a path
4652 let (qself, path) = if self.eat_lt() {
4653 // Parse a qualified path
4654 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4657 // Parse an unqualified path
4658 (None, self.parse_path(PathStyle::Expr)?)
4661 token::Not if qself.is_none() => {
4662 // Parse macro invocation
4664 let (delim, tts) = self.expect_delimited_token_tree()?;
4665 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4666 pat = PatKind::Mac(mac);
4668 token::DotDotDot | token::DotDotEq | token::DotDot => {
4669 let end_kind = match self.token {
4670 token::DotDot => RangeEnd::Excluded,
4671 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4672 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4673 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4676 let op_span = self.span;
4678 let span = lo.to(self.prev_span);
4679 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4681 let end = self.parse_pat_range_end()?;
4682 let op = Spanned { span: op_span, node: end_kind };
4683 pat = PatKind::Range(begin, end, op);
4685 token::OpenDelim(token::Brace) => {
4686 if qself.is_some() {
4687 let msg = "unexpected `{` after qualified path";
4688 let mut err = self.fatal(msg);
4689 err.span_label(self.span, msg);
4692 // Parse struct pattern
4694 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4696 self.recover_stmt();
4700 pat = PatKind::Struct(path, fields, etc);
4702 token::OpenDelim(token::Paren) => {
4703 if qself.is_some() {
4704 let msg = "unexpected `(` after qualified path";
4705 let mut err = self.fatal(msg);
4706 err.span_label(self.span, msg);
4709 // Parse tuple struct or enum pattern
4710 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4711 pat = PatKind::TupleStruct(path, fields, ddpos)
4713 _ => pat = PatKind::Path(qself, path),
4716 // Try to parse everything else as literal with optional minus
4717 match self.parse_literal_maybe_minus() {
4719 let op_span = self.span;
4720 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4721 self.check(&token::DotDotDot) {
4722 let end_kind = if self.eat(&token::DotDotDot) {
4723 RangeEnd::Included(RangeSyntax::DotDotDot)
4724 } else if self.eat(&token::DotDotEq) {
4725 RangeEnd::Included(RangeSyntax::DotDotEq)
4726 } else if self.eat(&token::DotDot) {
4729 panic!("impossible case: we already matched \
4730 on a range-operator token")
4732 let end = self.parse_pat_range_end()?;
4733 let op = Spanned { span: op_span, node: end_kind };
4734 pat = PatKind::Range(begin, end, op);
4736 pat = PatKind::Lit(begin);
4740 self.cancel(&mut err);
4741 let expected = expected.unwrap_or("pattern");
4743 "expected {}, found {}",
4745 self.this_token_descr(),
4747 let mut err = self.fatal(&msg);
4748 err.span_label(self.span, format!("expected {}", expected));
4755 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4756 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4758 if !allow_range_pat {
4761 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4763 PatKind::Range(..) => {
4764 let mut err = self.struct_span_err(
4766 "the range pattern here has ambiguous interpretation",
4768 err.span_suggestion(
4770 "add parentheses to clarify the precedence",
4771 format!("({})", pprust::pat_to_string(&pat)),
4772 // "ambiguous interpretation" implies that we have to be guessing
4773 Applicability::MaybeIncorrect
4784 /// Parses `ident` or `ident @ pat`.
4785 /// used by the copy foo and ref foo patterns to give a good
4786 /// error message when parsing mistakes like `ref foo(a, b)`.
4787 fn parse_pat_ident(&mut self,
4788 binding_mode: ast::BindingMode)
4789 -> PResult<'a, PatKind> {
4790 let ident = self.parse_ident()?;
4791 let sub = if self.eat(&token::At) {
4792 Some(self.parse_pat(Some("binding pattern"))?)
4797 // just to be friendly, if they write something like
4799 // we end up here with ( as the current token. This shortly
4800 // leads to a parse error. Note that if there is no explicit
4801 // binding mode then we do not end up here, because the lookahead
4802 // will direct us over to parse_enum_variant()
4803 if self.token == token::OpenDelim(token::Paren) {
4804 return Err(self.span_fatal(
4806 "expected identifier, found enum pattern"))
4809 Ok(PatKind::Ident(binding_mode, ident, sub))
4812 /// Parses a local variable declaration.
4813 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4814 let lo = self.prev_span;
4815 let pat = self.parse_top_level_pat()?;
4817 let (err, ty) = if self.eat(&token::Colon) {
4818 // Save the state of the parser before parsing type normally, in case there is a `:`
4819 // instead of an `=` typo.
4820 let parser_snapshot_before_type = self.clone();
4821 let colon_sp = self.prev_span;
4822 match self.parse_ty() {
4823 Ok(ty) => (None, Some(ty)),
4825 // Rewind to before attempting to parse the type and continue parsing
4826 let parser_snapshot_after_type = self.clone();
4827 mem::replace(self, parser_snapshot_before_type);
4829 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4830 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4831 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4837 let init = match (self.parse_initializer(err.is_some()), err) {
4838 (Ok(init), None) => { // init parsed, ty parsed
4841 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4842 // Could parse the type as if it were the initializer, it is likely there was a
4843 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4844 err.span_suggestion_short(
4846 "use `=` if you meant to assign",
4848 Applicability::MachineApplicable
4851 // As this was parsed successfully, continue as if the code has been fixed for the
4852 // rest of the file. It will still fail due to the emitted error, but we avoid
4856 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4858 // Couldn't parse the type nor the initializer, only raise the type error and
4859 // return to the parser state before parsing the type as the initializer.
4860 // let x: <parse_error>;
4861 mem::replace(self, snapshot);
4864 (Err(err), None) => { // init error, ty parsed
4865 // Couldn't parse the initializer and we're not attempting to recover a failed
4866 // parse of the type, return the error.
4870 let hi = if self.token == token::Semi {
4879 id: ast::DUMMY_NODE_ID,
4885 /// Parses a structure field.
4886 fn parse_name_and_ty(&mut self,
4889 attrs: Vec<Attribute>)
4890 -> PResult<'a, StructField> {
4891 let name = self.parse_ident()?;
4892 self.expect(&token::Colon)?;
4893 let ty = self.parse_ty()?;
4895 span: lo.to(self.prev_span),
4898 id: ast::DUMMY_NODE_ID,
4904 /// Emits an expected-item-after-attributes error.
4905 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4906 let message = match attrs.last() {
4907 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4908 _ => "expected item after attributes",
4911 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4912 if attrs.last().unwrap().is_sugared_doc {
4913 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4918 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4919 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4920 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4921 Ok(self.parse_stmt_(true))
4924 // Eat tokens until we can be relatively sure we reached the end of the
4925 // statement. This is something of a best-effort heuristic.
4927 // We terminate when we find an unmatched `}` (without consuming it).
4928 fn recover_stmt(&mut self) {
4929 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4932 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4933 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4934 // approximate - it can mean we break too early due to macros, but that
4935 // should only lead to sub-optimal recovery, not inaccurate parsing).
4937 // If `break_on_block` is `Break`, then we will stop consuming tokens
4938 // after finding (and consuming) a brace-delimited block.
4939 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4940 let mut brace_depth = 0;
4941 let mut bracket_depth = 0;
4942 let mut in_block = false;
4943 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4944 break_on_semi, break_on_block);
4946 debug!("recover_stmt_ loop {:?}", self.token);
4948 token::OpenDelim(token::DelimToken::Brace) => {
4951 if break_on_block == BlockMode::Break &&
4953 bracket_depth == 0 {
4957 token::OpenDelim(token::DelimToken::Bracket) => {
4961 token::CloseDelim(token::DelimToken::Brace) => {
4962 if brace_depth == 0 {
4963 debug!("recover_stmt_ return - close delim {:?}", self.token);
4968 if in_block && bracket_depth == 0 && brace_depth == 0 {
4969 debug!("recover_stmt_ return - block end {:?}", self.token);
4973 token::CloseDelim(token::DelimToken::Bracket) => {
4975 if bracket_depth < 0 {
4981 debug!("recover_stmt_ return - Eof");
4986 if break_on_semi == SemiColonMode::Break &&
4988 bracket_depth == 0 {
4989 debug!("recover_stmt_ return - Semi");
4994 if break_on_semi == SemiColonMode::Comma &&
4996 bracket_depth == 0 {
4997 debug!("recover_stmt_ return - Semi");
5010 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5011 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5013 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5018 fn is_async_block(&mut self) -> bool {
5019 self.token.is_keyword(keywords::Async) &&
5022 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5023 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5025 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5030 fn is_async_fn(&mut self) -> bool {
5031 self.token.is_keyword(keywords::Async) &&
5032 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5035 fn is_do_catch_block(&mut self) -> bool {
5036 self.token.is_keyword(keywords::Do) &&
5037 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5038 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5039 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5042 fn is_try_block(&mut self) -> bool {
5043 self.token.is_keyword(keywords::Try) &&
5044 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5045 self.span.rust_2018() &&
5046 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5047 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5050 fn is_union_item(&self) -> bool {
5051 self.token.is_keyword(keywords::Union) &&
5052 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5055 fn is_crate_vis(&self) -> bool {
5056 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5059 fn is_existential_type_decl(&self) -> bool {
5060 self.token.is_keyword(keywords::Existential) &&
5061 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5064 fn is_auto_trait_item(&mut self) -> bool {
5066 (self.token.is_keyword(keywords::Auto)
5067 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5068 || // unsafe auto trait
5069 (self.token.is_keyword(keywords::Unsafe) &&
5070 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5071 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5074 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5075 -> PResult<'a, Option<P<Item>>> {
5076 let token_lo = self.span;
5077 let (ident, def) = match self.token {
5078 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5080 let ident = self.parse_ident()?;
5081 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5082 match self.parse_token_tree() {
5083 TokenTree::Delimited(_, _, tts) => tts,
5084 _ => unreachable!(),
5086 } else if self.check(&token::OpenDelim(token::Paren)) {
5087 let args = self.parse_token_tree();
5088 let body = if self.check(&token::OpenDelim(token::Brace)) {
5089 self.parse_token_tree()
5094 TokenStream::new(vec![
5096 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5104 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5106 token::Ident(ident, _) if ident.name == "macro_rules" &&
5107 self.look_ahead(1, |t| *t == token::Not) => {
5108 let prev_span = self.prev_span;
5109 self.complain_if_pub_macro(&vis.node, prev_span);
5113 let ident = self.parse_ident()?;
5114 let (delim, tokens) = self.expect_delimited_token_tree()?;
5115 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5116 self.report_invalid_macro_expansion_item();
5119 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5121 _ => return Ok(None),
5124 let span = lo.to(self.prev_span);
5125 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5128 fn parse_stmt_without_recovery(&mut self,
5129 macro_legacy_warnings: bool)
5130 -> PResult<'a, Option<Stmt>> {
5131 maybe_whole!(self, NtStmt, |x| Some(x));
5133 let attrs = self.parse_outer_attributes()?;
5136 Ok(Some(if self.eat_keyword(keywords::Let) {
5138 id: ast::DUMMY_NODE_ID,
5139 node: StmtKind::Local(self.parse_local(attrs.into())?),
5140 span: lo.to(self.prev_span),
5142 } else if let Some(macro_def) = self.eat_macro_def(
5144 &source_map::respan(lo, VisibilityKind::Inherited),
5148 id: ast::DUMMY_NODE_ID,
5149 node: StmtKind::Item(macro_def),
5150 span: lo.to(self.prev_span),
5152 // Starts like a simple path, being careful to avoid contextual keywords
5153 // such as a union items, item with `crate` visibility or auto trait items.
5154 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5155 // like a path (1 token), but it fact not a path.
5156 // `union::b::c` - path, `union U { ... }` - not a path.
5157 // `crate::b::c` - path, `crate struct S;` - not a path.
5158 } else if self.token.is_path_start() &&
5159 !self.token.is_qpath_start() &&
5160 !self.is_union_item() &&
5161 !self.is_crate_vis() &&
5162 !self.is_existential_type_decl() &&
5163 !self.is_auto_trait_item() &&
5164 !self.is_async_fn() {
5165 let pth = self.parse_path(PathStyle::Expr)?;
5167 if !self.eat(&token::Not) {
5168 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5169 self.parse_struct_expr(lo, pth, ThinVec::new())?
5171 let hi = self.prev_span;
5172 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5175 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5176 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5177 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5180 return Ok(Some(Stmt {
5181 id: ast::DUMMY_NODE_ID,
5182 node: StmtKind::Expr(expr),
5183 span: lo.to(self.prev_span),
5187 // it's a macro invocation
5188 let id = match self.token {
5189 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5190 _ => self.parse_ident()?,
5193 // check that we're pointing at delimiters (need to check
5194 // again after the `if`, because of `parse_ident`
5195 // consuming more tokens).
5197 token::OpenDelim(_) => {}
5199 // we only expect an ident if we didn't parse one
5201 let ident_str = if id.name == keywords::Invalid.name() {
5206 let tok_str = self.this_token_descr();
5207 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5210 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5215 let (delim, tts) = self.expect_delimited_token_tree()?;
5216 let hi = self.prev_span;
5218 let style = if delim == MacDelimiter::Brace {
5219 MacStmtStyle::Braces
5221 MacStmtStyle::NoBraces
5224 if id.name == keywords::Invalid.name() {
5225 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5226 let node = if delim == MacDelimiter::Brace ||
5227 self.token == token::Semi || self.token == token::Eof {
5228 StmtKind::Mac(P((mac, style, attrs.into())))
5230 // We used to incorrectly stop parsing macro-expanded statements here.
5231 // If the next token will be an error anyway but could have parsed with the
5232 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5233 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5234 // These can continue an expression, so we can't stop parsing and warn.
5235 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5236 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5237 token::BinOp(token::And) | token::BinOp(token::Or) |
5238 token::AndAnd | token::OrOr |
5239 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5242 self.warn_missing_semicolon();
5243 StmtKind::Mac(P((mac, style, attrs.into())))
5245 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5246 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5247 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5248 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5252 id: ast::DUMMY_NODE_ID,
5257 // if it has a special ident, it's definitely an item
5259 // Require a semicolon or braces.
5260 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5261 self.report_invalid_macro_expansion_item();
5263 let span = lo.to(hi);
5265 id: ast::DUMMY_NODE_ID,
5267 node: StmtKind::Item({
5269 span, id /*id is good here*/,
5270 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5271 respan(lo, VisibilityKind::Inherited),
5277 // FIXME: Bad copy of attrs
5278 let old_directory_ownership =
5279 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5280 let item = self.parse_item_(attrs.clone(), false, true)?;
5281 self.directory.ownership = old_directory_ownership;
5285 id: ast::DUMMY_NODE_ID,
5286 span: lo.to(i.span),
5287 node: StmtKind::Item(i),
5290 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5291 if !attrs.is_empty() {
5292 if s.prev_token_kind == PrevTokenKind::DocComment {
5293 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5294 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5295 s.span_err(s.span, "expected statement after outer attribute");
5300 // Do not attempt to parse an expression if we're done here.
5301 if self.token == token::Semi {
5302 unused_attrs(&attrs, self);
5307 if self.token == token::CloseDelim(token::Brace) {
5308 unused_attrs(&attrs, self);
5312 // Remainder are line-expr stmts.
5313 let e = self.parse_expr_res(
5314 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5316 id: ast::DUMMY_NODE_ID,
5317 span: lo.to(e.span),
5318 node: StmtKind::Expr(e),
5325 /// Checks if this expression is a successfully parsed statement.
5326 fn expr_is_complete(&mut self, e: &Expr) -> bool {
5327 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5328 !classify::expr_requires_semi_to_be_stmt(e)
5331 /// Parses a block. No inner attributes are allowed.
5332 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5333 maybe_whole!(self, NtBlock, |x| x);
5337 if !self.eat(&token::OpenDelim(token::Brace)) {
5339 let tok = self.this_token_descr();
5340 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5341 let do_not_suggest_help =
5342 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5344 if self.token.is_ident_named("and") {
5345 e.span_suggestion_short(
5347 "use `&&` instead of `and` for the boolean operator",
5349 Applicability::MaybeIncorrect,
5352 if self.token.is_ident_named("or") {
5353 e.span_suggestion_short(
5355 "use `||` instead of `or` for the boolean operator",
5357 Applicability::MaybeIncorrect,
5361 // Check to see if the user has written something like
5366 // Which is valid in other languages, but not Rust.
5367 match self.parse_stmt_without_recovery(false) {
5369 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5370 || do_not_suggest_help {
5371 // if the next token is an open brace (e.g., `if a b {`), the place-
5372 // inside-a-block suggestion would be more likely wrong than right
5373 e.span_label(sp, "expected `{`");
5376 let mut stmt_span = stmt.span;
5377 // expand the span to include the semicolon, if it exists
5378 if self.eat(&token::Semi) {
5379 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5381 let sugg = pprust::to_string(|s| {
5382 use crate::print::pprust::{PrintState, INDENT_UNIT};
5383 s.ibox(INDENT_UNIT)?;
5385 s.print_stmt(&stmt)?;
5386 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5390 "try placing this code inside a block",
5392 // speculative, has been misleading in the past (closed Issue #46836)
5393 Applicability::MaybeIncorrect
5397 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5398 self.cancel(&mut e);
5402 e.span_label(sp, "expected `{`");
5406 self.parse_block_tail(lo, BlockCheckMode::Default)
5409 /// Parses a block. Inner attributes are allowed.
5410 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5411 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5414 self.expect(&token::OpenDelim(token::Brace))?;
5415 Ok((self.parse_inner_attributes()?,
5416 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5419 /// Parses the rest of a block expression or function body.
5420 /// Precondition: already parsed the '{'.
5421 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5422 let mut stmts = vec![];
5423 while !self.eat(&token::CloseDelim(token::Brace)) {
5424 let stmt = match self.parse_full_stmt(false) {
5427 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5429 id: ast::DUMMY_NODE_ID,
5430 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5436 if let Some(stmt) = stmt {
5438 } else if self.token == token::Eof {
5441 // Found only `;` or `}`.
5447 id: ast::DUMMY_NODE_ID,
5449 span: lo.to(self.prev_span),
5453 /// Parses a statement, including the trailing semicolon.
5454 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5455 // skip looking for a trailing semicolon when we have an interpolated statement
5456 maybe_whole!(self, NtStmt, |x| Some(x));
5458 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5460 None => return Ok(None),
5464 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5465 // expression without semicolon
5466 if classify::expr_requires_semi_to_be_stmt(expr) {
5467 // Just check for errors and recover; do not eat semicolon yet.
5469 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5472 self.recover_stmt();
5476 StmtKind::Local(..) => {
5477 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5478 if macro_legacy_warnings && self.token != token::Semi {
5479 self.warn_missing_semicolon();
5481 self.expect_one_of(&[], &[token::Semi])?;
5487 if self.eat(&token::Semi) {
5488 stmt = stmt.add_trailing_semicolon();
5491 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5495 fn warn_missing_semicolon(&self) {
5496 self.diagnostic().struct_span_warn(self.span, {
5497 &format!("expected `;`, found {}", self.this_token_descr())
5499 "This was erroneously allowed and will become a hard error in a future release"
5503 fn err_dotdotdot_syntax(&self, span: Span) {
5504 self.diagnostic().struct_span_err(span, {
5505 "unexpected token: `...`"
5507 span, "use `..` for an exclusive range", "..".to_owned(),
5508 Applicability::MaybeIncorrect
5510 span, "or `..=` for an inclusive range", "..=".to_owned(),
5511 Applicability::MaybeIncorrect
5515 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5518 /// BOUND = TY_BOUND | LT_BOUND
5519 /// LT_BOUND = LIFETIME (e.g., `'a`)
5520 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5521 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5523 fn parse_generic_bounds_common(&mut self,
5525 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5526 let mut bounds = Vec::new();
5527 let mut negative_bounds = Vec::new();
5528 let mut last_plus_span = None;
5529 let mut was_negative = false;
5531 // This needs to be synchronized with `Token::can_begin_bound`.
5532 let is_bound_start = self.check_path() || self.check_lifetime() ||
5533 self.check(&token::Not) || // used for error reporting only
5534 self.check(&token::Question) ||
5535 self.check_keyword(keywords::For) ||
5536 self.check(&token::OpenDelim(token::Paren));
5539 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5540 let inner_lo = self.span;
5541 let is_negative = self.eat(&token::Not);
5542 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5543 if self.token.is_lifetime() {
5544 if let Some(question_span) = question {
5545 self.span_err(question_span,
5546 "`?` may only modify trait bounds, not lifetime bounds");
5548 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5550 let inner_span = inner_lo.to(self.prev_span);
5551 self.expect(&token::CloseDelim(token::Paren))?;
5552 let mut err = self.struct_span_err(
5553 lo.to(self.prev_span),
5554 "parenthesized lifetime bounds are not supported"
5556 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5557 err.span_suggestion_short(
5558 lo.to(self.prev_span),
5559 "remove the parentheses",
5561 Applicability::MachineApplicable
5567 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5568 let path = self.parse_path(PathStyle::Type)?;
5570 self.expect(&token::CloseDelim(token::Paren))?;
5572 let poly_span = lo.to(self.prev_span);
5574 was_negative = true;
5575 if let Some(sp) = last_plus_span.or(colon_span) {
5576 negative_bounds.push(sp.to(poly_span));
5579 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5580 let modifier = if question.is_some() {
5581 TraitBoundModifier::Maybe
5583 TraitBoundModifier::None
5585 bounds.push(GenericBound::Trait(poly_trait, modifier));
5592 if !allow_plus || !self.eat_plus() {
5595 last_plus_span = Some(self.prev_span);
5599 if !negative_bounds.is_empty() || was_negative {
5600 let plural = negative_bounds.len() > 1;
5601 let last_span = negative_bounds.last().map(|sp| *sp);
5602 let mut err = self.struct_span_err(
5604 "negative trait bounds are not supported",
5606 if let Some(sp) = last_span {
5607 err.span_label(sp, "negative trait bounds are not supported");
5609 if let Some(bound_list) = colon_span {
5610 let bound_list = bound_list.to(self.prev_span);
5611 let mut new_bound_list = String::new();
5612 if !bounds.is_empty() {
5613 let mut snippets = bounds.iter().map(|bound| bound.span())
5614 .map(|span| self.sess.source_map().span_to_snippet(span));
5615 while let Some(Ok(snippet)) = snippets.next() {
5616 new_bound_list.push_str(" + ");
5617 new_bound_list.push_str(&snippet);
5619 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5621 err.span_suggestion_hidden(
5623 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5625 Applicability::MachineApplicable,
5634 fn parse_generic_bounds(&mut self, colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5635 self.parse_generic_bounds_common(true, colon_span)
5638 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5641 /// BOUND = LT_BOUND (e.g., `'a`)
5643 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5644 let mut lifetimes = Vec::new();
5645 while self.check_lifetime() {
5646 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5648 if !self.eat_plus() {
5655 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5656 fn parse_ty_param(&mut self,
5657 preceding_attrs: Vec<Attribute>)
5658 -> PResult<'a, GenericParam> {
5659 let ident = self.parse_ident()?;
5661 // Parse optional colon and param bounds.
5662 let bounds = if self.eat(&token::Colon) {
5663 self.parse_generic_bounds(Some(self.prev_span))?
5668 let default = if self.eat(&token::Eq) {
5669 Some(self.parse_ty()?)
5676 id: ast::DUMMY_NODE_ID,
5677 attrs: preceding_attrs.into(),
5679 kind: GenericParamKind::Type {
5685 /// Parses the following grammar:
5687 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5688 fn parse_trait_item_assoc_ty(&mut self)
5689 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5690 let ident = self.parse_ident()?;
5691 let mut generics = self.parse_generics()?;
5693 // Parse optional colon and param bounds.
5694 let bounds = if self.eat(&token::Colon) {
5695 self.parse_generic_bounds(None)?
5699 generics.where_clause = self.parse_where_clause()?;
5701 let default = if self.eat(&token::Eq) {
5702 Some(self.parse_ty()?)
5706 self.expect(&token::Semi)?;
5708 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5711 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5712 self.expect_keyword(keywords::Const)?;
5713 let ident = self.parse_ident()?;
5714 self.expect(&token::Colon)?;
5715 let ty = self.parse_ty()?;
5719 id: ast::DUMMY_NODE_ID,
5720 attrs: preceding_attrs.into(),
5722 kind: GenericParamKind::Const {
5728 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5729 /// a trailing comma and erroneous trailing attributes.
5730 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5731 let mut params = Vec::new();
5733 let attrs = self.parse_outer_attributes()?;
5734 if self.check_lifetime() {
5735 let lifetime = self.expect_lifetime();
5736 // Parse lifetime parameter.
5737 let bounds = if self.eat(&token::Colon) {
5738 self.parse_lt_param_bounds()
5742 params.push(ast::GenericParam {
5743 ident: lifetime.ident,
5745 attrs: attrs.into(),
5747 kind: ast::GenericParamKind::Lifetime,
5749 } else if self.check_keyword(keywords::Const) {
5750 // Parse const parameter.
5751 params.push(self.parse_const_param(attrs)?);
5752 } else if self.check_ident() {
5753 // Parse type parameter.
5754 params.push(self.parse_ty_param(attrs)?);
5756 // Check for trailing attributes and stop parsing.
5757 if !attrs.is_empty() {
5758 if !params.is_empty() {
5759 self.struct_span_err(
5761 &format!("trailing attribute after generic parameter"),
5763 .span_label(attrs[0].span, "attributes must go before parameters")
5766 self.struct_span_err(
5768 &format!("attribute without generic parameters"),
5772 "attributes are only permitted when preceding parameters",
5780 if !self.eat(&token::Comma) {
5787 /// Parses a set of optional generic type parameter declarations. Where
5788 /// clauses are not parsed here, and must be added later via
5789 /// `parse_where_clause()`.
5791 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5792 /// | ( < lifetimes , typaramseq ( , )? > )
5793 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5794 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5795 maybe_whole!(self, NtGenerics, |x| x);
5797 let span_lo = self.span;
5799 let params = self.parse_generic_params()?;
5803 where_clause: WhereClause {
5804 id: ast::DUMMY_NODE_ID,
5805 predicates: Vec::new(),
5806 span: syntax_pos::DUMMY_SP,
5808 span: span_lo.to(self.prev_span),
5811 Ok(ast::Generics::default())
5815 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5816 /// For the purposes of understanding the parsing logic of generic arguments, this function
5817 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5818 /// had the correct amount of leading angle brackets.
5820 /// ```ignore (diagnostics)
5821 /// bar::<<<<T as Foo>::Output>();
5822 /// ^^ help: remove extra angle brackets
5824 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5828 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5829 // We need to detect whether there are extra leading left angle brackets and produce an
5830 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5831 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5832 // then there won't be matching `>` tokens to find.
5834 // To explain how this detection works, consider the following example:
5836 // ```ignore (diagnostics)
5837 // bar::<<<<T as Foo>::Output>();
5838 // ^^ help: remove extra angle brackets
5841 // Parsing of the left angle brackets starts in this function. We start by parsing the
5842 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5845 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5846 // *Unmatched count:* 1
5847 // *`parse_path_segment` calls deep:* 0
5849 // This has the effect of recursing as this function is called if a `<` character
5850 // is found within the expected generic arguments:
5852 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5853 // *Unmatched count:* 2
5854 // *`parse_path_segment` calls deep:* 1
5856 // Eventually we will have recursed until having consumed all of the `<` tokens and
5857 // this will be reflected in the count:
5859 // *Upcoming tokens:* `T as Foo>::Output>;`
5860 // *Unmatched count:* 4
5861 // `parse_path_segment` calls deep:* 3
5863 // The parser will continue until reaching the first `>` - this will decrement the
5864 // unmatched angle bracket count and return to the parent invocation of this function
5865 // having succeeded in parsing:
5867 // *Upcoming tokens:* `::Output>;`
5868 // *Unmatched count:* 3
5869 // *`parse_path_segment` calls deep:* 2
5871 // This will continue until the next `>` character which will also return successfully
5872 // to the parent invocation of this function and decrement the count:
5874 // *Upcoming tokens:* `;`
5875 // *Unmatched count:* 2
5876 // *`parse_path_segment` calls deep:* 1
5878 // At this point, this function will expect to find another matching `>` character but
5879 // won't be able to and will return an error. This will continue all the way up the
5880 // call stack until the first invocation:
5882 // *Upcoming tokens:* `;`
5883 // *Unmatched count:* 2
5884 // *`parse_path_segment` calls deep:* 0
5886 // In doing this, we have managed to work out how many unmatched leading left angle
5887 // brackets there are, but we cannot recover as the unmatched angle brackets have
5888 // already been consumed. To remedy this, we keep a snapshot of the parser state
5889 // before we do the above. We can then inspect whether we ended up with a parsing error
5890 // and unmatched left angle brackets and if so, restore the parser state before we
5891 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5892 // recover by attempting to parse again.
5894 // In practice, the recursion of this function is indirect and there will be other
5895 // locations that consume some `<` characters - as long as we update the count when
5896 // this happens, it isn't an issue.
5898 let is_first_invocation = style == PathStyle::Expr;
5899 // Take a snapshot before attempting to parse - we can restore this later.
5900 let snapshot = if is_first_invocation {
5906 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5907 match self.parse_generic_args() {
5908 Ok(value) => Ok(value),
5909 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5910 // Cancel error from being unable to find `>`. We know the error
5911 // must have been this due to a non-zero unmatched angle bracket
5915 // Swap `self` with our backup of the parser state before attempting to parse
5916 // generic arguments.
5917 let snapshot = mem::replace(self, snapshot.unwrap());
5920 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5921 snapshot.count={:?}",
5922 snapshot.unmatched_angle_bracket_count,
5925 // Eat the unmatched angle brackets.
5926 for _ in 0..snapshot.unmatched_angle_bracket_count {
5930 // Make a span over ${unmatched angle bracket count} characters.
5931 let span = lo.with_hi(
5932 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5934 let plural = snapshot.unmatched_angle_bracket_count > 1;
5939 "unmatched angle bracket{}",
5940 if plural { "s" } else { "" }
5946 "remove extra angle bracket{}",
5947 if plural { "s" } else { "" }
5950 Applicability::MachineApplicable,
5954 // Try again without unmatched angle bracket characters.
5955 self.parse_generic_args()
5961 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5962 /// possibly including trailing comma.
5963 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5964 let mut args = Vec::new();
5965 let mut bindings = Vec::new();
5966 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
5967 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
5969 let args_lo = self.span;
5972 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5973 // Parse lifetime argument.
5974 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5975 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5976 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5977 // Parse associated type binding.
5979 let ident = self.parse_ident()?;
5981 let ty = self.parse_ty()?;
5982 let span = lo.to(self.prev_span);
5983 bindings.push(TypeBinding {
5984 id: ast::DUMMY_NODE_ID,
5989 assoc_ty_bindings.push(span);
5990 } else if self.check_const_arg() {
5991 // FIXME(const_generics): to distinguish between idents for types and consts,
5992 // we should introduce a GenericArg::Ident in the AST and distinguish when
5993 // lowering to the HIR. For now, idents for const args are not permitted.
5995 // Parse const argument.
5996 let expr = if let token::OpenDelim(token::Brace) = self.token {
5997 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
5998 } else if self.token.is_ident() {
5999 // FIXME(const_generics): to distinguish between idents for types and consts,
6000 // we should introduce a GenericArg::Ident in the AST and distinguish when
6001 // lowering to the HIR. For now, idents for const args are not permitted.
6003 self.fatal("identifiers may currently not be used for const generics")
6006 // FIXME(const_generics): this currently conflicts with emplacement syntax
6007 // with negative integer literals.
6008 self.parse_literal_maybe_minus()?
6010 let value = AnonConst {
6011 id: ast::DUMMY_NODE_ID,
6014 args.push(GenericArg::Const(value));
6015 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6016 } else if self.check_type() {
6017 // Parse type argument.
6018 args.push(GenericArg::Type(self.parse_ty()?));
6019 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6024 if !self.eat(&token::Comma) {
6029 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6030 // preserve ordering of generic parameters with respect to associated type binding, so we
6031 // lose that information after parsing.
6032 if misplaced_assoc_ty_bindings.len() > 0 {
6033 let mut err = self.struct_span_err(
6034 args_lo.to(self.prev_span),
6035 "associated type bindings must be declared after generic parameters",
6037 for span in misplaced_assoc_ty_bindings {
6040 "this associated type binding should be moved after the generic parameters",
6046 Ok((args, bindings))
6049 /// Parses an optional where-clause and places it in `generics`.
6051 /// ```ignore (only-for-syntax-highlight)
6052 /// where T : Trait<U, V> + 'b, 'a : 'b
6054 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6055 maybe_whole!(self, NtWhereClause, |x| x);
6057 let mut where_clause = WhereClause {
6058 id: ast::DUMMY_NODE_ID,
6059 predicates: Vec::new(),
6060 span: syntax_pos::DUMMY_SP,
6063 if !self.eat_keyword(keywords::Where) {
6064 return Ok(where_clause);
6066 let lo = self.prev_span;
6068 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6069 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6070 // change we parse those generics now, but report an error.
6071 if self.choose_generics_over_qpath() {
6072 let generics = self.parse_generics()?;
6073 self.struct_span_err(
6075 "generic parameters on `where` clauses are reserved for future use",
6077 .span_label(generics.span, "currently unsupported")
6083 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6084 let lifetime = self.expect_lifetime();
6085 // Bounds starting with a colon are mandatory, but possibly empty.
6086 self.expect(&token::Colon)?;
6087 let bounds = self.parse_lt_param_bounds();
6088 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6089 ast::WhereRegionPredicate {
6090 span: lo.to(self.prev_span),
6095 } else if self.check_type() {
6096 // Parse optional `for<'a, 'b>`.
6097 // This `for` is parsed greedily and applies to the whole predicate,
6098 // the bounded type can have its own `for` applying only to it.
6099 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6100 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6101 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6102 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6104 // Parse type with mandatory colon and (possibly empty) bounds,
6105 // or with mandatory equality sign and the second type.
6106 let ty = self.parse_ty()?;
6107 if self.eat(&token::Colon) {
6108 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6109 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6110 ast::WhereBoundPredicate {
6111 span: lo.to(self.prev_span),
6112 bound_generic_params: lifetime_defs,
6117 // FIXME: Decide what should be used here, `=` or `==`.
6118 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6119 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6120 let rhs_ty = self.parse_ty()?;
6121 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6122 ast::WhereEqPredicate {
6123 span: lo.to(self.prev_span),
6126 id: ast::DUMMY_NODE_ID,
6130 return self.unexpected();
6136 if !self.eat(&token::Comma) {
6141 where_clause.span = lo.to(self.prev_span);
6145 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6146 -> PResult<'a, (Vec<Arg> , bool)> {
6147 self.expect(&token::OpenDelim(token::Paren))?;
6150 let mut c_variadic = false;
6151 let (args, recovered): (Vec<Option<Arg>>, bool) =
6152 self.parse_seq_to_before_end(
6153 &token::CloseDelim(token::Paren),
6154 SeqSep::trailing_allowed(token::Comma),
6156 // If the argument is a C-variadic argument we should not
6157 // enforce named arguments.
6158 let enforce_named_args = if p.token == token::DotDotDot {
6163 match p.parse_arg_general(enforce_named_args, false,
6166 if let TyKind::CVarArgs = arg.ty.node {
6168 if p.token != token::CloseDelim(token::Paren) {
6171 "`...` must be the last argument of a C-variadic function");
6182 let lo = p.prev_span;
6183 // Skip every token until next possible arg or end.
6184 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6185 // Create a placeholder argument for proper arg count (issue #34264).
6186 let span = lo.to(p.prev_span);
6187 Ok(Some(dummy_arg(span)))
6194 self.eat(&token::CloseDelim(token::Paren));
6197 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6199 if c_variadic && args.is_empty() {
6201 "C-variadic function must be declared with at least one named argument");
6204 Ok((args, c_variadic))
6207 /// Parses the argument list and result type of a function declaration.
6208 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6210 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6211 let ret_ty = self.parse_ret_ty(true)?;
6220 /// Returns the parsed optional self argument and whether a self shortcut was used.
6221 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6222 let expect_ident = |this: &mut Self| match this.token {
6223 // Preserve hygienic context.
6224 token::Ident(ident, _) =>
6225 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6228 let isolated_self = |this: &mut Self, n| {
6229 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6230 this.look_ahead(n + 1, |t| t != &token::ModSep)
6233 // Parse optional self parameter of a method.
6234 // Only a limited set of initial token sequences is considered self parameters, anything
6235 // else is parsed as a normal function parameter list, so some lookahead is required.
6236 let eself_lo = self.span;
6237 let (eself, eself_ident, eself_hi) = match self.token {
6238 token::BinOp(token::And) => {
6244 (if isolated_self(self, 1) {
6246 SelfKind::Region(None, Mutability::Immutable)
6247 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6248 isolated_self(self, 2) {
6251 SelfKind::Region(None, Mutability::Mutable)
6252 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6253 isolated_self(self, 2) {
6255 let lt = self.expect_lifetime();
6256 SelfKind::Region(Some(lt), Mutability::Immutable)
6257 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6258 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6259 isolated_self(self, 3) {
6261 let lt = self.expect_lifetime();
6263 SelfKind::Region(Some(lt), Mutability::Mutable)
6266 }, expect_ident(self), self.prev_span)
6268 token::BinOp(token::Star) => {
6273 // Emit special error for `self` cases.
6274 let msg = "cannot pass `self` by raw pointer";
6275 (if isolated_self(self, 1) {
6277 self.struct_span_err(self.span, msg)
6278 .span_label(self.span, msg)
6280 SelfKind::Value(Mutability::Immutable)
6281 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6282 isolated_self(self, 2) {
6285 self.struct_span_err(self.span, msg)
6286 .span_label(self.span, msg)
6288 SelfKind::Value(Mutability::Immutable)
6291 }, expect_ident(self), self.prev_span)
6293 token::Ident(..) => {
6294 if isolated_self(self, 0) {
6297 let eself_ident = expect_ident(self);
6298 let eself_hi = self.prev_span;
6299 (if self.eat(&token::Colon) {
6300 let ty = self.parse_ty()?;
6301 SelfKind::Explicit(ty, Mutability::Immutable)
6303 SelfKind::Value(Mutability::Immutable)
6304 }, eself_ident, eself_hi)
6305 } else if self.token.is_keyword(keywords::Mut) &&
6306 isolated_self(self, 1) {
6310 let eself_ident = expect_ident(self);
6311 let eself_hi = self.prev_span;
6312 (if self.eat(&token::Colon) {
6313 let ty = self.parse_ty()?;
6314 SelfKind::Explicit(ty, Mutability::Mutable)
6316 SelfKind::Value(Mutability::Mutable)
6317 }, eself_ident, eself_hi)
6322 _ => return Ok(None),
6325 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6326 Ok(Some(Arg::from_self(eself, eself_ident)))
6329 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6330 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6331 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6333 self.expect(&token::OpenDelim(token::Paren))?;
6335 // Parse optional self argument
6336 let self_arg = self.parse_self_arg()?;
6338 // Parse the rest of the function parameter list.
6339 let sep = SeqSep::trailing_allowed(token::Comma);
6340 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6341 if self.check(&token::CloseDelim(token::Paren)) {
6342 (vec![self_arg], false)
6343 } else if self.eat(&token::Comma) {
6344 let mut fn_inputs = vec![self_arg];
6345 let (mut input, recovered) = self.parse_seq_to_before_end(
6346 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6347 fn_inputs.append(&mut input);
6348 (fn_inputs, recovered)
6350 match self.expect_one_of(&[], &[]) {
6351 Err(err) => return Err(err),
6352 Ok(recovered) => (vec![self_arg], recovered),
6356 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6360 // Parse closing paren and return type.
6361 self.expect(&token::CloseDelim(token::Paren))?;
6365 output: self.parse_ret_ty(true)?,
6370 /// Parses the `|arg, arg|` header of a closure.
6371 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6372 let inputs_captures = {
6373 if self.eat(&token::OrOr) {
6376 self.expect(&token::BinOp(token::Or))?;
6377 let args = self.parse_seq_to_before_tokens(
6378 &[&token::BinOp(token::Or), &token::OrOr],
6379 SeqSep::trailing_allowed(token::Comma),
6380 TokenExpectType::NoExpect,
6381 |p| p.parse_fn_block_arg()
6387 let output = self.parse_ret_ty(true)?;
6390 inputs: inputs_captures,
6396 /// Parses the name and optional generic types of a function header.
6397 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6398 let id = self.parse_ident()?;
6399 let generics = self.parse_generics()?;
6403 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6404 attrs: Vec<Attribute>) -> P<Item> {
6408 id: ast::DUMMY_NODE_ID,
6416 /// Parses an item-position function declaration.
6417 fn parse_item_fn(&mut self,
6419 asyncness: Spanned<IsAsync>,
6420 constness: Spanned<Constness>,
6422 -> PResult<'a, ItemInfo> {
6423 let (ident, mut generics) = self.parse_fn_header()?;
6424 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6425 let decl = self.parse_fn_decl(allow_c_variadic)?;
6426 generics.where_clause = self.parse_where_clause()?;
6427 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6428 let header = FnHeader { unsafety, asyncness, constness, abi };
6429 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6432 /// Returns `true` if we are looking at `const ID`
6433 /// (returns `false` for things like `const fn`, etc.).
6434 fn is_const_item(&mut self) -> bool {
6435 self.token.is_keyword(keywords::Const) &&
6436 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6437 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6440 /// Parses all the "front matter" for a `fn` declaration, up to
6441 /// and including the `fn` keyword:
6445 /// - `const unsafe fn`
6448 fn parse_fn_front_matter(&mut self)
6456 let is_const_fn = self.eat_keyword(keywords::Const);
6457 let const_span = self.prev_span;
6458 let unsafety = self.parse_unsafety();
6459 let asyncness = self.parse_asyncness();
6460 let asyncness = respan(self.prev_span, asyncness);
6461 let (constness, unsafety, abi) = if is_const_fn {
6462 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6464 let abi = if self.eat_keyword(keywords::Extern) {
6465 self.parse_opt_abi()?.unwrap_or(Abi::C)
6469 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6471 self.expect_keyword(keywords::Fn)?;
6472 Ok((constness, unsafety, asyncness, abi))
6475 /// Parses an impl item.
6476 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6477 maybe_whole!(self, NtImplItem, |x| x);
6478 let attrs = self.parse_outer_attributes()?;
6479 let mut unclosed_delims = vec![];
6480 let (mut item, tokens) = self.collect_tokens(|this| {
6481 let item = this.parse_impl_item_(at_end, attrs);
6482 unclosed_delims.append(&mut this.unclosed_delims);
6485 self.unclosed_delims.append(&mut unclosed_delims);
6487 // See `parse_item` for why this clause is here.
6488 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6489 item.tokens = Some(tokens);
6494 fn parse_impl_item_(&mut self,
6496 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6498 let vis = self.parse_visibility(false)?;
6499 let defaultness = self.parse_defaultness();
6500 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6501 let (name, alias, generics) = type_?;
6502 let kind = match alias {
6503 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6504 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6506 (name, kind, generics)
6507 } else if self.is_const_item() {
6508 // This parses the grammar:
6509 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6510 self.expect_keyword(keywords::Const)?;
6511 let name = self.parse_ident()?;
6512 self.expect(&token::Colon)?;
6513 let typ = self.parse_ty()?;
6514 self.expect(&token::Eq)?;
6515 let expr = self.parse_expr()?;
6516 self.expect(&token::Semi)?;
6517 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6519 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6520 attrs.extend(inner_attrs);
6521 (name, node, generics)
6525 id: ast::DUMMY_NODE_ID,
6526 span: lo.to(self.prev_span),
6537 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6539 VisibilityKind::Inherited => {}
6541 let is_macro_rules: bool = match self.token {
6542 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6545 let mut err = if is_macro_rules {
6546 let mut err = self.diagnostic()
6547 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6548 err.span_suggestion(
6550 "try exporting the macro",
6551 "#[macro_export]".to_owned(),
6552 Applicability::MaybeIncorrect // speculative
6556 let mut err = self.diagnostic()
6557 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6558 err.help("try adjusting the macro to put `pub` inside the invocation");
6566 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6567 -> DiagnosticBuilder<'a>
6569 let expected_kinds = if item_type == "extern" {
6570 "missing `fn`, `type`, or `static`"
6572 "missing `fn`, `type`, or `const`"
6575 // Given this code `path(`, it seems like this is not
6576 // setting the visibility of a macro invocation, but rather
6577 // a mistyped method declaration.
6578 // Create a diagnostic pointing out that `fn` is missing.
6580 // x | pub path(&self) {
6581 // | ^ missing `fn`, `type`, or `const`
6583 // ^^ `sp` below will point to this
6584 let sp = prev_span.between(self.prev_span);
6585 let mut err = self.diagnostic().struct_span_err(
6587 &format!("{} for {}-item declaration",
6588 expected_kinds, item_type));
6589 err.span_label(sp, expected_kinds);
6593 /// Parse a method or a macro invocation in a trait impl.
6594 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6595 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6596 ast::ImplItemKind)> {
6597 // code copied from parse_macro_use_or_failure... abstraction!
6598 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6600 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6601 ast::ImplItemKind::Macro(mac)))
6603 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
6604 let ident = self.parse_ident()?;
6605 let mut generics = self.parse_generics()?;
6606 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6607 generics.where_clause = self.parse_where_clause()?;
6609 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6610 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6611 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6612 ast::MethodSig { header, decl },
6618 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6619 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6620 let ident = self.parse_ident()?;
6621 let mut tps = self.parse_generics()?;
6623 // Parse optional colon and supertrait bounds.
6624 let bounds = if self.eat(&token::Colon) {
6625 self.parse_generic_bounds(Some(self.prev_span))?
6630 if self.eat(&token::Eq) {
6631 // it's a trait alias
6632 let bounds = self.parse_generic_bounds(None)?;
6633 tps.where_clause = self.parse_where_clause()?;
6634 self.expect(&token::Semi)?;
6635 if is_auto == IsAuto::Yes {
6636 let msg = "trait aliases cannot be `auto`";
6637 self.struct_span_err(self.prev_span, msg)
6638 .span_label(self.prev_span, msg)
6641 if unsafety != Unsafety::Normal {
6642 let msg = "trait aliases cannot be `unsafe`";
6643 self.struct_span_err(self.prev_span, msg)
6644 .span_label(self.prev_span, msg)
6647 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6649 // it's a normal trait
6650 tps.where_clause = self.parse_where_clause()?;
6651 self.expect(&token::OpenDelim(token::Brace))?;
6652 let mut trait_items = vec![];
6653 while !self.eat(&token::CloseDelim(token::Brace)) {
6654 let mut at_end = false;
6655 match self.parse_trait_item(&mut at_end) {
6656 Ok(item) => trait_items.push(item),
6660 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6665 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6669 fn choose_generics_over_qpath(&self) -> bool {
6670 // There's an ambiguity between generic parameters and qualified paths in impls.
6671 // If we see `<` it may start both, so we have to inspect some following tokens.
6672 // The following combinations can only start generics,
6673 // but not qualified paths (with one exception):
6674 // `<` `>` - empty generic parameters
6675 // `<` `#` - generic parameters with attributes
6676 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6677 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6678 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6679 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6680 // `<` const - generic const parameter
6681 // The only truly ambiguous case is
6682 // `<` IDENT `>` `::` IDENT ...
6683 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6684 // because this is what almost always expected in practice, qualified paths in impls
6685 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6686 self.token == token::Lt &&
6687 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6688 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6689 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6690 t == &token::Colon || t == &token::Eq) ||
6691 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6694 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6695 self.expect(&token::OpenDelim(token::Brace))?;
6696 let attrs = self.parse_inner_attributes()?;
6698 let mut impl_items = Vec::new();
6699 while !self.eat(&token::CloseDelim(token::Brace)) {
6700 let mut at_end = false;
6701 match self.parse_impl_item(&mut at_end) {
6702 Ok(impl_item) => impl_items.push(impl_item),
6706 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6711 Ok((impl_items, attrs))
6714 /// Parses an implementation item, `impl` keyword is already parsed.
6716 /// impl<'a, T> TYPE { /* impl items */ }
6717 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6718 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6720 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6721 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6722 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6723 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6724 -> PResult<'a, ItemInfo> {
6725 // First, parse generic parameters if necessary.
6726 let mut generics = if self.choose_generics_over_qpath() {
6727 self.parse_generics()?
6729 ast::Generics::default()
6732 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6733 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6735 ast::ImplPolarity::Negative
6737 ast::ImplPolarity::Positive
6740 // Parse both types and traits as a type, then reinterpret if necessary.
6741 let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6742 let ty_first = if self.token.is_keyword(keywords::For) &&
6743 self.look_ahead(1, |t| t != &token::Lt) {
6744 let span = self.prev_span.between(self.span);
6745 self.struct_span_err(span, "missing trait in a trait impl").emit();
6746 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6751 // If `for` is missing we try to recover.
6752 let has_for = self.eat_keyword(keywords::For);
6753 let missing_for_span = self.prev_span.between(self.span);
6755 let ty_second = if self.token == token::DotDot {
6756 // We need to report this error after `cfg` expansion for compatibility reasons
6757 self.bump(); // `..`, do not add it to expected tokens
6758 Some(DummyResult::raw_ty(self.prev_span, true))
6759 } else if has_for || self.token.can_begin_type() {
6760 Some(self.parse_ty()?)
6765 generics.where_clause = self.parse_where_clause()?;
6767 let (impl_items, attrs) = self.parse_impl_body()?;
6769 let item_kind = match ty_second {
6770 Some(ty_second) => {
6771 // impl Trait for Type
6773 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6774 .span_suggestion_short(
6777 " for ".to_string(),
6778 Applicability::MachineApplicable,
6782 let ty_first = ty_first.into_inner();
6783 let path = match ty_first.node {
6784 // This notably includes paths passed through `ty` macro fragments (#46438).
6785 TyKind::Path(None, path) => path,
6787 self.span_err(ty_first.span, "expected a trait, found type");
6788 err_path(ty_first.span)
6791 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6793 ItemKind::Impl(unsafety, polarity, defaultness,
6794 generics, Some(trait_ref), ty_second, impl_items)
6798 ItemKind::Impl(unsafety, polarity, defaultness,
6799 generics, None, ty_first, impl_items)
6803 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6806 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6807 if self.eat_keyword(keywords::For) {
6809 let params = self.parse_generic_params()?;
6811 // We rely on AST validation to rule out invalid cases: There must not be type
6812 // parameters, and the lifetime parameters must not have bounds.
6819 /// Parses `struct Foo { ... }`.
6820 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6821 let class_name = self.parse_ident()?;
6823 let mut generics = self.parse_generics()?;
6825 // There is a special case worth noting here, as reported in issue #17904.
6826 // If we are parsing a tuple struct it is the case that the where clause
6827 // should follow the field list. Like so:
6829 // struct Foo<T>(T) where T: Copy;
6831 // If we are parsing a normal record-style struct it is the case
6832 // that the where clause comes before the body, and after the generics.
6833 // So if we look ahead and see a brace or a where-clause we begin
6834 // parsing a record style struct.
6836 // Otherwise if we look ahead and see a paren we parse a tuple-style
6839 let vdata = if self.token.is_keyword(keywords::Where) {
6840 generics.where_clause = self.parse_where_clause()?;
6841 if self.eat(&token::Semi) {
6842 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6843 VariantData::Unit(ast::DUMMY_NODE_ID)
6845 // If we see: `struct Foo<T> where T: Copy { ... }`
6846 let (fields, recovered) = self.parse_record_struct_body()?;
6847 VariantData::Struct(fields, ast::DUMMY_NODE_ID, recovered)
6849 // No `where` so: `struct Foo<T>;`
6850 } else if self.eat(&token::Semi) {
6851 VariantData::Unit(ast::DUMMY_NODE_ID)
6852 // Record-style struct definition
6853 } else if self.token == token::OpenDelim(token::Brace) {
6854 let (fields, recovered) = self.parse_record_struct_body()?;
6855 VariantData::Struct(fields, ast::DUMMY_NODE_ID, recovered)
6856 // Tuple-style struct definition with optional where-clause.
6857 } else if self.token == token::OpenDelim(token::Paren) {
6858 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6859 generics.where_clause = self.parse_where_clause()?;
6860 self.expect(&token::Semi)?;
6863 let token_str = self.this_token_descr();
6864 let mut err = self.fatal(&format!(
6865 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6868 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6872 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6875 /// Parses `union Foo { ... }`.
6876 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6877 let class_name = self.parse_ident()?;
6879 let mut generics = self.parse_generics()?;
6881 let vdata = if self.token.is_keyword(keywords::Where) {
6882 generics.where_clause = self.parse_where_clause()?;
6883 let (fields, recovered) = self.parse_record_struct_body()?;
6884 VariantData::Struct(fields, ast::DUMMY_NODE_ID, recovered)
6885 } else if self.token == token::OpenDelim(token::Brace) {
6886 let (fields, recovered) = self.parse_record_struct_body()?;
6887 VariantData::Struct(fields, ast::DUMMY_NODE_ID, recovered)
6889 let token_str = self.this_token_descr();
6890 let mut err = self.fatal(&format!(
6891 "expected `where` or `{{` after union name, found {}", token_str));
6892 err.span_label(self.span, "expected `where` or `{` after union name");
6896 Ok((class_name, ItemKind::Union(vdata, generics), None))
6899 fn consume_block(&mut self, delim: token::DelimToken) {
6900 let mut brace_depth = 0;
6902 if self.eat(&token::OpenDelim(delim)) {
6904 } else if self.eat(&token::CloseDelim(delim)) {
6905 if brace_depth == 0 {
6911 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6919 fn parse_record_struct_body(
6921 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6922 let mut fields = Vec::new();
6923 let mut recovered = false;
6924 if self.eat(&token::OpenDelim(token::Brace)) {
6925 while self.token != token::CloseDelim(token::Brace) {
6926 let field = self.parse_struct_decl_field().map_err(|e| {
6927 self.recover_stmt();
6932 Ok(field) => fields.push(field),
6938 self.eat(&token::CloseDelim(token::Brace));
6940 let token_str = self.this_token_descr();
6941 let mut err = self.fatal(&format!(
6942 "expected `where`, or `{{` after struct name, found {}", token_str));
6943 err.span_label(self.span, "expected `where`, or `{` after struct name");
6947 Ok((fields, recovered))
6950 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6951 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6952 // Unit like structs are handled in parse_item_struct function
6953 let fields = self.parse_unspanned_seq(
6954 &token::OpenDelim(token::Paren),
6955 &token::CloseDelim(token::Paren),
6956 SeqSep::trailing_allowed(token::Comma),
6958 let attrs = p.parse_outer_attributes()?;
6960 let vis = p.parse_visibility(true)?;
6961 let ty = p.parse_ty()?;
6963 span: lo.to(ty.span),
6966 id: ast::DUMMY_NODE_ID,
6975 /// Parses a structure field declaration.
6976 fn parse_single_struct_field(&mut self,
6979 attrs: Vec<Attribute> )
6980 -> PResult<'a, StructField> {
6981 let mut seen_comma: bool = false;
6982 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6983 if self.token == token::Comma {
6990 token::CloseDelim(token::Brace) => {}
6991 token::DocComment(_) => {
6992 let previous_span = self.prev_span;
6993 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6994 self.bump(); // consume the doc comment
6995 let comma_after_doc_seen = self.eat(&token::Comma);
6996 // `seen_comma` is always false, because we are inside doc block
6997 // condition is here to make code more readable
6998 if seen_comma == false && comma_after_doc_seen == true {
7001 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7004 if seen_comma == false {
7005 let sp = self.sess.source_map().next_point(previous_span);
7006 err.span_suggestion(
7008 "missing comma here",
7010 Applicability::MachineApplicable
7017 let sp = self.sess.source_map().next_point(self.prev_span);
7018 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7019 self.this_token_descr()));
7020 if self.token.is_ident() {
7021 // This is likely another field; emit the diagnostic and keep going
7022 err.span_suggestion(
7024 "try adding a comma",
7026 Applicability::MachineApplicable,
7037 /// Parses an element of a struct declaration.
7038 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7039 let attrs = self.parse_outer_attributes()?;
7041 let vis = self.parse_visibility(false)?;
7042 self.parse_single_struct_field(lo, vis, attrs)
7045 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7046 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7047 /// If the following element can't be a tuple (i.e., it's a function definition), then
7048 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7049 /// so emit a proper diagnostic.
7050 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7051 maybe_whole!(self, NtVis, |x| x);
7053 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7054 if self.is_crate_vis() {
7055 self.bump(); // `crate`
7056 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7059 if !self.eat_keyword(keywords::Pub) {
7060 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7061 // keyword to grab a span from for inherited visibility; an empty span at the
7062 // beginning of the current token would seem to be the "Schelling span".
7063 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7065 let lo = self.prev_span;
7067 if self.check(&token::OpenDelim(token::Paren)) {
7068 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7069 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7070 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7071 // by the following tokens.
7072 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
7075 self.bump(); // `crate`
7076 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7078 lo.to(self.prev_span),
7079 VisibilityKind::Crate(CrateSugar::PubCrate),
7082 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7085 self.bump(); // `in`
7086 let path = self.parse_path(PathStyle::Mod)?; // `path`
7087 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7088 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7090 id: ast::DUMMY_NODE_ID,
7093 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7094 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7095 t.is_keyword(keywords::SelfLower))
7097 // `pub(self)` or `pub(super)`
7099 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7100 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7101 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7103 id: ast::DUMMY_NODE_ID,
7106 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7107 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7109 let msg = "incorrect visibility restriction";
7110 let suggestion = r##"some possible visibility restrictions are:
7111 `pub(crate)`: visible only on the current crate
7112 `pub(super)`: visible only in the current module's parent
7113 `pub(in path::to::module)`: visible only on the specified path"##;
7114 let path = self.parse_path(PathStyle::Mod)?;
7115 let sp = self.prev_span;
7116 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7117 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7118 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7119 err.help(suggestion);
7120 err.span_suggestion(
7121 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7123 err.emit(); // emit diagnostic, but continue with public visibility
7127 Ok(respan(lo, VisibilityKind::Public))
7130 /// Parses defaultness (i.e., `default` or nothing).
7131 fn parse_defaultness(&mut self) -> Defaultness {
7132 // `pub` is included for better error messages
7133 if self.check_keyword(keywords::Default) &&
7134 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7135 t.is_keyword(keywords::Const) ||
7136 t.is_keyword(keywords::Fn) ||
7137 t.is_keyword(keywords::Unsafe) ||
7138 t.is_keyword(keywords::Extern) ||
7139 t.is_keyword(keywords::Type) ||
7140 t.is_keyword(keywords::Pub)) {
7141 self.bump(); // `default`
7142 Defaultness::Default
7148 fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
7149 if self.eat(&token::Semi) {
7150 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
7151 err.span_suggestion_short(
7153 "remove this semicolon",
7155 Applicability::MachineApplicable,
7157 if !items.is_empty() {
7158 let previous_item = &items[items.len()-1];
7159 let previous_item_kind_name = match previous_item.node {
7160 // say "braced struct" because tuple-structs and
7161 // braceless-empty-struct declarations do take a semicolon
7162 ItemKind::Struct(..) => Some("braced struct"),
7163 ItemKind::Enum(..) => Some("enum"),
7164 ItemKind::Trait(..) => Some("trait"),
7165 ItemKind::Union(..) => Some("union"),
7168 if let Some(name) = previous_item_kind_name {
7169 err.help(&format!("{} declarations are not followed by a semicolon", name));
7179 /// Given a termination token, parses all of the items in a module.
7180 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7181 let mut items = vec![];
7182 while let Some(item) = self.parse_item()? {
7184 self.maybe_consume_incorrect_semicolon(&items);
7187 if !self.eat(term) {
7188 let token_str = self.this_token_descr();
7189 if !self.maybe_consume_incorrect_semicolon(&items) {
7190 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7191 err.span_label(self.span, "expected item");
7196 let hi = if self.span.is_dummy() {
7203 inner: inner_lo.to(hi),
7209 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7210 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7211 self.expect(&token::Colon)?;
7212 let ty = self.parse_ty()?;
7213 self.expect(&token::Eq)?;
7214 let e = self.parse_expr()?;
7215 self.expect(&token::Semi)?;
7216 let item = match m {
7217 Some(m) => ItemKind::Static(ty, m, e),
7218 None => ItemKind::Const(ty, e),
7220 Ok((id, item, None))
7223 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7224 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7225 let (in_cfg, outer_attrs) = {
7226 let mut strip_unconfigured = crate::config::StripUnconfigured {
7228 features: None, // don't perform gated feature checking
7230 let mut outer_attrs = outer_attrs.to_owned();
7231 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7232 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7235 let id_span = self.span;
7236 let id = self.parse_ident()?;
7237 if self.eat(&token::Semi) {
7238 if in_cfg && self.recurse_into_file_modules {
7239 // This mod is in an external file. Let's go get it!
7240 let ModulePathSuccess { path, directory_ownership, warn } =
7241 self.submod_path(id, &outer_attrs, id_span)?;
7242 let (module, mut attrs) =
7243 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7244 // Record that we fetched the mod from an external file
7246 let attr = Attribute {
7247 id: attr::mk_attr_id(),
7248 style: ast::AttrStyle::Outer,
7249 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7250 tokens: TokenStream::empty(),
7251 is_sugared_doc: false,
7252 span: syntax_pos::DUMMY_SP,
7254 attr::mark_known(&attr);
7257 Ok((id, ItemKind::Mod(module), Some(attrs)))
7259 let placeholder = ast::Mod {
7260 inner: syntax_pos::DUMMY_SP,
7264 Ok((id, ItemKind::Mod(placeholder), None))
7267 let old_directory = self.directory.clone();
7268 self.push_directory(id, &outer_attrs);
7270 self.expect(&token::OpenDelim(token::Brace))?;
7271 let mod_inner_lo = self.span;
7272 let attrs = self.parse_inner_attributes()?;
7273 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7275 self.directory = old_directory;
7276 Ok((id, ItemKind::Mod(module), Some(attrs)))
7280 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7281 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7282 self.directory.path.to_mut().push(&path.as_str());
7283 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7285 // We have to push on the current module name in the case of relative
7286 // paths in order to ensure that any additional module paths from inline
7287 // `mod x { ... }` come after the relative extension.
7289 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7290 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7291 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7292 if let Some(ident) = relative.take() { // remove the relative offset
7293 self.directory.path.to_mut().push(ident.as_str());
7296 self.directory.path.to_mut().push(&id.as_str());
7300 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7301 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7304 // On windows, the base path might have the form
7305 // `\\?\foo\bar` in which case it does not tolerate
7306 // mixed `/` and `\` separators, so canonicalize
7309 let s = s.replace("/", "\\");
7310 Some(dir_path.join(s))
7316 /// Returns a path to a module.
7317 pub fn default_submod_path(
7319 relative: Option<ast::Ident>,
7321 source_map: &SourceMap) -> ModulePath
7323 // If we're in a foo.rs file instead of a mod.rs file,
7324 // we need to look for submodules in
7325 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7326 // `./<id>.rs` and `./<id>/mod.rs`.
7327 let relative_prefix_string;
7328 let relative_prefix = if let Some(ident) = relative {
7329 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7330 &relative_prefix_string
7335 let mod_name = id.to_string();
7336 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7337 let secondary_path_str = format!("{}{}{}mod.rs",
7338 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7339 let default_path = dir_path.join(&default_path_str);
7340 let secondary_path = dir_path.join(&secondary_path_str);
7341 let default_exists = source_map.file_exists(&default_path);
7342 let secondary_exists = source_map.file_exists(&secondary_path);
7344 let result = match (default_exists, secondary_exists) {
7345 (true, false) => Ok(ModulePathSuccess {
7347 directory_ownership: DirectoryOwnership::Owned {
7352 (false, true) => Ok(ModulePathSuccess {
7353 path: secondary_path,
7354 directory_ownership: DirectoryOwnership::Owned {
7359 (false, false) => Err(Error::FileNotFoundForModule {
7360 mod_name: mod_name.clone(),
7361 default_path: default_path_str,
7362 secondary_path: secondary_path_str,
7363 dir_path: dir_path.display().to_string(),
7365 (true, true) => Err(Error::DuplicatePaths {
7366 mod_name: mod_name.clone(),
7367 default_path: default_path_str,
7368 secondary_path: secondary_path_str,
7374 path_exists: default_exists || secondary_exists,
7379 fn submod_path(&mut self,
7381 outer_attrs: &[Attribute],
7383 -> PResult<'a, ModulePathSuccess> {
7384 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7385 return Ok(ModulePathSuccess {
7386 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7387 // All `#[path]` files are treated as though they are a `mod.rs` file.
7388 // This means that `mod foo;` declarations inside `#[path]`-included
7389 // files are siblings,
7391 // Note that this will produce weirdness when a file named `foo.rs` is
7392 // `#[path]` included and contains a `mod foo;` declaration.
7393 // If you encounter this, it's your own darn fault :P
7394 Some(_) => DirectoryOwnership::Owned { relative: None },
7395 _ => DirectoryOwnership::UnownedViaMod(true),
7402 let relative = match self.directory.ownership {
7403 DirectoryOwnership::Owned { relative } => relative,
7404 DirectoryOwnership::UnownedViaBlock |
7405 DirectoryOwnership::UnownedViaMod(_) => None,
7407 let paths = Parser::default_submod_path(
7408 id, relative, &self.directory.path, self.sess.source_map());
7410 match self.directory.ownership {
7411 DirectoryOwnership::Owned { .. } => {
7412 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7414 DirectoryOwnership::UnownedViaBlock => {
7416 "Cannot declare a non-inline module inside a block \
7417 unless it has a path attribute";
7418 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7419 if paths.path_exists {
7420 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7422 err.span_note(id_sp, &msg);
7426 DirectoryOwnership::UnownedViaMod(warn) => {
7428 if let Ok(result) = paths.result {
7429 return Ok(ModulePathSuccess { warn: true, ..result });
7432 let mut err = self.diagnostic().struct_span_err(id_sp,
7433 "cannot declare a new module at this location");
7434 if !id_sp.is_dummy() {
7435 let src_path = self.sess.source_map().span_to_filename(id_sp);
7436 if let FileName::Real(src_path) = src_path {
7437 if let Some(stem) = src_path.file_stem() {
7438 let mut dest_path = src_path.clone();
7439 dest_path.set_file_name(stem);
7440 dest_path.push("mod.rs");
7441 err.span_note(id_sp,
7442 &format!("maybe move this module `{}` to its own \
7443 directory via `{}`", src_path.display(),
7444 dest_path.display()));
7448 if paths.path_exists {
7449 err.span_note(id_sp,
7450 &format!("... or maybe `use` the module `{}` instead \
7451 of possibly redeclaring it",
7459 /// Reads a module from a source file.
7460 fn eval_src_mod(&mut self,
7462 directory_ownership: DirectoryOwnership,
7465 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7466 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7467 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7468 let mut err = String::from("circular modules: ");
7469 let len = included_mod_stack.len();
7470 for p in &included_mod_stack[i.. len] {
7471 err.push_str(&p.to_string_lossy());
7472 err.push_str(" -> ");
7474 err.push_str(&path.to_string_lossy());
7475 return Err(self.span_fatal(id_sp, &err[..]));
7477 included_mod_stack.push(path.clone());
7478 drop(included_mod_stack);
7481 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7482 p0.cfg_mods = self.cfg_mods;
7483 let mod_inner_lo = p0.span;
7484 let mod_attrs = p0.parse_inner_attributes()?;
7485 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7487 self.sess.included_mod_stack.borrow_mut().pop();
7491 /// Parses a function declaration from a foreign module.
7492 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7493 -> PResult<'a, ForeignItem> {
7494 self.expect_keyword(keywords::Fn)?;
7496 let (ident, mut generics) = self.parse_fn_header()?;
7497 let decl = self.parse_fn_decl(true)?;
7498 generics.where_clause = self.parse_where_clause()?;
7500 self.expect(&token::Semi)?;
7501 Ok(ast::ForeignItem {
7504 node: ForeignItemKind::Fn(decl, generics),
7505 id: ast::DUMMY_NODE_ID,
7511 /// Parses a static item from a foreign module.
7512 /// Assumes that the `static` keyword is already parsed.
7513 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7514 -> PResult<'a, ForeignItem> {
7515 let mutbl = self.eat_keyword(keywords::Mut);
7516 let ident = self.parse_ident()?;
7517 self.expect(&token::Colon)?;
7518 let ty = self.parse_ty()?;
7520 self.expect(&token::Semi)?;
7524 node: ForeignItemKind::Static(ty, mutbl),
7525 id: ast::DUMMY_NODE_ID,
7531 /// Parses a type from a foreign module.
7532 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7533 -> PResult<'a, ForeignItem> {
7534 self.expect_keyword(keywords::Type)?;
7536 let ident = self.parse_ident()?;
7538 self.expect(&token::Semi)?;
7539 Ok(ast::ForeignItem {
7542 node: ForeignItemKind::Ty,
7543 id: ast::DUMMY_NODE_ID,
7549 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7550 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7551 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7553 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7554 self.parse_path_segment_ident()
7558 let mut idents = vec![];
7559 let mut replacement = vec![];
7560 let mut fixed_crate_name = false;
7561 // Accept `extern crate name-like-this` for better diagnostics
7562 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7563 if self.token == dash { // Do not include `-` as part of the expected tokens list
7564 while self.eat(&dash) {
7565 fixed_crate_name = true;
7566 replacement.push((self.prev_span, "_".to_string()));
7567 idents.push(self.parse_ident()?);
7570 if fixed_crate_name {
7571 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7572 let mut fixed_name = format!("{}", ident.name);
7573 for part in idents {
7574 fixed_name.push_str(&format!("_{}", part.name));
7576 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7578 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7579 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7580 err.multipart_suggestion(
7583 Applicability::MachineApplicable,
7590 /// Parses `extern crate` links.
7595 /// extern crate foo;
7596 /// extern crate bar as foo;
7598 fn parse_item_extern_crate(&mut self,
7600 visibility: Visibility,
7601 attrs: Vec<Attribute>)
7602 -> PResult<'a, P<Item>> {
7603 // Accept `extern crate name-like-this` for better diagnostics
7604 let orig_name = self.parse_crate_name_with_dashes()?;
7605 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7606 (rename, Some(orig_name.name))
7610 self.expect(&token::Semi)?;
7612 let span = lo.to(self.prev_span);
7613 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7616 /// Parses `extern` for foreign ABIs modules.
7618 /// `extern` is expected to have been
7619 /// consumed before calling this method.
7623 /// ```ignore (only-for-syntax-highlight)
7627 fn parse_item_foreign_mod(&mut self,
7629 opt_abi: Option<Abi>,
7630 visibility: Visibility,
7631 mut attrs: Vec<Attribute>)
7632 -> PResult<'a, P<Item>> {
7633 self.expect(&token::OpenDelim(token::Brace))?;
7635 let abi = opt_abi.unwrap_or(Abi::C);
7637 attrs.extend(self.parse_inner_attributes()?);
7639 let mut foreign_items = vec![];
7640 while !self.eat(&token::CloseDelim(token::Brace)) {
7641 foreign_items.push(self.parse_foreign_item()?);
7644 let prev_span = self.prev_span;
7645 let m = ast::ForeignMod {
7647 items: foreign_items
7649 let invalid = keywords::Invalid.ident();
7650 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7653 /// Parses `type Foo = Bar;`
7655 /// `existential type Foo: Bar;`
7658 /// without modifying the parser state.
7659 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7660 // This parses the grammar:
7661 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7662 if self.check_keyword(keywords::Type) ||
7663 self.check_keyword(keywords::Existential) &&
7664 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7665 let existential = self.eat_keyword(keywords::Existential);
7666 assert!(self.eat_keyword(keywords::Type));
7667 Some(self.parse_existential_or_alias(existential))
7673 /// Parses a type alias or existential type.
7674 fn parse_existential_or_alias(
7677 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7678 let ident = self.parse_ident()?;
7679 let mut tps = self.parse_generics()?;
7680 tps.where_clause = self.parse_where_clause()?;
7681 let alias = if existential {
7682 self.expect(&token::Colon)?;
7683 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7684 AliasKind::Existential(bounds)
7686 self.expect(&token::Eq)?;
7687 let ty = self.parse_ty()?;
7690 self.expect(&token::Semi)?;
7691 Ok((ident, alias, tps))
7694 /// Parses the part of an enum declaration following the `{`.
7695 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7696 let mut variants = Vec::new();
7697 let mut all_nullary = true;
7698 let mut any_disr = vec![];
7699 while self.token != token::CloseDelim(token::Brace) {
7700 let variant_attrs = self.parse_outer_attributes()?;
7701 let vlo = self.span;
7704 let mut disr_expr = None;
7706 let ident = self.parse_ident()?;
7707 if self.check(&token::OpenDelim(token::Brace)) {
7708 // Parse a struct variant.
7709 all_nullary = false;
7710 let (fields, recovered) = self.parse_record_struct_body()?;
7711 struct_def = VariantData::Struct(fields, ast::DUMMY_NODE_ID, recovered);
7712 } else if self.check(&token::OpenDelim(token::Paren)) {
7713 all_nullary = false;
7714 struct_def = VariantData::Tuple(
7715 self.parse_tuple_struct_body()?,
7718 } else if self.eat(&token::Eq) {
7719 disr_expr = Some(AnonConst {
7720 id: ast::DUMMY_NODE_ID,
7721 value: self.parse_expr()?,
7723 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7726 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7728 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7731 let vr = ast::Variant_ {
7733 attrs: variant_attrs,
7737 variants.push(respan(vlo.to(self.prev_span), vr));
7739 if !self.eat(&token::Comma) {
7740 if self.token.is_ident() && !self.token.is_reserved_ident() {
7741 let sp = self.sess.source_map().next_point(self.prev_span);
7742 let mut err = self.struct_span_err(sp, "missing comma");
7743 err.span_suggestion_short(
7747 Applicability::MaybeIncorrect,
7755 self.expect(&token::CloseDelim(token::Brace))?;
7756 if !any_disr.is_empty() && !all_nullary {
7757 let mut err = self.struct_span_err(
7759 "discriminator values can only be used with a field-less enum",
7761 for sp in any_disr {
7762 err.span_label(sp, "only valid in field-less enums");
7767 Ok(ast::EnumDef { variants })
7770 /// Parses an enum declaration.
7771 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7772 let id = self.parse_ident()?;
7773 let mut generics = self.parse_generics()?;
7774 generics.where_clause = self.parse_where_clause()?;
7775 self.expect(&token::OpenDelim(token::Brace))?;
7777 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7778 self.recover_stmt();
7779 self.eat(&token::CloseDelim(token::Brace));
7782 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7785 /// Parses a string as an ABI spec on an extern type or module. Consumes
7786 /// the `extern` keyword, if one is found.
7787 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7789 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7791 self.expect_no_suffix(sp, "ABI spec", suf);
7793 match abi::lookup(&s.as_str()) {
7794 Some(abi) => Ok(Some(abi)),
7796 let prev_span = self.prev_span;
7797 let mut err = struct_span_err!(
7798 self.sess.span_diagnostic,
7801 "invalid ABI: found `{}`",
7803 err.span_label(prev_span, "invalid ABI");
7804 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7815 fn is_static_global(&mut self) -> bool {
7816 if self.check_keyword(keywords::Static) {
7817 // Check if this could be a closure
7818 !self.look_ahead(1, |token| {
7819 if token.is_keyword(keywords::Move) {
7823 token::BinOp(token::Or) | token::OrOr => true,
7834 attrs: Vec<Attribute>,
7835 macros_allowed: bool,
7836 attributes_allowed: bool,
7837 ) -> PResult<'a, Option<P<Item>>> {
7838 let mut unclosed_delims = vec![];
7839 let (ret, tokens) = self.collect_tokens(|this| {
7840 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7841 unclosed_delims.append(&mut this.unclosed_delims);
7844 self.unclosed_delims.append(&mut unclosed_delims);
7846 // Once we've parsed an item and recorded the tokens we got while
7847 // parsing we may want to store `tokens` into the item we're about to
7848 // return. Note, though, that we specifically didn't capture tokens
7849 // related to outer attributes. The `tokens` field here may later be
7850 // used with procedural macros to convert this item back into a token
7851 // stream, but during expansion we may be removing attributes as we go
7854 // If we've got inner attributes then the `tokens` we've got above holds
7855 // these inner attributes. If an inner attribute is expanded we won't
7856 // actually remove it from the token stream, so we'll just keep yielding
7857 // it (bad!). To work around this case for now we just avoid recording
7858 // `tokens` if we detect any inner attributes. This should help keep
7859 // expansion correct, but we should fix this bug one day!
7862 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7863 i.tokens = Some(tokens);
7870 /// Parses one of the items allowed by the flags.
7871 fn parse_item_implementation(
7873 attrs: Vec<Attribute>,
7874 macros_allowed: bool,
7875 attributes_allowed: bool,
7876 ) -> PResult<'a, Option<P<Item>>> {
7877 maybe_whole!(self, NtItem, |item| {
7878 let mut item = item.into_inner();
7879 let mut attrs = attrs;
7880 mem::swap(&mut item.attrs, &mut attrs);
7881 item.attrs.extend(attrs);
7887 let visibility = self.parse_visibility(false)?;
7889 if self.eat_keyword(keywords::Use) {
7891 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7892 self.expect(&token::Semi)?;
7894 let span = lo.to(self.prev_span);
7895 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7896 return Ok(Some(item));
7899 if self.eat_keyword(keywords::Extern) {
7900 if self.eat_keyword(keywords::Crate) {
7901 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7904 let opt_abi = self.parse_opt_abi()?;
7906 if self.eat_keyword(keywords::Fn) {
7907 // EXTERN FUNCTION ITEM
7908 let fn_span = self.prev_span;
7909 let abi = opt_abi.unwrap_or(Abi::C);
7910 let (ident, item_, extra_attrs) =
7911 self.parse_item_fn(Unsafety::Normal,
7912 respan(fn_span, IsAsync::NotAsync),
7913 respan(fn_span, Constness::NotConst),
7915 let prev_span = self.prev_span;
7916 let item = self.mk_item(lo.to(prev_span),
7920 maybe_append(attrs, extra_attrs));
7921 return Ok(Some(item));
7922 } else if self.check(&token::OpenDelim(token::Brace)) {
7923 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7929 if self.is_static_global() {
7932 let m = if self.eat_keyword(keywords::Mut) {
7935 Mutability::Immutable
7937 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7938 let prev_span = self.prev_span;
7939 let item = self.mk_item(lo.to(prev_span),
7943 maybe_append(attrs, extra_attrs));
7944 return Ok(Some(item));
7946 if self.eat_keyword(keywords::Const) {
7947 let const_span = self.prev_span;
7948 if self.check_keyword(keywords::Fn)
7949 || (self.check_keyword(keywords::Unsafe)
7950 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7951 // CONST FUNCTION ITEM
7952 let unsafety = self.parse_unsafety();
7954 let (ident, item_, extra_attrs) =
7955 self.parse_item_fn(unsafety,
7956 respan(const_span, IsAsync::NotAsync),
7957 respan(const_span, Constness::Const),
7959 let prev_span = self.prev_span;
7960 let item = self.mk_item(lo.to(prev_span),
7964 maybe_append(attrs, extra_attrs));
7965 return Ok(Some(item));
7969 if self.eat_keyword(keywords::Mut) {
7970 let prev_span = self.prev_span;
7971 let mut err = self.diagnostic()
7972 .struct_span_err(prev_span, "const globals cannot be mutable");
7973 err.span_label(prev_span, "cannot be mutable");
7974 err.span_suggestion(
7976 "you might want to declare a static instead",
7977 "static".to_owned(),
7978 Applicability::MaybeIncorrect,
7982 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7983 let prev_span = self.prev_span;
7984 let item = self.mk_item(lo.to(prev_span),
7988 maybe_append(attrs, extra_attrs));
7989 return Ok(Some(item));
7992 // `unsafe async fn` or `async fn`
7994 self.check_keyword(keywords::Unsafe) &&
7995 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7997 self.check_keyword(keywords::Async) &&
7998 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
8001 // ASYNC FUNCTION ITEM
8002 let unsafety = self.parse_unsafety();
8003 self.expect_keyword(keywords::Async)?;
8004 let async_span = self.prev_span;
8005 self.expect_keyword(keywords::Fn)?;
8006 let fn_span = self.prev_span;
8007 let (ident, item_, extra_attrs) =
8008 self.parse_item_fn(unsafety,
8009 respan(async_span, IsAsync::Async {
8010 closure_id: ast::DUMMY_NODE_ID,
8011 return_impl_trait_id: ast::DUMMY_NODE_ID,
8013 respan(fn_span, Constness::NotConst),
8015 let prev_span = self.prev_span;
8016 let item = self.mk_item(lo.to(prev_span),
8020 maybe_append(attrs, extra_attrs));
8021 if self.span.rust_2015() {
8022 self.diagnostic().struct_span_err_with_code(
8024 "`async fn` is not permitted in the 2015 edition",
8025 DiagnosticId::Error("E0670".into())
8028 return Ok(Some(item));
8030 if self.check_keyword(keywords::Unsafe) &&
8031 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8032 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8034 // UNSAFE TRAIT ITEM
8035 self.bump(); // `unsafe`
8036 let is_auto = if self.eat_keyword(keywords::Trait) {
8039 self.expect_keyword(keywords::Auto)?;
8040 self.expect_keyword(keywords::Trait)?;
8043 let (ident, item_, extra_attrs) =
8044 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8045 let prev_span = self.prev_span;
8046 let item = self.mk_item(lo.to(prev_span),
8050 maybe_append(attrs, extra_attrs));
8051 return Ok(Some(item));
8053 if self.check_keyword(keywords::Impl) ||
8054 self.check_keyword(keywords::Unsafe) &&
8055 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8056 self.check_keyword(keywords::Default) &&
8057 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8058 self.check_keyword(keywords::Default) &&
8059 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8061 let defaultness = self.parse_defaultness();
8062 let unsafety = self.parse_unsafety();
8063 self.expect_keyword(keywords::Impl)?;
8064 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8065 let span = lo.to(self.prev_span);
8066 return Ok(Some(self.mk_item(span, ident, item, visibility,
8067 maybe_append(attrs, extra_attrs))));
8069 if self.check_keyword(keywords::Fn) {
8072 let fn_span = self.prev_span;
8073 let (ident, item_, extra_attrs) =
8074 self.parse_item_fn(Unsafety::Normal,
8075 respan(fn_span, IsAsync::NotAsync),
8076 respan(fn_span, Constness::NotConst),
8078 let prev_span = self.prev_span;
8079 let item = self.mk_item(lo.to(prev_span),
8083 maybe_append(attrs, extra_attrs));
8084 return Ok(Some(item));
8086 if self.check_keyword(keywords::Unsafe)
8087 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8088 // UNSAFE FUNCTION ITEM
8089 self.bump(); // `unsafe`
8090 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8091 self.check(&token::OpenDelim(token::Brace));
8092 let abi = if self.eat_keyword(keywords::Extern) {
8093 self.parse_opt_abi()?.unwrap_or(Abi::C)
8097 self.expect_keyword(keywords::Fn)?;
8098 let fn_span = self.prev_span;
8099 let (ident, item_, extra_attrs) =
8100 self.parse_item_fn(Unsafety::Unsafe,
8101 respan(fn_span, IsAsync::NotAsync),
8102 respan(fn_span, Constness::NotConst),
8104 let prev_span = self.prev_span;
8105 let item = self.mk_item(lo.to(prev_span),
8109 maybe_append(attrs, extra_attrs));
8110 return Ok(Some(item));
8112 if self.eat_keyword(keywords::Mod) {
8114 let (ident, item_, extra_attrs) =
8115 self.parse_item_mod(&attrs[..])?;
8116 let prev_span = self.prev_span;
8117 let item = self.mk_item(lo.to(prev_span),
8121 maybe_append(attrs, extra_attrs));
8122 return Ok(Some(item));
8124 if let Some(type_) = self.eat_type() {
8125 let (ident, alias, generics) = type_?;
8127 let item_ = match alias {
8128 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8129 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8131 let prev_span = self.prev_span;
8132 let item = self.mk_item(lo.to(prev_span),
8137 return Ok(Some(item));
8139 if self.eat_keyword(keywords::Enum) {
8141 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8142 let prev_span = self.prev_span;
8143 let item = self.mk_item(lo.to(prev_span),
8147 maybe_append(attrs, extra_attrs));
8148 return Ok(Some(item));
8150 if self.check_keyword(keywords::Trait)
8151 || (self.check_keyword(keywords::Auto)
8152 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8154 let is_auto = if self.eat_keyword(keywords::Trait) {
8157 self.expect_keyword(keywords::Auto)?;
8158 self.expect_keyword(keywords::Trait)?;
8162 let (ident, item_, extra_attrs) =
8163 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8164 let prev_span = self.prev_span;
8165 let item = self.mk_item(lo.to(prev_span),
8169 maybe_append(attrs, extra_attrs));
8170 return Ok(Some(item));
8172 if self.eat_keyword(keywords::Struct) {
8174 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8175 let prev_span = self.prev_span;
8176 let item = self.mk_item(lo.to(prev_span),
8180 maybe_append(attrs, extra_attrs));
8181 return Ok(Some(item));
8183 if self.is_union_item() {
8186 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8187 let prev_span = self.prev_span;
8188 let item = self.mk_item(lo.to(prev_span),
8192 maybe_append(attrs, extra_attrs));
8193 return Ok(Some(item));
8195 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8196 return Ok(Some(macro_def));
8199 // Verify whether we have encountered a struct or method definition where the user forgot to
8200 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8201 if visibility.node.is_pub() &&
8202 self.check_ident() &&
8203 self.look_ahead(1, |t| *t != token::Not)
8205 // Space between `pub` keyword and the identifier
8208 // ^^^ `sp` points here
8209 let sp = self.prev_span.between(self.span);
8210 let full_sp = self.prev_span.to(self.span);
8211 let ident_sp = self.span;
8212 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8213 // possible public struct definition where `struct` was forgotten
8214 let ident = self.parse_ident().unwrap();
8215 let msg = format!("add `struct` here to parse `{}` as a public struct",
8217 let mut err = self.diagnostic()
8218 .struct_span_err(sp, "missing `struct` for struct definition");
8219 err.span_suggestion_short(
8220 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8223 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8224 let ident = self.parse_ident().unwrap();
8226 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8231 self.consume_block(token::Paren);
8232 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8233 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8235 ("fn", kw_name, false)
8236 } else if self.check(&token::OpenDelim(token::Brace)) {
8238 ("fn", kw_name, false)
8239 } else if self.check(&token::Colon) {
8243 ("fn` or `struct", "function or struct", true)
8245 self.consume_block(token::Brace);
8247 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8248 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8250 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8254 err.span_suggestion_short(
8255 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8258 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8259 err.span_suggestion(
8261 "if you meant to call a macro, try",
8262 format!("{}!", snippet),
8263 // this is the `ambiguous` conditional branch
8264 Applicability::MaybeIncorrect
8267 err.help("if you meant to call a macro, remove the `pub` \
8268 and add a trailing `!` after the identifier");
8272 } else if self.look_ahead(1, |t| *t == token::Lt) {
8273 let ident = self.parse_ident().unwrap();
8274 self.eat_to_tokens(&[&token::Gt]);
8276 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8277 if let Ok(Some(_)) = self.parse_self_arg() {
8278 ("fn", "method", false)
8280 ("fn", "function", false)
8282 } else if self.check(&token::OpenDelim(token::Brace)) {
8283 ("struct", "struct", false)
8285 ("fn` or `struct", "function or struct", true)
8287 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8288 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8290 err.span_suggestion_short(
8292 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8293 format!(" {} ", kw),
8294 Applicability::MachineApplicable,
8300 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8303 /// Parses a foreign item.
8304 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8305 maybe_whole!(self, NtForeignItem, |ni| ni);
8307 let attrs = self.parse_outer_attributes()?;
8309 let visibility = self.parse_visibility(false)?;
8311 // FOREIGN STATIC ITEM
8312 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8313 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8314 if self.token.is_keyword(keywords::Const) {
8316 .struct_span_err(self.span, "extern items cannot be `const`")
8319 "try using a static value",
8320 "static".to_owned(),
8321 Applicability::MachineApplicable
8324 self.bump(); // `static` or `const`
8325 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8327 // FOREIGN FUNCTION ITEM
8328 if self.check_keyword(keywords::Fn) {
8329 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8331 // FOREIGN TYPE ITEM
8332 if self.check_keyword(keywords::Type) {
8333 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8336 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8340 ident: keywords::Invalid.ident(),
8341 span: lo.to(self.prev_span),
8342 id: ast::DUMMY_NODE_ID,
8345 node: ForeignItemKind::Macro(mac),
8350 if !attrs.is_empty() {
8351 self.expected_item_err(&attrs)?;
8359 /// This is the fall-through for parsing items.
8360 fn parse_macro_use_or_failure(
8362 attrs: Vec<Attribute> ,
8363 macros_allowed: bool,
8364 attributes_allowed: bool,
8366 visibility: Visibility
8367 ) -> PResult<'a, Option<P<Item>>> {
8368 if macros_allowed && self.token.is_path_start() &&
8369 !(self.is_async_fn() && self.span.rust_2015()) {
8370 // MACRO INVOCATION ITEM
8372 let prev_span = self.prev_span;
8373 self.complain_if_pub_macro(&visibility.node, prev_span);
8375 let mac_lo = self.span;
8378 let pth = self.parse_path(PathStyle::Mod)?;
8379 self.expect(&token::Not)?;
8381 // a 'special' identifier (like what `macro_rules!` uses)
8382 // is optional. We should eventually unify invoc syntax
8384 let id = if self.token.is_ident() {
8387 keywords::Invalid.ident() // no special identifier
8389 // eat a matched-delimiter token tree:
8390 let (delim, tts) = self.expect_delimited_token_tree()?;
8391 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8392 self.report_invalid_macro_expansion_item();
8395 let hi = self.prev_span;
8396 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8397 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8398 return Ok(Some(item));
8401 // FAILURE TO PARSE ITEM
8402 match visibility.node {
8403 VisibilityKind::Inherited => {}
8405 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8409 if !attributes_allowed && !attrs.is_empty() {
8410 self.expected_item_err(&attrs)?;
8415 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8416 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8417 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8419 if self.token.is_path_start() &&
8420 !(self.is_async_fn() && self.span.rust_2015()) {
8421 let prev_span = self.prev_span;
8423 let pth = self.parse_path(PathStyle::Mod)?;
8425 if pth.segments.len() == 1 {
8426 if !self.eat(&token::Not) {
8427 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8430 self.expect(&token::Not)?;
8433 if let Some(vis) = vis {
8434 self.complain_if_pub_macro(&vis.node, prev_span);
8439 // eat a matched-delimiter token tree:
8440 let (delim, tts) = self.expect_delimited_token_tree()?;
8441 if delim != MacDelimiter::Brace {
8442 self.expect(&token::Semi)?;
8445 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8451 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8452 where F: FnOnce(&mut Self) -> PResult<'a, R>
8454 // Record all tokens we parse when parsing this item.
8455 let mut tokens = Vec::new();
8456 let prev_collecting = match self.token_cursor.frame.last_token {
8457 LastToken::Collecting(ref mut list) => {
8458 Some(mem::replace(list, Vec::new()))
8460 LastToken::Was(ref mut last) => {
8461 tokens.extend(last.take());
8465 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8466 let prev = self.token_cursor.stack.len();
8468 let last_token = if self.token_cursor.stack.len() == prev {
8469 &mut self.token_cursor.frame.last_token
8471 &mut self.token_cursor.stack[prev].last_token
8474 // Pull out the tokens that we've collected from the call to `f` above.
8475 let mut collected_tokens = match *last_token {
8476 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8477 LastToken::Was(_) => panic!("our vector went away?"),
8480 // If we're not at EOF our current token wasn't actually consumed by
8481 // `f`, but it'll still be in our list that we pulled out. In that case
8483 let extra_token = if self.token != token::Eof {
8484 collected_tokens.pop()
8489 // If we were previously collecting tokens, then this was a recursive
8490 // call. In that case we need to record all the tokens we collected in
8491 // our parent list as well. To do that we push a clone of our stream
8492 // onto the previous list.
8493 match prev_collecting {
8495 list.extend(collected_tokens.iter().cloned());
8496 list.extend(extra_token);
8497 *last_token = LastToken::Collecting(list);
8500 *last_token = LastToken::Was(extra_token);
8504 Ok((ret?, TokenStream::new(collected_tokens)))
8507 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8508 let attrs = self.parse_outer_attributes()?;
8509 self.parse_item_(attrs, true, false)
8513 fn is_import_coupler(&mut self) -> bool {
8514 self.check(&token::ModSep) &&
8515 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8516 *t == token::BinOp(token::Star))
8519 /// Parses a `UseTree`.
8522 /// USE_TREE = [`::`] `*` |
8523 /// [`::`] `{` USE_TREE_LIST `}` |
8525 /// PATH `::` `{` USE_TREE_LIST `}` |
8526 /// PATH [`as` IDENT]
8528 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8531 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8532 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8533 self.check(&token::BinOp(token::Star)) ||
8534 self.is_import_coupler() {
8535 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8536 let mod_sep_ctxt = self.span.ctxt();
8537 if self.eat(&token::ModSep) {
8538 prefix.segments.push(
8539 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8543 if self.eat(&token::BinOp(token::Star)) {
8546 UseTreeKind::Nested(self.parse_use_tree_list()?)
8549 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8550 prefix = self.parse_path(PathStyle::Mod)?;
8552 if self.eat(&token::ModSep) {
8553 if self.eat(&token::BinOp(token::Star)) {
8556 UseTreeKind::Nested(self.parse_use_tree_list()?)
8559 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8563 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8566 /// Parses a `UseTreeKind::Nested(list)`.
8569 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8571 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8572 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8573 &token::CloseDelim(token::Brace),
8574 SeqSep::trailing_allowed(token::Comma), |this| {
8575 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8579 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8580 if self.eat_keyword(keywords::As) {
8581 self.parse_ident_or_underscore().map(Some)
8587 /// Parses a source module as a crate. This is the main entry point for the parser.
8588 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8590 let krate = Ok(ast::Crate {
8591 attrs: self.parse_inner_attributes()?,
8592 module: self.parse_mod_items(&token::Eof, lo)?,
8593 span: lo.to(self.span),
8598 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8599 let ret = match self.token {
8600 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8601 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8608 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8609 match self.parse_optional_str() {
8610 Some((s, style, suf)) => {
8611 let sp = self.prev_span;
8612 self.expect_no_suffix(sp, "string literal", suf);
8616 let msg = "expected string literal";
8617 let mut err = self.fatal(msg);
8618 err.span_label(self.span, msg);
8624 fn report_invalid_macro_expansion_item(&self) {
8625 self.struct_span_err(
8627 "macros that expand to items must be delimited with braces or followed by a semicolon",
8628 ).multipart_suggestion(
8629 "change the delimiters to curly braces",
8631 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8632 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8634 Applicability::MaybeIncorrect,
8636 self.sess.source_map.next_point(self.prev_span),
8639 Applicability::MaybeIncorrect,
8643 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8644 fn eat_bad_pub(&mut self) {
8645 if self.token.is_keyword(keywords::Pub) {
8646 match self.parse_visibility(false) {
8648 let mut err = self.diagnostic()
8649 .struct_span_err(vis.span, "unnecessary visibility qualifier");
8650 err.span_label(vis.span, "`pub` not permitted here");
8653 Err(mut err) => err.emit(),
8659 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8660 for unmatched in unclosed_delims.iter() {
8661 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8662 "incorrect close delimiter: `{}`",
8663 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8665 err.span_label(unmatched.found_span, "incorrect close delimiter");
8666 if let Some(sp) = unmatched.candidate_span {
8667 err.span_label(sp, "close delimiter possibly meant for this");
8669 if let Some(sp) = unmatched.unclosed_span {
8670 err.span_label(sp, "un-closed delimiter");
8674 unclosed_delims.clear();